relay

package
v0.0.14 Latest Latest
Warning

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

Go to latest
Published: Aug 4, 2024 License: CC0-1.0 Imports: 56 Imported by: 0

Documentation

Index

Constants

View Source
const (
	WriteWait       = 3 * time.Second
	PongWait        = 6 * time.Second
	PingPeriod      = 3 * time.Second
	ReadBufferSize  = 4096
	WriteBufferSize = 4096
	IgnoreAfter     = 16
	MaxMessageSize  = 4 * units.Mb
)

Variables

View Source
var (
	Reason       = normalize.Reason
	AuthRequired = reasons.AuthRequired
	Blocked      = reasons.Blocked
	Duplicate    = reasons.Duplicate
	Error        = reasons.Error
	Invalid      = reasons.Invalid
	Unsupported  = reasons.Unsupported
	NewOK        = okenvelope.NewFrom
	NewEID       = eventid.NewWith[B]
	NewNotice    = noticeenvelope.NewFrom[B]
	NewResult    = eventenvelope.NewResultWith
)
View Source
var Commands []*Command
View Source
var MaxLimit int
View Source
var Software = "https://git.replicatr.dev"
View Source
var Version = "v0.0.1"

Functions

func DecryptDM

func DecryptDM(ev *event.T, meSec, youPub B) (decryptedStr B, err E)

DecryptDM decrypts a DM, kind 4, 1059 or 1060

func FilterClampLimit

func FilterClampLimit(c Ctx, f *filter.T)

func GetListeningFilters

func GetListeningFilters() (respFilters *filters.T)

func MakeReply

func MakeReply(ev *event.T, content S) (evo *event.T)

MakeReply creates an appropriate reply event from a provided event that is being replied to (not quoting, just the right tags, timestamps and kind).

func PointerHasher

func PointerHasher[V any](_ maphash.Seed, k *V) uint64

func RemoveListener

func RemoveListener(ws WS)

RemoveListener removes WebSocket conn from listeners (no need to cancel contexts as they are all inherited from the main connection context)

func RemoveListenerId

func RemoveListenerId(ws WS, id SubID)

RemoveListenerId removes a specific subscription id from listeners for a given ws client and cancel its specific context

func RequestAuth

func RequestAuth(c Ctx, envType S)

func SetListener

func SetListener(id S, ws WS, f *filters.T, c context.C)

SetListener adds a filter to a connection.

func SprintHeader

func SprintHeader(hdr http.Header) func() (s S)

Types

type AddRelay

type AddRelay struct {
	PubKey string `arg:"--addpubkey" help:"public key of client to add"`
	Admin  bool   `arg:"--admin"  help:"set client as admin"`
}

type B

type B = []byte

func NoComplexFilters

func NoComplexFilters(c Ctx, id SubID, f *filter.T) (reject bool, msg B)

NoComplexFilters disallows filters with more than 3 tags or total of 6 of kinds and tags in sum..

func NoEmptyFilters

func NoEmptyFilters(c Ctx, id SubID, f *filter.T) (reject bool, msg B)

NoEmptyFilters disallows filters that don't have at least a tag, a kind, an author or an id, or since or until.

func NoSearchQueries

func NoSearchQueries(c Ctx, id SubID, f *filter.T) (reject bool, msg B)

type Command

type Command struct {
	Name string
	Help string
	Func func(rl *R, prefix S, ev *event.T, cmd *Command, args ...S) (reply *event.T, err E)
}

type Config

