relayconfig

package
v0.1.9 Latest Latest
Warning

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

Go to latest
Published: Dec 1, 2026 License: AGPL-3.0 Imports: 29 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package relayconfig owns saved profiles, active relay selection and frontend choice.

Index

Constants

View Source
const (
	ConfigFileEnvironment = "WINDSHARE_CONFIG_FILE"

	MaximumProfiles       = 64
	MaximumBootstrapNodes = 16
)
View Source
const (
	Automatic = "automatic"
	Selected  = "selected"
)
View Source
const (
	MaxTURNServices = 8
	DefaultTURNTTL  = 1800
	MinimumTURNTTL  = 60
	MaximumTURNTTL  = 86400
	TURNStatic      = "shared_static"
	TURNCoturn      = "coturn"
	TURNCloudflare  = "cloudflare"
	RoleParallel    = "parallel"
	RoleFallback    = "fallback"
)

Variables

View Source
var (
	ErrConfig   = errors.New("invalid sharing configuration")
	ErrRelayURL = errors.New("invalid relay URL")
	// Decode wraps both ErrConfig and ErrRepeatedMember for ambiguous names.
	ErrRepeatedMember = configjson.ErrRepeatedMember
)
View Source
var (
	// ErrRelayIdentityChanged reports that an enrolled relay advertised a
	// different node identity than the saved credential expects.
	ErrRelayIdentityChanged = errors.New("enrolled relay identity changed")
	// ErrProfileLimitReached reports that the saved profile table is full.
	ErrProfileLimitReached = fmt.Errorf("limit of %d relay profiles reached", MaximumProfiles)
	// ErrInvalidPreference reports an invalid interactive relay preference edit.
	ErrInvalidPreference = errors.New("invalid sharing preference")
)
View Source
var ErrCorruptEligibility = errors.New("corrupt community eligibility state")

ErrCorruptEligibility identifies malformed or oversized derived community-eligibility.json state so callers can distinguish recoverable sidecar corruption from primary settings or filesystem I/O failures.

View Source
var (

	// ErrEmptyConfigFileEnv reports that WINDSHARE_CONFIG_FILE is set to an empty
	// string, which cannot name a configuration file.
	ErrEmptyConfigFileEnv = errors.New(
		ConfigFileEnvironment + " is set but empty; set it to a configuration file path or unset it to use the default",
	)
)
View Source
var ErrFrontURL = errors.New("invalid frontend URL")

Functions

func Encode

func Encode(config Config) ([]byte, error)

Encode serializes only portable user settings.

func FormatLoadError added in v0.1.8

func FormatLoadError(err error) string

FormatLoadError returns a safe, actionable diagnostic for any error returned while loading sharing configuration. It is pure and never inspects ambient process environment variables or filesystem state.

func FormatSaveError added in v0.1.8

func FormatSaveError(err error) string

FormatSaveError returns a safe, actionable diagnostic for any error returned while saving sharing configuration. If err already carries a typed *ConfigError (for example, an OpLoad failure during read-modify-write), its recorded operation is preserved rather than overwritten.

func IsUsageError added in v0.1.8

func IsUsageError(err error) bool

IsUsageError reports whether err represents a user configuration or environment error (empty WINDSHARE_CONFIG_FILE, missing explicit env file on load, or invalid/oversized configuration content) rather than an external storage or filesystem I/O failure.

func Path

func Path() (string, error)

Path returns the resolved configuration file path or ErrEmptyConfigFileEnv when WINDSHARE_CONFIG_FILE is set to an empty string.

func RelayRouteGuidance

func RelayRouteGuidance(hint networkendpoint.RelayBaseHint) string

RelayRouteGuidance applies to an observed HTTP failure. The same spelling can still name a working mount or an unused profile.

func SafeValidationMessage added in v0.1.8

func SafeValidationMessage(err error) string

SafeValidationMessage returns a package-authored validation message for err, falling back to the matching static sentinel so untrusted outer wrappers never leak arbitrary text.

func Save

func Save(config Config) error

Save replaces the entire allowed set. Merging would silently retain providers that a newly imported private-only configuration deliberately excludes.

