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
- Variables
- func AllowedHost(host string) bool
- func BlockedAddr(a netip.Addr) bool
- func BuildPayload(n Notification, mode string) ([]byte, error)
- func Excerpt(s string) string
- func Title(n Notification) string
- func ValidateEndpoint(raw string) error
- type Notification
- type Options
- type Resolver
- type Service
- func (s *Service) Close()
- func (s *Service) Dropped() int64
- func (s *Service) Enabled() bool
- func (s *Service) HasSubscriptions(ctx context.Context, userID string) bool
- func (s *Service) PublicKey() string
- func (s *Service) Send(userID string, n Notification)
- func (s *Service) Subscribe(ctx context.Context, userID string, in SubscribeInput) error
- func (s *Service) Subscriptions(ctx context.Context, userID string) ([]Subscription, error)
- func (s *Service) Unsubscribe(ctx context.Context, userID, endpoint string) error
- type SubscribeInput
- type Subscription
- type VAPID
- type ValidationError
Constants ¶
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).
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.
const MaxEndpointLen = 2048
MaxEndpointLen bounds a subscription endpoint.
const MaxSubscriptionsPerUser = 10
MaxSubscriptionsPerUser bounds the browsers one user can register.
const VAPIDFile = "vapid.json"
VAPIDFile is the name of the VAPID key file inside the data directory.
Variables ¶
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.
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.
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 ¶
AllowedHost reports whether host (lower case, no port) is on the push service allowlist.
func BlockedAddr ¶
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 ¶
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 ¶
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 (*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 ¶
Dropped is the number of notifications Send discarded because the queue was full.
func (*Service) HasSubscriptions ¶
HasSubscriptions reports whether userID has at least one subscription. A database error counts as none: the dispatcher skips the push.
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 ¶
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 ¶
Subscriptions lists userID's subscriptions, oldest first.
type SubscribeInput ¶
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 ¶
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 ¶
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 ¶
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