type Config struct {
	InitCfgCmd       *InitCfg       `arg:"subcommand:initcfg" json:"-" help:"initialize relay configuration files"`
	ExportCmd        *ExportCmd     `arg:"subcommand:export" json:"-" help:"export database as line structured JSON"`
	ImportCmd        *ImportCmd     `arg:"subcommand:import" json:"-" help:"import data from line structured JSON"`
	PubKeyCmd        *PubKey        `arg:"subcommand:pubkey" json:"-" help:"print relay canister public key"`
	AddRelayCmd      *AddRelay      `arg:"subcommand:addrelay" json:"-" help:"add a relay to the cluster"`
	RemoveRelayCmd   *RemoveRelay   `arg:"subcommand:removerelay" json:"-" help:"remove a relay from the cluster"`
	GetPermissionCmd *GetPermission `arg:"subcommand:getpermission" json:"-" help:"get permission of a relay"`
	Wipe             *WipeBDB       `arg:"subcommand:wipebdb" json:"-" help:"empties local badger database (bdb)"`
	// Rescan           *RescanAC      `arg:"subcommand:rescan" json:"-" help:"clear and regenerate access counter records"`
	Listen       []string `arg:"-l,--listen,separate" json:"listen" help:"network address to listen on"`
	EventStore   string   `arg:"-e,--eventstore" json:"eventstore" help:"select event store backend [ic,badger,iconly]"`
	CanisterAddr string   `` /* 126-byte string literal not displayed */
	CanisterId   string   `arg:"-I,--canisterid" json:"canister_id" help:"IC canister ID to use"`
	Profile      string   `arg:"-p,--profile" default:"replicatr" json:"-"  help:"profile name to use for storage"` // default:"replicatr"
	Name         string   `arg:"-n,--name" json:"name"  help:"name of relay for NIP-11"`                            // default:"replicatr relay"
	Description  string   `arg:"-d,--description" json:"description" help:"description of relay for NIP-11"`
	Pubkey       string   `arg:"--pubkey" json:"pubkey" help:"public key of relay operator"`
	Contact      string   `arg:"-c,--contact" json:"contact,omitempty" help:"non-nostr relay operator contact details"`
	Icon         string   `arg:"-i,--icon" json:"icon"  help:"icon to show on relay information pages"`                // default:"https://i.nostr.build/n8vM.png"
	AuthRequired bool     `arg:"-a,--auth" json:"auth_required"  help:"NIP-42 authentication required for all access"` // default:"false"
	Public       bool     `arg:"--public" json:"public"  help:"allow public read access to users not on ACL"`          // default:"true"
	Owners       []string `arg:"-o,--owner,separate" json:"owners" help:"specify public keys of users with owner level permissions on relay"`
	SecKey       string   `` /* 131-byte string literal not displayed */
	// Whitelist permits ONLY inbound connections from specified IP addresses.
	Whitelist []string `arg:"-w,--whitelist,separate" json:"ip_whitelist" help:"IP addresses that are only allowed to access"`
	// AllowIPs is for bypassing authentication required for clients based on IP
	// addresses... primarily for testing with wireguard VPN clients run by the
	// developer, as these are stable, non-routeable addresses, this skips the
	// requirement enforced by AuthRequired.
	AllowIPs []string `arg:"-A,--allow,separate" json:"allow_ip" help:"IP addresses that are always allowed to access"`
	// DBSizeLimit configures a target maximum size to maintain the local
	// event store cache at, in megabytes (1,000,000 bytes).
	DBSizeLimit int `arg:"-S,--sizelimit" json:"db_size_limit" help:"set the maximum size of the badger event store in bytes"` // default:"0"
	// DBLowWater is the proportion of the DBSizeLimit to prune the database
	// down to when performing a garbage collection run.
	DBLowWater int `arg:"-L,--lowwater" json:"db_low_water" help:"set target percentage for database size during garbage collection"` // default:"86"
	// DBHighWater is the proportion of the DBSizeLimit at which a garbage
	// collection run is triggered.
	DBHighWater int `` // default:"92"
	/* 134-byte string literal not displayed */
	// GCFrequency is the frequency to run a check on the database size and
	// if it breaches DBHighWater to prune it back to DBLowWater percentage
	// of DBSizeLimit in minutes.
	GCFrequency int    `arg:"-G,--gcfreq" json:"gc_frequency" help:"frequency in seconds to check if database needs garbage collection"`            // default:"300"
	MaxProcs    int    `arg:"--maxprocs" json:"max_procs" help:"maximum number of goroutines to use"`                                               // default:"128"
	LogLevel    string `arg:"--loglevel"  help:"set log level [off,fatal,error,warn,info,debug,trace] (can also use GODEBUG environment variable)"` // default:"info"
	PProf       bool   `arg:"--pprof" help:"enable CPU and memory profiling"`
	GCRatio     int    `arg:"--gcratio" help:"set GC percentage for triggering GC sweeps"`             // default:"100"
	MemLimit    int64  `arg:"--memlimit" help:"set memory limit on process to constrain memory usage"` // default:"500000000"
	// PollFrequency is how often the L2 is queried for recent events
	PollFrequency time.Duration `arg:"--pollfrequency" help:"if a level 2 event store is enabled how often it polls"`
	// PollOverlap is the multiple of the PollFrequency within which polling the L2
	// is done to ensure any slow synchrony on the L2 is covered (2-4 usually)
	PollOverlap timestamp.T `arg:"--polloverlap" help:"if a level 2 event store is enabled, multiple of poll freq overlap to account for latency"`
}

func GetDefaultConfig

func GetDefaultConfig() *Config

func (*Config) Load

func (c *Config) Load(filename string) (err error)

func (*Config) Save

func (c *Config) Save(filename string) (err error)

type CountEvent

