app

package
v0.25.6 Latest Latest
Warning

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

Go to latest
Published: Nov 5, 2025 License: Unlicense Imports: 76 Imported by: 0

Documentation

Index

Constants

View Source
const (
	DefaultWriteWait      = 10 * time.Second
	DefaultPongWait       = 60 * time.Second
	DefaultPingWait       = DefaultPongWait / 2
	DefaultWriteTimeout   = 3 * time.Second
	DefaultMaxMessageSize = 512000 // Match khatru's MaxMessageSize
	// ClientMessageSizeLimit is the maximum message size that clients can handle
	// This is set to 100MB to allow large messages
	ClientMessageSizeLimit = 100 * 1024 * 1024 // 100MB
)
View Source
const Type = "socketapi"

Variables

View Source
var Ok = OKs{
	Ok: func(
		l *Listener, env eventenvelope.I, format string,
		params ...any,
	) (err error) {
		return okenvelope.NewFrom(
			env.Id(), true, []byte{},
		).Write(l)
	},
	AuthRequired: func(
		l *Listener, env eventenvelope.I, format string,
		params ...any,
	) (err error) {
		return okenvelope.NewFrom(
			env.Id(), false, reason.AuthRequired.F(format, params...),
		).Write(l)
	},
	PoW: func(
		l *Listener, env eventenvelope.I, format string,
		params ...any,
	) (err error) {
		return okenvelope.NewFrom(
			env.Id(), false, reason.PoW.F(format, params...),
		).Write(l)
	},
	Duplicate: func(
		l *Listener, env eventenvelope.I, format string,
		params ...any,
	) (err error) {
		return okenvelope.NewFrom(
			env.Id(), false, reason.Duplicate.F(format, params...),
		).Write(l)
	},
	Blocked: func(
		l *Listener, env eventenvelope.I, format string,
		params ...any,
	) (err error) {
		return okenvelope.NewFrom(
			env.Id(), false, reason.Blocked.F(format, params...),
		).Write(l)
	},
	RateLimited: func(
		l *Listener, env eventenvelope.I, format string,
		params ...any,
	) (err error) {
		return okenvelope.NewFrom(
			env.Id(), false, reason.RateLimited.F(format, params...),
		).Write(l)
	},
	Invalid: func(
		l *Listener, env eventenvelope.I, format string,
		params ...any,
	) (err error) {
		return okenvelope.NewFrom(
			env.Id(), false, reason.Invalid.F(format, params...),
		).Write(l)
	},
	Error: func(
		l *Listener, env eventenvelope.I, format string,
		params ...any,
	) (err error) {
		return okenvelope.NewFrom(
			env.Id(), false, reason.Error.F(format, params...),
		).Write(l)
	},
	Unsupported: func(
		l *Listener, env eventenvelope.I, format string,
		params ...any,
	) (err error) {
		return okenvelope.NewFrom(
			env.Id(), false, reason.Unsupported.F(format, params...),
		).Write(l)
	},
	Restricted: func(
		l *Listener, env eventenvelope.I, format string,
		params ...any,
	) (err error) {
		return okenvelope.NewFrom(
			env.Id(), false, reason.Restricted.F(format, params...),
		).Write(l)
	},
}

Ok provides a collection of handler functions for managing different types of operational outcomes, each corresponding to specific error or status conditions such as authentication requirements, rate limiting, and invalid inputs.

Functions

func GetReactAppFS added in v0.6.0

func GetReactAppFS() http.FileSystem

GetReactAppFS returns a http.FileSystem from the embedded React app

func GetRemoteFromReq

func GetRemoteFromReq(r *http.Request) (rr string)

GetRemoteFromReq retrieves the originating IP address of the client from an HTTP request, considering standard and non-standard proxy headers.

Parameters

  • r: The HTTP request object containing details of the client and routing information.

Return Values

  • rr: A string value representing the IP address of the originating remote client.

Expected behaviour

The function first checks for the standardized "Forwarded" header (RFC 7239) to identify the original client IP. If that isn't available, it falls back to the "X-Forwarded-For" header. If both headers are absent, it defaults to using the request's RemoteAddr.

For the "Forwarded" header, it extracts the client IP from the "for" parameter. For the "X-Forwarded-For" header, if it contains one IP, it returns that. If it contains two IPs, it returns the second.

func LogProxyInfo added in v0.9.3

func LogProxyInfo(r *http.Request, prefix string)

LogProxyInfo logs comprehensive proxy information for debugging

func Run

func Run(
	ctx context.Context, cfg *config.C, db *database.D,
) (quit chan struct{})

func ServeEmbeddedWeb added in v0.11.0

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

