Documentation
¶
Overview ¶
Package webpush delivers Web Push messages to browser push services without a third-party dependency: payload encryption per RFC 8291 (the aes128gcm content coding of RFC 8188) and application-server identification per RFC 8292 (VAPID), built only on the standard library.
The package is deliberately small and strict. Everything that arrives from a browser (the PushSubscription) is untrusted input that names a URL this process will POST to, so Subscription.Validate and the Sender's default HTTP client together refuse anything that is not a public https endpoint. Errors returned to callers name the endpoint's host at most: the endpoint path and query are bearer capabilities (anyone holding them can push to the user), and the subscription keys and VAPID private key are secrets, so none of them may leak into logs through an error string.
Index ¶
Constants ¶
const ( // MaxPayloadSize is the largest plaintext Encrypt accepts: the 4096-byte // body budget minus the RFC 8188 header (with the 65-byte sender key as // keyid), the one-byte padding delimiter, and the GCM tag. MaxPayloadSize = maxBodySize - headerLen - recordOver )
Variables ¶
var ErrPayloadTooLarge = fmt.Errorf("webpush: payload exceeds %d bytes", MaxPayloadSize)
ErrPayloadTooLarge is returned when the plaintext would encrypt to a body larger than push services accept. Callers should shrink the payload (send an id and let the client fetch details) rather than retry.
Functions ¶
func Encrypt ¶
func Encrypt(plaintext []byte, sub Subscription) ([]byte, error)
Encrypt produces the aes128gcm request body for plaintext addressed to sub: the RFC 8188 header (salt, rs, idlen, keyid = a fresh sender public key) followed by a single encrypted record.
A new ephemeral sender key and salt are drawn for every message. RFC 8291 requires this: the content key is derived from the ECDH secret and the salt, so reusing either across messages would reuse an AES-GCM key/nonce pair, which is catastrophic for GCM.
func EndpointHost ¶
EndpointHost is the endpoint's host alone -- what may be shown or logged about a subscription. The path is a capability and is never shown.
Types ¶
type GoneError ¶
GoneError means the push service says the subscription no longer exists (404 or 410). It will never succeed again; the caller should delete it.
type Keys ¶
type Keys struct {
// contains filtered or unexported fields
}
Keys is a VAPID application-server key pair (P-256). The public half is what the browser receives as applicationServerKey when subscribing; every push must then be signed by the private half or the push service refuses it, which is what ties a subscription to this server.
func LoadOrCreateKeys ¶
LoadOrCreateKeys returns the key pair persisted at <dir>/vapid.json, generating and writing one on first use.
Stability matters more than anything else here: every browser subscription is bound to the public key it was created with, so silently minting a new pair (because the file was unreadable or corrupt) would orphan every existing subscription. Any problem with an existing file is therefore an error, never a regeneration.
func (*Keys) PublicKey ¶
PublicKey is the uncompressed 65-byte public point, base64url without padding: exactly the applicationServerKey format pushManager.subscribe expects.
func (*Keys) VAPIDAuthorization ¶
func (k *Keys) VAPIDAuthorization(endpoint, subject string, now time.Time, expiry time.Duration) (string, error)
VAPIDAuthorization returns the Authorization header value "vapid t=<jwt>, k=<public key>" (RFC 8292 section 3) for endpoint.
expiry 0 means 12h; anything above 24h is capped at 24h because push services reject longer-lived tokens. subject is the contact the push service may use to reach the operator and must be a mailto: or https: URI.
type Message ¶
type Message struct {
Payload []byte
// TTL is how long the push service should hold the message for an
// offline device. 0 means 24h. Sub-second precision is truncated.
TTL time.Duration
// Urgency is "", "very-low", "low", "normal" or "high" (RFC 8030 5.3).
Urgency string
// Topic, when set, lets a newer message replace an undelivered older one
// with the same topic (RFC 8030 5.4): at most 32 base64url characters.
Topic string
}
Message is one push to deliver.
type Sender ¶
type Sender struct {
Keys *Keys
Subject string // VAPID "sub": mailto: or https: contact for the operator.
// HTTP is the client used for delivery. nil selects a built-in client
// with a 30s timeout that refuses non-public addresses and never follows
// redirects. A caller-supplied client is used as is, so it carries the
// caller's own SSRF and redirect policy.
HTTP *http.Client
// AllowInsecure permits http:// endpoints and, when HTTP is nil, skips
// the public-address dial check. It exists for tests against
// httptest.Server and must never be set in production.
AllowInsecure bool
Now func() time.Time
}
Sender delivers Web Push messages. The zero value is not usable: Keys and Subject are required.
func (*Sender) Send ¶
Send encrypts msg for sub and POSTs it to the subscription's endpoint. It returns nil on any 2xx (push services answer 201 Created).
Errors are typed for retry decisions: *GoneError (delete the subscription), *StatusError (see Permanent and RetryAfter), or a wrapped transport error, which is always transient.
func (*Sender) ValidateSubscription ¶
func (s *Sender) ValidateSubscription(sub Subscription) error
ValidateSubscription is Subscription.Validate under this sender's own scheme policy, so a caller accepting subscriptions (the daemon's POST handler) refuses exactly what Send would later refuse.
type StatusError ¶
type StatusError struct {
Host string
Status int
Body string // first 512 bytes of the response body
RetryAfter time.Duration // from Retry-After, 0 if absent or unparseable
Permanent bool
}
StatusError is any other non-2xx response. Permanent separates "this request will never succeed as sent" (bad payload, bad VAPID, too large) from "try again later" (rate limiting, push-service outage).
func (*StatusError) Error ¶
func (e *StatusError) Error() string
type Subscription ¶
type Subscription struct {
Endpoint string
// P256dh is the user agent's uncompressed P-256 public key (65 bytes),
// base64url. Padded or standard-alphabet spellings are accepted too.
P256dh string
// Auth is the 16-byte authentication secret, base64url.
Auth string
}
Subscription is the browser's PushSubscription, as delivered by PushSubscription.toJSON(): the push-service endpoint plus the user agent's public key and auth secret.
func (Subscription) Validate ¶
func (s Subscription) Validate() error
Validate reports whether the subscription is usable: an absolute https endpoint with a host and no userinfo, and keys of the right shape with p256dh on the curve. It is meant to run when a subscription is first stored, so a bad one is rejected at the API boundary rather than failing every delivery later.