type CountEvent func(c Ctx, f *filter.T) (cnt int, err error)

CountEvent is a function to count the events that match the filter.

type CountEvents

type CountEvents []CountEvent

type Ctx

type Ctx = context.T

type E

type E = error

func EncryptDM

func EncryptDM(ev *event.T, meSec, youPub B) (evo *event.T, err E)

EncryptDM encrypts a DM, kind 4, 1059 or 1060

type EV

type EV = *event.T

type Event

type Event func(c Ctx, ev EV) E

Event are a closure type that responds to an event.

type Events

type Events []Event

type ExportCmd

type ExportCmd struct {
	ToFile string `arg:"-f,--tofile" help:"write to file instead of stdout"`
}

type GetPermission

type GetPermission struct {
}

type Handle

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

func H

func H(rl *R, c Ctx, ws WS, svcURL S, kill func()) (h *Handle)

func (*Handle) H

func (h *Handle) H() (rl *R, c Ctx, ws WS, svcURL S, kill func())

type Handler

type Handler = http.HandlerFunc

type Headers

type Headers [][]S

func (Headers) Len

func (h Headers) Len() int

func (Headers) Less

func (h Headers) Less(i, j int) bool

func (Headers) Swap

func (h Headers) Swap(i, j int)

type Hook

type Hook func(c Ctx)

Hook is a function that does anything but responds to a context cancel from the controlling process so it can be shut down along with the calling process.

type Hooks

type Hooks []Hook

type ImportCmd

type ImportCmd struct {
	FromFile     []string `arg:"-f,--fromfile,separate" help:"read from files instead of stdin (can use flag repeatedly for multiple files)"`
	StartingFrom int      `arg:"--importfrom" help:"start scanning import file from this position in bytes"`
}

type InitCfg

type InitCfg struct{}

type Listener

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

type ListenerMap

type ListenerMap = *xsync.MapOf[S, *Listener]

type N added in v0.0.14

type N = int

type Notice

type Notice = noticeenvelope.T

type OK

type OK = okenvelope.T

type OnEventSaved

type OnEventSaved func(c Ctx, ev EV)

OnEventSaved runs when an event is stored.

type OnEventSaveds

type OnEventSaveds []OnEventSaved

type OverrideDeletion

type OverrideDeletion func(c Ctx, tgt, del *event.T) (ok bool, msg B)

OverrideDeletion checks a delete request and overrides it according to policy.

type OverrideDeletions

type OverrideDeletions []OverrideDeletion

type OverwriteFilter

type OverwriteFilter func(c Ctx, f *filter.T)

OverwriteFilter rewrites the content of a filter according to policy.

type OverwriteFilters

type OverwriteFilters []OverwriteFilter

type OverwriteRelayInfo

type OverwriteRelayInfo func(c Ctx, r Req, info *relayinfo.T) *relayinfo.T

OverwriteRelayInfo is a function that can be provided to rewrite the nip-11 relay information document.

type OverwriteRelayInfos

type OverwriteRelayInfos []OverwriteRelayInfo

type OverwriteResponseEvent

type OverwriteResponseEvent func(c Ctx, ev EV)

OverwriteResponseEvent rewrites an event response.

type OverwriteResponseEvents

type OverwriteResponseEvents []OverwriteResponseEvent

type PubKey

type PubKey struct{}

type QueryEvent

type QueryEvent func(c Ctx, f *filter.T) (C event.C, err error)

QueryEvent is a closure for making a query to the event store.

type QueryEvents

type QueryEvents []QueryEvent

type R

type R struct {
	Ctx            Ctx
	Cancel         context.F
	WG             *sync.WaitGroup
	Router         *http.ServeMux
	Info           *relayinfo.T
	Config         *Config
	MaxMessageSize int64 // Maximum message size allowed from peer.
	RelayPubHex    S
	RelayNpub      S
	OverwriteRelayInfos
	OverwriteResponseEvents
	OverwriteReqFilter   OverwriteFilters
	OverwriteCountFilter OverwriteFilters
	OverrideDeletions
	RejectEvents
	RejectReqFilters   RejectFilters
	RejectCountFilters RejectFilters
	QueryEvents
	StoreEvents  Events
	DeleteEvents Events
	CountEvents
	OnEventSaveds
	OnConnects    Hooks
	OnDisconnects Hooks
	WriteWait     time.Duration // WriteWait is the time allowed to write a message to the peer.
	PongWait      time.Duration // PongWait is the time allowed to read the next pong message from the peer.
	PingPeriod    time.Duration // PingPeriod is the time between pings. Must be less than pongWait.

	Whitelist []S    // whitelist of allowed IPs for access
	ACL       *acl.T // ACL is the list of users and privileges on this relay
	// contains filtered or unexported fields
}