ServeEmbeddedWeb serves the embedded web application

func TLSConfig added in v0.19.0

func TLSConfig(m *autocert.Manager, certs ...string) (tc *tls.Config)

TLSConfig returns a TLS configuration that works with LetsEncrypt automatic SSL cert issuer as well as any provided certificate files from providers.

The certs are provided in the form of paths where .pem and .key files exist

func ValidateTLSConfig added in v0.19.0

func ValidateTLSConfig(domains []string, certs []string) (err error)

ValidateTLSConfig checks if the TLS configuration is valid

Types

type Listener

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

func (*Listener) Ctx added in v0.4.0

func (l *Listener) Ctx() context.Context

Ctx returns the listener's context, but creates a new context for each operation to prevent cancellation from affecting subsequent operations

func (*Listener) DroppedMessages added in v0.24.1

func (l *Listener) DroppedMessages() int

DroppedMessages returns the total number of messages that were dropped because the message processing queue was full.

func (*Listener) GetSerialsFromFilter

func (l *Listener) GetSerialsFromFilter(f *filter.F) (
	sers types.Uint40s, err error,
)

func (*Listener) HandleAuth

func (l *Listener) HandleAuth(b []byte) (err error)

func (*Listener) HandleClose

func (l *Listener) HandleClose(req []byte) (err error)

HandleClose processes a CLOSE envelope by unmarshalling the request, validates the presence of an <id> field, and signals cancellation for the associated listener through the server's publisher mechanism.

func (*Listener) HandleCount added in v0.10.0

func (l *Listener) HandleCount(msg []byte) (err error)

HandleCount processes a COUNT envelope by parsing the request, verifying permissions, invoking the database CountEvents for each provided filter, and responding with a COUNT response containing the aggregate count.

func (*Listener) HandleDelete

func (l *Listener) HandleDelete(env *eventenvelope.Submission) (err error)

func (*Listener) HandleEvent

func (l *Listener) HandleEvent(msg []byte) (err error)

func (*Listener) HandleMessage

func (l *Listener) HandleMessage(msg []byte, remote string)

func (*Listener) HandleReq

func (l *Listener) HandleReq(msg []byte) (err error)

func (*Listener) QueryAllVersions added in v0.17.4

func (l *Listener) QueryAllVersions(ctx context.Context, f *filter.F) (event.S, error)

QueryAllVersions queries events using the database QueryAllVersions method

func (*Listener) QueryEvents added in v0.17.4

func (l *Listener) QueryEvents(ctx context.Context, f *filter.F) (event.S, error)

QueryEvents queries events using the database QueryEvents method

func (*Listener) QueueMessage added in v0.24.1

func (l *Listener) QueueMessage(data []byte, remote string) bool

QueueMessage queues a message for asynchronous processing. Returns true if the message was queued, false if the queue was full.

func (*Listener) RemainingCapacity added in v0.24.1

func (l *Listener) RemainingCapacity() int

RemainingCapacity returns the number of slots available in the message processing queue.

func (*Listener) Write

func (l *Listener) Write(p []byte) (n int, err error)

func (*Listener) WriteControl added in v0.23.0

func (l *Listener) WriteControl(messageType int, data []byte, deadline time.Time) (err error)

WriteControl sends a control message through the write channel

type Map

type Map map[*websocket.Conn]map[string]Subscription

Map is a map of filters associated with a collection of ws.Listener connections.

type NIP86Request added in v0.17.0

type NIP86Request struct {
	Method string        `json:"method"`
	Params []interface{} `json:"params"`
}

NIP86Request represents a NIP-86 JSON-RPC request

type NIP86Response added in v0.17.0

type NIP86Response struct {
	Result interface{} `json:"result,omitempty"`
	Error  string      `json:"error,omitempty"`
}

NIP86Response represents a NIP-86 JSON-RPC response

type OK

type OK func(
	l *Listener, env eventenvelope.I, format string, params ...any,
) (err error)

OK represents a function that processes events or operations, using provided parameters to generate formatted messages and return errors if any issues occur during processing.

type OKs

type OKs struct {
	Ok           OK
	AuthRequired OK
	PoW          OK
	Duplicate    OK
	Blocked      OK
	RateLimited  OK
	Invalid      OK
	Error        OK
	Unsupported  OK
	Restricted   OK
}

OKs provides a collection of handler functions for managing different types of operational outcomes, each corresponding to specific error or status conditions such as authentication requirements, rate limiting, and invalid inputs.

type P

