nrc

package
v0.48.10 Latest Latest
Warning

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

Go to latest
Published: Jan 9, 2026 License: Unlicense Imports: 22 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// KindNRCRequest is the event kind for NRC requests.
	KindNRCRequest = 24891
	// KindNRCResponse is the event kind for NRC responses.
	KindNRCResponse = 24892
)
View Source
const (
	// DefaultSessionTimeout is the default inactivity timeout for sessions.
	DefaultSessionTimeout = 30 * time.Minute
	// DefaultMaxSubscriptions is the default maximum subscriptions per session.
	DefaultMaxSubscriptions = 100
)

Variables

View Source
var (
	// ErrUnauthorized is returned when a client is not authorized.
	ErrUnauthorized = errors.New("unauthorized")
	// ErrInvalidSession is returned when a session ID is invalid or not found.
	ErrInvalidSession = errors.New("invalid session")
	// ErrTooManySubscriptions is returned when a session has too many subscriptions.
	ErrTooManySubscriptions = errors.New("too many subscriptions")
	// ErrInvalidMessageType is returned when the message type is invalid.
	ErrInvalidMessageType = errors.New("invalid message type")
	// ErrSessionExpired is returned when a session has expired.
	ErrSessionExpired = errors.New("session expired")
	// ErrDecryptionFailed is returned when message decryption fails.
	ErrDecryptionFailed = errors.New("decryption failed")
	// ErrEncryptionFailed is returned when message encryption fails.
	ErrEncryptionFailed = errors.New("encryption failed")
	// ErrRelayConnectionFailed is returned when connection to the local relay fails.
	ErrRelayConnectionFailed = errors.New("relay connection failed")
	// ErrRendezvousConnectionFailed is returned when connection to the rendezvous relay fails.
	ErrRendezvousConnectionFailed = errors.New("rendezvous relay connection failed")
)

Functions

func GenerateCATConnectionURI

func GenerateCATConnectionURI(relayPubkey []byte, rendezvousRelay string, mintURL string) (uri string, err error)

GenerateCATConnectionURI creates a new NRC connection URI for CAT authentication.

func GenerateConnectionURI

func GenerateConnectionURI(relayPubkey []byte, rendezvousRelay string, deviceName string) (uri string, secret []byte, err error)

GenerateConnectionURI creates a new NRC connection URI with a random secret.

func MarshalResponseContent

func MarshalResponseContent(resp *ResponseMessage) ([]byte, error)

MarshalResponseContent marshals an NRC response for encryption.

Types

type AuthMode

type AuthMode int

AuthMode defines the authentication mode for NRC connections.

const (
	// AuthModeSecret uses a shared secret for authentication.
	AuthModeSecret AuthMode = iota
	// AuthModeCAT uses Cashu Access Tokens for authentication.
	AuthModeCAT
)

type Bridge

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

Bridge connects a private relay to a public rendezvous relay.

func NewBridge

func NewBridge(config *BridgeConfig) *Bridge

NewBridge creates a new NRC bridge.

func (*Bridge) AddAuthorizedSecret

func (b *Bridge) AddAuthorizedSecret(pubkeyHex, deviceName string)

AddAuthorizedSecret adds an authorized secret (derived pubkey).

func (*Bridge) ListAuthorizedSecrets

func (b *Bridge) ListAuthorizedSecrets() map[string]string

ListAuthorizedSecrets returns a copy of the authorized secrets map.

func (*Bridge) RemoveAuthorizedSecret

func (b *Bridge) RemoveAuthorizedSecret(pubkeyHex string)

RemoveAuthorizedSecret removes an authorized secret.

func (*Bridge) SessionCount

func (b *Bridge) SessionCount() int

SessionCount returns the number of active sessions.

func (*Bridge) Start

func (b *Bridge) Start() error

Start starts the bridge and begins listening for NRC requests.

func (*Bridge) Stop

func (b *Bridge) Stop()

Stop stops the bridge.

func (*Bridge) UpdateAuthorizedSecrets

func (b *Bridge) UpdateAuthorizedSecrets(secrets map[string]string)

