webhooks

package
v1.6.0 Latest Latest
Warning

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

Go to latest
Published: Nov 11, 2026 License: AGPL-3.0 Imports: 37 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 (
	// EmailBatch is the type of a batched delivery.
	EmailBatch = "email.batch"
	// BatchSize is the most events one batch carries.
	BatchSize = 100
)

Batched email events (review 2026-11 EN-8). An endpoint that batches gets its email.* events as one POST of type email.batch with up to BatchSize events, so a million-recipient send is ten thousand requests rather than a million.

View Source
const (
	EmailSent       = "email.sent"
	EmailDelivered  = "email.delivered"
	EmailDeferred   = "email.deferred"
	EmailBounced    = "email.bounced"
	EmailComplained = "email.complained"
	EmailOpened     = "email.opened"
	EmailClicked    = "email.clicked"
)

The "Email" group: campaign and automation email (transactional mail has its own message.* group). Review 2026-11 EN-6.

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.

View Source
const PreviousSecretGrace = 24 * time.Hour

PreviousSecretGrace is how long a replaced secret keeps signing beside the new one (review 2026-11 IN-1).

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: "message.cancelled", 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 CheckEvents

func CheckEvents(ctx context.Context, q *store.Queries, wsID uuid.UUID, p *authz.Principal, names []string) *api.Problem

CheckEvents refuses subscriptions (event names, "group.*" or "*") with an event the caller couldn't see in ReputeCast. The problem names the event, and who can help; the permission key is its permission field.

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 EmitEmail

func EmitEmail(ctx context.Context, q store.DBTX, workspaceID, messageID uuid.UUID, event string, at time.Time, extra func(*EmailEvent)) error

EmitEmail queues an email.* event about one campaign or automation message, in the transaction that records what it reports. Nothing is read when no endpoint of the workspace takes the event.

func Listens

func Listens(ctx context.Context, q store.DBTX, workspaceID uuid.UUID, event string) (bool, error)

Listens reports whether any endpoint of the workspace takes event.

func NewSecret

func NewSecret() string

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

func Permissions

func Permissions(event string) []authz.Permission

Permissions returns the view permissions an event needs (the integrations' triggers share them).

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 header and rejects timestamps older than tolerance. After a rotation the header holds two comma-separated signatures; either matching is enough.

Types

type BatchData

type BatchData struct {
	Count  int               `json:"count"`
	Events []json.RawMessage `json:"events"`
}

BatchData is the data of an email.batch event: the events in the order they happened, each the envelope it would have been posted as alone.

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 folds waiting email.* events into batches, 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 EmailEvent

type EmailEvent struct {
	MessageID         string    `json:"message_id"`
	Stream            string    `json:"stream" enum:"broadcast,automation"`
	To                string    `json:"to"`
	ContactID         string    `json:"contact_id,omitempty"`
	CampaignID        string    `json:"campaign_id,omitempty"`
	AutomationID      string    `json:"automation_id,omitempty"`
	AutomationStep    string    `json:"automation_step,omitempty"`
	Provider          string    `json:"provider,omitempty"`
	ProviderMessageID string    `json:"provider_message_id,omitempty"`
	MailboxProvider   string    `json:"mailbox_provider,omitempty"`
	At                time.Time `json:"at"`
	// Reason is a bounce's or deferral's code and text.
	Reason string `json:"reason,omitempty"`
	// URL is the clicked link (email.clicked).
	URL string `json:"url,omitempty"`
	// Machine marks an open a privacy proxy or scanner made (email.opened).
	Machine bool `json:"machine,omitempty"`
}

EmailEvent is the data of an email.* event.

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 EventNeeds

type EventNeeds struct {
	// Permissions are the view permissions of what the event carries.
	Permissions []authz.Permission
	// Contacts: the event carries contacts (an address, a phone number, a
	// profile) from every list.
	Contacts bool
}

EventNeeds is what receiving an event needs.

func NeedsOf

func NeedsOf(event string) EventNeeds

NeedsOf returns what receiving an event needs (an email.batch as its email.* events). A group nobody has described counts as carrying contacts, so a new event never goes further than contacts do until someone decides otherwise.

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. It sends its events on the creator's behalf (a key's creator for a key).

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 and, for PreviousSecretGrace, with the replaced one too: X-ReputeCast-Signature then holds both, comma-separated, the new first.

func (*Service) SetEnabled

func (s *Service) SetEnabled(ctx context.Context, ws *store.Workspace, p *authz.Principal, 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, on behalf of the person who resumed it: they must be able to see what its events carry, as when setting them.

func (*Service) Test

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

func (*Service) Update

Update changes an endpoint's URL, name or events. From then on it sends its events on behalf of the person who saved them.

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"`
	// PayloadHidden says why the payload and the response are left out: the
	// reader can't see what the event carries in ReputeCast.
	PayloadHidden string `json:"payloadHidden,omitempty"`
}

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"`
	// BatchEmail sends the endpoint's email.* events as one POST with up to
	// 100 events (type email.batch) instead of one POST each.
	BatchEmail bool `json:"batchEmail,omitempty"`
}

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"`
	// BatchEmail sends email.* events in batches of up to 100 (review
	// 2026-11 EN-8).
	BatchEmail bool `json:"batchEmail"`
	// 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"`
	// PreviousSecretUntil: until then the replaced secret signs beside the
	// new one (review 2026-11 IN-1).
	PreviousSecretUntil *time.Time `json:"previousSecretUntil,omitempty"`
	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"`
	// PausedReason says why ReputeCast paused the endpoint: the person it
	// sent for can no longer see what its events carry.
	PausedReason string `json:"pausedReason,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