type P struct {

	// Mx is the mutex for the Map.
	Mx sync.RWMutex
	// Map is the map of subscribers and subscriptions from the websocket api.
	Map
	// WriteChans maps websocket connections to their write channels
	WriteChans WriteChanMap
	// contains filtered or unexported fields
}

P is a structure that manages subscriptions and associated filters for websocket listeners. It uses a mutex to synchronize access to a map storing subscriber connections and their filter configurations.

func NewPublisher

func NewPublisher(c context.Context) (publisher *P)

func (*P) Deliver

func (p *P) Deliver(ev *event.E)

Deliver processes and distributes an event to all matching subscribers based on their filter configurations.

Parameters

- ev (*event.E): The event to be delivered to subscribed clients.

Expected behaviour

Delivers the event to all subscribers whose filters match the event. It applies authentication checks if required by the server and skips delivery for unauthenticated users when events are privileged.

func (*P) GetWriteChan added in v0.23.0

func (p *P) GetWriteChan(conn *websocket.Conn) (chan publish.WriteRequest, bool)

GetWriteChan returns the write channel for a websocket connection

func (*P) Receive

func (p *P) Receive(msg typer.T)

Receive handles incoming messages to manage websocket listener subscriptions and associated filters.

Parameters

- msg (publisher.Message): The incoming message to process; expected to be of type *W to trigger subscription management actions.

Expected behaviour

- Checks if the message is of type *W.

- If Cancel is true, removes a subscriber by ID or the entire listener.

- Otherwise, adds the subscription to the map under a mutex lock.

- Logs actions related to subscription creation or removal.

func (*P) SetWriteChan added in v0.23.0

func (p *P) SetWriteChan(conn *websocket.Conn, writeChan chan publish.WriteRequest)

SetWriteChan stores the write channel for a websocket connection If writeChan is nil, the entry is removed from the map

func (*P) Type

func (p *P) Type() (typeName string)

type PaymentProcessor added in v0.8.0

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

PaymentProcessor handles NWC payment notifications and updates subscriptions

func NewPaymentProcessor added in v0.8.0

func NewPaymentProcessor(
	ctx context.Context, cfg *config.C, db *database.D,
) (pp *PaymentProcessor, err error)

NewPaymentProcessor creates a new payment processor

func (*PaymentProcessor) CreateWelcomeNote added in v0.8.0

func (pp *PaymentProcessor) CreateWelcomeNote(userPubkey []byte) error

CreateWelcomeNote creates a welcome note for first-time users with private tag for authorization

func (*PaymentProcessor) SetDashboardURL added in v0.8.2

func (pp *PaymentProcessor) SetDashboardURL(url string)

SetDashboardURL sets the dynamic dashboard URL based on HTTP request

func (*PaymentProcessor) Start added in v0.8.0

func (pp *PaymentProcessor) Start() error

Start begins listening for payment notifications

func (*PaymentProcessor) Stop added in v0.8.0

func (pp *PaymentProcessor) Stop()

Stop gracefully stops the payment processor

func (*PaymentProcessor) UpdateRelayProfile added in v0.8.4

func (pp *PaymentProcessor) UpdateRelayProfile() error

UpdateRelayProfile creates or updates the relay's kind 0 profile with subscription information

type Server

type Server struct {
	Config *config.C
	Ctx    context.Context

	Admins [][]byte
	Owners [][]byte
	*database.D
	// contains filtered or unexported fields
}

func (*Server) DashboardURL added in v0.8.2

func (s *Server) DashboardURL(req *http.Request) (url string)

func (*Server) HandleRelayInfo

func (s *Server) HandleRelayInfo(w http.ResponseWriter, r *http.Request)

HandleRelayInfo generates and returns a relay information document in JSON format based on the server's configuration and supported NIPs.

Parameters

  • w: HTTP response writer used to send the generated document.

  • r: HTTP request object containing incoming client request data.

Expected Behaviour

The function constructs a relay information document using either the Informer interface implementation or predefined server configuration. It returns this document as a JSON response to the client.

func (*Server) HandleWebsocket

func (s *Server) HandleWebsocket(w http.ResponseWriter, r *http.Request)

func (*Server) Pinger

func (s *Server) Pinger(
	ctx context.Context, listener *Listener, ticker *time.Ticker,
)

func (*Server) ServeHTTP

func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)

func (*Server) ServiceURL

func (s *Server) ServiceURL(req *http.Request) (url string)

func (*Server) UserInterface added in v0.6.0

func (s *Server) UserInterface()

UserInterface sets up a basic Nostr NDK interface that allows users to log into the relay user interface

func (*Server) WebSocketURL added in v0.11.0

func (s *Server) WebSocketURL(req *http.Request) (url string)