func SelectRelays

func SelectRelays(config Config, override []string) ([]relayprofile.Candidate, error)

SelectRelays treats a saved list or explicit override as the complete allowed set. No infrastructure is added implicitly, including development listeners.

func ShareIntent

func ShareIntent(config Config, override []string) (relayprofile.Intent, error)

func ValidateBootstrapNodes added in v0.1.7

func ValidateBootstrapNodes(nodes []string) error

ValidateBootstrapNodes enforces the shared count ceiling and strict public HTTPS origin rules for both user configuration and embedded release manifests.

func ValidateFrontURL

func ValidateFrontURL(raw string) error

Reject literal whitespace rather than rewriting the saved address: capability construction trims some copied characters and encodes others into the path. Explicitly escaped path characters remain part of the configured address.

func ValidateTURNServices added in v0.1.6

func ValidateTURNServices(services []TURNService) error

func ValidationDiagnostic added in v0.1.8

func ValidationDiagnostic(err error) (string, bool)

ValidationDiagnostic returns a safe, package-authored validation message when err carries specific diagnostic detail beyond bare ErrConfig.

Types

type AccessOp added in v0.1.8

type AccessOp uint8

AccessOp identifies whether a configuration storage failure occurred while reading or writing saved settings.

const (
	OpLoad AccessOp = iota
	OpSave
)

func (AccessOp) String added in v0.1.8

func (op AccessOp) String() string

type Config

type Config struct {
	BootstrapNodes []string
	TURNServices   []TURNService
	FrontURL       string
	Profiles       []relayprofile.Candidate
	ActiveRelays   []string
	CommunityNodes *bool
	ConfiguredOnly bool
}

func Decode

func Decode(reader io.Reader) (Config, error)

func Load

func Load() (Config, error)

func ReadSettings

func ReadSettings(tx *statefile.Transaction) (Config, error)

ReadSettings lets external transaction owners observe settings under the shared commit lock when the path was already supplied explicitly.

func (Config) CommunityEnabled added in v0.1.7

func (c Config) CommunityEnabled() bool

func (Config) CredentialProfile

func (c Config) CredentialProfile(address, key string) relayprofile.Candidate

CredentialProfile updates only the secret for an existing endpoint. A manual credential carries no discovery metadata and cannot withdraw a published capability.

func (Config) OwnedNative added in v0.1.7

func (c Config) OwnedNative() []relayprofile.Candidate

func (Config) Preferences

func (c Config) Preferences(defaultFrontend string) Preferences

func (Config) RefreshMetadata added in v0.1.7

func (c Config) RefreshMetadata(p relayprofile.Candidate) (Config, error)

RefreshMetadata preserves the device identity across capability rediscovery.

func (*Config) RemoveRelay added in v0.1.5

func (c *Config) RemoveRelay(address string) error

func (Config) ReplaceIdentity added in v0.1.7

func (c Config) ReplaceIdentity(p relayprofile.Candidate) (Config, error)

func (*Config) SetEnabled

func (c *Config) SetEnabled(address string, enabled bool) error

func (*Config) SetMode

func (c *Config) SetMode(mode string) error

func (Config) SettingsRevision

func (config Config) SettingsRevision() string

func (Config) Validate

func (config Config) Validate() error

type ConfigError added in v0.1.8

type ConfigError struct {
	Op         AccessOp
	Kind       FailureKind
	Origin     PathOrigin
	Path       string
	FailedPath string
	Cause      error
}

ConfigError describes a structured failure while reading, writing, or validating a saved configuration file. Path and FailedPath store raw resolved paths; terminal-safe escaping is applied only when rendering text.

func DescribeError added in v0.1.8

func DescribeError(err error) (ConfigError, bool)

DescribeError extracts a structured configuration access or validation failure without inspecting ambient process state. Arbitrary unknown errors return ok == false so callers keep untrusted causes opaque.

func (ConfigError) Detail added in v0.1.8

func (err ConfigError) Detail() StructuredDetail

Detail returns structured location and machine reason metadata for localized UI rendering without raw English sentences or OS-locale errno text.

func (*ConfigError) Error added in v0.1.8

