daemon

package
v0.4.1 Latest Latest
Warning

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

Go to latest
Published: May 10, 2026 License: MIT Imports: 33 Imported by: 0

Documentation

Index

Constants

View Source
const MaxRequestBodySize = 1 << 20 // 1 MB

MaxRequestBodySize limits the size of JSON request bodies to prevent unbounded memory consumption from oversized or malicious payloads.

View Source
const ProxyPortRetryInterval = 30 * time.Second

ProxyPortRetryInterval is how often we retry binding port_conflict proxies (EDGE-4).

Variables

View Source
var (
	// ErrDaemonAlreadyRunning is returned when trying to start a daemon
	// while another instance is already running on the same socket.
	ErrDaemonAlreadyRunning = errors.New("daemon already running")

	// ErrDaemonNotRunning is returned when trying to connect to a daemon
	// that is not running (socket file does not exist).
	ErrDaemonNotRunning = errors.New("daemon not running")

	// ErrProxyNotFound is returned when trying to disconnect a proxy
	// that does not exist or has already been torn down.
	ErrProxyNotFound = errors.New("proxy not found")

	// ErrUnauthorized is returned when a request lacks valid authentication.
	ErrUnauthorized = errors.New("unauthorized")
)

Functions

func InstrumentHandler

func InstrumentHandler(next http.Handler, metrics *sdk.Metrics, audit *sdk.AuditLogger) http.Handler

InstrumentHandler wraps an HTTP handler with Prometheus metrics and audit logging. If both metrics and audit are nil, the handler is returned unchanged (zero overhead).

func NewProxyStore added in v0.4.0

func NewProxyStore(path string) (*proxyStore, error)

NewProxyStore creates a store backed by the given file path. If the file exists and is valid JSON, entries are loaded. If the file is missing, starts empty. If the file is corrupt, attempts recovery from .tmp backup.

func ParseJSON

func ParseJSON(r *http.Request, dst any) error

ParseJSON reads and decodes a JSON request body with size limits.

func ProxiesFilePath added in v0.4.0

func ProxiesFilePath(configDir string) string

ProxiesFilePath returns the path to proxies.json given a config directory.

func RespondError

func RespondError(w http.ResponseWriter, status int, msg string)

RespondError writes a JSON error response.

func RespondJSON

func RespondJSON(w http.ResponseWriter, status int, data any)

RespondJSON writes a JSON response with the given status code.

func RespondText

func RespondText(w http.ResponseWriter, status int, text string)

RespondText writes a plain text response.

func WantsText

func WantsText(r *http.Request) bool

WantsText returns true if the client prefers plain text output.

Types

type AuthAddRequest

type AuthAddRequest struct {
	PeerID  string `json:"peer_id"`
	Comment string `json:"comment,omitempty"`
	Role    string `json:"role,omitempty"` // "admin" or "member" (default: "member")
}

AuthAddRequest is the body for POST /v1/auth.

type AuthEntry

type AuthEntry struct {
	PeerID    string `json:"peer_id"`
	Comment   string `json:"comment,omitempty"`
	Verified  string `json:"verified,omitempty"`   // e.g. "sha256:a1b2c3d4"
	ExpiresAt string `json:"expires_at,omitempty"` // RFC3339, empty = never
	Group     string `json:"group,omitempty"`      // pairing group ID
	Role      string `json:"role"`                 // "admin" or "member"
}

AuthEntry is returned by GET /v1/auth.

type BandwidthPeer

type BandwidthPeer struct {
	TotalIn  int64   `json:"total_in"`
	TotalOut int64   `json:"total_out"`
	RateIn   float64 `json:"rate_in"`
	RateOut  float64 `json:"rate_out"`
}

BandwidthPeer holds per-peer bandwidth stats.

type BandwidthStats

type BandwidthStats struct {
	TotalIn  int64                    `json:"total_in"`
	TotalOut int64                    `json:"total_out"`
	RateIn   float64                  `json:"rate_in"`
	RateOut  float64                  `json:"rate_out"`
	ByPeer   map[string]BandwidthPeer `json:"by_peer,omitempty"`
}

BandwidthStats is returned by GET /v1/bandwidth.

type Client

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

Client connects to a running daemon via its Unix socket.

func NewClient

func NewClient(socketPath, cookiePath string) (*Client, error)

NewClient creates a new daemon client. It reads the auth cookie automatically from the cookie file next to the socket.

func (*Client) AuthAdd

func (c *Client) AuthAdd(peerID, comment string) error

AuthAdd adds an authorized peer.

func (*Client) AuthList

func (c *Client) AuthList() ([]AuthEntry, error)

