push

package
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Oct 12, 2026 License: Apache-2.0 Imports: 29 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package push is bubbles' Web Push: VAPID keys, the subscription store, the payload builder and the sender. Web Push is the only traffic the server originates, and the destination URL is supplied by users, so every destination passes two independent checks: the endpoint allowlist at subscription time (ValidateEndpoint) and the address guard at connection time (guardedDialer).

Index

Constants

View Source
const (
	// TTLSeconds is how long a push service holds an undelivered message.
	TTLSeconds = 3600
	// MaxExcerptChars is the body excerpt length of the "full" payload.
	MaxExcerptChars = 120
)

Delivery parameters (plan pipeline step 7).

View Source
const (
	// DefaultWorkers is the size of the send worker pool.
	DefaultWorkers = 4
	// DefaultQueueSize bounds the notifications waiting for a worker; beyond
	// it Send drops (and counts) instead of blocking the dispatcher.
	DefaultQueueSize = 1024
	// RequestTimeout is the deadline of one request to a push service.
	RequestTimeout = 10 * time.Second
	// MaxFailures is the number of consecutive failed deliveries after which a
	// subscription is deleted.
	MaxFailures = 5
)

Sender defaults and limits.

View Source
const MaxEndpointLen = 2048

MaxEndpointLen bounds a subscription endpoint.

View Source
const MaxSubscriptionsPerUser = 10

MaxSubscriptionsPerUser bounds the browsers one user can register.

View Source
const VAPIDFile = "vapid.json"

VAPIDFile is the name of the VAPID key file inside the data directory.

Variables

View Source
var ErrBlockedAddress = errors.New("push: destination address is not allowed")

ErrBlockedAddress is returned when a push destination resolves to an address that is not a public unicast address.

View Source
var ErrEndpointOwned = errors.New("push endpoint belongs to another account")

ErrEndpointOwned is returned by Subscribe when the endpoint belongs to another user and the request does not carry that subscription's keys.

View Source
var ErrTooManySubscriptions = errors.New("too many push subscriptions")

ErrTooManySubscriptions is returned by Subscribe when the user already has MaxSubscriptionsPerUser subscriptions and the endpoint is not one of them.

Functions

func AllowedHost

func AllowedHost(host string) bool

AllowedHost reports whether host (lower case, no port) is on the push service allowlist.

func BlockedAddr

func BlockedAddr(a netip.Addr) bool

BlockedAddr reports whether a is not a public unicast address: private, loopback, link-local (including the 169.254.169.254 metadata address), CGNAT, multicast, unspecified, broadcast, reserved or documentation space. IPv4-mapped IPv6 addresses are judged by their IPv4 form and, because a resolver has no business returning them, refused outright as well.

func BuildPayload

func BuildPayload(n Notification, mode string) ([]byte, error)

BuildPayload renders the JSON a service worker receives. mode is a settings.Push* value: the minimal payload carries only the title and the ids, never any message text; the full one adds an excerpt of at most MaxExcerptChars characters.

func Excerpt

func Excerpt(s string) string

Excerpt collapses all white space in s to single spaces, drops control characters and cuts the result to MaxExcerptChars characters, ending in an ellipsis when it was cut.

func Title

func Title(n Notification) string

Title is the notification title: "<sender> in #<channel>", or just "<sender>" for direct messages.

func ValidateEndpoint

func ValidateEndpoint(raw string) error

ValidateEndpoint checks that raw is a URL the server may POST to: https, no credentials, no fragment, port 443 or none, and a host (never an IP literal) on the push service allowlist. The returned error text is safe to show to the user.

Types

type Notification

type Notification struct {
	ChannelID   string
	ChannelName string
	ChannelKind string
	MessageID   string
	SenderName  string
	Body        string
	// Critical marks a critical alert (push urgency "high").
	Critical bool
}

Notification is what the dispatcher hands to the sender for one recipient. Body is the plain-text message text; it reaches the push payload only when the admin chose push_payload "full".

type Options