UpdateAuthorizedSecrets updates the map of authorized secrets. This allows dynamic management of authorized connections through the UI.

type BridgeConfig

type BridgeConfig struct {
	// RendezvousURL is the WebSocket URL of the public relay.
	RendezvousURL string
	// LocalRelayURL is the WebSocket URL of the local private relay.
	LocalRelayURL string
	// Signer is the relay's signer for signing response events.
	Signer signer.I
	// AuthorizedSecrets maps derived pubkeys to device names (secret-based auth).
	AuthorizedSecrets map[string]string
	// CashuVerifier is used for CAT token verification (optional).
	CashuVerifier *verifier.Verifier
	// SessionTimeout is the inactivity timeout for sessions.
	SessionTimeout time.Duration
}

BridgeConfig holds configuration for the NRC bridge.

type Client

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

Client connects to a private relay through the NRC tunnel.

func NewClient

func NewClient(connectionURI string) (*Client, error)

NewClient creates a new NRC client from a connection URI.

func (*Client) Close

func (c *Client) Close()

Close closes the client connection.

func (*Client) Connect

func (c *Client) Connect(ctx context.Context) error

Connect establishes the connection to the rendezvous relay.

func (*Client) Count

func (c *Client) Count(ctx context.Context, subID string, filters ...*filter.F) (int64, error)

Count sends a COUNT request to the private relay.

func (*Client) Publish

func (c *Client) Publish(ctx context.Context, ev *event.E) (bool, string, error)

Publish publishes an event to the private relay.

func (*Client) RelayURL

func (c *Client) RelayURL() string

RelayURL returns a pseudo-URL for this NRC connection.

func (*Client) Subscribe

func (c *Client) Subscribe(ctx context.Context, subID string, filters ...*filter.F) (<-chan *event.E, error)

Subscribe creates a subscription to the private relay.

func (*Client) Unsubscribe

func (c *Client) Unsubscribe(ctx context.Context, subID string) error

Unsubscribe closes a subscription.

type ConnectionURI

type ConnectionURI struct {
	// RelayPubkey is the public key of the private relay (32 bytes).
	RelayPubkey []byte
	// RendezvousRelay is the WebSocket URL of the public relay.
	RendezvousRelay string
	// AuthMode indicates whether to use secret or CAT authentication.
	AuthMode AuthMode
	// DeviceName is an optional human-readable device identifier.
	DeviceName string

	// CAT-based authentication fields
	MintURL string
	// contains filtered or unexported fields
}

ConnectionURI represents a parsed nostr+relayconnect:// URI.

func ParseConnectionURI

func ParseConnectionURI(nrcURI string) (conn *ConnectionURI, err error)

ParseConnectionURI parses a nostr+relayconnect:// URI.

Secret-based URI format:

nostr+relayconnect://<relay-pubkey>?relay=<rendezvous-relay>&secret=<client-secret>[&name=<device-name>]

CAT-based URI format:

nostr+relayconnect://<relay-pubkey>?relay=<rendezvous-relay>&auth=cat&mint=<mint-url>

func (*ConnectionURI) GetClientSigner

func (c *ConnectionURI) GetClientSigner() signer.I

GetClientSigner returns the signer derived from the secret (secret-based auth only).

func (*ConnectionURI) GetConversationKey

func (c *ConnectionURI) GetConversationKey() []byte

GetConversationKey returns the NIP-44 conversation key (secret-based auth only).

type RequestMessage

type RequestMessage struct {
	Type    string // EVENT, REQ, CLOSE, AUTH, COUNT
	Payload []any
}

RequestMessage represents a parsed NRC request message.

func ParseRequestContent

func ParseRequestContent(content []byte) (*RequestMessage, error)

ParseRequestContent parses the decrypted content of an NRC request.

type ResponseMessage

type ResponseMessage struct {
	Type    string // EVENT, OK, EOSE, NOTICE, CLOSED, COUNT, AUTH
	Payload []any
}

ResponseMessage represents an NRC response message to be sent.

type Session

