pax_global_header00006660000000000000000000000064141762702310014515gustar00rootroot0000000000000052 comment=9f057bcddd4d4ee494899af787cd67cfa868c80b webpush-go-1.2.0/000077500000000000000000000000001417627023100135755ustar00rootroot00000000000000webpush-go-1.2.0/.github/000077500000000000000000000000001417627023100151355ustar00rootroot00000000000000webpush-go-1.2.0/.github/dependabot.yml000066400000000000000000000002221417627023100177610ustar00rootroot00000000000000version: 2 updates: - package-ecosystem: gomod directory: "/" schedule: interval: weekly time: "13:00" open-pull-requests-limit: 10 webpush-go-1.2.0/.gitignore000066400000000000000000000000331417627023100155610ustar00rootroot00000000000000vendor/** .DS_Store *.out webpush-go-1.2.0/LICENSE000066400000000000000000000020551417627023100146040ustar00rootroot00000000000000MIT 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. webpush-go-1.2.0/README.md000066400000000000000000000026721417627023100150630ustar00rootroot00000000000000# 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) webpush-go-1.2.0/example/000077500000000000000000000000001417627023100152305ustar00rootroot00000000000000webpush-go-1.2.0/example/README.md000066400000000000000000000006271417627023100165140ustar00rootroot00000000000000# example ## Access index.html Replace the public VAPID key in index.html. Use a tool such as SimpleHTTPServer to run a web server: ``` python -m SimpleHTTPServer 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 ``` webpush-go-1.2.0/example/index.html000066400000000000000000000031071417627023100172260ustar00rootroot00000000000000 Webpush Golang Example webpush-go-1.2.0/example/main.go000066400000000000000000000011511417627023100165010ustar00rootroot00000000000000package 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() } webpush-go-1.2.0/example/service-worker.js000066400000000000000000000005141417627023100205350ustar00rootroot00000000000000self.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)); }); webpush-go-1.2.0/go.mod000066400000000000000000000002521417627023100147020ustar00rootroot00000000000000module github.com/SherClockHolmes/webpush-go require ( github.com/golang-jwt/jwt v3.2.2+incompatible golang.org/x/crypto v0.0.0-20190131182504-b8fe1690c613 ) go 1.13 webpush-go-1.2.0/go.sum000066400000000000000000000006301417627023100147270ustar00rootroot00000000000000github.com/golang-jwt/jwt v3.2.2+incompatible h1:IfV12K8xAKAnZqdXVzCZ+TOjboZ2keLg81eXfW3O+oY= github.com/golang-jwt/jwt v3.2.2+incompatible/go.mod h1:8pz2t5EyA70fFQQSrl6XZXzqecmYZeUEB8OUGHkxJ+I= golang.org/x/crypto v0.0.0-20190131182504-b8fe1690c613 h1:MQ/ZZiDsUapFFiMS+vzwXkCTeEKaum+Do5rINYJDmxc= golang.org/x/crypto v0.0.0-20190131182504-b8fe1690c613/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= webpush-go-1.2.0/urgency.go000066400000000000000000000015241417627023100156020ustar00rootroot00000000000000package 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 } webpush-go-1.2.0/vapid.go000066400000000000000000000046721417627023100152400ustar00rootroot00000000000000package webpush import ( "crypto/ecdsa" "crypto/elliptic" "crypto/rand" "encoding/base64" "fmt" "math/big" "net/url" "time" "github.com/golang-jwt/jwt" ) // 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, ) (string, error) { // Create the JWT token subURL, err := url.Parse(endpoint) if err != nil { return "", err } token := jwt.NewWithClaims(jwt.SigningMethodES256, jwt.MapClaims{ "aud": fmt.Sprintf("%s://%s", subURL.Scheme, subURL.Host), "exp": time.Now().Add(time.Hour * 12).Unix(), "sub": fmt.Sprintf("mailto:%s", 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 fmt.Sprintf( "vapid t=%s, k=%s", jwtString, 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) } webpush-go-1.2.0/vapid_test.go000066400000000000000000000043061417627023100162710ustar00rootroot00000000000000package webpush import ( "encoding/base64" "fmt" "strings" "testing" "github.com/golang-jwt/jwt" ) 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, ) 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] } webpush-go-1.2.0/webpush.go000066400000000000000000000155701417627023100156110ustar00rootroot00000000000000package webpush import ( "bytes" "context" "crypto/aes" "crypto/cipher" "crypto/elliptic" "crypto/rand" "crypto/sha256" "encoding/base64" "encoding/binary" "errors" "io" "net/http" "strconv" "strings" "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 } // 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 dh 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") } sx, _ := curve.ScalarMult(sharedX, sharedY, localPrivateKey) sharedECDHSecret := sx.Bytes() 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-Length", strconv.Itoa(len(ciphertext))) 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)) } // Get VAPID Authorization header vapidAuthHeader, err := getVAPIDAuthorizationHeader( s.Endpoint, options.Subscriber, options.VAPIDPublicKey, options.VAPIDPrivateKey, ) 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 } webpush-go-1.2.0/webpush_test.go000066400000000000000000000045421417627023100166450ustar00rootroot00000000000000package 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) } }