webpush

package module
v0.0.0-...-0e572db Latest Latest
Warning

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

Go to latest
Published: Apr 3, 2021 License: Apache-2.0 Imports: 19 Imported by: 1

Documentation

Index

Constants

This section is empty.

Variables

View Source
var DefaultMux = NewMux()
View Source
var ReceiveBaseUrl = "https://127.0.0.1:5228/"
View Source
var SharedWPAuth = []byte{1}

Functions

func HTTPHandlerSend

func HTTPHandlerSend(w http.ResponseWriter, r *http.Request)

Used to push a message from a remote sender.

Mapped to /s/[DESTID]?... Local

q or path can be used to pass command. Body and query string are sent. TODO: compatibility with cloud events and webpush TODO: RBAC (including admin check for system notifications)

func InitMux

func InitMux(mux *Mux, hmux *http.ServeMux, auth *auth.Auth)

func NewRequest

func NewRequest(dest string, key, authK []byte,
	message string, ttlSec int, vapid *auth.Auth) (*http.Request, error)

NewVapidRequest creates a valid Web Push HTTP request for sending a message to a subscriber, using Vapid authentication.

You can add more headers to configure collapsing, TTL.

func Send

func Send(msgType string, meta ...string)

Send a message to the default mux. Will serialize the event and save it for debugging.

Local handlers and debug tools/admin can subscribe.

func SubscribeHandler

func SubscribeHandler(res http.ResponseWriter, req *http.Request)

Subscribe creates a subscription. Initial version is just a random - some interface will be added later, to allow sets.

Types

type Backoff

type Backoff interface {
	BackoffSleep()
	BackoffReset()
}

type ChannelHandler

type ChannelHandler struct {
	MsgChan chan *Message
}

func NewChannelHandler

func NewChannelHandler() *ChannelHandler

func (*ChannelHandler) HandleMessage

func (u *ChannelHandler) HandleMessage(ctx context.Context, cmdS string, meta map[string]string, data []byte)

func (*ChannelHandler) WaitEvent

func (u *ChannelHandler) WaitEvent(name string) *Message

type HandlerCallbackFunc

type HandlerCallbackFunc func(ctx context.Context, cmdS string, meta map[string]string, data []byte)

Adapter from func to interface

func (HandlerCallbackFunc) HandleMessage

func (f HandlerCallbackFunc) HandleMessage(ctx context.Context, cmdS string, meta map[string]string, data []byte)

ServeHTTP calls f(w, r).

type Message

type Message struct {
	MessageData

	// VIPs in the path
	Path []string `json:"path,omitempty"`

	// JSON-serializable payload.
	// Interface means will be serialized as base64 if []byte, as String if string or actual Json without encouding
	// otherwise.
	Data interface{} `json:"data,omitempty"`

	// If received from a remote, the connection it was received on.
	// nil if generated locally
	Connection *MsgConnection `json:"-"`
}

Records recent received messages and broadcasts, for debug and UI

func NewMessage

func NewMessage(cmdS string, meta map[string]string) *Message

NewMessage creates a new message, originated locally

func ParseJSON

func ParseJSON(data []byte) *Message

func (*Message) Binary

func (ev *Message) Binary() []byte