func (err *ConfigError) Error() string

func (ConfigError) TargetPath added in v0.1.8

func (err ConfigError) TargetPath() string

TargetPath returns the specific failing filesystem target for CLI diagnostics when it differs from the settings path, mapping ephemeral staging files back to the settings file path.

func (*ConfigError) Unwrap added in v0.1.8

func (err *ConfigError) Unwrap() error

func (ConfigError) UserPath added in v0.1.8

func (err ConfigError) UserPath() string

UserPath returns the user-facing path for GUI diagnostics: it surfaces the exact pending commit file for corrupt commits while keeping internal lock and staging temp filenames hidden behind the main configuration file path.

type Eligibility added in v0.1.7

type Eligibility struct {
	Disabled map[string]bool `json:"disabled,omitempty"`
	Paused   bool            `json:"paused,omitempty"`
	Notified bool            `json:"notified,omitempty"`
}

func EvaluateEligibility added in v0.1.7

func EvaluateEligibility(current Eligibility, c Config, observed map[string]serviceauthority.PublicRelay) Eligibility

EvaluateEligibility derives current community eligibility from previously recorded refusals, the active configuration, and any fresh owner observations. Only an explicit signed refusal is sticky across offline periods; a later reachable observation in any other state releases the refusal and its notice.

func ReadEligibility added in v0.1.7

func ReadEligibility(tx *statefile.Transaction) (Eligibility, error)

func ReconcileEligibility added in v0.1.7

func ReconcileEligibility(tx *statefile.Transaction, c Config, observed map[string]serviceauthority.PublicRelay) (Eligibility, error)

type FailureKind added in v0.1.8

type FailureKind string

FailureKind classifies why reading, writing, or validating saved sharing configuration failed so CLI and GUI layers can render tailored diagnostics.

const (
	FailureEmptyEnvPath   FailureKind = "empty_env_path"
	FailureNotFound       FailureKind = "not_found"
	FailurePermission     FailureKind = "permission_denied"
	FailureNotDirectory   FailureKind = "parent_not_directory"
	FailureNotRegularFile FailureKind = "not_regular_file"
	FailureCorruptCommit  FailureKind = "corrupt_commit"
	FailureStorageIO      FailureKind = "storage_io"
	FailureOversized      FailureKind = "oversized"
	FailureRepeatedMember FailureKind = "repeated_member"
	FailureInvalidRelay   FailureKind = "invalid_relay"
	FailureInvalidFront   FailureKind = "invalid_frontend"
	FailureInvalidContent FailureKind = "invalid_content"
)

type FailureReason added in v0.1.8

type FailureReason string

FailureReason provides a machine-readable sub-cause so desktop clients can render fully localized diagnostics without embedding raw English Go strings or OS-locale errno text.

const (
	ReasonRepeatedCaseInsensitive FailureReason = "repeated_case_insensitive"
	ReasonRelayNumericHost        FailureReason = "relay_numeric_host"
	ReasonRelayWhitespace         FailureReason = "relay_whitespace"
	ReasonRelayURLFormat          FailureReason = "relay_url_format"
	ReasonFrontendWhitespace      FailureReason = "frontend_whitespace"
	ReasonFrontendURLFormat       FailureReason = "frontend_url_format"
	ReasonFrontendInvalidHost     FailureReason = "frontend_invalid_host"
	ReasonFrontendInvalidPort     FailureReason = "frontend_invalid_port"
	ReasonTooManyBootstrapNodes   FailureReason = "too_many_bootstrap_nodes"
	ReasonInvalidBootstrapNode    FailureReason = "invalid_bootstrap_node"
	ReasonInvalidRelayMetadataURL FailureReason = "invalid_relay_metadata_url"
	ReasonDiskFull                FailureReason = "disk_full"
	ReasonReadOnlyFilesystem      FailureReason = "read_only_filesystem"
	ReasonFileInUse               FailureReason = "file_in_use"
	ReasonInvalidPath             FailureReason = "invalid_path"
	ReasonSymlinkLoop             FailureReason = "symlink_loop"
	ReasonStorageUnavailable      FailureReason = "storage_unavailable"
)

type FileStore

