pax_global_header00006660000000000000000000000064147707253130014523gustar00rootroot0000000000000052 comment=780767cdc86abd7db317804951fc70e61ec6353c golang-github-sherclockholmes-webpush-go-1.4.0/000077500000000000000000000000001477072531300215155ustar00rootroot00000000000000golang-github-sherclockholmes-webpush-go-1.4.0/.github/000077500000000000000000000000001477072531300230555ustar00rootroot00000000000000golang-github-sherclockholmes-webpush-go-1.4.0/.github/dependabot.yml000066400000000000000000000002221477072531300257010ustar00rootroot00000000000000version: 2 updates: - package-ecosystem: gomod directory: "/" schedule: interval: weekly time: "13:00" open-pull-requests-limit: 10 golang-github-sherclockholmes-webpush-go-1.4.0/.gitignore000066400000000000000000000000331477072531300235010ustar00rootroot00000000000000vendor/** .DS_Store *.out golang-github-sherclockholmes-webpush-go-1.4.0/LICENSE000066400000000000000000000020551477072531300225240ustar00rootroot00000000000000MIT License Copyright (c) 2016 Ethan Holmes Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. golang-github-sherclockholmes-webpush-go-1.4.0/README.md000066400000000000000000000026721477072531300230030ustar00rootroot00000000000000# webpush-go [![Go Report Card](https://goreportcard.com/badge/github.com/SherClockHolmes/webpush-go)](https://goreportcard.com/report/github.com/SherClockHolmes/webpush-go) [![GoDoc](https://godoc.org/github.com/SherClockHolmes/webpush-go?status.svg)](https://godoc.org/github.com/SherClockHolmes/webpush-go) Web Push API Encryption with VAPID support. ```bash go get -u github.com/SherClockHolmes/webpush-go ``` ## Example For a full example, refer to the code in the [example](example/) directory. ```go package main import ( "encoding/json" webpush "github.com/SherClockHolmes/webpush-go" ) func main() { // Decode subscription s := &webpush.Subscription{} json.Unmarshal([]byte(""), s) // Send Notification resp, err := webpush.SendNotification([]byte("Test"), s, &webpush.Options{ Subscriber: "example@example.com", VAPIDPublicKey: "", VAPIDPrivateKey: "", TTL: 30, }) if err != nil { // TODO: Handle error } defer resp.Body.Close() } ``` ### Generating VAPID Keys Use the helper method `GenerateVAPIDKeys` to generate the VAPID key pair. ```golang privateKey, publicKey, err := webpush.GenerateVAPIDKeys() if err != nil { // TODO: Handle error } ``` ## Development 1. Install [Go 1.11+](https://golang.org/) 2. `go mod vendor` 3. `go test` #### For other language implementations visit: [WebPush Libs](https://github.com/web-push-libs) golang-github-sherclockholmes-webpush-go-1.4.0/example/000077500000000000000000000000001477072531300231505ustar00rootroot00000000000000golang-github-sherclockholmes-webpush-go-1.4.0/example/README.md000066400000000000000000000006231477072531300244300ustar00rootroot00000000000000# example ## Access index.html Replace the public VAPID key in index.html. Use a tool such as SimpleHTTPServer to run a web server: ``` python3 -m http.server 8000 ``` Go to `http://localhost:8000` and copy the logged subsciption from the console. ## Test send a notification Replace the public/private VAPID keys. Use the subscription you had from the first section. ```bash go run main.go ``` golang-github-sherclockholmes-webpush-go-1.4.0/example/index.html000066400000000000000000000031071477072531300251460ustar00rootroot00000000000000 Webpush Golang Example golang-github-sherclockholmes-webpush-go-1.4.0/example/main.go000066400000000000000000000011511477072531300244210ustar00rootroot00000000000000package main import ( "encoding/json" webpush "github.com/SherClockHolmes/webpush-go" ) const ( subscription = `` vapidPublicKey = "" vapidPrivateKey = "" ) func main() { // Decode subscription s := &webpush.Subscription{} json.Unmarshal([]byte(subscription), s) // Send Notification resp, err := webpush.SendNotification([]byte("Test"), s, &webpush.Options{ Subscriber: "example@example.com", // Do not include "mailto:" VAPIDPublicKey: vapidPublicKey, VAPIDPrivateKey: vapidPrivateKey, TTL: 30, }) if err != nil { // TODO: Handle error } defer resp.Body.Close() } golang-github-sherclockholmes-webpush-go-1.4.0/example/service-worker.js000066400000000000000000000005141477072531300264550ustar00rootroot00000000000000self.addEventListener('push', event => { console.log('[Service Worker] Push Received.'); console.log(`[Service Worker] Push had this data: "${event.data.text()}"`); const title = 'Test Webpush'; const options = { body: event.data.text(), }; event.waitUntil(self.registration.showNotification(title, options)); }); golang-github-sherclockholmes-webpush-go-1.4.0/go.mod000066400000000000000000000002051477072531300226200ustar00rootroot00000000000000module github.com/SherClockHolmes/webpush-go require ( github.com/golang-jwt/jwt/v5 v5.2.1 golang.org/x/crypto v0.31.0 ) go 1.13 golang-github-sherclockholmes-webpush-go-1.4.0/go.sum000066400000000000000000000135371477072531300226610ustar00rootroot00000000000000github.com/golang-jwt/jwt/v5 v5.2.1 h1:OuVbFODueb089Lh128TAcimifWaLhJwVflnrgM17wHk= github.com/golang-jwt/jwt/v5 v5.2.1/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk= github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliYc= golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU= golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8= golang.org/x/crypto v0.31.0 h1:ihbySMvVjLAeSH1IbfcRTkD/iNscyz8rGzjF/E5hV6U= golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= golang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= golang.org/x/mod v0.15.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= golang.org/x/net v0.15.0/go.mod h1:idbUs1IY1+zTqbi8yxTbhexhEEk5ur9LInksu6HrEpk= golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44= golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.3.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y= golang.org/x/sync v0.6.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/telemetry v0.0.0-20240228155512-f48c80bd79b2/go.mod h1:TeRTkGYfJXctD9OcfyVLyj2J3IxLnKwHJR8f4D8a3YE= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo= golang.org/x/term v0.12.0/go.mod h1:owVbMEjm3cBLCHdkQu9b1opXd4ETQWc3BhuQGKgXgvU= golang.org/x/term v0.17.0/go.mod h1:lLRBjIVuehSbZlaOtGMbcMncT+aqLLLmKrsjNrUguwk= golang.org/x/term v0.20.0/go.mod h1:8UkIAJTvZgivsXaD6/pH6U9ecQzZ45awqEOzuCvwpFY= golang.org/x/term v0.27.0/go.mod h1:iMsnZpn0cago0GOrHO2+Y7u7JPn5AylBrcoWkElMTSM= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= golang.org/x/tools v0.13.0/go.mod h1:HvlwmtVNQAhOuCjW7xxvovg8wbNq7LwfXh/k7wXUl58= golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang-github-sherclockholmes-webpush-go-1.4.0/urgency.go000066400000000000000000000015241477072531300235220ustar00rootroot00000000000000package webpush // 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. type Urgency string 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" ) // Checking allowable values for the urgency header func isValidUrgency(urgency Urgency) bool { switch urgency { case UrgencyVeryLow, UrgencyLow, UrgencyNormal, UrgencyHigh: return true } return false } golang-github-sherclockholmes-webpush-go-1.4.0/vapid.go000066400000000000000000000050641477072531300231540ustar00rootroot00000000000000package webpush import ( "crypto/ecdsa" "crypto/elliptic" "crypto/rand" "encoding/base64" "math/big" "net/url" "strings" "time" "github.com/golang-jwt/jwt/v5" ) // GenerateVAPIDKeys will create a private and public VAPID key pair func GenerateVAPIDKeys() (privateKey, publicKey string, err error) { // Get the private key from the P256 curve curve := elliptic.P256() private, x, y, err := elliptic.GenerateKey(curve, rand.Reader) if err != nil { return } public := elliptic.Marshal(curve, x, y) // Convert to base64 publicKey = base64.RawURLEncoding.EncodeToString(public) privateKey = base64.RawURLEncoding.EncodeToString(private) return } // Generates the ECDSA public and private keys for the JWT encryption func generateVAPIDHeaderKeys(privateKey []byte) *ecdsa.PrivateKey { // Public key curve := elliptic.P256() px, py := curve.ScalarMult( curve.Params().Gx, curve.Params().Gy, privateKey, ) pubKey := ecdsa.PublicKey{ Curve: curve, X: px, Y: py, } // Private key d := &big.Int{} d.SetBytes(privateKey) return &ecdsa.PrivateKey{ PublicKey: pubKey, D: d, } } // getVAPIDAuthorizationHeader func getVAPIDAuthorizationHeader( endpoint, subscriber, vapidPublicKey, vapidPrivateKey string, expiration time.Time, ) (string, error) { // Create the JWT token subURL, err := url.Parse(endpoint) if err != nil { return "", err } // Unless subscriber is an HTTPS URL, assume an e-mail address if !strings.HasPrefix(subscriber, "https:") { subscriber = "mailto:" + subscriber } token := jwt.NewWithClaims(jwt.SigningMethodES256, jwt.MapClaims{ "aud": subURL.Scheme + "://" + subURL.Host, "exp": time.Now().Add(time.Hour * 12).Unix(), "sub": subscriber, }) // Decode the VAPID private key decodedVapidPrivateKey, err := decodeVapidKey(vapidPrivateKey) if err != nil { return "", err } privKey := generateVAPIDHeaderKeys(decodedVapidPrivateKey) // Sign token with private key jwtString, err := token.SignedString(privKey) if err != nil { return "", err } // Decode the VAPID public key pubKey, err := decodeVapidKey(vapidPublicKey) if err != nil { return "", err } return "vapid t=" + jwtString + ", k=" + base64.RawURLEncoding.EncodeToString(pubKey), nil } // Need to decode the vapid private key in multiple base64 formats // Solution from: https://github.com/SherClockHolmes/webpush-go/issues/29 func decodeVapidKey(key string) ([]byte, error) { bytes, err := base64.URLEncoding.DecodeString(key) if err == nil { return bytes, nil } return base64.RawURLEncoding.DecodeString(key) } golang-github-sherclockholmes-webpush-go-1.4.0/vapid_test.go000066400000000000000000000043611477072531300242120ustar00rootroot00000000000000package webpush import ( "encoding/base64" "fmt" "strings" "testing" "time" "github.com/golang-jwt/jwt/v5" ) func TestVAPID(t *testing.T) { s := getStandardEncodedTestSubscription() sub := "test@test.com" // Generate vapid keys vapidPrivateKey, vapidPublicKey, err := GenerateVAPIDKeys() if err != nil { t.Fatal(err) } // Get authentication header vapidAuthHeader, err := getVAPIDAuthorizationHeader( s.Endpoint, sub, vapidPublicKey, vapidPrivateKey, time.Now().Add(time.Hour*12), ) if err != nil { t.Fatal(err) } // Validate the token in the Authorization header tokenString := getTokenFromAuthorizationHeader(vapidAuthHeader, t) token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) { if _, ok := token.Method.(*jwt.SigningMethodECDSA); !ok { t.Fatal("Wrong validation method need ECDSA!") } // To decode the token it needs the VAPID public key b64 := base64.RawURLEncoding decodedVapidPrivateKey, err := b64.DecodeString(vapidPrivateKey) if err != nil { t.Fatal("Could not decode VAPID private key") } privKey := generateVAPIDHeaderKeys(decodedVapidPrivateKey) return privKey.Public(), nil }) // Check the claims on the token if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid { expectedSub := fmt.Sprintf("mailto:%s", sub) if expectedSub != claims["sub"] { t.Fatalf( "Incorreect mailto, expected=%s, got=%s", expectedSub, claims["sub"], ) } if claims["aud"] == "" { t.Fatal("Audience should not be empty") } } else { t.Fatal(err) } } func TestVAPIDKeys(t *testing.T) { privateKey, publicKey, err := GenerateVAPIDKeys() if err != nil { t.Fatal(err) } if len(privateKey) != 43 { t.Fatal("Generated incorrect VAPID private key") } if len(publicKey) != 87 { t.Fatal("Generated incorrect VAPID public key") } } // Helper function for extracting the token from the Authorization header func getTokenFromAuthorizationHeader(tokenHeader string, t *testing.T) string { hsplit := strings.Split(tokenHeader, " ") if len(hsplit) < 3 { t.Fatal("Failed to auth split header") } tsplit := strings.Split(hsplit[1], "=") if len(tsplit) < 2 { t.Fatal("Failed to t split header on =") } return tsplit[1][:len(tsplit[1])-1] } golang-github-sherclockholmes-webpush-go-1.4.0/webpush.go000066400000000000000000000164271477072531300235330ustar00rootroot00000000000000package webpush import ( "bytes" "context" "crypto/aes" "crypto/cipher" "crypto/elliptic" "crypto/rand" "crypto/sha256" "encoding/base64" "encoding/binary" "errors" "io" "net/http" "strconv" "strings" "time" "golang.org/x/crypto/hkdf" ) const MaxRecordSize uint32 = 4096 var ErrMaxPadExceeded = errors.New("payload has exceeded the maximum length") // saltFunc generates a salt of 16 bytes var saltFunc = func() ([]byte, error) { salt := make([]byte, 16) _, err := io.ReadFull(rand.Reader, salt) if err != nil { return salt, err } return salt, nil } // HTTPClient is an interface for sending the notification HTTP request / testing type HTTPClient interface { Do(*http.Request) (*http.Response, error) } // Options are config and extra params needed to send a notification 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 Urgency Urgency // Set the Urgency header to change a message priority (Optional) VAPIDPublicKey string // VAPID public key, passed in VAPID Authorization header VAPIDPrivateKey string // VAPID private key, used to sign VAPID JWT token VapidExpiration time.Time // optional expiration for VAPID JWT token (defaults to now + 12 hours) } // Keys are the base64 encoded values from PushSubscription.getKey() type Keys struct { Auth string `json:"auth"` P256dh string `json:"p256dh"` } // Subscription represents a PushSubscription object from the Push API type Subscription struct { Endpoint string `json:"endpoint"` Keys Keys `json:"keys"` } // SendNotification calls SendNotificationWithContext with default context for backwards-compatibility func SendNotification(message []byte, s *Subscription, options *Options) (*http.Response, error) { return SendNotificationWithContext(context.Background(), message, s, options) } // SendNotificationWithContext sends a push notification to a subscription's endpoint // Message Encryption for Web Push, and VAPID protocols. // FOR MORE INFORMATION SEE RFC8291: https://datatracker.ietf.org/doc/rfc8291 func SendNotificationWithContext(ctx context.Context, message []byte, s *Subscription, options *Options) (*http.Response, error) { // Authentication secret (auth_secret) authSecret, err := decodeSubscriptionKey(s.Keys.Auth) if err != nil { return nil, err } // dh (Diffie Hellman) dh, err := decodeSubscriptionKey(s.Keys.P256dh) if err != nil { return nil, err } // Generate 16 byte salt salt, err := saltFunc() if err != nil { return nil, err } // Create the ecdh_secret shared key pair curve := elliptic.P256() // Application server key pairs (single use) localPrivateKey, x, y, err := elliptic.GenerateKey(curve, rand.Reader) if err != nil { return nil, err } localPublicKey := elliptic.Marshal(curve, x, y) // Combine application keys with receiver's EC public key sharedX, sharedY := elliptic.Unmarshal(curve, dh) if sharedX == nil { return nil, errors.New("Unmarshal Error: Public key is not a valid point on the curve") } // Derive ECDH shared secret sx, sy := curve.ScalarMult(sharedX, sharedY, localPrivateKey) if !curve.IsOnCurve(sx, sy) { return nil, errors.New("Encryption error: ECDH shared secret isn't on curve") } mlen := curve.Params().BitSize / 8 sharedECDHSecret := make([]byte, mlen) sx.FillBytes(sharedECDHSecret) hash := sha256.New // ikm prkInfoBuf := bytes.NewBuffer([]byte("WebPush: info\x00")) prkInfoBuf.Write(dh) prkInfoBuf.Write(localPublicKey) prkHKDF := hkdf.New(hash, sharedECDHSecret, authSecret, prkInfoBuf.Bytes()) ikm, err := getHKDFKey(prkHKDF, 32) if err != nil { return nil, err } // Derive Content Encryption Key contentEncryptionKeyInfo := []byte("Content-Encoding: aes128gcm\x00") contentHKDF := hkdf.New(hash, ikm, salt, contentEncryptionKeyInfo) contentEncryptionKey, err := getHKDFKey(contentHKDF, 16) if err != nil { return nil, err } // Derive the Nonce nonceInfo := []byte("Content-Encoding: nonce\x00") nonceHKDF := hkdf.New(hash, ikm, salt, nonceInfo) nonce, err := getHKDFKey(nonceHKDF, 12) if err != nil { return nil, err } // Cipher c, err := aes.NewCipher(contentEncryptionKey) if err != nil { return nil, err } gcm, err := cipher.NewGCM(c) if err != nil { return nil, err } // Get the record size recordSize := options.RecordSize if recordSize == 0 { recordSize = MaxRecordSize } recordLength := int(recordSize) - 16 // Encryption Content-Coding Header recordBuf := bytes.NewBuffer(salt) rs := make([]byte, 4) binary.BigEndian.PutUint32(rs, recordSize) recordBuf.Write(rs) recordBuf.Write([]byte{byte(len(localPublicKey))}) recordBuf.Write(localPublicKey) // Data dataBuf := bytes.NewBuffer(message) // Pad content to max record size - 16 - header // Padding ending delimeter dataBuf.Write([]byte("\x02")) if err := pad(dataBuf, recordLength-recordBuf.Len()); err != nil { return nil, err } // Compose the ciphertext ciphertext := gcm.Seal([]byte{}, nonce, dataBuf.Bytes(), nil) recordBuf.Write(ciphertext) // POST request req, err := http.NewRequest("POST", s.Endpoint, recordBuf) if err != nil { return nil, err } if ctx != nil { req = req.WithContext(ctx) } req.Header.Set("Content-Encoding", "aes128gcm") req.Header.Set("Content-Type", "application/octet-stream") req.Header.Set("TTL", strconv.Itoa(options.TTL)) // Сheck the optional headers if len(options.Topic) > 0 { req.Header.Set("Topic", options.Topic) } if isValidUrgency(options.Urgency) { req.Header.Set("Urgency", string(options.Urgency)) } expiration := options.VapidExpiration if expiration.IsZero() { expiration = time.Now().Add(time.Hour * 12) } // Get VAPID Authorization header vapidAuthHeader, err := getVAPIDAuthorizationHeader( s.Endpoint, options.Subscriber, options.VAPIDPublicKey, options.VAPIDPrivateKey, expiration, ) if err != nil { return nil, err } req.Header.Set("Authorization", vapidAuthHeader) // Send the request var client HTTPClient if options.HTTPClient != nil { client = options.HTTPClient } else { client = &http.Client{} } return client.Do(req) } // decodeSubscriptionKey decodes a base64 subscription key. // if necessary, add "=" padding to the key for URL decode func decodeSubscriptionKey(key string) ([]byte, error) { // "=" padding buf := bytes.NewBufferString(key) if rem := len(key) % 4; rem != 0 { buf.WriteString(strings.Repeat("=", 4-rem)) } bytes, err := base64.StdEncoding.DecodeString(buf.String()) if err == nil { return bytes, nil } return base64.URLEncoding.DecodeString(buf.String()) } // Returns a key of length "length" given an hkdf function func getHKDFKey(hkdf io.Reader, length int) ([]byte, error) { key := make([]byte, length) n, err := io.ReadFull(hkdf, key) if n != len(key) || err != nil { return key, err } return key, nil } func pad(payload *bytes.Buffer, maxPadLen int) error { payloadLen := payload.Len() if payloadLen > maxPadLen { return ErrMaxPadExceeded } padLen := maxPadLen - payloadLen padding := make([]byte, padLen) payload.Write(padding) return nil } golang-github-sherclockholmes-webpush-go-1.4.0/webpush_test.go000066400000000000000000000045421477072531300245650ustar00rootroot00000000000000package webpush import ( "net/http" "strings" "testing" ) type testHTTPClient struct{} func (*testHTTPClient) Do(*http.Request) (*http.Response, error) { return &http.Response{StatusCode: 201}, nil } func getURLEncodedTestSubscription() *Subscription { return &Subscription{ Endpoint: "https://updates.push.services.mozilla.com/wpush/v2/gAAAAA", Keys: Keys{ P256dh: "BNNL5ZaTfK81qhXOx23-wewhigUeFb632jN6LvRWCFH1ubQr77FE_9qV1FuojuRmHP42zmf34rXgW80OvUVDgTk", Auth: "zqbxT6JKstKSY9JKibZLSQ", }, } } func getStandardEncodedTestSubscription() *Subscription { return &Subscription{ Endpoint: "https://updates.push.services.mozilla.com/wpush/v2/gAAAAA", Keys: Keys{ P256dh: "BNNL5ZaTfK81qhXOx23+wewhigUeFb632jN6LvRWCFH1ubQr77FE/9qV1FuojuRmHP42zmf34rXgW80OvUVDgTk=", Auth: "zqbxT6JKstKSY9JKibZLSQ==", }, } } func TestSendNotificationToURLEncodedSubscription(t *testing.T) { resp, err := SendNotification([]byte("Test"), getURLEncodedTestSubscription(), &Options{ HTTPClient: &testHTTPClient{}, RecordSize: 3070, Subscriber: "", Topic: "test_topic", TTL: 0, Urgency: "low", VAPIDPublicKey: "test-public", VAPIDPrivateKey: "test-private", }) if err != nil { t.Fatal(err) } if resp.StatusCode != 201 { t.Fatalf( "Incorreect status code, expected=%d, got=%d", resp.StatusCode, 201, ) } } func TestSendNotificationToStandardEncodedSubscription(t *testing.T) { resp, err := SendNotification([]byte("Test"), getStandardEncodedTestSubscription(), &Options{ HTTPClient: &testHTTPClient{}, Subscriber: "", Topic: "test_topic", TTL: 0, Urgency: "low", VAPIDPrivateKey: "testKey", }) if err != nil { t.Fatal(err) } if resp.StatusCode != 201 { t.Fatalf( "Incorreect status code, expected=%d, got=%d", resp.StatusCode, 201, ) } } func TestSendTooLargeNotification(t *testing.T) { _, err := SendNotification([]byte(strings.Repeat("Test", int(MaxRecordSize))), getStandardEncodedTestSubscription(), &Options{ HTTPClient: &testHTTPClient{}, Subscriber: "", Topic: "test_topic", TTL: 0, Urgency: "low", VAPIDPrivateKey: "testKey", }) if err == nil { t.Fatalf("Error is nil, expected=%s", ErrMaxPadExceeded) } }