AuthList returns the authorized peers.

func (*Client) AuthListText

func (c *Client) AuthListText() (string, error)

AuthListText returns authorized peers as plain text.

func (*Client) AuthRemove

func (c *Client) AuthRemove(peerID string) error

AuthRemove removes an authorized peer.

func (*Client) ConfigReload

func (c *Client) ConfigReload() (*ConfigReloadResult, error)

ConfigReload asks the daemon to reload config from disk without restart.

func (*Client) ConfigReloadStatus

func (c *Client) ConfigReloadStatus() (*ConfigReloadState, error)

ConfigReloadStatus returns the daemon's config reload state.

func (*Client) ConfigReloadStatusText

func (c *Client) ConfigReloadStatusText() (string, error)

ConfigReloadStatusText returns the daemon's config reload state as plain text.

func (*Client) Connect

func (c *Client) Connect(peer, service, listen string) (*ConnectResponse, error)

Connect creates a TCP proxy to a remote service via the daemon.

func (*Client) Disconnect

func (c *Client) Disconnect(id string) error

Disconnect tears down an ephemeral proxy.

func (*Client) Expose

func (c *Client) Expose(name, localAddress string) error

Expose registers a service on the P2P host.

func (*Client) GrantCreate

func (c *Client) GrantCreate(req GrantRequest) (*GrantInfo, error)

GrantCreate creates a new data access grant for a peer.

func (*Client) GrantDelegate

func (c *Client) GrantDelegate(req GrantDelegateRequest) (map[string]string, error)

GrantDelegate delegates a grant to another peer with optional restrictions.

func (*Client) GrantExtendFull

func (c *Client) GrantExtendFull(req GrantExtendRequest) error

GrantExtendFull extends a grant with full request options (duration and/or max-refreshes).

func (*Client) GrantList

func (c *Client) GrantList() (*GrantListResponse, error)

GrantList returns all active data access grants.

func (*Client) GrantRevoke

func (c *Client) GrantRevoke(peer string) error

GrantRevoke revokes a peer's data access grant.

func (*Client) InviteCancel

func (c *Client) InviteCancel(id string) error

InviteCancel cancels an active invite session.

func (*Client) InviteCreate

func (c *Client) InviteCreate(name string, ttlSeconds, count int, relay string) (*InviteCreateResponse, error)

InviteCreate creates a new async invite via the daemon (relay-delegated).

func (*Client) InviteWait

func (c *Client) InviteWait(ctx context.Context, id string) (*InviteWaitResponse, error)

InviteWait long-polls until the invite is joined, expires, or ctx is cancelled.

func (*Client) Lock

func (c *Client) Lock() error

Lock disables sensitive operations on the running daemon.

func (*Client) NotifySinks

func (c *Client) NotifySinks() ([]NotifySinkInfo, error)

NotifySinks returns all configured notification sinks.

func (*Client) NotifyTest

func (c *Client) NotifyTest() (map[string]string, error)

NotifyTest sends a test notification to all configured sinks.

func (*Client) Paths

func (c *Client) Paths() ([]PathInfo, error)

Paths returns per-peer path information (type, transport, IP version, RTT).

func (*Client) PathsText

func (c *Client) PathsText() (string, error)

PathsText returns per-peer path information as plain text.

func (*Client) Peers

func (c *Client) Peers(all bool) ([]PeerInfo, error)

Peers returns the list of connected peers. If all is true, includes non-shurli DHT peers.

func (*Client) PeersText

func (c *Client) PeersText(all bool) (string, error)

PeersText returns peers as plain text. If all is true, includes non-shurli DHT peers.

func (*Client) Ping

func (c *Client) Ping(peer string, count, intervalMs int) (*PingResponse, error)

Ping pings a peer via the daemon.

func (*Client) PingText

func (c *Client) PingText(peer string, count, intervalMs int) (string, error)

PingText pings a peer via the daemon, returns plain text output.

func (*Client) PluginDisable

func (c *Client) PluginDisable(name string) error

PluginDisable disables a plugin.

func (*Client) PluginDisableAll

func (c *Client) PluginDisableAll() (int, error)

PluginDisableAll disables all active plugins (kill switch).

func (*Client) PluginEnable

func (c *Client) PluginEnable(name string) error

PluginEnable enables a plugin.

func (*Client) PluginInfo

func (c *Client) PluginInfo(name string) (*PluginInfoResponse, error)

PluginInfo returns details for a single plugin.

func (*Client) PluginList

func (c *Client) PluginList() ([]PluginInfoResponse, error)

PluginList returns all registered plugins.

func (*Client) PouchList

