webpush

package
v1.1.0 Latest Latest
Warning

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

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

Documentation

Overview

Package webpush speaks the Web Push protocol with the standard library only (design expansion phase 8, X22):

  • RFC 8030, the generic event delivery: a POST to the subscription's push resource with TTL, Urgency and Topic, answered 201 Created;
  • RFC 8292, VAPID: an ES256 JWT that identifies the workspace to the push services, carried in "Authorization: vapid t=…, k=…";
  • RFC 8291 with RFC 8188's aes128gcm content coding: the payload is encrypted for the browser with a fresh ECDH key and a random salt.

It knows nothing about workspaces, sites or campaigns (internal/push does that). The encryption is checked against RFC 8291's Appendix A and RFC 8188's example; webpushtest is an in-process push service that verifies the JWT and decrypts what it receives, for tests and the demo.

Index

Constants

View Source
const (
	// RecordSize is the record size written in the header. Push services
	// accept 4096-byte bodies (RFC 8030 §7.2), so one record carries the
	// whole message.
	RecordSize = 4096

	// MaxPayload is the most plaintext one message carries.
	MaxPayload = RecordSize - headerLen - tagLen - 1
)
View Source
const MaxTTL = 28 * 24 * time.Hour

MaxTTL is the longest time push services keep a message (FCM's limit, the shortest of the major services).

View Source
const MaxTokenLifetime = 24 * time.Hour

MaxTokenLifetime is RFC 8292's limit on "exp": at most 24 hours from the time of the request.

View Source
const TokenLifetime = 12 * time.Hour

TokenLifetime is what ReputeCast signs for. Tokens are reused for an hour per push service, so a token is always well inside the limit.

Variables

View Source
var (
	ErrTooLarge = fmt.Errorf("webpush: the payload is over %d bytes", MaxPayload)
	ErrBody     = errors.New("webpush: the body isn't aes128gcm content")
)

Errors from encrypting and decrypting.

View Source
var (
	ErrAuthorization = errors.New("webpush: not a vapid authorization")
	ErrSignature     = errors.New("webpush: the token's signature doesn't verify")
	ErrClaims        = errors.New("webpush: the token's claims are invalid")
)

Errors from verifying a token.

View Source
var (
	ErrEndpoint = errors.New("webpush: the endpoint isn't an https URL")
	ErrKeys     = errors.New("webpush: the subscription's keys are malformed")
)

Errors from ParseSubscription.

Functions

func Decode

func Decode(s string) ([]byte, error)

Decode reads base64url with or without padding (browsers send both).

func Decrypt

func Decrypt(ua *ecdh.PrivateKey, authSecret, body []byte) ([]byte, error)

Decrypt reads a Web Push message as the browser does, with the subscription's private key and authentication secret. The in-process push service uses it to check what it receives.

func Encode

func Encode(b []byte) string

Encode writes bytes as unpadded base64url.

func Encrypt

func Encrypt(sub Subscription, plaintext []byte) ([]byte, error)

Encrypt encrypts plaintext for a subscription with a fresh key pair and salt. The result is the request body, sent with Content-Encoding: aes128gcm.

func Origin

func Origin(endpoint string) (string, error)

Origin is the push service's origin, the JWT's audience: the scheme and host of the endpoint ("https://fcm.googleapis.com").

func ParseAuthorization

func ParseAuthorization(h string) (token string, key []byte, err error)

ParseAuthorization splits "vapid t=…, k=…" into the token and the key.

func TopicFor

func TopicFor(tag string) string

TopicFor turns a notification tag into a Topic header value: at most 32 characters of the base64url alphabet (RFC 8030 §5.4).

Types

type Claims

type Claims struct {
	Aud string `json:"aud"`
	Exp int64  `json:"exp"`
	Sub string `json:"sub,omitempty"`
}

Claims are a VAPID token's claims: the push service's origin, the expiry and the contact address ("mailto:support@acme.io").

func Verify

func Verify(header, aud string, now time.Time) (Claims, []byte, error)

Verify checks a request's Authorization header as a push service does: the signature, the audience and an expiry in the future and at most 24 hours away. It returns the claims and the signing key.

func VerifyToken

func VerifyToken(token string, pub []byte) (Claims, error)

VerifyToken checks an ES256 JWT against an uncompressed P-256 public key and returns its claims. It checks the signature only; Verify checks the audience and the expiry too.

type Message

type Message struct {
	// Payload is the plaintext; Send encrypts it.
	Payload []byte
	// TTL is how long the push service keeps the message while the
	// browser is offline. After that it's dropped.
	TTL time.Duration
	// Urgency is normal when empty.
	Urgency Urgency
	// Topic replaces an undelivered message with the same topic (see
	// TopicFor).
	Topic string
}

Message is one push message to one subscription.

type Outcome

type Outcome string

Outcome is what a push service did with a message.

const (
	// Accepted: 201 Created, the push service will deliver it.
	Accepted Outcome = "accepted"
	// Gone: 404 or 410, the subscription ended (the browser unsubscribed
	// or the push service expired it). Remove it.
	Gone Outcome = "gone"
	// TooLarge: 413, the payload is over the push service's limit.
	TooLarge Outcome = "too_large"
	// RateLimited: 429, retry after RetryAfter.
	RateLimited Outcome = "rate_limited"
	// Rejected: 400, 401 or 403. The request or the key was refused; a
	// 403 usually means the subscription was made with other keys.
	Rejected Outcome = "rejected"
	// Unavailable: a 5xx answer or no answer at all. Retry later.
	Unavailable Outcome = "unavailable"
)

Outcomes.

type Result

type Result struct {
	Outcome Outcome
	// Status is the HTTP status, 0 when nothing answered.
	Status int
	// RetryAfter is the push service's Retry-After, for 429 and 503.
	RetryAfter time.Duration
	// Location is the message resource of an accepted message.
	Location string
	// Detail is the start of the push service's explanation, for the
	// Events tab ("410 Gone · push subscription has unsubscribed or
	// expired").
	Detail string
}

Result is a push service's answer.

func Classify

func Classify(resp *http.Response) Result

Classify reads a push service's answer.

func (Result) Retryable

func (r Result) Retryable() bool

Retryable reports whether sending again later may work.

type Sender

type Sender struct {
	Key *VAPIDKey
	// Contact is the "sub" claim: "mailto:support@acme.io".
	Contact string
	// HTTP is the client push services are called with (the SSRF-guarded
	// client in production, the in-process push service in tests and the
	// demo).
	HTTP *http.Client
	Now  func() time.Time
	// contains filtered or unexported fields
}

Sender sends messages signed with one workspace's VAPID key.

func (*Sender) Request

func (s *Sender) Request(ctx context.Context, sub Subscription, m Message) (*http.Request, error)

Request builds the push request for a message: encrypted, signed, with its TTL, urgency and topic.

func (*Sender) Send

func (s *Sender) Send(ctx context.Context, sub Subscription, m Message) (Result, error)

Send delivers a message to the subscription's push service and says what it did. A network failure is an Unavailable result, not an error; the error is for a request that can't be built (bad keys, a payload too large).

type Subscription

type Subscription struct {
	// Endpoint is the push resource URL (https://fcm.googleapis.com/…).
	Endpoint string
	// P256dh is the browser's ECDH public key, 65 bytes uncompressed.
	P256dh []byte
	// Auth is the 16-byte authentication secret.
	Auth []byte
}

Subscription is what a browser's PushManager.subscribe() returns: the push resource and the keys the payload is encrypted for.

func ParseSubscription

func ParseSubscription(endpoint, p256dh, auth string) (Subscription, error)

ParseSubscription checks a subscription as a browser sent it: an https endpoint, a P-256 public key and a 16-byte secret.

type Urgency

type Urgency string

Urgency is a message's urgency (RFC 8030 §5.3): push services and browsers deliver low-urgency messages when it suits the battery.

const (
	UrgencyVeryLow Urgency = "very-low"
	UrgencyLow     Urgency = "low"
	UrgencyNormal  Urgency = "normal"
	UrgencyHigh    Urgency = "high"
)

Urgencies.

type VAPIDKey

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

VAPIDKey is the key pair that identifies a workspace to the browsers' push services (RFC 8292): an ECDSA P-256 key. The public key is the applicationServerKey the browser subscribes with; the private key never leaves the server (internal/push seals it at rest).

func GenerateVAPIDKey

func GenerateVAPIDKey() (*VAPIDKey, error)

GenerateVAPIDKey makes a new key pair.

func ParseVAPIDKey

func ParseVAPIDKey(raw []byte) (*VAPIDKey, error)

ParseVAPIDKey reads a private key stored as its 32-byte scalar.

func (*VAPIDKey) Authorization

func (k *VAPIDKey) Authorization(aud, sub string, exp time.Time) (string, error)

Authorization is the header value of a push request: "vapid t=<JWT>, k=<public key>".

func (*VAPIDKey) PrivateBytes

func (k *VAPIDKey) PrivateBytes() []byte

PrivateBytes is the private scalar, 32 bytes, for sealing at rest.

func (*VAPIDKey) PublicKey

func (k *VAPIDKey) PublicKey() []byte

PublicKey is the uncompressed P-256 point, 65 bytes (0x04 || X || Y).

func (*VAPIDKey) PublicKeyString

func (k *VAPIDKey) PublicKeyString() string

PublicKeyString is the public key in base64url, as browsers take it for applicationServerKey and as the "k" parameter carries it.

func (*VAPIDKey) Token

func (k *VAPIDKey) Token(aud, sub string, exp time.Time) (string, error)

Token signs a VAPID JWT for the push service at aud.

Directories

Path Synopsis
Package webpushtest is an in-process push service for tests and the demo: it answers the requests FCM, Mozilla's autopush, Apple and Windows would get, checks the VAPID token as they do, decrypts the payload when it made the subscription, and records every message.
Package webpushtest is an in-process push service for tests and the demo: it answers the requests FCM, Mozilla's autopush, Apple and Windows would get, checks the VAPID token as they do, decrypts the payload when it made the subscription, and records every message.

Jump to

Keyboard shortcuts

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