type FileStore struct{ Path string }

FileStore is injectable so applications never read another caller's configuration implicitly.

func (FileStore) Load

func (store FileStore) Load() (Config, error)

func (FileStore) Location

func (store FileStore) Location() (string, error)

Location identifies the namespace shared by settings and durable setup commits.

func (FileStore) Read added in v0.1.8

func (store FileStore) Read(ctx context.Context, action func(*statefile.Transaction, Config) error) error

Read observes settings and sidecar state without acquiring a write lock or creating directories/lock files unless a pending multi-file commit awaits recovery, in which case statefile.Read escalates to a locked transaction.

func (FileStore) ReadCommunityState added in v0.1.7

func (s FileStore) ReadCommunityState(ctx context.Context) (Config, Eligibility, error)

ReadCommunityState reads saved settings and derives current community eligibility without acquiring a write lock unless commit recovery is pending. When only community-eligibility.json is corrupt, the decoded Config is still returned alongside an error matching ErrCorruptEligibility.

func (FileStore) Save

func (store FileStore) Save(config Config) error

func (FileStore) TakeCommunityNotice added in v0.1.7

func (s FileStore) TakeCommunityNotice(ctx context.Context) (bool, error)

func (FileStore) Transact added in v0.1.8

func (store FileStore) Transact(ctx context.Context, action func(*statefile.Transaction, Config) error) error

Transact serializes read-modify-write state operations under the store's lock, preserving configuration path origin and wrapping commit/lock failures as save errors while keeping read-phase failures typed as load errors.

func (FileStore) Update

func (store FileStore) Update(ctx context.Context, change func(*Config) error) (Config, error)

Update serializes user edits across processes. Network activity never runs in its callback; setup commits use the same storage transaction boundary.

type PathOrigin added in v0.1.8

type PathOrigin uint8

PathOrigin identifies how a configuration file path was chosen.

const (
	OriginDefault PathOrigin = iota
	OriginEnvironment
	OriginExplicit
)

func (PathOrigin) String added in v0.1.8

func (origin PathOrigin) String() string

type PreferenceEdit

type PreferenceEdit struct {
	Action string `json:"action"`
	Value  string `json:"value"`
}

func (PreferenceEdit) Apply

func (e PreferenceEdit) Apply(c *Config) error

type Preferences

type Preferences struct {
	CommunityNotice uint64      `json:"community_notice,omitempty"`
	CommunityNodes  bool        `json:"community_nodes"`
	Mode            string      `json:"mode"`
	Frontend        string      `json:"frontend"`
	CustomFrontend  bool        `json:"custom_frontend"`
	Relays          []RelayView `json:"relays"`
	AtCapacity      bool        `json:"at_capacity"`
}

type RelayView

type RelayView struct {
	URL             string `json:"url"`
	Enabled         bool   `json:"enabled"`
	ConsoleURL      string `json:"console_url,omitempty"`
	OfferedFrontend string `json:"offered_frontend,omitempty"`
}

type StructuredDetail added in v0.1.8

type StructuredDetail struct {
	Field     string
	Member    string
	Reason    FailureReason
	ReasonArg string
}

StructuredDetail carries localized-UI metadata extracted from a ConfigError.

type TURNService added in v0.1.6

type TURNService struct {
	ID           string   `json:"id"`
	Kind         string   `json:"kind"`
	Role         string   `json:"role,omitempty"`
	URLs         []string `json:"urls,omitempty"`
	Username     string   `json:"username,omitempty"`
	Password     string   `json:"password,omitempty"`
	SharedSecret string   `json:"shared_secret,omitempty"`
	KeyID        string   `json:"key_id,omitempty"`
	APIToken     string   `json:"api_token,omitempty"`
	TTLSeconds   int      `json:"ttl_seconds,omitempty"`
}

func CloneTURNServices added in v0.1.6

func CloneTURNServices(services []TURNService) []TURNService

func (TURNService) EffectiveRole added in v0.1.6

func (service TURNService) EffectiveRole() string

func (TURNService) TTL added in v0.1.6

func (service TURNService) TTL() int

Jump to

Keyboard shortcuts

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