R is the data structure holding state of the relay.

func NewRelay

func NewRelay(c Ctx, cancel context.F, inf *relayinfo.T, conf *Config) (r *R)

func (*R) AddEvent

func (rl *R) AddEvent(c Ctx, ev EV) (err E)

AddEvent sends an event through then normal add pipeline, as if it was received from a websocket.

func (*R) AuthCheck

func (rl *R) AuthCheck(c Ctx)

AuthCheck sends out a request if auth is required (this is an OnConnects method). It just asks for auth if enabled, saving the client time waiting until after sending a req.

func (*R) BroadcastEvent

func (rl *R) BroadcastEvent(ev EV)

BroadcastEvent emits an event to all listeners whose filters' match, skipping all filters and actions it also doesn't attempt to store the event or trigger any reactions or callbacks

func (*R) Chat

func (rl *R) Chat(c Ctx, ev *event.T) (err E)

Chat implements the control interface, intercepting kind 4 encrypted direct messages and processing them if they are for the relay's pubkey

func (*R) Deny

func (rl *R) Deny(ws WS) (deny bool)

func (*R) Export

func (rl *R) Export(db *badger.Backend, filename string, wg *sync.WaitGroup)

Export prints the JSON of all events or writes them to a file.

func (*R) FilterPrivileged

func (rl *R) FilterPrivileged(c Ctx, id SubID, f *filter.T) (reject bool, msg B)

FilterPrivileged interacts between filters and the privileges of the users according to the access control settings of the relay, checking whether the request is authorised, if not, requesting authorisation.

If there is an ACL configured, it acts as a whitelist, no access without being on the ACL.

If the message is a private message, only authenticated users may get these events who also match one of the parties in the conversation.

func (*R) HandleNIP11

func (rl *R) HandleNIP11(w Responder, r Req)

HandleNIP11 is a http handler for NIP-11 relayinfo.T requests

func (*R) HandleWebsocket

func (rl *R) HandleWebsocket(svcURL S) func(w Responder, r Req)

HandleWebsocket is a http handler that accepts and manages websocket connections.

func (*R) Import

func (rl *R) Import(db eventstore.Store, files []string, wg *sync.WaitGroup, start int)

Import a collection of JSON events from stdin or from one or more files, line structured JSON.

func (*R) Init

func (rl *R) Init()

func (*R) IsAuthed

func (rl *R) IsAuthed(c Ctx, envType S) bool

func (*R) Kill

func (rl *R) Kill(c Ctx, cancel context.F, ws WS, ticker *time.Ticker) func()

func (*R) OverrideDelete

func (rl *R) OverrideDelete(c Ctx, tgt, del EV) (ok bool, msg B)

OverrideDelete decides whether to veto a delete event.

Temporarily removing delete functionality until a proper tombstone/indexing strategy is devised to filter out these events from database results.

func (*R) ServeHTTP

func (rl *R) ServeHTTP(w Responder, r Req)

ServeHTTP implements http.Handler enveloper.

This is the main starting function of the relay. This launches HandleWebsocket which runs the message handling main loop.

func (*R) Wipe

func (rl *R) Wipe(store *bdb.Backend) (err error)

Wipe clears the badgerDB local event store/cache.

type RejectEvent

type RejectEvent func(c Ctx, ev EV) (rej bool, msg string)

RejectEvent checks whether policy would reject an event.

type RejectEvents

type RejectEvents []RejectEvent

type RejectFilter

type RejectFilter func(c Ctx, id SubID, f *filter.T) (reject bool, msg B)

RejectFilter is a closure to examine a filter and if it is invalid, reject it.

type RejectFilters

type RejectFilters []RejectFilter

type RemoveRelay

type RemoveRelay struct {
	PubKey string `arg:"--removepubkey" help:"public key of client to remove"`
}

type Req

type Req = *http.Request

type RescanAC

type RescanAC struct{}

type Responder

type Responder = http.ResponseWriter

type S

type S = string

type SubID

type SubID = *subscriptionid.T

type WS

type WS = *relayws.WS

func GetConnection

func GetConnection(c Ctx) WS

type WipeBDB

type WipeBDB struct{}

Directories

Path Synopsis
IC
badger/keys
Package keys is a composable framework for constructing badger keys from fields of events.
Package keys is a composable framework for constructing badger keys from fields of events.
l2
Package l2 is a testing data store that implements a level 2 cache for events with a badger eventstore.
Package l2 is a testing data store that implements a level 2 cache for events with a badger eventstore.

Jump to

Keyboard shortcuts

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