webpush

package module
v2.0.0 Latest Latest
Warning

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

Go to latest
Published: Jan 16, 2025 License: MIT Imports: 25 Imported by: 0

README

webpush-go

GoDoc

Web Push API Encryption with VAPID support.

This library is a fork of SherClockHolmes/webpush-go. See CHANGELOG.md for details on migrating from the upstream library.

go get -u github.com/ergochat/webpush-go/v2

Example

For a full example, refer to the code in the example directory.

package main

import (
	"encoding/json"

	webpush "github.com/ergochat/webpush-go/v2"
)

func main() {
	// Decode subscription
	s := &webpush.Subscription{}
	json.Unmarshal([]byte("<YOUR_SUBSCRIPTION>"), s)
	vapidKeys := new(webpush.VAPIDKeys)
	json.Unmarshal([]byte("<YOUR_VAPID_KEYS">), vapidKeys)

	// Send Notification
	resp, err := webpush.SendNotification([]byte("Test"), s, &webpush.Options{
		Subscriber:      "example@example.com",
		VAPIDKeys:       vapidKeys,
		TTL:             3600, // seconds
	})
	if err != nil {
		// TODO: Handle error
	}
	defer resp.Body.Close()
}
Generating VAPID Keys

Use the helper method GenerateVAPIDKeys to generate the VAPID key pair.

vapidKeys, err := webpush.GenerateVAPIDKeys()
if err != nil {
	// TODO: Handle error
}

Development

  1. Install Go 1.20+
  2. go mod vendor
  3. go test
For other language implementations visit:

WebPush Libs

Documentation

Index

Constants

View Source
const MaxRecordSize uint32 = 4096

Variables

View Source
var (
	ErrRecordSizeTooSmall = errors.New("record size too small for message")
)

Functions

func EncryptNotification

func EncryptNotification(message []byte, keys Keys, recordSize uint32) ([]byte, error)

EncryptNotification implements the encryption algorithm specified by RFC 8291 for web push (RFC 8188's aes128gcm content-encoding, with the key material derived from elliptic curve Diffie-Hellman over the P-256 curve).

func SendNotification

func SendNotification(ctx context.Context, message []byte, s *Subscription, options *Options) (*http.Response, error)

SendNotification sends a push notification to a subscription's endpoint, applying encryption (RFC 8291) and adding a VAPID header (RFC 8292).

Types

type HTTPClient

type HTTPClient interface {
	Do(*http.Request) (*http.Response, error)
}

HTTPClient is an interface for sending the notification HTTP request / testing

type Keys

type Keys struct {
	Auth   [16]byte
	P256dh *ecdh.PublicKey
}

Keys represents a subscription's keys (its ECDH public key on the P-256 curve and its 16-byte authentication secret).

func DecodeSubscriptionKeys

func DecodeSubscriptionKeys(auth, p256dh string) (keys Keys, err error)

DecodeSubscriptionKeys decodes and validates a base64-encoded pair of subscription keys (the authentication secret and ECDH public key).

func (*Keys) Equal

func (k *Keys) Equal(o Keys) bool

Equal compares two Keys for equality.

func (*Keys) MarshalJSON

func (k *Keys) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler, allowing serialization to JSON.

func (*Keys) UnmarshalJSON

func (k *Keys) UnmarshalJSON(b []byte) (err error)

MarshalJSON implements json.Unmarshaler, allowing deserialization from JSON.

type Options

type Options struct {
	HTTPClient      HTTPClient // Will replace with *http.Client by default if not included
	RecordSize      uint32     // Limit the record size
	Subscriber      string     // Sub in VAPID JWT token
	Topic           string     // Set the Topic header to collapse a pending messages (Optional)
	TTL             int        // Set the TTL on the endpoint POST request, in seconds
	Urgency         Urgency    // Set the Urgency header to change a message priority (Optional)
	VAPIDKeys       *VAPIDKeys // VAPID public-private keypair to generate the VAPID Authorization header
	VapidExpiration time.Time  // optional expiration for VAPID JWT token (defaults to now + 12 hours)
}

Options are config and extra params needed to send a notification

type Subscription

type Subscription struct {
	Endpoint string `json:"endpoint"`
	Keys     Keys   `json:"keys"`
}

Subscription represents a PushSubscription object from the Push API

type Urgency

type Urgency string

Urgency indicates to the push service how important a message is to the user. This can be used by the push service to help conserve the battery life of a user's device by only waking up for important messages when battery is low.

const (
	// UrgencyVeryLow requires device state: on power and Wi-Fi
	UrgencyVeryLow Urgency = "very-low"
	// UrgencyLow requires device state: on either power or Wi-Fi
	UrgencyLow Urgency = "low"
	// UrgencyNormal excludes device state: low battery
	UrgencyNormal Urgency = "normal"
	// UrgencyHigh admits device state: low battery
	UrgencyHigh Urgency = "high"
)

type VAPIDKeys

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

VAPIDKeys is a public-private keypair for use in VAPID. It marshals to a JSON string containing the PEM of the PKCS8 of the private key.

func DecodeLegacyVAPIDPrivateKey

func DecodeLegacyVAPIDPrivateKey(key string) (*VAPIDKeys, error)

DecodeLegacyVAPIDPrivateKey decodes the legacy string private key format returned by GenerateVAPIDKeys in v1.

func ECDSAToVAPIDKeys

func ECDSAToVAPIDKeys(privKey *ecdsa.PrivateKey) (result *VAPIDKeys, err error)

ECDSAToVAPIDKeys wraps an existing ecdsa.PrivateKey in VAPIDKeys for use in VAPID header signing.

func GenerateVAPIDKeys

func GenerateVAPIDKeys() (result *VAPIDKeys, err error)

GenerateVAPIDKeys generates a VAPID keypair (an ECDSA keypair on the P-256 curve).

func (*VAPIDKeys) Equal

func (v *VAPIDKeys) Equal(o *VAPIDKeys) bool

Equal compares two VAPIDKeys for equality.

func (*VAPIDKeys) MarshalJSON

func (v *VAPIDKeys) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler, allowing serialization to JSON.

func (*VAPIDKeys) PrivateKey

func (v *VAPIDKeys) PrivateKey() *ecdsa.PrivateKey

PrivateKey returns the private key of the keypair.

func (*VAPIDKeys) PublicKeyString

func (v *VAPIDKeys) PublicKeyString() string

PublicKeyString returns the base64url-encoded uncompressed public key of the keypair, as defined in RFC8292.

func (*VAPIDKeys) UnmarshalJSON

func (v *VAPIDKeys) UnmarshalJSON(b []byte) error

MarshalJSON implements json.Unmarshaler, allowing deserialization from JSON.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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