13
vendor/github.com/status-im/status-go/protocol/pushnotificationserver/errors.go
generated
vendored
Normal file
13
vendor/github.com/status-im/status-go/protocol/pushnotificationserver/errors.go
generated
vendored
Normal file
@@ -0,0 +1,13 @@
|
||||
package pushnotificationserver
|
||||
|
||||
import "errors"
|
||||
|
||||
var ErrInvalidPushNotificationRegistrationVersion = errors.New("invalid version")
|
||||
var ErrEmptyPushNotificationRegistrationPayload = errors.New("empty payload")
|
||||
var ErrMalformedPushNotificationRegistrationInstallationID = errors.New("invalid installationID")
|
||||
var ErrEmptyPushNotificationRegistrationPublicKey = errors.New("no public key")
|
||||
var ErrCouldNotUnmarshalPushNotificationRegistration = errors.New("could not unmarshal preferences")
|
||||
var ErrMalformedPushNotificationRegistrationDeviceToken = errors.New("invalid device token")
|
||||
var ErrMalformedPushNotificationRegistrationGrant = errors.New("invalid grant")
|
||||
var ErrMalformedPushNotificationRegistrationAccessToken = errors.New("invalid access token")
|
||||
var ErrUnknownPushNotificationRegistrationTokenType = errors.New("invalid token type")
|
||||
97
vendor/github.com/status-im/status-go/protocol/pushnotificationserver/gorush.go
generated
vendored
Normal file
97
vendor/github.com/status-im/status-go/protocol/pushnotificationserver/gorush.go
generated
vendored
Normal file
@@ -0,0 +1,97 @@
|
||||
package pushnotificationserver
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
|
||||
"go.uber.org/zap"
|
||||
|
||||
"github.com/status-im/status-go/eth-node/types"
|
||||
"github.com/status-im/status-go/protocol/protobuf"
|
||||
)
|
||||
|
||||
const defaultNewMessageNotificationText = "You have a new message"
|
||||
const defaultMentionNotificationText = "Someone mentioned you"
|
||||
const defaultRequestToJoinCommunityNotificationText = "Someone requested to join a community you are an admin of"
|
||||
|
||||
type GoRushRequestData struct {
|
||||
EncryptedMessage string `json:"encryptedMessage"`
|
||||
ChatID string `json:"chatId"`
|
||||
PublicKey string `json:"publicKey"`
|
||||
}
|
||||
|
||||
type GoRushRequestNotification struct {
|
||||
Tokens []string `json:"tokens"`
|
||||
Platform uint `json:"platform"`
|
||||
Message string `json:"message"`
|
||||
Topic string `json:"topic"`
|
||||
Data *GoRushRequestData `json:"data"`
|
||||
}
|
||||
|
||||
type GoRushRequest struct {
|
||||
Notifications []*GoRushRequestNotification `json:"notifications"`
|
||||
}
|
||||
|
||||
type RequestAndRegistration struct {
|
||||
Request *protobuf.PushNotification
|
||||
Registration *protobuf.PushNotificationRegistration
|
||||
}
|
||||
|
||||
func tokenTypeToGoRushPlatform(tokenType protobuf.PushNotificationRegistration_TokenType) uint {
|
||||
switch tokenType {
|
||||
case protobuf.PushNotificationRegistration_APN_TOKEN:
|
||||
return 1
|
||||
case protobuf.PushNotificationRegistration_FIREBASE_TOKEN:
|
||||
return 2
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func PushNotificationRegistrationToGoRushRequest(requestAndRegistrations []*RequestAndRegistration) *GoRushRequest {
|
||||
goRushRequests := &GoRushRequest{}
|
||||
for _, requestAndRegistration := range requestAndRegistrations {
|
||||
request := requestAndRegistration.Request
|
||||
registration := requestAndRegistration.Registration
|
||||
var text string
|
||||
if request.Type == protobuf.PushNotification_MESSAGE {
|
||||
text = defaultNewMessageNotificationText
|
||||
} else if request.Type == protobuf.PushNotification_REQUEST_TO_JOIN_COMMUNITY {
|
||||
text = defaultRequestToJoinCommunityNotificationText
|
||||
} else {
|
||||
text = defaultMentionNotificationText
|
||||
}
|
||||
goRushRequests.Notifications = append(goRushRequests.Notifications,
|
||||
&GoRushRequestNotification{
|
||||
Tokens: []string{registration.DeviceToken},
|
||||
Platform: tokenTypeToGoRushPlatform(registration.TokenType),
|
||||
Message: text,
|
||||
Topic: registration.ApnTopic,
|
||||
Data: &GoRushRequestData{
|
||||
EncryptedMessage: types.EncodeHex(request.Message),
|
||||
ChatID: types.EncodeHex(request.ChatId),
|
||||
PublicKey: types.EncodeHex(request.PublicKey),
|
||||
},
|
||||
})
|
||||
}
|
||||
return goRushRequests
|
||||
}
|
||||
|
||||
func sendGoRushNotification(request *GoRushRequest, url string, logger *zap.Logger) error {
|
||||
payload, err := json.Marshal(request)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
response, err := http.Post(url+"/api/push", "application/json", bytes.NewReader(payload))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer response.Body.Close()
|
||||
body, _ := ioutil.ReadAll(response.Body)
|
||||
|
||||
logger.Info("Sent gorush request", zap.String("response", string(body)))
|
||||
|
||||
return nil
|
||||
}
|
||||
367
vendor/github.com/status-im/status-go/protocol/pushnotificationserver/migrations/migrations.go
generated
vendored
Normal file
367
vendor/github.com/status-im/status-go/protocol/pushnotificationserver/migrations/migrations.go
generated
vendored
Normal file
@@ -0,0 +1,367 @@
|
||||
// Code generated by go-bindata. DO NOT EDIT.
|
||||
// sources:
|
||||
// 1593601728_initial_schema.down.sql (200B)
|
||||
// 1593601728_initial_schema.up.sql (675B)
|
||||
// 1598419937_add_push_notifications_table.down.sql (51B)
|
||||
// 1598419937_add_push_notifications_table.up.sql (104B)
|
||||
// doc.go (382B)
|
||||
|
||||
package migrations
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"compress/gzip"
|
||||
"crypto/sha256"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
func bindataRead(data []byte, name string) ([]byte, error) {
|
||||
gz, err := gzip.NewReader(bytes.NewBuffer(data))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read %q: %w", name, err)
|
||||
}
|
||||
|
||||
var buf bytes.Buffer
|
||||
_, err = io.Copy(&buf, gz)
|
||||
clErr := gz.Close()
|
||||
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read %q: %w", name, err)
|
||||
}
|
||||
if clErr != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return buf.Bytes(), nil
|
||||
}
|
||||
|
||||
type asset struct {
|
||||
bytes []byte
|
||||
info os.FileInfo
|
||||
digest [sha256.Size]byte
|
||||
}
|
||||
|
||||
type bindataFileInfo struct {
|
||||
name string
|
||||
size int64
|
||||
mode os.FileMode
|
||||
modTime time.Time
|
||||
}
|
||||
|
||||
func (fi bindataFileInfo) Name() string {
|
||||
return fi.name
|
||||
}
|
||||
func (fi bindataFileInfo) Size() int64 {
|
||||
return fi.size
|
||||
}
|
||||
func (fi bindataFileInfo) Mode() os.FileMode {
|
||||
return fi.mode
|
||||
}
|
||||
func (fi bindataFileInfo) ModTime() time.Time {
|
||||
return fi.modTime
|
||||
}
|
||||
func (fi bindataFileInfo) IsDir() bool {
|
||||
return false
|
||||
}
|
||||
func (fi bindataFileInfo) Sys() interface{} {
|
||||
return nil
|
||||
}
|
||||
|
||||
var __1593601728_initial_schemaDownSql = []byte("\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\xff\x72\x09\xf2\x0f\x50\x08\x71\x74\xf2\x71\x55\x28\x28\x2d\xce\x88\xcf\xcb\x2f\xc9\x4c\xcb\x4c\x4e\x2c\xc9\xcc\xcf\x8b\x2f\x4e\x2d\x2a\x4b\x2d\x8a\x2f\x4a\x4d\xcf\x2c\x2e\x29\x02\x8b\x15\x5b\x73\x81\xb5\x78\xfa\xb9\xb8\x46\x28\x64\xa6\x54\xc4\x13\xa7\x2d\xbe\xa0\x34\x29\x27\x33\x39\x3e\x3b\xb5\x92\x72\x13\xe2\x33\xf3\x8a\x4b\x12\x73\x72\x20\x8a\x33\x53\xac\xb9\xb8\x00\x01\x00\x00\xff\xff\x90\x39\xe0\x1c\xc8\x00\x00\x00")
|
||||
|
||||
func _1593601728_initial_schemaDownSqlBytes() ([]byte, error) {
|
||||
return bindataRead(
|
||||
__1593601728_initial_schemaDownSql,
|
||||
"1593601728_initial_schema.down.sql",
|
||||
)
|
||||
}
|
||||
|
||||
func _1593601728_initial_schemaDownSql() (*asset, error) {
|
||||
bytes, err := _1593601728_initial_schemaDownSqlBytes()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
info := bindataFileInfo{name: "1593601728_initial_schema.down.sql", size: 200, mode: os.FileMode(0644), modTime: time.Unix(1704739012, 0)}
|
||||
a := &asset{bytes: bytes, info: info, digest: [32]uint8{0x88, 0x8a, 0x61, 0x81, 0x57, 0x45, 0x9b, 0x97, 0x9b, 0x1f, 0xf6, 0x94, 0x8a, 0x20, 0xb3, 0x2b, 0xff, 0x69, 0x49, 0xf4, 0x58, 0xcc, 0xd0, 0x55, 0xcc, 0x9a, 0x8b, 0xb6, 0x7f, 0x29, 0x53, 0xc1}}
|
||||
return a, nil
|
||||
}
|
||||
|
||||
var __1593601728_initial_schemaUpSql = []byte("\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\xff\xac\x91\x31\x6b\xc3\x30\x14\x84\x77\xfd\x8a\x37\xc6\x90\xa1\xbb\x27\xd9\x91\xa9\x40\x48\xad\x23\x97\x6c\xc2\xb5\xd5\xe6\x51\x23\x07\x49\x31\xf5\xbf\x2f\x71\x86\x2a\x69\x87\x10\xb2\x1e\x8f\xbb\xf7\xdd\x95\x35\xa3\x9a\x81\xa6\x85\x60\xc0\x2b\x90\x4a\x03\xdb\xf1\xad\xde\xc2\xe1\x18\xf6\xc6\x8d\x11\x3f\xb0\x6b\x23\x8e\xce\x04\xeb\x27\xeb\x8d\xb7\x9f\x18\xa2\x5f\xb4\x00\x2b\x02\x70\x38\xbe\x0f\xd8\x99\x2f\x3b\x43\x21\x54\xb1\xb8\xc8\x46\x88\x35\x01\x40\x17\x62\x3b\x0c\x67\x07\xec\xe1\x8d\xd6\xe5\x33\xad\x2f\x6e\x26\xeb\x03\x8e\x0e\xb8\xd4\x17\x7a\x9a\xb4\x38\x9f\xc4\x46\xf2\xd7\x86\xad\x7e\x33\xd7\xd7\x19\x19\x28\x09\xa5\x92\x95\xe0\xa5\x86\x9a\xbd\x08\x5a\x32\x92\xe5\x84\xdc\x83\x8b\xbd\x75\x11\xe3\x7c\x26\xf5\x38\xb5\xd1\xfe\x8f\x1a\x66\x17\xf7\x36\x62\x77\xe2\x4c\x59\x60\xc3\x2a\xda\x08\x0d\x4f\x09\x40\x7a\x9d\xa5\xdf\x71\xb9\x61\x3b\xc0\xfe\xdb\xdc\x36\x81\x49\xea\x57\xf2\xc6\xdd\x92\xfe\xb2\xfc\x01\xc9\xe6\x7a\xe7\x7b\x3e\xf9\xbb\x64\x4e\xc8\x4f\x00\x00\x00\xff\xff\xcc\xa0\x4d\x54\xa3\x02\x00\x00")
|
||||
|
||||
func _1593601728_initial_schemaUpSqlBytes() ([]byte, error) {
|
||||
return bindataRead(
|
||||
__1593601728_initial_schemaUpSql,
|
||||
"1593601728_initial_schema.up.sql",
|
||||
)
|
||||
}
|
||||
|
||||
func _1593601728_initial_schemaUpSql() (*asset, error) {
|
||||
bytes, err := _1593601728_initial_schemaUpSqlBytes()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
info := bindataFileInfo{name: "1593601728_initial_schema.up.sql", size: 675, mode: os.FileMode(0644), modTime: time.Unix(1704739012, 0)}
|
||||
a := &asset{bytes: bytes, info: info, digest: [32]uint8{0xfd, 0x61, 0x90, 0x79, 0xd9, 0x14, 0x65, 0xe9, 0x96, 0x53, 0x17, 0x33, 0x54, 0xeb, 0x8b, 0x5d, 0x95, 0x99, 0x10, 0x36, 0x58, 0xdd, 0xb2, 0xbf, 0x45, 0xd9, 0xbb, 0xc4, 0x92, 0xe, 0xce, 0x2}}
|
||||
return a, nil
|
||||
}
|
||||
|
||||
var __1598419937_add_push_notifications_tableDownSql = []byte("\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\xff\x72\x09\xf2\x0f\x50\x08\x71\x74\xf2\x71\x55\x28\x28\x2d\xce\x88\xcf\xcb\x2f\xc9\x4c\xcb\x4c\x4e\x2c\xc9\xcc\xcf\x8b\x2f\x4e\x2d\x2a\x4b\x2d\x42\x11\x2b\xb6\xe6\x02\x04\x00\x00\xff\xff\xb7\xdc\x38\x53\x33\x00\x00\x00")
|
||||
|
||||
func _1598419937_add_push_notifications_tableDownSqlBytes() ([]byte, error) {
|
||||
return bindataRead(
|
||||
__1598419937_add_push_notifications_tableDownSql,
|
||||
"1598419937_add_push_notifications_table.down.sql",
|
||||
)
|
||||
}
|
||||
|
||||
func _1598419937_add_push_notifications_tableDownSql() (*asset, error) {
|
||||
bytes, err := _1598419937_add_push_notifications_tableDownSqlBytes()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
info := bindataFileInfo{name: "1598419937_add_push_notifications_table.down.sql", size: 51, mode: os.FileMode(0644), modTime: time.Unix(1704739012, 0)}
|
||||
a := &asset{bytes: bytes, info: info, digest: [32]uint8{0xc, 0x98, 0xc8, 0x30, 0x45, 0x5b, 0xc5, 0x7d, 0x13, 0x5d, 0xe7, 0xc8, 0x23, 0x43, 0xf7, 0xdc, 0x9c, 0xe2, 0xdd, 0x63, 0xf0, 0xb7, 0x16, 0x40, 0xc, 0xda, 0xb9, 0x16, 0x70, 0x2b, 0x5a, 0x7e}}
|
||||
return a, nil
|
||||
}
|
||||
|
||||
var __1598419937_add_push_notifications_tableUpSql = []byte("\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\xff\x72\x0e\x72\x75\x0c\x71\x55\x08\x71\x74\xf2\x71\x55\xf0\x74\x53\xf0\xf3\x0f\x51\x70\x8d\xf0\x0c\x0e\x09\x56\x28\x28\x2d\xce\x88\xcf\xcb\x2f\xc9\x4c\xcb\x4c\x4e\x2c\xc9\xcc\xcf\x8b\x2f\x4e\x2d\x2a\x4b\x2d\x42\x11\x2b\x56\xd0\xe0\x52\x50\xc8\x4c\x51\x70\xf2\xf1\x77\x02\xeb\xf6\x0b\xf5\xf1\xd1\xe1\x52\x50\x08\xf5\xf3\x0c\x0c\x75\xd5\xc8\x4c\xd1\xe4\xd2\xb4\xe6\x02\x04\x00\x00\xff\xff\xf3\xc8\x52\x6b\x68\x00\x00\x00")
|
||||
|
||||
func _1598419937_add_push_notifications_tableUpSqlBytes() ([]byte, error) {
|
||||
return bindataRead(
|
||||
__1598419937_add_push_notifications_tableUpSql,
|
||||
"1598419937_add_push_notifications_table.up.sql",
|
||||
)
|
||||
}
|
||||
|
||||
func _1598419937_add_push_notifications_tableUpSql() (*asset, error) {
|
||||
bytes, err := _1598419937_add_push_notifications_tableUpSqlBytes()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
info := bindataFileInfo{name: "1598419937_add_push_notifications_table.up.sql", size: 104, mode: os.FileMode(0644), modTime: time.Unix(1704739012, 0)}
|
||||
a := &asset{bytes: bytes, info: info, digest: [32]uint8{0x2, 0x3e, 0xef, 0xf, 0xc2, 0xdf, 0xbc, 0x99, 0x7a, 0xc2, 0xd3, 0x64, 0x4f, 0x4c, 0x7e, 0xfc, 0x2e, 0x8c, 0xa7, 0x54, 0xd3, 0x4d, 0x25, 0x98, 0x41, 0xbc, 0xea, 0xd7, 0x2, 0xc1, 0xd0, 0x52}}
|
||||
return a, nil
|
||||
}
|
||||
|
||||
var _docGo = []byte("\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\xff\x84\x8f\x3d\x6e\xec\x30\x0c\x84\x7b\x9d\x62\xb0\xcd\x36\xcf\x52\xf3\xaa\x74\x29\xd3\xe7\x02\x5c\x89\x96\x88\xb5\x24\x43\xa4\xf7\xe7\xf6\x81\x37\x01\xe2\x2e\xed\x87\xf9\x86\xc3\x10\xf0\x59\x44\x31\xcb\xc2\x10\x45\xe3\xc8\xaa\x34\x9e\xb8\x70\xa4\x4d\x19\xa7\x2c\x56\xb6\x8b\x8f\xbd\x06\x35\xb2\x4d\x27\xa9\xa1\x4a\x1e\x64\x1c\x6e\xff\x4f\x2e\x04\x44\x6a\x67\x43\xa1\x96\x16\x7e\x75\x29\xd4\x68\x98\xb4\x8c\xbb\x58\x01\x61\x1d\x3c\xcb\xc3\xe3\xdd\xb0\x30\xa9\xc1\x0a\xd9\x59\x61\x85\x11\x49\x79\xaf\x99\xfb\x40\xee\xd3\x45\x5a\x22\x23\xbf\xa3\x8f\xf9\x40\xf6\x85\x91\x96\x85\x13\xe6\xd1\xeb\xcb\x55\xaa\x8c\x24\x83\xa3\xf5\xf1\xfc\x07\x52\x65\x43\xa3\xca\xba\xfb\x85\x6e\x8c\xd6\x7f\xce\x83\x5a\xfa\xfb\x23\xdc\xfb\xb8\x2a\x48\xc1\x8f\x95\xa3\x71\xf2\xce\xad\x14\xaf\x94\x19\xdf\x39\xe9\x4d\x9d\x0b\x21\xf7\xb7\xcc\x8d\x77\xf3\xb8\x73\x5a\xaf\xf9\x90\xc4\xd4\xe1\x7d\xf8\x05\x3e\x77\xf8\xe0\xbe\x02\x00\x00\xff\xff\x4d\x1d\x5d\x50\x7e\x01\x00\x00")
|
||||
|
||||
func docGoBytes() ([]byte, error) {
|
||||
return bindataRead(
|
||||
_docGo,
|
||||
"doc.go",
|
||||
)
|
||||
}
|
||||
|
||||
func docGo() (*asset, error) {
|
||||
bytes, err := docGoBytes()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
info := bindataFileInfo{name: "doc.go", size: 382, mode: os.FileMode(0644), modTime: time.Unix(1704739012, 0)}
|
||||
a := &asset{bytes: bytes, info: info, digest: [32]uint8{0xc0, 0x2f, 0x1e, 0x64, 0x9, 0x93, 0xe4, 0x8b, 0xf2, 0x98, 0x5a, 0x45, 0xe2, 0x80, 0x88, 0x67, 0x7a, 0x2d, 0xd7, 0x4b, 0xd1, 0x73, 0xb6, 0x6d, 0x15, 0xc2, 0x0, 0x34, 0xcd, 0xa0, 0xdb, 0x20}}
|
||||
return a, nil
|
||||
}
|
||||
|
||||
// Asset loads and returns the asset for the given name.
|
||||
// It returns an error if the asset could not be found or
|
||||
// could not be loaded.
|
||||
func Asset(name string) ([]byte, error) {
|
||||
canonicalName := strings.Replace(name, "\\", "/", -1)
|
||||
if f, ok := _bindata[canonicalName]; ok {
|
||||
a, err := f()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Asset %s can't read by error: %v", name, err)
|
||||
}
|
||||
return a.bytes, nil
|
||||
}
|
||||
return nil, fmt.Errorf("Asset %s not found", name)
|
||||
}
|
||||
|
||||
// AssetString returns the asset contents as a string (instead of a []byte).
|
||||
func AssetString(name string) (string, error) {
|
||||
data, err := Asset(name)
|
||||
return string(data), err
|
||||
}
|
||||
|
||||
// MustAsset is like Asset but panics when Asset would return an error.
|
||||
// It simplifies safe initialization of global variables.
|
||||
func MustAsset(name string) []byte {
|
||||
a, err := Asset(name)
|
||||
if err != nil {
|
||||
panic("asset: Asset(" + name + "): " + err.Error())
|
||||
}
|
||||
|
||||
return a
|
||||
}
|
||||
|
||||
// MustAssetString is like AssetString but panics when Asset would return an
|
||||
// error. It simplifies safe initialization of global variables.
|
||||
func MustAssetString(name string) string {
|
||||
return string(MustAsset(name))
|
||||
}
|
||||
|
||||
// AssetInfo loads and returns the asset info for the given name.
|
||||
// It returns an error if the asset could not be found or
|
||||
// could not be loaded.
|
||||
func AssetInfo(name string) (os.FileInfo, error) {
|
||||
canonicalName := strings.Replace(name, "\\", "/", -1)
|
||||
if f, ok := _bindata[canonicalName]; ok {
|
||||
a, err := f()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("AssetInfo %s can't read by error: %v", name, err)
|
||||
}
|
||||
return a.info, nil
|
||||
}
|
||||
return nil, fmt.Errorf("AssetInfo %s not found", name)
|
||||
}
|
||||
|
||||
// AssetDigest returns the digest of the file with the given name. It returns an
|
||||
// error if the asset could not be found or the digest could not be loaded.
|
||||
func AssetDigest(name string) ([sha256.Size]byte, error) {
|
||||
canonicalName := strings.Replace(name, "\\", "/", -1)
|
||||
if f, ok := _bindata[canonicalName]; ok {
|
||||
a, err := f()
|
||||
if err != nil {
|
||||
return [sha256.Size]byte{}, fmt.Errorf("AssetDigest %s can't read by error: %v", name, err)
|
||||
}
|
||||
return a.digest, nil
|
||||
}
|
||||
return [sha256.Size]byte{}, fmt.Errorf("AssetDigest %s not found", name)
|
||||
}
|
||||
|
||||
// Digests returns a map of all known files and their checksums.
|
||||
func Digests() (map[string][sha256.Size]byte, error) {
|
||||
mp := make(map[string][sha256.Size]byte, len(_bindata))
|
||||
for name := range _bindata {
|
||||
a, err := _bindata[name]()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
mp[name] = a.digest
|
||||
}
|
||||
return mp, nil
|
||||
}
|
||||
|
||||
// AssetNames returns the names of the assets.
|
||||
func AssetNames() []string {
|
||||
names := make([]string, 0, len(_bindata))
|
||||
for name := range _bindata {
|
||||
names = append(names, name)
|
||||
}
|
||||
return names
|
||||
}
|
||||
|
||||
// _bindata is a table, holding each asset generator, mapped to its name.
|
||||
var _bindata = map[string]func() (*asset, error){
|
||||
"1593601728_initial_schema.down.sql": _1593601728_initial_schemaDownSql,
|
||||
"1593601728_initial_schema.up.sql": _1593601728_initial_schemaUpSql,
|
||||
"1598419937_add_push_notifications_table.down.sql": _1598419937_add_push_notifications_tableDownSql,
|
||||
"1598419937_add_push_notifications_table.up.sql": _1598419937_add_push_notifications_tableUpSql,
|
||||
"doc.go": docGo,
|
||||
}
|
||||
|
||||
// AssetDebug is true if the assets were built with the debug flag enabled.
|
||||
const AssetDebug = false
|
||||
|
||||
// AssetDir returns the file names below a certain
|
||||
// directory embedded in the file by go-bindata.
|
||||
// For example if you run go-bindata on data/... and data contains the
|
||||
// following hierarchy:
|
||||
//
|
||||
// data/
|
||||
// foo.txt
|
||||
// img/
|
||||
// a.png
|
||||
// b.png
|
||||
//
|
||||
// then AssetDir("data") would return []string{"foo.txt", "img"},
|
||||
// AssetDir("data/img") would return []string{"a.png", "b.png"},
|
||||
// AssetDir("foo.txt") and AssetDir("notexist") would return an error, and
|
||||
// AssetDir("") will return []string{"data"}.
|
||||
func AssetDir(name string) ([]string, error) {
|
||||
node := _bintree
|
||||
if len(name) != 0 {
|
||||
canonicalName := strings.Replace(name, "\\", "/", -1)
|
||||
pathList := strings.Split(canonicalName, "/")
|
||||
for _, p := range pathList {
|
||||
node = node.Children[p]
|
||||
if node == nil {
|
||||
return nil, fmt.Errorf("Asset %s not found", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
if node.Func != nil {
|
||||
return nil, fmt.Errorf("Asset %s not found", name)
|
||||
}
|
||||
rv := make([]string, 0, len(node.Children))
|
||||
for childName := range node.Children {
|
||||
rv = append(rv, childName)
|
||||
}
|
||||
return rv, nil
|
||||
}
|
||||
|
||||
type bintree struct {
|
||||
Func func() (*asset, error)
|
||||
Children map[string]*bintree
|
||||
}
|
||||
|
||||
var _bintree = &bintree{nil, map[string]*bintree{
|
||||
"1593601728_initial_schema.down.sql": {_1593601728_initial_schemaDownSql, map[string]*bintree{}},
|
||||
"1593601728_initial_schema.up.sql": {_1593601728_initial_schemaUpSql, map[string]*bintree{}},
|
||||
"1598419937_add_push_notifications_table.down.sql": {_1598419937_add_push_notifications_tableDownSql, map[string]*bintree{}},
|
||||
"1598419937_add_push_notifications_table.up.sql": {_1598419937_add_push_notifications_tableUpSql, map[string]*bintree{}},
|
||||
"doc.go": {docGo, map[string]*bintree{}},
|
||||
}}
|
||||
|
||||
// RestoreAsset restores an asset under the given directory.
|
||||
func RestoreAsset(dir, name string) error {
|
||||
data, err := Asset(name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
info, err := AssetInfo(name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = os.MkdirAll(_filePath(dir, filepath.Dir(name)), os.FileMode(0755))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = os.WriteFile(_filePath(dir, name), data, info.Mode())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return os.Chtimes(_filePath(dir, name), info.ModTime(), info.ModTime())
|
||||
}
|
||||
|
||||
// RestoreAssets restores an asset under the given directory recursively.
|
||||
func RestoreAssets(dir, name string) error {
|
||||
children, err := AssetDir(name)
|
||||
// File
|
||||
if err != nil {
|
||||
return RestoreAsset(dir, name)
|
||||
}
|
||||
// Dir
|
||||
for _, child := range children {
|
||||
err = RestoreAssets(dir, filepath.Join(name, child))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func _filePath(dir, name string) string {
|
||||
canonicalName := strings.Replace(name, "\\", "/", -1)
|
||||
return filepath.Join(append([]string{dir}, strings.Split(canonicalName, "/")...)...)
|
||||
}
|
||||
194
vendor/github.com/status-im/status-go/protocol/pushnotificationserver/persistence.go
generated
vendored
Normal file
194
vendor/github.com/status-im/status-go/protocol/pushnotificationserver/persistence.go
generated
vendored
Normal file
@@ -0,0 +1,194 @@
|
||||
package pushnotificationserver
|
||||
|
||||
import (
|
||||
"crypto/ecdsa"
|
||||
"database/sql"
|
||||
"strings"
|
||||
|
||||
"github.com/golang/protobuf/proto"
|
||||
sqlite3 "github.com/mutecomm/go-sqlcipher/v4"
|
||||
|
||||
"github.com/status-im/status-go/eth-node/crypto"
|
||||
"github.com/status-im/status-go/protocol/protobuf"
|
||||
)
|
||||
|
||||
type Persistence interface {
|
||||
// GetPushNotificationRegistrationByPublicKeyAndInstallationID retrieve a push notification registration from storage given a public key and installation id
|
||||
GetPushNotificationRegistrationByPublicKeyAndInstallationID(publicKey []byte, installationID string) (*protobuf.PushNotificationRegistration, error)
|
||||
// GetPushNotificationRegistrationByPublicKey retrieve all the push notification registrations from storage given a public key
|
||||
GetPushNotificationRegistrationByPublicKeys(publicKeys [][]byte) ([]*PushNotificationIDAndRegistration, error)
|
||||
// GetPushNotificationRegistrationPublicKeys return all the public keys stored
|
||||
GetPushNotificationRegistrationPublicKeys() ([][]byte, error)
|
||||
|
||||
//GetPushNotificationRegistrationVersion returns the latest version or 0 for a given pk and installationID
|
||||
GetPushNotificationRegistrationVersion(publicKey []byte, installationID string) (uint64, error)
|
||||
// UnregisterPushNotificationRegistration unregister a given pk/installationID
|
||||
UnregisterPushNotificationRegistration(publicKey []byte, installationID string, version uint64) error
|
||||
|
||||
// DeletePushNotificationRegistration deletes a push notification registration from storage given a public key and installation id
|
||||
DeletePushNotificationRegistration(publicKey []byte, installationID string) error
|
||||
// SavePushNotificationRegistration saves a push notification option to the db
|
||||
SavePushNotificationRegistration(publicKey []byte, registration *protobuf.PushNotificationRegistration) error
|
||||
// GetIdentity returns the server identity key
|
||||
GetIdentity() (*ecdsa.PrivateKey, error)
|
||||
// SaveIdentity saves the server identity key
|
||||
SaveIdentity(*ecdsa.PrivateKey) error
|
||||
// PushNotificationExists checks whether a push notification exists and inserts it otherwise
|
||||
PushNotificationExists([]byte) (bool, error)
|
||||
}
|
||||
|
||||
type SQLitePersistence struct {
|
||||
db *sql.DB
|
||||
}
|
||||
|
||||
func NewSQLitePersistence(db *sql.DB) Persistence {
|
||||
return &SQLitePersistence{db: db}
|
||||
}
|
||||
|
||||
func (p *SQLitePersistence) GetPushNotificationRegistrationByPublicKeyAndInstallationID(publicKey []byte, installationID string) (*protobuf.PushNotificationRegistration, error) {
|
||||
var marshaledRegistration []byte
|
||||
err := p.db.QueryRow(`SELECT registration FROM push_notification_server_registrations WHERE public_key = ? AND installation_id = ? AND registration IS NOT NULL`, publicKey, installationID).Scan(&marshaledRegistration)
|
||||
|
||||
if err == sql.ErrNoRows {
|
||||
return nil, nil
|
||||
} else if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
registration := &protobuf.PushNotificationRegistration{}
|
||||
if err := proto.Unmarshal(marshaledRegistration, registration); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return registration, nil
|
||||
}
|
||||
|
||||
func (p *SQLitePersistence) GetPushNotificationRegistrationVersion(publicKey []byte, installationID string) (uint64, error) {
|
||||
var version uint64
|
||||
err := p.db.QueryRow(`SELECT version FROM push_notification_server_registrations WHERE public_key = ? AND installation_id = ?`, publicKey, installationID).Scan(&version)
|
||||
|
||||
if err == sql.ErrNoRows {
|
||||
return 0, nil
|
||||
} else if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
return version, nil
|
||||
}
|
||||
|
||||
type PushNotificationIDAndRegistration struct {
|
||||
ID []byte
|
||||
Registration *protobuf.PushNotificationRegistration
|
||||
}
|
||||
|
||||
func (p *SQLitePersistence) GetPushNotificationRegistrationByPublicKeys(publicKeys [][]byte) ([]*PushNotificationIDAndRegistration, error) {
|
||||
// TODO: check for a max number of keys
|
||||
|
||||
publicKeyArgs := make([]interface{}, 0, len(publicKeys))
|
||||
for _, pk := range publicKeys {
|
||||
publicKeyArgs = append(publicKeyArgs, pk)
|
||||
}
|
||||
|
||||
inVector := strings.Repeat("?, ", len(publicKeys)-1) + "?"
|
||||
|
||||
rows, err := p.db.Query(`SELECT public_key,registration FROM push_notification_server_registrations WHERE registration IS NOT NULL AND public_key IN (`+inVector+`)`, publicKeyArgs...) // nolint: gosec
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var registrations []*PushNotificationIDAndRegistration
|
||||
for rows.Next() {
|
||||
response := &PushNotificationIDAndRegistration{}
|
||||
var marshaledRegistration []byte
|
||||
err := rows.Scan(&response.ID, &marshaledRegistration)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
registration := &protobuf.PushNotificationRegistration{}
|
||||
// Skip if there's no registration
|
||||
if marshaledRegistration == nil {
|
||||
continue
|
||||
}
|
||||
|
||||
if err := proto.Unmarshal(marshaledRegistration, registration); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
response.Registration = registration
|
||||
registrations = append(registrations, response)
|
||||
}
|
||||
return registrations, nil
|
||||
}
|
||||
|
||||
func (p *SQLitePersistence) GetPushNotificationRegistrationPublicKeys() ([][]byte, error) {
|
||||
rows, err := p.db.Query(`SELECT public_key FROM push_notification_server_registrations WHERE registration IS NOT NULL`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var publicKeys [][]byte
|
||||
for rows.Next() {
|
||||
var publicKey []byte
|
||||
err := rows.Scan(&publicKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
publicKeys = append(publicKeys, publicKey)
|
||||
}
|
||||
return publicKeys, nil
|
||||
}
|
||||
|
||||
func (p *SQLitePersistence) SavePushNotificationRegistration(publicKey []byte, registration *protobuf.PushNotificationRegistration) error {
|
||||
marshaledRegistration, err := proto.Marshal(registration)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = p.db.Exec(`INSERT INTO push_notification_server_registrations (public_key, installation_id, version, registration) VALUES (?, ?, ?, ?)`, publicKey, registration.InstallationId, registration.Version, marshaledRegistration)
|
||||
return err
|
||||
}
|
||||
|
||||
func (p *SQLitePersistence) UnregisterPushNotificationRegistration(publicKey []byte, installationID string, version uint64) error {
|
||||
_, err := p.db.Exec(`UPDATE push_notification_server_registrations SET registration = NULL, version = ? WHERE public_key = ? AND installation_id = ?`, version, publicKey, installationID)
|
||||
return err
|
||||
}
|
||||
|
||||
func (p *SQLitePersistence) DeletePushNotificationRegistration(publicKey []byte, installationID string) error {
|
||||
_, err := p.db.Exec(`DELETE FROM push_notification_server_registrations WHERE public_key = ? AND installation_id = ?`, publicKey, installationID)
|
||||
return err
|
||||
}
|
||||
|
||||
func (p *SQLitePersistence) SaveIdentity(privateKey *ecdsa.PrivateKey) error {
|
||||
_, err := p.db.Exec(`INSERT INTO push_notification_server_identity (private_key) VALUES (?)`, crypto.FromECDSA(privateKey))
|
||||
return err
|
||||
}
|
||||
|
||||
func (p *SQLitePersistence) GetIdentity() (*ecdsa.PrivateKey, error) {
|
||||
var pkBytes []byte
|
||||
err := p.db.QueryRow(`SELECT private_key FROM push_notification_server_identity LIMIT 1`).Scan(&pkBytes)
|
||||
if err == sql.ErrNoRows {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
pk, err := crypto.ToECDSA(pkBytes)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return pk, nil
|
||||
}
|
||||
|
||||
func (p *SQLitePersistence) PushNotificationExists(messageID []byte) (bool, error) {
|
||||
_, err := p.db.Exec(`INSERT INTO push_notification_server_notifications VALUES (?)`, messageID)
|
||||
if err != nil && err.(sqlite3.Error).ExtendedCode == sqlite3.ErrConstraintUnique {
|
||||
return true, nil
|
||||
} else if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
return false, nil
|
||||
}
|
||||
556
vendor/github.com/status-im/status-go/protocol/pushnotificationserver/server.go
generated
vendored
Normal file
556
vendor/github.com/status-im/status-go/protocol/pushnotificationserver/server.go
generated
vendored
Normal file
@@ -0,0 +1,556 @@
|
||||
package pushnotificationserver
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/ecdsa"
|
||||
"encoding/hex"
|
||||
|
||||
"github.com/golang/protobuf/proto"
|
||||
"github.com/google/uuid"
|
||||
"github.com/pkg/errors"
|
||||
"go.uber.org/zap"
|
||||
|
||||
"github.com/status-im/status-go/eth-node/crypto"
|
||||
"github.com/status-im/status-go/eth-node/crypto/ecies"
|
||||
"github.com/status-im/status-go/eth-node/types"
|
||||
"github.com/status-im/status-go/protocol/common"
|
||||
"github.com/status-im/status-go/protocol/protobuf"
|
||||
)
|
||||
|
||||
const encryptedPayloadKeyLength = 16
|
||||
const defaultGorushURL = "https://gorush.status.im"
|
||||
|
||||
var errUnhandledPushNotificationType = errors.New("unhandled push notification type")
|
||||
|
||||
type Config struct {
|
||||
Enabled bool
|
||||
// Identity is our identity key
|
||||
Identity *ecdsa.PrivateKey
|
||||
// GorushUrl is the url for the gorush service
|
||||
GorushURL string
|
||||
|
||||
Logger *zap.Logger
|
||||
}
|
||||
|
||||
type Server struct {
|
||||
persistence Persistence
|
||||
config *Config
|
||||
messageSender *common.MessageSender
|
||||
// SentRequests keeps track of the requests sent to gorush, for testing only
|
||||
SentRequests int64
|
||||
}
|
||||
|
||||
func New(config *Config, persistence Persistence, messageSender *common.MessageSender) *Server {
|
||||
if len(config.GorushURL) == 0 {
|
||||
config.GorushURL = defaultGorushURL
|
||||
|
||||
}
|
||||
return &Server{persistence: persistence, config: config, messageSender: messageSender}
|
||||
}
|
||||
|
||||
func (s *Server) Start() error {
|
||||
if s.config.Logger == nil {
|
||||
logger, err := zap.NewDevelopment()
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "failed to create a logger")
|
||||
}
|
||||
s.config.Logger = logger
|
||||
}
|
||||
|
||||
s.config.Logger.Info("starting push notification server")
|
||||
if s.config.Identity == nil {
|
||||
s.config.Logger.Debug("Identity nil")
|
||||
// Pull identity from database
|
||||
identity, err := s.persistence.GetIdentity()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if identity == nil {
|
||||
identity, err = crypto.GenerateKey()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := s.persistence.SaveIdentity(identity); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
s.config.Identity = identity
|
||||
}
|
||||
|
||||
pks, err := s.persistence.GetPushNotificationRegistrationPublicKeys()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// listen to all topics for users registered
|
||||
for _, pk := range pks {
|
||||
if err := s.listenToPublicKeyQueryTopic(pk); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
s.config.Logger.Info("started push notification server", zap.String("identity", types.EncodeHex(crypto.FromECDSAPub(&s.config.Identity.PublicKey))))
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// HandlePushNotificationRegistration builds a response for the registration and sends it back to the user
|
||||
func (s *Server) HandlePushNotificationRegistration(publicKey *ecdsa.PublicKey, payload []byte) error {
|
||||
response := s.buildPushNotificationRegistrationResponse(publicKey, payload)
|
||||
if response == nil {
|
||||
return nil
|
||||
}
|
||||
encodedMessage, err := proto.Marshal(response)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
rawMessage := common.RawMessage{
|
||||
Payload: encodedMessage,
|
||||
MessageType: protobuf.ApplicationMetadataMessage_PUSH_NOTIFICATION_REGISTRATION_RESPONSE,
|
||||
// we skip encryption as might be sent from an ephemeral key
|
||||
SkipEncryptionLayer: true,
|
||||
}
|
||||
|
||||
_, err = s.messageSender.SendPrivate(context.Background(), publicKey, &rawMessage)
|
||||
return err
|
||||
}
|
||||
|
||||
// HandlePushNotificationQuery builds a response for the query and sends it back to the user
|
||||
func (s *Server) HandlePushNotificationQuery(publicKey *ecdsa.PublicKey, messageID []byte, query *protobuf.PushNotificationQuery) error {
|
||||
if query == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
response := s.buildPushNotificationQueryResponse(query)
|
||||
if response == nil {
|
||||
return nil
|
||||
}
|
||||
response.MessageId = messageID
|
||||
encodedMessage, err := proto.Marshal(response)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
rawMessage := common.RawMessage{
|
||||
Payload: encodedMessage,
|
||||
MessageType: protobuf.ApplicationMetadataMessage_PUSH_NOTIFICATION_QUERY_RESPONSE,
|
||||
// we skip encryption as sent from an ephemeral key
|
||||
SkipEncryptionLayer: true,
|
||||
}
|
||||
|
||||
_, err = s.messageSender.SendPrivate(context.Background(), publicKey, &rawMessage)
|
||||
return err
|
||||
}
|
||||
|
||||
// HandlePushNotificationRequest will send a gorush notification and send a response back to the user
|
||||
func (s *Server) HandlePushNotificationRequest(publicKey *ecdsa.PublicKey,
|
||||
messageID []byte,
|
||||
request *protobuf.PushNotificationRequest) error {
|
||||
s.config.Logger.Debug("handling pn request", zap.Binary("message-id", messageID))
|
||||
|
||||
// This is at-most-once semantic for now
|
||||
exists, err := s.persistence.PushNotificationExists(messageID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if exists {
|
||||
s.config.Logger.Debug("already handled")
|
||||
return nil
|
||||
}
|
||||
|
||||
response, requestsAndRegistrations := s.buildPushNotificationRequestResponse(request)
|
||||
//AndSendNotification(&request)
|
||||
if response == nil {
|
||||
return nil
|
||||
}
|
||||
err = s.sendPushNotification(requestsAndRegistrations)
|
||||
if err != nil {
|
||||
s.config.Logger.Error("failed to send go rush notification", zap.Error(err))
|
||||
return err
|
||||
}
|
||||
encodedMessage, err := proto.Marshal(response)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
rawMessage := common.RawMessage{
|
||||
Payload: encodedMessage,
|
||||
MessageType: protobuf.ApplicationMetadataMessage_PUSH_NOTIFICATION_RESPONSE,
|
||||
// We skip encryption here as the message has been sent from an ephemeral key
|
||||
SkipEncryptionLayer: true,
|
||||
}
|
||||
|
||||
_, err = s.messageSender.SendPrivate(context.Background(), publicKey, &rawMessage)
|
||||
return err
|
||||
}
|
||||
|
||||
// buildGrantSignatureMaterial builds a grant for a specific server.
|
||||
// We use 3 components:
|
||||
// 1) The client public key. Not sure this applies to our signature scheme, but best to be conservative. https://crypto.stackexchange.com/questions/15538/given-a-message-and-signature-find-a-public-key-that-makes-the-signature-valid
|
||||
// 2) The server public key
|
||||
// 3) The access token
|
||||
// By verifying this signature, a client can trust the server was instructed to store this access token.
|
||||
func (s *Server) buildGrantSignatureMaterial(clientPublicKey *ecdsa.PublicKey, serverPublicKey *ecdsa.PublicKey, accessToken string) []byte {
|
||||
var signatureMaterial []byte
|
||||
signatureMaterial = append(signatureMaterial, crypto.CompressPubkey(clientPublicKey)...)
|
||||
signatureMaterial = append(signatureMaterial, crypto.CompressPubkey(serverPublicKey)...)
|
||||
signatureMaterial = append(signatureMaterial, []byte(accessToken)...)
|
||||
a := crypto.Keccak256(signatureMaterial)
|
||||
return a
|
||||
}
|
||||
|
||||
func (s *Server) verifyGrantSignature(clientPublicKey *ecdsa.PublicKey, accessToken string, grant []byte) error {
|
||||
signatureMaterial := s.buildGrantSignatureMaterial(clientPublicKey, &s.config.Identity.PublicKey, accessToken)
|
||||
recoveredPublicKey, err := crypto.SigToPub(signatureMaterial, grant)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if !common.IsPubKeyEqual(recoveredPublicKey, clientPublicKey) {
|
||||
return errors.New("pubkey mismatch")
|
||||
}
|
||||
return nil
|
||||
|
||||
}
|
||||
|
||||
func (s *Server) generateSharedKey(publicKey *ecdsa.PublicKey) ([]byte, error) {
|
||||
return ecies.ImportECDSA(s.config.Identity).GenerateShared(
|
||||
ecies.ImportECDSAPublic(publicKey),
|
||||
encryptedPayloadKeyLength,
|
||||
encryptedPayloadKeyLength,
|
||||
)
|
||||
}
|
||||
|
||||
func (s *Server) validateUUID(u string) error {
|
||||
if len(u) == 0 {
|
||||
return errors.New("empty uuid")
|
||||
}
|
||||
_, err := uuid.Parse(u)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *Server) decryptRegistration(publicKey *ecdsa.PublicKey, payload []byte) ([]byte, error) {
|
||||
sharedKey, err := s.generateSharedKey(publicKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return common.Decrypt(payload, sharedKey)
|
||||
}
|
||||
|
||||
// validateRegistration validates a new message against the last one received for a given installationID and and public key
|
||||
// and return the decrypted message
|
||||
func (s *Server) validateRegistration(publicKey *ecdsa.PublicKey, payload []byte) (*protobuf.PushNotificationRegistration, error) {
|
||||
if payload == nil {
|
||||
return nil, ErrEmptyPushNotificationRegistrationPayload
|
||||
}
|
||||
|
||||
if publicKey == nil {
|
||||
return nil, ErrEmptyPushNotificationRegistrationPublicKey
|
||||
}
|
||||
|
||||
decryptedPayload, err := s.decryptRegistration(publicKey, payload)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
registration := &protobuf.PushNotificationRegistration{}
|
||||
|
||||
if err := proto.Unmarshal(decryptedPayload, registration); err != nil {
|
||||
return nil, ErrCouldNotUnmarshalPushNotificationRegistration
|
||||
}
|
||||
|
||||
if registration.Version < 1 {
|
||||
return nil, ErrInvalidPushNotificationRegistrationVersion
|
||||
}
|
||||
|
||||
if err := s.validateUUID(registration.InstallationId); err != nil {
|
||||
return nil, ErrMalformedPushNotificationRegistrationInstallationID
|
||||
}
|
||||
|
||||
previousVersion, err := s.persistence.GetPushNotificationRegistrationVersion(common.HashPublicKey(publicKey), registration.InstallationId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if registration.Version <= previousVersion {
|
||||
return nil, ErrInvalidPushNotificationRegistrationVersion
|
||||
}
|
||||
|
||||
// unregistering message
|
||||
if registration.Unregister {
|
||||
return registration, nil
|
||||
}
|
||||
|
||||
if err := s.validateUUID(registration.AccessToken); err != nil {
|
||||
return nil, ErrMalformedPushNotificationRegistrationAccessToken
|
||||
}
|
||||
|
||||
if len(registration.Grant) == 0 {
|
||||
return nil, ErrMalformedPushNotificationRegistrationGrant
|
||||
}
|
||||
|
||||
if err := s.verifyGrantSignature(publicKey, registration.AccessToken, registration.Grant); err != nil {
|
||||
|
||||
s.config.Logger.Error("failed to verify grant", zap.Error(err))
|
||||
return nil, ErrMalformedPushNotificationRegistrationGrant
|
||||
}
|
||||
|
||||
if len(registration.DeviceToken) == 0 {
|
||||
return nil, ErrMalformedPushNotificationRegistrationDeviceToken
|
||||
}
|
||||
|
||||
if registration.TokenType == protobuf.PushNotificationRegistration_UNKNOWN_TOKEN_TYPE {
|
||||
return nil, ErrUnknownPushNotificationRegistrationTokenType
|
||||
}
|
||||
|
||||
return registration, nil
|
||||
}
|
||||
|
||||
// buildPushNotificationQueryResponse check if we have the client information and send them back
|
||||
func (s *Server) buildPushNotificationQueryResponse(query *protobuf.PushNotificationQuery) *protobuf.PushNotificationQueryResponse {
|
||||
|
||||
s.config.Logger.Debug("handling push notification query")
|
||||
response := &protobuf.PushNotificationQueryResponse{}
|
||||
if query == nil || len(query.PublicKeys) == 0 {
|
||||
return response
|
||||
}
|
||||
|
||||
registrations, err := s.persistence.GetPushNotificationRegistrationByPublicKeys(query.PublicKeys)
|
||||
if err != nil {
|
||||
s.config.Logger.Error("failed to retrieve registration", zap.Error(err))
|
||||
return response
|
||||
}
|
||||
|
||||
for _, idAndResponse := range registrations {
|
||||
|
||||
registration := idAndResponse.Registration
|
||||
|
||||
info := &protobuf.PushNotificationQueryInfo{
|
||||
PublicKey: idAndResponse.ID,
|
||||
Grant: registration.Grant,
|
||||
Version: registration.Version,
|
||||
InstallationId: registration.InstallationId,
|
||||
}
|
||||
|
||||
// if instructed to only allow from contacts, send back a list
|
||||
if registration.AllowFromContactsOnly {
|
||||
info.AllowedKeyList = registration.AllowedKeyList
|
||||
} else {
|
||||
info.AccessToken = registration.AccessToken
|
||||
}
|
||||
response.Info = append(response.Info, info)
|
||||
}
|
||||
|
||||
response.Success = true
|
||||
return response
|
||||
}
|
||||
|
||||
func (s *Server) contains(list [][]byte, chatID []byte) bool {
|
||||
for _, list := range list {
|
||||
if bytes.Equal(list, chatID) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
type reportResult struct {
|
||||
sendNotification bool
|
||||
report *protobuf.PushNotificationReport
|
||||
}
|
||||
|
||||
// buildPushNotificationReport checks the request against the registration and
|
||||
// returns whether we should send the notification and what the response should be
|
||||
func (s *Server) buildPushNotificationReport(pn *protobuf.PushNotification, registration *protobuf.PushNotificationRegistration) (*reportResult, error) {
|
||||
response := &reportResult{}
|
||||
report := &protobuf.PushNotificationReport{
|
||||
PublicKey: pn.PublicKey,
|
||||
InstallationId: pn.InstallationId,
|
||||
}
|
||||
|
||||
if pn.Type == protobuf.PushNotification_UNKNOWN_PUSH_NOTIFICATION_TYPE {
|
||||
s.config.Logger.Warn("unhandled type")
|
||||
return nil, errUnhandledPushNotificationType
|
||||
}
|
||||
|
||||
if registration == nil {
|
||||
s.config.Logger.Warn("empty registration")
|
||||
report.Error = protobuf.PushNotificationReport_NOT_REGISTERED
|
||||
} else if registration.AccessToken != pn.AccessToken {
|
||||
s.config.Logger.Debug("invalid token")
|
||||
report.Error = protobuf.PushNotificationReport_WRONG_TOKEN
|
||||
} else if (s.isMessageNotification(pn) && !s.isValidMessageNotification(pn, registration)) || (s.isMentionNotification(pn) && !s.isValidMentionNotification(pn, registration)) || (s.isRequestToJoinCommunityNotification(pn) && !s.isValidRequestToJoinCommunityNotification(pn, registration)) {
|
||||
s.config.Logger.Debug("filtered notification")
|
||||
// We report as successful but don't send the notification
|
||||
// for privacy reasons, as otherwise we would disclose that
|
||||
// the sending client has been blocked or that the registering
|
||||
// client has not joined a given public chat
|
||||
report.Success = true
|
||||
} else {
|
||||
response.sendNotification = true
|
||||
s.config.Logger.Debug("sending push notification")
|
||||
report.Success = true
|
||||
}
|
||||
|
||||
response.report = report
|
||||
|
||||
return response, nil
|
||||
}
|
||||
|
||||
// buildPushNotificationRequestResponse will build a response
|
||||
func (s *Server) buildPushNotificationRequestResponse(request *protobuf.PushNotificationRequest) (*protobuf.PushNotificationResponse, []*RequestAndRegistration) {
|
||||
response := &protobuf.PushNotificationResponse{}
|
||||
// We don't even send a response in this case
|
||||
if request == nil || len(request.MessageId) == 0 {
|
||||
s.config.Logger.Warn("empty message id")
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
response.MessageId = request.MessageId
|
||||
|
||||
// collect successful requests & registrations
|
||||
var requestAndRegistrations []*RequestAndRegistration
|
||||
|
||||
for _, pn := range request.Requests {
|
||||
registration, err := s.persistence.GetPushNotificationRegistrationByPublicKeyAndInstallationID(pn.PublicKey, pn.InstallationId)
|
||||
var report *protobuf.PushNotificationReport
|
||||
if err != nil {
|
||||
report = &protobuf.PushNotificationReport{
|
||||
PublicKey: pn.PublicKey,
|
||||
Error: protobuf.PushNotificationReport_UNKNOWN_ERROR_TYPE,
|
||||
InstallationId: pn.InstallationId,
|
||||
}
|
||||
} else {
|
||||
response, err := s.buildPushNotificationReport(pn, registration)
|
||||
if err != nil {
|
||||
s.config.Logger.Warn("unhandled type")
|
||||
continue
|
||||
}
|
||||
|
||||
if response.sendNotification {
|
||||
requestAndRegistrations = append(requestAndRegistrations, &RequestAndRegistration{
|
||||
Request: pn,
|
||||
Registration: registration,
|
||||
})
|
||||
}
|
||||
report = response.report
|
||||
|
||||
}
|
||||
|
||||
response.Reports = append(response.Reports, report)
|
||||
}
|
||||
|
||||
s.config.Logger.Debug("built pn request")
|
||||
if len(requestAndRegistrations) == 0 {
|
||||
s.config.Logger.Warn("no request and registration")
|
||||
return response, nil
|
||||
}
|
||||
|
||||
return response, requestAndRegistrations
|
||||
}
|
||||
|
||||
func (s *Server) sendPushNotification(requestAndRegistrations []*RequestAndRegistration) error {
|
||||
if len(requestAndRegistrations) == 0 {
|
||||
return nil
|
||||
}
|
||||
s.SentRequests++
|
||||
goRushRequest := PushNotificationRegistrationToGoRushRequest(requestAndRegistrations)
|
||||
return sendGoRushNotification(goRushRequest, s.config.GorushURL, s.config.Logger)
|
||||
}
|
||||
|
||||
// listenToPublicKeyQueryTopic listen to a topic derived from the hashed public key
|
||||
func (s *Server) listenToPublicKeyQueryTopic(hashedPublicKey []byte) error {
|
||||
if s.messageSender == nil {
|
||||
return nil
|
||||
}
|
||||
encodedPublicKey := hex.EncodeToString(hashedPublicKey)
|
||||
_, err := s.messageSender.JoinPublic(encodedPublicKey)
|
||||
return err
|
||||
}
|
||||
|
||||
// buildPushNotificationRegistrationResponse will check the registration is valid, save it, and listen to the topic for the queries
|
||||
func (s *Server) buildPushNotificationRegistrationResponse(publicKey *ecdsa.PublicKey, payload []byte) *protobuf.PushNotificationRegistrationResponse {
|
||||
|
||||
s.config.Logger.Debug("handling push notification registration")
|
||||
response := &protobuf.PushNotificationRegistrationResponse{
|
||||
RequestId: common.Shake256(payload),
|
||||
}
|
||||
|
||||
registration, err := s.validateRegistration(publicKey, payload)
|
||||
|
||||
if err != nil {
|
||||
if err == ErrInvalidPushNotificationRegistrationVersion {
|
||||
response.Error = protobuf.PushNotificationRegistrationResponse_VERSION_MISMATCH
|
||||
} else {
|
||||
response.Error = protobuf.PushNotificationRegistrationResponse_MALFORMED_MESSAGE
|
||||
}
|
||||
s.config.Logger.Warn("registration did not validate", zap.Error(err))
|
||||
return response
|
||||
}
|
||||
|
||||
if registration.Unregister {
|
||||
s.config.Logger.Debug("unregistering client")
|
||||
// We save an empty registration, only keeping version and installation-id
|
||||
if err := s.persistence.UnregisterPushNotificationRegistration(common.HashPublicKey(publicKey), registration.InstallationId, registration.Version); err != nil {
|
||||
response.Error = protobuf.PushNotificationRegistrationResponse_INTERNAL_ERROR
|
||||
s.config.Logger.Error("failed to unregister ", zap.Error(err))
|
||||
return response
|
||||
}
|
||||
|
||||
} else if err := s.persistence.SavePushNotificationRegistration(common.HashPublicKey(publicKey), registration); err != nil {
|
||||
response.Error = protobuf.PushNotificationRegistrationResponse_INTERNAL_ERROR
|
||||
s.config.Logger.Error("failed to save registration", zap.Error(err))
|
||||
return response
|
||||
}
|
||||
|
||||
if err := s.listenToPublicKeyQueryTopic(common.HashPublicKey(publicKey)); err != nil {
|
||||
response.Error = protobuf.PushNotificationRegistrationResponse_INTERNAL_ERROR
|
||||
s.config.Logger.Error("failed to listen to topic", zap.Error(err))
|
||||
return response
|
||||
|
||||
}
|
||||
response.Success = true
|
||||
|
||||
s.config.Logger.Debug("handled push notification registration successfully")
|
||||
|
||||
return response
|
||||
}
|
||||
|
||||
func (s *Server) isMentionNotification(pn *protobuf.PushNotification) bool {
|
||||
return pn.Type == protobuf.PushNotification_MENTION
|
||||
}
|
||||
|
||||
// isValidMentionNotification checks:
|
||||
// this is a mention
|
||||
// mentions are enabled
|
||||
// the user joined the public chat
|
||||
// the author is not blocked
|
||||
func (s *Server) isValidMentionNotification(pn *protobuf.PushNotification, registration *protobuf.PushNotificationRegistration) bool {
|
||||
return s.isMentionNotification(pn) && !registration.BlockMentions && s.contains(registration.AllowedMentionsChatList, pn.ChatId) && !s.contains(registration.BlockedChatList, pn.Author)
|
||||
}
|
||||
|
||||
func (s *Server) isMessageNotification(pn *protobuf.PushNotification) bool {
|
||||
return pn.Type == protobuf.PushNotification_MESSAGE
|
||||
}
|
||||
|
||||
// isValidMessageNotification checks:
|
||||
// this is a message
|
||||
// the chat is not muted
|
||||
// the author is not blocked
|
||||
func (s *Server) isValidMessageNotification(pn *protobuf.PushNotification, registration *protobuf.PushNotificationRegistration) bool {
|
||||
return s.isMessageNotification(pn) && !s.contains(registration.BlockedChatList, pn.ChatId) && !s.contains(registration.MutedChatList, pn.ChatId) && !s.contains(registration.BlockedChatList, pn.Author)
|
||||
}
|
||||
|
||||
func (s *Server) isRequestToJoinCommunityNotification(pn *protobuf.PushNotification) bool {
|
||||
return pn.Type == protobuf.PushNotification_REQUEST_TO_JOIN_COMMUNITY
|
||||
}
|
||||
|
||||
// isValidRequestToJoinCommunityNotification checks:
|
||||
// this is a request to join a community
|
||||
// the author is not blocked
|
||||
func (s *Server) isValidRequestToJoinCommunityNotification(pn *protobuf.PushNotification, registration *protobuf.PushNotificationRegistration) bool {
|
||||
return s.isRequestToJoinCommunityNotification(pn) && !s.contains(registration.BlockedChatList, pn.Author)
|
||||
}
|
||||
Reference in New Issue
Block a user