func (c *Client) PouchList() (*PouchListResponse, error)

PouchList returns all non-expired tokens in the grant pouch (receiver's view).

func (*Client) ProxyAdd added in v0.4.0

func (c *Client) ProxyAdd(name, peer, service string, port int) (*ProxyAddResponse, error)

ProxyAdd creates a persistent proxy.

func (*Client) ProxyDisable added in v0.4.0

func (c *Client) ProxyDisable(name string) error

ProxyDisable disables a persistent proxy without removing it.

func (*Client) ProxyEnable added in v0.4.0

func (c *Client) ProxyEnable(name string) error

ProxyEnable enables a disabled persistent proxy.

func (*Client) ProxyList added in v0.4.0

func (c *Client) ProxyList() (*ProxyListResponse, error)

ProxyList returns all persistent proxies.

func (*Client) ProxyRemove added in v0.4.0

func (c *Client) ProxyRemove(name string) error

ProxyRemove deletes a persistent proxy.

func (*Client) Reconnect

func (c *Client) Reconnect(peer string) (*ReconnectResponse, error)

Reconnect clears dial backoffs for a peer and triggers immediate reconnection.

func (*Client) RemoteServices

func (c *Client) RemoteServices(peer string) (*RemoteServiceResponse, error)

RemoteServices queries a remote peer's services via the daemon.

func (*Client) RemoteServicesText

func (c *Client) RemoteServicesText(peer string) (string, error)

RemoteServicesText queries a remote peer's services, returns plain text.

func (*Client) Resolve

func (c *Client) Resolve(name string) (*ResolveResponse, error)

Resolve resolves a name to a peer ID.

func (*Client) ResolveText

func (c *Client) ResolveText(name string) (string, error)

ResolveText resolves a name, returns plain text output.

func (*Client) Services

func (c *Client) Services() ([]ServiceInfo, error)

Services returns the list of registered services.

func (*Client) ServicesText

func (c *Client) ServicesText() (string, error)

ServicesText returns services as plain text.

func (*Client) SetTimeout added in v0.4.0

func (c *Client) SetTimeout(d time.Duration)

SetTimeout overrides the daemon client's request timeout. Use it for best-effort, fire-and-forget calls (such as tryDaemonConfigReload) where waiting up to the default 30s would be excessive. Values <= 0 are ignored so callers cannot accidentally disable the safety net.

func (*Client) Shutdown

func (c *Client) Shutdown() error

Shutdown requests the daemon to shut down gracefully.

func (*Client) Status

func (c *Client) Status() (*StatusResponse, error)

Status returns the daemon's status.

func (*Client) StatusText

func (c *Client) StatusText() (string, error)

StatusText returns the daemon's status as plain text.

func (*Client) Traceroute

func (c *Client) Traceroute(peer string) (*sdk.TraceResult, error)

Traceroute traces the path to a peer and returns the result as JSON.

func (*Client) TracerouteText

func (c *Client) TracerouteText(peer string) (string, error)

TracerouteText traces the path to a peer, returns plain text output.

func (*Client) Unexpose

func (c *Client) Unexpose(name string) error

Unexpose removes a service from the P2P host.

func (*Client) Unlock

func (c *Client) Unlock() error

Unlock enables sensitive operations on the running daemon.

type ConfigReloadResult

type ConfigReloadResult struct {
	Changed  []string `json:"changed"`            // list of changed fields (e.g. "transfer.receive_mode")
	Reverted []string `json:"reverted,omitempty"` // fields that were rolled back due to errors
}

ConfigReloadResult describes what changed during a config reload.

type ConfigReloadState

type ConfigReloadState struct {
	LastReloadTime      time.Time `json:"last_reload_time,omitempty"`
	LastSuccess         bool      `json:"last_success"`
	LastError           string    `json:"last_error,omitempty"`
	LastChanged         []string  `json:"last_changed,omitempty"`
	LastReverted        []string  `json:"last_reverted,omitempty"`
	ConsecutiveFailures int       `json:"consecutive_failures"`
	TotalReloads        int       `json:"total_reloads"`
	TotalFailures       int       `json:"total_failures"`
}

ConfigReloadState tracks the last config reload for self-healing and admin visibility.

type ConfigReloader

type ConfigReloader interface {
	ReloadConfig() (*ConfigReloadResult, error)
}

ConfigReloader allows hot-reloading config from disk without daemon restart.

type ConnectRequest

type ConnectRequest struct {
	Peer    string `json:"peer"`
	Service string `json:"service"`
	Listen  string `json:"listen"`
}

ConnectRequest is the body for POST /v1/connect.

type ConnectResponse

type ConnectResponse struct {
	ID            string `json:"id"`
	ListenAddress string `json:"listen_address"`
	PathType      string `json:"path_type,omitempty"`
	Address       string `json:"address,omitempty"`
}

ConnectResponse is returned by POST /v1/connect.

type DataResponse

type DataResponse struct {
	Data any `json:"data"`
}

DataResponse wraps a successful response.

type ErrorResponse

type ErrorResponse struct {
	Error string `json:"error"`
}

ErrorResponse is returned on failure.

type ExposeRequest

type ExposeRequest struct {
	Name         string `json:"name"`
	LocalAddress string `json:"local_address"`
}

ExposeRequest is the body for POST /v1/expose.

type GaterReloader

type GaterReloader interface {
	ReloadFromFile() error // reload authorized_keys and update the gater
}

GaterReloader allows hot-reloading the authorized peers list.

type GrantDelegateRequest

type GrantDelegateRequest struct {
	Peer           string   `json:"peer"`                      // peer holding the original grant
	To             string   `json:"to"`                        // target peer to delegate to
	Duration       string   `json:"duration,omitempty"`        // optional: shorter duration
	Services       []string `json:"services,omitempty"`        // optional: fewer services
	MaxDelegations int      `json:"max_delegations,omitempty"` // optional: further delegation hops
	Transports     string   `json:"transports,omitempty"`      // optional: narrower transport caveat (lan,direct,relay)
}

GrantDelegateRequest is the request body for delegating a grant to another peer.

type GrantExtendRequest

type GrantExtendRequest struct {
	Peer         string `json:"peer"`                    // peer name or ID
	Duration     string `json:"duration,omitempty"`      // additional time
	MaxRefreshes *int   `json:"max_refreshes,omitempty"` // B4: update max refresh count (nil = no change)
}

GrantExtendRequest is the request body for extending a grant.

type GrantInfo

type GrantInfo struct {
	Peer           string   `json:"peer"`
	PeerID         string   `json:"peer_id"`
	Services       []string `json:"services,omitempty"`
	ExpiresAt      string   `json:"expires_at,omitempty"` // RFC3339, empty for permanent
	CreatedAt      string   `json:"created_at"`
	Permanent      bool     `json:"permanent,omitempty"`
	Remaining      string   `json:"remaining,omitempty"`       // human-readable, empty for permanent
	MaxDelegations int      `json:"max_delegations,omitempty"` // 0=none, N=limited, -1=unlimited
	AutoRefresh    bool     `json:"auto_refresh,omitempty"`    // B4: token refresh enabled
	MaxRefreshes   int      `json:"max_refreshes,omitempty"`   // B4: total allowed
	RefreshesUsed  int      `json:"refreshes_used,omitempty"`  // B4: consumed so far
	Transports     string   `json:"transports,omitempty"`      // transport caveat string (e.g. "lan,direct,relay"); empty = any
	DataBudget     int64    `json:"data_budget,omitempty"`     // per-peer relay data budget in bytes: 0=global default, -1=unlimited, >0=absolute
	DataBudgetHR   string   `json:"data_budget_hr,omitempty"`  // human-readable form of DataBudget ("unlimited", "20GB", etc.) — presentation only
}

GrantInfo represents a grant in API responses.

type GrantListResponse

type GrantListResponse struct {
	Grants []GrantInfo `json:"grants"`
}

GrantListResponse is the response for listing grants.

type GrantRequest

type GrantRequest struct {
	Peer           string   `json:"peer"`               // peer name or ID
	Duration       string   `json:"duration"`           // e.g. "1h", "7d", "30m"
	Services       []string `json:"services,omitempty"` // empty = all services
	Permanent      bool     `json:"permanent,omitempty"`
	MaxDelegations int      `json:"max_delegations,omitempty"` // 0=none, N=limited, -1=unlimited
	AutoRefresh    bool     `json:"auto_refresh,omitempty"`    // B4: opt-in token refresh
	MaxRefreshes   int      `json:"max_refreshes,omitempty"`   // B4: max refresh count
	Transports     string   `json:"transports,omitempty"`      // transport caveat: comma-separated "lan,direct,relay" or decimal bitmask; empty = no caveat
	Budget         string   `json:"budget,omitempty"`          // per-peer data budget (e.g. "20GB", "unlimited"); stored in Grant.DataBudget
}

GrantRequest is the request body for creating a data access grant.

type GrantRevokeRequest

type GrantRevokeRequest struct {
	Peer string `json:"peer"` // peer name or ID
}

GrantRevokeRequest is the request body for revoking a grant.

type InviteCreateRequest

type InviteCreateRequest struct {
	Name       string `json:"name,omitempty"`
	Count      int    `json:"count,omitempty"`       // default 1
	TTLSeconds int    `json:"ttl_seconds,omitempty"` // default 86400 (24h)
	Relay      string `json:"relay,omitempty"`       // specific relay address to store invite on
}

InviteCreateRequest is the body for POST /v1/invite.

type InviteCreateResponse

type InviteCreateResponse struct {
	InviteID  string   `json:"invite_id"`
	Codes     []string `json:"codes"`
	GroupID   string   `json:"group_id"`
	TTL       int      `json:"ttl_seconds"`
	ExpiresAt string   `json:"expires_at"`
}

InviteCreateResponse is returned by POST /v1/invite.

type InviteWaitResponse

type InviteWaitResponse struct {
	Status string `json:"status"` // "complete", "partial", "expired", "cancelled"
	Used   int    `json:"used"`
	Total  int    `json:"total"`
}

InviteWaitResponse is returned by GET /v1/invite/{id}/wait.

type MOTDInfo

type MOTDInfo struct {
	RelayPeerID string `json:"relay_peer_id"`
	RelayName   string `json:"relay_name,omitempty"`
	Message     string `json:"message"`
	Type        string `json:"type"`
	Timestamp   string `json:"timestamp"`
}

MOTDInfo describes a MOTD or goodbye message from a relay.

type NotificationsStatus

type NotificationsStatus struct {
	Sinks []string `json:"sinks"` // names of configured sinks
}

NotificationsStatus is the notifications section in the status response.

type NotifySinkInfo

type NotifySinkInfo struct {
	Name   string `json:"name"`
	Status string `json:"status"` // "active"
}

NotifySinkInfo represents a configured notification sink.

type PathInfo

type PathInfo struct {
	PeerID      string  `json:"peer_id"`
	PathType    string  `json:"path_type"`
	Address     string  `json:"address"`
	ConnectedAt string  `json:"connected_at"`
	Transport   string  `json:"transport"`
	IPVersion   string  `json:"ip_version"`
	LastRTTMs   float64 `json:"last_rtt_ms,omitempty"`
}

PathInfo is returned by GET /v1/paths. Mirrors sdk.PeerPathInfo JSON tags.

type PeerInfo

type PeerInfo struct {
	ID           string   `json:"id"`
	Addresses    []string `json:"addresses"`
	AgentVersion string   `json:"agent_version,omitempty"`
}

PeerInfo is returned by GET /v1/peers.

type PeerPathSummary added in v0.4.0

type PeerPathSummary struct {
	PathType    string `json:"path_type"`               // "DIRECT" or "RELAYED"
	RelayPeerID string `json:"relay_peer_id,omitempty"` // relay peer ID if relayed
	RelayName   string `json:"relay_name,omitempty"`    // relay name if known
}

PeerPathSummary describes how a peer is connected (for status display).

type PingRequest

type PingRequest struct {
	Peer       string `json:"peer"`
	Count      int    `json:"count,omitempty"`       // 0 = continuous
	IntervalMs int    `json:"interval_ms,omitempty"` // default 1000
}

PingRequest is the body for POST /v1/ping.

type PingResponse

type PingResponse struct {
	Results []sdk.PingResult `json:"results"`
	Stats   sdk.PingStats    `json:"stats"`
}

PingResponse wraps ping results for non-streaming responses.

type PluginDisableAllResponse

type PluginDisableAllResponse struct {
	Disabled int    `json:"disabled"`
	Error    string `json:"error,omitempty"`
}

PluginDisableAllResponse is returned by POST /v1/plugins/disable-all.

type PluginInfoResponse

type PluginInfoResponse struct {
	Name       string   `json:"name"`
	Version    string   `json:"version"`
	Type       string   `json:"type"`  // "built-in" or "installed"
	State      string   `json:"state"` // "loading", "ready", "active", "draining", "stopped"
	Enabled    bool     `json:"enabled"`
	Commands   []string `json:"commands"`
	Routes     []string `json:"routes"`
	Protocols  []string `json:"protocols"`
	ConfigKey  string   `json:"config_key"`
	CrashCount int      `json:"crash_count"`
}

PluginInfoResponse is returned by GET /v1/plugins and GET /v1/plugins/{name}.

type PouchEntryInfo

type PouchEntryInfo struct {
	Issuer     string   `json:"issuer"`               // issuer name or truncated ID
	IssuerID   string   `json:"issuer_id"`            // full peer ID
	Services   []string `json:"services,omitempty"`   // empty = all
	ExpiresAt  string   `json:"expires_at,omitempty"` // RFC3339, empty for permanent
	Remaining  string   `json:"remaining,omitempty"`  // human-readable
	Permanent  bool     `json:"permanent,omitempty"`
	Transports string   `json:"transports,omitempty"` // effective transport mask parsed from token caveats (AND of all transport caveats); empty = unrestricted
}

PouchEntryInfo represents a received grant token in API responses.

type PouchListResponse

type PouchListResponse struct {
	Entries []PouchEntryInfo `json:"entries"`
}

PouchListResponse is the response for listing pouch entries.

type ProxyAddRequest added in v0.4.0

type ProxyAddRequest struct {
	Name    string `json:"name"`
	Peer    string `json:"peer"`
	Service string `json:"service"`
	Port    int    `json:"port"`
}

ProxyAddRequest is the body for POST /v1/proxies.

type ProxyAddResponse added in v0.4.0

type ProxyAddResponse struct {
	Name          string `json:"name"`
	ListenAddress string `json:"listen_address"`
	Status        string `json:"status"`
}

ProxyAddResponse is returned by POST /v1/proxies.

type ProxyEntry added in v0.4.0

type ProxyEntry struct {
	Name    string `json:"name"`
	Peer    string `json:"peer"`
	Service string `json:"service"`
	Port    int    `json:"port"`
	Enabled bool   `json:"enabled"`
}

ProxyEntry is a single persistent proxy stored in proxies.json.

type ProxyListResponse added in v0.4.0

type ProxyListResponse struct {
	Proxies []ProxyStatusInfo `json:"proxies"`
}

ProxyListResponse is returned by GET /v1/proxies.

type ProxyStatusInfo added in v0.4.0

type ProxyStatusInfo struct {
	Name    string `json:"name"`
	Peer    string `json:"peer"`
	Service string `json:"service"`
	Port    int    `json:"port"`
	Listen  string `json:"listen,omitempty"`
	Status  string `json:"status"` // "active", "waiting", "disabled", "error: ...", "port_conflict"
	Enabled bool   `json:"enabled"`
}

ProxyStatusInfo describes a proxy in API responses (list + status).

func ProxyListOffline added in v0.4.0

func ProxyListOffline(configDir string) ([]ProxyStatusInfo, error)

ProxyListOffline reads proxies.json directly when the daemon is not running (EDGE-7).

type ReconnectRequest

type ReconnectRequest struct {
	Peer string `json:"peer"` // peer name or ID
}

ReconnectRequest is the request body for POST /v1/reconnect.

type ReconnectResponse

type ReconnectResponse struct {
	Peer   string `json:"peer"`
	PeerID string `json:"peer_id"`
	Status string `json:"status"` // "reconnecting" or "not_watched"
}

ReconnectResponse is returned by POST /v1/reconnect.

type RelayGrantInfo

type RelayGrantInfo struct {
	RelayPeerID      string `json:"relay_peer_id"`
	RelayName        string `json:"relay_name,omitempty"` // parsed from agent version
	Permanent        bool   `json:"permanent,omitempty"`
	Remaining        string `json:"remaining,omitempty"`         // human-readable time left
	SessionBudget    string `json:"session_budget,omitempty"`    // e.g. "2 GB" or "unlimited"
	SessionUsed      string `json:"session_used,omitempty"`      // e.g. "1.2 GB"
	SessionRemaining string `json:"session_remaining,omitempty"` // e.g. "800 MB"
	SessionDuration  string `json:"session_duration,omitempty"`  // e.g. "2h"
}

RelayGrantInfo describes a cached relay grant receipt for status display.

type RelayHealthEntry

type RelayHealthEntry struct {
	PeerID      string  `json:"peer_id"`
	Score       float64 `json:"score"`
	RTTMs       float64 `json:"rtt_ms"`
	SuccessRate float64 `json:"success_rate"`
	ProbeCount  int     `json:"probe_count"`
	IsStatic    bool    `json:"is_static"`
}

RelayHealthEntry is one relay's health status.

type RelayHealthResponse

type RelayHealthResponse struct {
	Relays []RelayHealthEntry `json:"relays"`
}

RelayHealthResponse is returned by GET /v1/relay-health.

type RelayStatus

type RelayStatus struct {
	Address      string `json:"address"`
	PeerID       string `json:"peer_id"`
	ShortID      string `json:"short_id"`
	Connected    bool   `json:"connected"`
	RelayName    string `json:"relay_name,omitempty"`
	AgentVersion string `json:"agent_version,omitempty"`
}

RelayStatus describes a configured relay's connection state.

type RemoteServiceRequest

type RemoteServiceRequest struct {
	Peer string `json:"peer"` // peer name or ID
}

RemoteServiceRequest is sent to POST /v1/services/remote.

type RemoteServiceResponse

type RemoteServiceResponse struct {
	Services []sdk.RemoteServiceInfo `json:"services"`
}

RemoteServiceResponse is returned by POST /v1/services/remote.

type ResolveRequest

type ResolveRequest struct {
	Name string `json:"name"`
}

ResolveRequest is the body for POST /v1/resolve.

type ResolveResponse

type ResolveResponse struct {
	Name   string `json:"name"`
	PeerID string `json:"peer_id"`
	Source string `json:"source"` // "local_config", "peer_id" (direct parse)
}

ResolveResponse is returned by POST /v1/resolve.

type RuntimeInfo

type RuntimeInfo interface {
	Network() *sdk.Network
	ConfigFile() string
	AuthKeysPath() string
	GaterForHotReload() GaterReloader // nil if gating disabled
	Version() string
	StartTime() time.Time
	PingProtocolID() string
	ConnectToPeer(ctx context.Context, peerID peer.ID) error // DHT + relay fallback
	Interfaces() *sdk.InterfaceSummary                       // nil before discovery
	PathTracker() *sdk.PathTracker                           // nil before bootstrap
	PathProtector() *sdk.PathProtector                       // nil before bootstrap (TS-5)
	BandwidthTracker() *sdk.BandwidthTracker                 // nil when disabled
	RelayHealth() *sdk.RelayHealth                           // nil when disabled
	STUNResult() *sdk.STUNResult                             // nil before probe
	PQCPolicy() string                                       // active PQC policy ("mandatory", "opportunistic", "disabled")
	IsRelaying() bool                                        // true if peer relay enabled
	RelayAddresses() []string                                // relay multiaddrs from config
	RelayNameFromConfig(peerID string) string                // config-based relay name lookup
	DiscoveryNetwork() string                                // DHT namespace (empty = global)
	RelayMOTDs() []MOTDInfo                                  // MOTD/goodbye messages from relays
	ConfigReloader() ConfigReloader                          // nil if reload not supported
	GrantStore() *grants.Store                               // nil before initialization
	GrantPouch() *grants.Pouch                               // nil before initialization
	GrantProtocol() *grants.GrantProtocol                    // nil before initialization
	GrantsAutoRefresh() bool                                 // config default for auto-refresh
	GrantsMaxRefreshDuration() string                        // config default for max refresh duration (e.g. "3d")
	NotifyRouter() *notify.Router                            // nil before initialization
	PeerManager() *sdk.PeerManager                           // nil before initialization
	GrantCacheSnapshot() []*grants.GrantReceipt              // nil if no grant cache
}

RuntimeInfo provides the daemon server with access to the P2P runtime. This interface decouples the daemon package from the cmd/shurli serveRuntime struct.

type Server

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

Server is the daemon's Unix socket HTTP API server.

func NewServer

func NewServer(runtime RuntimeInfo, socketPath, cookiePath, version string) *Server

NewServer creates a new daemon API server.

func (*Server) DetectAlreadyConnected added in v0.4.0

func (s *Server) DetectAlreadyConnected()

DetectAlreadyConnected checks all persistent proxies and flips "waiting" to "active" for any peer that is already connected. Called once after RestoreProxies + event loop subscription, to catch peers that connected during bootstrap before the subscription started.

func (*Server) IsLocked

func (s *Server) IsLocked() bool

IsLocked returns whether sensitive operations are currently locked.

func (*Server) Listener

func (s *Server) Listener() net.Listener

Listener returns the underlying net.Listener (for health checks).

func (*Server) OnPeerConnected added in v0.4.0

func (s *Server) OnPeerConnected(pid peer.ID)

OnPeerConnected is called when a peer connects (via libp2p event bus subscription). Flips persistent proxies targeting that peer from "waiting" to "active".

func (*Server) OnPeerDeauthorized added in v0.4.0

func (s *Server) OnPeerDeauthorized(pid peer.ID)

OnPeerDeauthorized is called when a peer is removed from authorized_keys (F2). Stops all persistent proxies targeting that peer.

func (*Server) OnPeerDisconnected added in v0.4.0

func (s *Server) OnPeerDisconnected(pid peer.ID)

OnPeerDisconnected is called when a peer disconnects. Flips persistent proxies targeting that peer from "active" to "waiting". Applies GATETIME logic (NOVEL-2): rapid disconnects increment quickDeathCount.

func (*Server) PollProxyStatus added in v0.4.0

func (s *Server) PollProxyStatus()

PollProxyStatus polls peer connectedness for all persistent proxies and flips status to match reality. Catches missed EvtPeerConnectednessChanged events (e.g., relay connections established by PathDialer/reconnect, item #33). Called periodically from the proxy event loop's 30s ticker.

func (*Server) ProxyStatusList added in v0.4.0

func (s *Server) ProxyStatusList() []ProxyStatusInfo

ProxyStatusList returns status info for all proxies (persistent + ephemeral).

func (*Server) RestoreProxies added in v0.4.0

func (s *Server) RestoreProxies()

RestoreProxies restores persistent proxies from proxies.json. Called AFTER bootstrap completes (F3: peers must be reachable). Each enabled proxy gets its TCP listener bound immediately. Status is set to "waiting" — the peer event loop flips to "active".

func (*Server) RetryPortConflicts added in v0.4.0

func (s *Server) RetryPortConflicts()

RetryPortConflicts attempts to rebind all port_conflict proxies (EDGE-4). Called periodically from the proxy event loop.

func (*Server) SetInstrumentation

func (s *Server) SetInstrumentation(metrics *sdk.Metrics, audit *sdk.AuditLogger)

SetInstrumentation configures optional metrics and audit logging. Must be called before Start(). Both parameters are nil-safe.

func (*Server) SetProxyStore added in v0.4.0

func (s *Server) SetProxyStore(store *proxyStore)

SetProxyStore configures persistent proxy storage. Must be called before RestoreProxies(). Nil-safe.

func (*Server) SetRegistry

func (s *Server) SetRegistry(r *plugin.Registry)

SetRegistry configures the plugin registry for plugin management API endpoints. Must be called before Start(). Nil-safe (plugin endpoints return 503 if nil).

func (*Server) ShutdownCh

func (s *Server) ShutdownCh() <-chan struct{}

ShutdownCh returns a channel that is closed when a shutdown is requested via the API (POST /v1/shutdown).

func (*Server) SocketPath

func (s *Server) SocketPath() string

SocketPath returns the path to the Unix socket.

func (*Server) Start

func (s *Server) Start() error

Start creates the Unix socket, writes the cookie file, and starts serving. It returns immediately - the server runs in a background goroutine.

func (*Server) Stop

func (s *Server) Stop()

Stop gracefully shuts down the HTTP server, closes all proxies, and cleans up the socket and cookie files.

type ServiceInfo

type ServiceInfo struct {
	Name         string `json:"name"`
	Protocol     string `json:"protocol"`
	LocalAddress string `json:"local_address"`
	Enabled      bool   `json:"enabled"`
}

ServiceInfo is returned by GET /v1/services.

type StatusResponse

type StatusResponse struct {
	PeerID            string                     `json:"peer_id"`
	Version           string                     `json:"version"`
	UptimeSeconds     int                        `json:"uptime_seconds"`
	ConnectedPeers    int                        `json:"connected_peers"`
	ListenAddrs       []string                   `json:"listen_addresses"`
	RelayAddrs        []string                   `json:"relay_addresses"`
	ServicesCount     int                        `json:"services_count"`
	HasGlobalIPv6     bool                       `json:"has_global_ipv6"`
	HasGlobalIPv4     bool                       `json:"has_global_ipv4"`
	NATType           string                     `json:"nat_type,omitempty"`
	STUNExternalAddrs []string                   `json:"stun_external_addrs,omitempty"`
	IsRelaying        bool                       `json:"is_relaying"`
	Reachability      *sdk.ReachabilityGrade     `json:"reachability,omitempty"`
	Relays            []RelayStatus              `json:"relays,omitempty"`
	MOTDs             []MOTDInfo                 `json:"motds,omitempty"`
	ExpiringGrants    []GrantInfo                `json:"expiring_grants,omitempty"` // grants expiring within 10 minutes
	RelayGrants       []RelayGrantInfo           `json:"relay_grants,omitempty"`    // client-side cached relay grant receipts
	Notifications     *NotificationsStatus       `json:"notifications,omitempty"`
	ConfigReload      *ConfigReloadState         `json:"config_reload,omitempty"`
	PluginStatus      map[string]map[string]any  `json:"plugin_status,omitempty"`
	PeerPaths         map[string]PeerPathSummary `json:"peer_paths,omitempty"` // peer ID -> connection summary
	Proxies           []ProxyStatusInfo          `json:"proxies,omitempty"`
	PQC               *sdk.PQCStatus             `json:"pqc,omitempty"`
}

StatusResponse is returned by GET /v1/status.

type TraceRequest

type TraceRequest struct {
	Peer string `json:"peer"`
}

TraceRequest is the body for POST /v1/traceroute.

Jump to

Keyboard shortcuts

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