Return a binary representation of the data: either the []byte for raw data, or the marshalled json starting with {.

func (*Message) MarshalJSON

func (ev *Message) MarshalJSON() []byte

func (*Message) SetDataJSON

func (ev *Message) SetDataJSON(data interface{}) *Message

type MessageData

type MessageData struct {
	Id    string
	To    string
	Meta  map[string]string
	From  string
	Topic string

	Time int64
}

type MessageHandler

type MessageHandler interface {
	// Handle a message. Context may provide access to the actual message object
	// and mux.
	HandleMessage(ctx context.Context, cmdS string, meta map[string]string, data []byte)
}

Local processing of messages. Interface doesn't use any specific struct, to avoid creating deps.

type MsgConnection

type MsgConnection struct {

	// Key used in mux to track this connection
	Name string

	// Authenticated Vip associated with the connection. Messages will not be forwarded if
	// the VIP is in Path or From of the message.
	VIP string

	// Broadcast subscriptions to forward to the remote. Will have a 'From' set to current node.
	// VPN and upstream server use "*" to receive/pass up all events.
	// TODO: keep some messages local, by using To=., and indicate broadcasts as *.
	SubscriptionsToSend []string

	// OnMessage is called when a message for this connection is dispatched.
	// The message should be either a broadcast, have as To the vip of the connection or
	// another vip reachable from the connection.
	//
	// The topic of the message should be in the Subscription list if the destination is this vip.
	//
	// Internal handlers may use the same interface.
	SendMessageToRemote func(ev *Message) error

	Conn net.Conn
	// contains filtered or unexported fields
}

One connection - incoming or outgoing. Can send messages to the remote end, which may in turn forward messages for other nodes.

Incoming messages are dispatched to the mux, which may deliver locally or forward.

func (*MsgConnection) Close

func (mc *MsgConnection) Close()

func (*MsgConnection) HandleMessageStream

func (mconn *MsgConnection) HandleMessageStream(cb func(message *Message), br *bufio.Reader, from string)

Messages received from remote.

from is the authenticated VIP of the sender. self is my own VIP

type Mux

type Mux struct {

	// Allows regular HTTP Handlers to process messages.
	// A message is mapped to a request. Like CloudEvents, response from the
	// http request can be mapped to a Send (not supported yet).
	ServeMux *http.ServeMux

	// Auth holds the private key and Id of this node. Used to encrypt and decrypt.
	Auth *auth.Auth

	OnMessageForNode []OnMessage
	// contains filtered or unexported fields
}

Mux handles processing messages for this node, and sending messages from local code.

func NewMux

func NewMux() *Mux

func (*Mux) AddConnection

func (mux *Mux) AddConnection(id string, cp *MsgConnection)

id - remote id. "uds" for the primary upstream uds connection to host (android app or wifi/root app)

func (*Mux) AddHandler

func (mux *Mux) AddHandler(path string, cp MessageHandler)

Add a local handler for a specific message type. Special topics: *, /open, /close

func (*Mux) AddHandlerRole

func (mux *Mux) AddHandlerRole(path string, role ...string)

Add a handler that checks the role

func (*Mux) HTTPHandlerWebpush

func (mux *Mux) HTTPHandlerWebpush(w http.ResponseWriter, r *http.Request)

Webpush handler - on /push[/VIP], on the HTTPS handler

Auth: VAPID or client cert - results in VIP of sender

func (*Mux) HTTPUDS

func (mux *Mux) HTTPUDS(w http.ResponseWriter, r *http.Request)

Currently mapped to /dmesh/uds - sends a message to a specific connection, defaults to the UDS connection to the android or root dmwifi app.

func (*Mux) HandleMessageForNode

func (mux *Mux) HandleMessageForNode(ev *Message) error

Called for local events (host==. or empty). Called when a message is received from one of the local streams ( UDS, etc ), if the final destination is the current node.

Message will be passed to one or more of the local handlers, based on type.

TODO: authorization (based on identity of the caller)

func (*Mux) Id

func (mux *Mux) Id() string

func (*Mux) OnRemoteMessage

func (mux *Mux) OnRemoteMessage(ev *Message, connName string) error

Message from a remote, will be forwarded to subscribed connections.

func (*Mux) ProcessMessage

func (mux *Mux) ProcessMessage(line []byte, ctx *auth.ReqContext) *Message

ProcessMessage parses an incoming message, from a remote connection. Message is further processed using one of the methods.

func (*Mux) RemoveConnection

func (mux *Mux) RemoveConnection(id string, cp *MsgConnection)

func (*Mux) Send

func (mux *Mux) Send(msgType string, data interface{}, meta ...string) error

func (*Mux) SendMessage

func (mux *Mux) SendMessage(ev *Message) error

Publish a message. Will be distributed to remote listeners. TODO: routing for directed messages (to specific destination) TODO: up/down indication for multicast, subscription

func (*Mux) SendMsg

func (mux *Mux) SendMsg(ev *Message) error

Send a message to one or more connections.

type OnMessage

type OnMessage func(*Message)

type Pubsub

type Pubsub struct {
	// Messages are mapped to HTTP request with URL /msg/TOPIC
	// Long lived connections register as /sub/SUBID
	Mux http.ServeMux

	Topics map[string]*Topic
}

func NewPubsub

func NewPubsub() *Pubsub

func (*Pubsub) HandleMsg

func (gw *Pubsub) HandleMsg(w http.ResponseWriter, r *http.Request)

Handles incoming pubusb messages. 4xx, 5xx - message will be retried.

func (*Pubsub) OnMessage

func (*Pubsub) OnMessage()

func (*Pubsub) Publish

func (*Pubsub) Publish(ctx context.Context, cmdS string, meta map[string]string, data []byte) error

func (*Pubsub) SendMsg

func (gw *Pubsub) SendMsg(dst string, meta map[string]string, data []byte)

type Sub

type Sub struct {
	ID string

	// URL - if set, the message will be posted.
	Dest string

	HTTPHandler http.Handler
}

type Subscription

type Subscription struct {
	// Endpoint is the URL to send the Web Push message to. Comes from the
	// endpoint field of the PushSubscription.
	Endpoint string

	// Key is the client's public key. From the getKey("p256dh") or keys.p256dh field.
	Key []byte

	// Auth is a value used by the client to validate the encryption. From the
	// keys.auth field.
	// The encrypted aes128gcm will have 16 bytes authentication tag derived from this.
	// This is the pre-shared authentication secret.
	Auth []byte

	// Used by the UA to receive messages, as PUSH promises
	Location string
}

Subscription holds the useful values from a PushSubscription object acquired from the browser.

https://w3c.github.io/push-api/

Returned as result of /subscribe

func SubscriptionFromJSON

func SubscriptionFromJSON(b []byte) (*Subscription, error)

SubscriptionFromJSON is a convenience function that takes a JSON encoded PushSubscription object acquired from the browser and returns a pointer to a Subscription

type Topic

type Topic struct {
	Name string

	// Upstream brokers
	Brokers []Sub

	Subs []*Sub
}

type UA

type UA struct {
	// URL of the subscribe for the push service
	PushService string
}

UA represents a "user agent" - or client using the webpush protocol

func (*UA) Subscribe

func (ua *UA) Subscribe() (sub *Subscription, err error)

Create a subscription, using the Webpush standard protocol.

URL is "/subscribe", no header required ( but passing a VAPID or mtls), response in 'location' for read and Link for sub endpoint.

Jump to

Keyboard shortcuts

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