type SprocketManager added in v0.12.0

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

SprocketManager handles sprocket script execution and management

func NewSprocketManager added in v0.12.0

func NewSprocketManager(ctx context.Context, appName string, enabled bool) *SprocketManager

NewSprocketManager creates a new sprocket manager

func (*SprocketManager) DeleteSprocketVersion added in v0.12.0

func (sm *SprocketManager) DeleteSprocketVersion(filename string) error

DeleteSprocketVersion deletes a specific sprocket version

func (*SprocketManager) GetSprocketStatus added in v0.12.0

func (sm *SprocketManager) GetSprocketStatus() map[string]interface{}

GetSprocketStatus returns the current status of the sprocket

func (*SprocketManager) GetSprocketVersions added in v0.12.0

func (sm *SprocketManager) GetSprocketVersions() ([]map[string]interface{}, error)

GetSprocketVersions returns a list of all sprocket script versions

func (*SprocketManager) IsDisabled added in v0.12.2

func (sm *SprocketManager) IsDisabled() bool

IsDisabled returns whether sprocket is disabled due to failure

func (*SprocketManager) IsEnabled added in v0.12.0

func (sm *SprocketManager) IsEnabled() bool

IsEnabled returns whether sprocket is enabled

func (*SprocketManager) IsRunning added in v0.12.0

func (sm *SprocketManager) IsRunning() bool

IsRunning returns whether sprocket is currently running

func (*SprocketManager) ProcessEvent added in v0.12.0

func (sm *SprocketManager) ProcessEvent(evt *event.E) (*SprocketResponse, error)

ProcessEvent sends an event to the sprocket script and waits for a response

func (*SprocketManager) RestartSprocket added in v0.12.0

func (sm *SprocketManager) RestartSprocket() error

RestartSprocket stops and starts the sprocket script

func (*SprocketManager) Shutdown added in v0.12.0

func (sm *SprocketManager) Shutdown()

Shutdown gracefully shuts down the sprocket manager

func (*SprocketManager) StartSprocket added in v0.12.0

func (sm *SprocketManager) StartSprocket() error

StartSprocket starts the sprocket script

func (*SprocketManager) StopSprocket added in v0.12.0

func (sm *SprocketManager) StopSprocket() error

StopSprocket stops the sprocket script gracefully, with SIGKILL fallback

func (*SprocketManager) UpdateSprocket added in v0.12.0

func (sm *SprocketManager) UpdateSprocket(scriptContent string) error

UpdateSprocket updates the sprocket script and restarts it with zero downtime

type SprocketResponse added in v0.12.0

type SprocketResponse struct {
	ID     string `json:"id"`
	Action string `json:"action"` // accept, reject, or shadowReject
	Msg    string `json:"msg"`    // NIP-20 response message (only used for reject)
}

SprocketResponse represents a response from the sprocket script

type Subscription

type Subscription struct {
	AuthedPubkey []byte
	*filter.S
	// contains filtered or unexported fields
}

type W

type W struct {
	*websocket.Conn

	// If Cancel is true, this is a close command.
	Cancel bool

	// Id is the subscription Id. If Cancel is true, cancel the named
	// subscription, otherwise, cancel the publisher for the socket.
	Id string

	// The Receiver holds the event channel for receiving notifications or data
	// relevant to this WebSocket connection.
	Receiver event.C

	// Filters holds a collection of filters used to match or process events
	// associated with this WebSocket connection. It is used to determine which
	// notifications or data should be received by the subscriber.
	Filters *filter.S

	// AuthedPubkey is the authenticated pubkey associated with the listener (if any).
	AuthedPubkey []byte
	// contains filtered or unexported fields
}

func (*W) Type

func (w *W) Type() (typeName string)

type WriteChanMap added in v0.23.0

type WriteChanMap map[*websocket.Conn]chan publish.WriteRequest

WriteChanMap maps websocket connections to their write channels

Source Files

  • blossom.go
  • handle-auth.go
  • handle-close.go
  • handle-count.go
  • handle-delete.go
  • handle-event.go
  • handle-message.go
  • handle-nip86.go
  • handle-relayinfo.go
  • handle-req.go
  • handle-websocket.go
  • helpers.go
  • listener.go
  • main.go
  • ok.go
  • payment_processor.go
  • publisher.go
  • server.go
  • sprocket.go
  • tls.go
  • web.go

Directories

Path Synopsis
Package config provides a go-simpler.org/env configuration table and helpers for working with the list of key/value lists stored in .env files.
Package config provides a go-simpler.org/env configuration table and helpers for working with the list of key/value lists stored in .env files.

Jump to

Keyboard shortcuts

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