type Session struct {
	// ID is the unique session identifier.
	ID string
	// ClientPubkey is the public key of the connected client.
	ClientPubkey []byte
	// ConversationKey is the NIP-44 conversation key for this session.
	ConversationKey []byte
	// DeviceName is the optional device identifier.
	DeviceName string
	// AuthMode is the authentication mode used.
	AuthMode AuthMode

	// CreatedAt is when the session was created.
	CreatedAt time.Time
	// LastActivity is the timestamp of the last activity.
	LastActivity time.Time
	// contains filtered or unexported fields
}

Session represents an NRC client session through the tunnel.

func NewSession

func NewSession(id string, clientPubkey, conversationKey []byte, authMode AuthMode, deviceName string) *Session

NewSession creates a new session.

func (*Session) AddSubscription

func (s *Session) AddSubscription(subID string) error

AddSubscription adds a new subscription to the session.

func (*Session) Close

func (s *Session) Close()

Close closes the session and cleans up resources.

func (*Session) Context

func (s *Session) Context() context.Context

Context returns the session's context.

func (*Session) Events

func (s *Session) Events() <-chan *SessionEvent

Events returns the channel for receiving events destined for this session.

func (*Session) GetSubscription

func (s *Session) GetSubscription(subID string) *Subscription

GetSubscription returns a subscription by ID.

func (*Session) HasSubscription

func (s *Session) HasSubscription(subID string) bool

HasSubscription checks if a subscription exists.

func (*Session) IncrementEventCount

func (s *Session) IncrementEventCount(subID string)

IncrementEventCount increments the event count for a subscription.

func (*Session) IsExpired

func (s *Session) IsExpired(timeout time.Duration) bool

IsExpired checks if the session has been inactive too long.

func (*Session) MarkEOSE

func (s *Session) MarkEOSE(subID string)

MarkEOSE marks a subscription as having sent EOSE.

func (*Session) RemoveSubscription

func (s *Session) RemoveSubscription(subID string)

RemoveSubscription removes a subscription from the session.

func (*Session) SendEvent

func (s *Session) SendEvent(ev *SessionEvent) bool

SendEvent sends an event to the session's event channel.

func (*Session) SubscriptionCount

func (s *Session) SubscriptionCount() int

SubscriptionCount returns the number of active subscriptions.

func (*Session) Touch

func (s *Session) Touch()

Touch updates the last activity timestamp.

type SessionEvent

type SessionEvent struct {
	// Type is the response type (EVENT, OK, EOSE, NOTICE, CLOSED, COUNT, AUTH).
	Type string
	// Payload is the response payload array.
	Payload []any
	// RequestEventID is the ID of the request event this responds to (if applicable).
	RequestEventID string
}

SessionEvent wraps a relay response for delivery to the client.

type SessionManager

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

SessionManager manages multiple NRC sessions.

func NewSessionManager

func NewSessionManager(timeout time.Duration) *SessionManager

NewSessionManager creates a new session manager.

func (*SessionManager) CleanupExpired

func (m *SessionManager) CleanupExpired() int

CleanupExpired removes expired sessions.

func (*SessionManager) Close

func (m *SessionManager) Close()

Close closes all sessions.

func (*SessionManager) Count

func (m *SessionManager) Count() int

Count returns the number of active sessions.

func (*SessionManager) Get

func (m *SessionManager) Get(sessionID string) *Session

Get returns a session by ID.

func (*SessionManager) GetOrCreate

func (m *SessionManager) GetOrCreate(sessionID string, clientPubkey, conversationKey []byte, authMode AuthMode, deviceName string) *Session

GetOrCreate gets an existing session or creates a new one.

func (*SessionManager) Remove

func (m *SessionManager) Remove(sessionID string)

Remove removes a session.

type Subscription

type Subscription struct {
	// ID is the client's subscription ID.
	ID string
	// CreatedAt is when the subscription was created.
	CreatedAt time.Time
	// EventCount tracks how many events have been sent.
	EventCount int64
	// EOSESent indicates whether EOSE has been sent.
	EOSESent bool
}

Subscription represents a tunneled subscription.

Source Files

  • bridge.go
  • client.go
  • errors.go
  • session.go
  • uri.go

Jump to

Keyboard shortcuts

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