type Options struct {
	// DB holds the push_subscriptions table. Required.
	DB *store.DB
	// Settings supplies web_push_enabled and push_payload. Required.
	Settings *settings.Store
	// DataDir is where vapid.json lives. Required.
	DataDir string
	// Logger receives delivery warnings; it never sees endpoints. nil discards.
	Logger *slog.Logger
	// Workers and QueueSize default to DefaultWorkers and DefaultQueueSize.
	Workers   int
	QueueSize int
	// Resolver resolves push service host names; nil means the system
	// resolver. The address guard checks every answer.
	Resolver Resolver
	// contains filtered or unexported fields
}

Options configures New.

type Resolver

type Resolver interface {
	LookupNetIP(ctx context.Context, network, host string) ([]netip.Addr, error)
}

Resolver looks up host names. *net.Resolver implements it.

type Service

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

Service owns the VAPID keys, the subscription table and the send worker pool.

func New

func New(o Options) (*Service, error)

New loads (or creates) the VAPID keys and starts the send workers. Close stops them.

func (*Service) Close

func (s *Service) Close()

Close stops the workers; queued notifications are discarded and requests in flight are cancelled. It is idempotent.

func (*Service) Dropped

func (s *Service) Dropped() int64

Dropped is the number of notifications Send discarded because the queue was full.

func (*Service) Enabled

func (s *Service) Enabled() bool

Enabled reports the admin setting web_push_enabled.

func (*Service) HasSubscriptions

func (s *Service) HasSubscriptions(ctx context.Context, userID string) bool

HasSubscriptions reports whether userID has at least one subscription. A database error counts as none: the dispatcher skips the push.

func (*Service) PublicKey

func (s *Service) PublicKey() string

PublicKey is the VAPID public key browsers subscribe with.

func (*Service) Send

func (s *Service) Send(userID string, n Notification)

Send queues n for every subscription of userID. It never blocks: when the queue is full the notification is dropped and counted.

func (*Service) Subscribe

func (s *Service) Subscribe(ctx context.Context, userID string, in SubscribeInput) error

Subscribe stores in for userID, or refreshes the row with the same endpoint (a browser that re-subscribes clears its failure count; another account signing in on the same browser takes the row over only with identical keys, otherwise ErrEndpointOwned). Invalid input is a *ValidationError; a user at the limit gets ErrTooManySubscriptions.

func (*Service) Subscriptions

func (s *Service) Subscriptions(ctx context.Context, userID string) ([]Subscription, error)

Subscriptions lists userID's subscriptions, oldest first.

func (*Service) Unsubscribe

func (s *Service) Unsubscribe(ctx context.Context, userID, endpoint string) error

Unsubscribe removes userID's subscription with endpoint. Removing one that does not exist, or that belongs to someone else, is a no-op.

type SubscribeInput

type SubscribeInput struct {
	Endpoint  string
	P256DH    string
	Auth      string
	UserAgent string
}

SubscribeInput is a browser PushSubscription.

type Subscription

type Subscription struct {
	ID           string
	UserID       string
	Endpoint     string
	P256DH       string
	Auth         string
	UserAgent    string
	CreatedAt    int64
	LastOKAt     *int64
	FailureCount int
}

Subscription is a stored Web Push subscription.

type VAPID

type VAPID struct {
	PrivateKey string `json:"private_key"`
	PublicKey  string `json:"public_key"`
}

VAPID is the server's application server key pair (RFC 8292). Both keys are base64url without padding: the private key is the 32-byte P-256 scalar, the public key the 65-byte uncompressed point browsers take as applicationServerKey.

func LoadOrCreateVAPID

func LoadOrCreateVAPID(dataDir string) (VAPID, error)

LoadOrCreateVAPID reads <dataDir>/vapid.json, generating and storing a new key pair (file mode 0600) when the file does not exist. An existing file that is unreadable or inconsistent is an error, never silently replaced: a new key pair would invalidate every browser subscription.

type ValidationError

type ValidationError struct{ Fields map[string]string }

ValidationError lists the request fields Subscribe rejected, field to reason; the field names are the JSON paths of the request body.

func (*ValidationError) Error

func (e *ValidationError) Error() string

Jump to

Keyboard shortcuts

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