daemon

package
v0.0.0-...-de45444 Latest Latest
Warning

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

Go to latest
Published: Jun 17, 2026 License: MIT Imports: 44 Imported by: 0 modules, 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

Index

Constants

This section is empty.

Variables

View Source
var ErrIdentityExists = errors.New("daemon: identity already initialised in data dir")

ErrIdentityExists is returned by InitIdentity when dataDir already holds a node identity bundle. Recovery onto a directory that already has an identity is a footgun (it would silently shadow or clobber the live identity), so the caller must point at a fresh --data-dir or remove the existing bundle first.

Functions

func InitIdentity

func InitIdentity(dataDir string, seed []byte, now time.Time) (*identity.Bundle, []byte, error)

InitIdentity provisions the node's post-quantum identity bundle under dataDir/identity/ and returns it along with the 32-byte master seed.

  • If seed is nil, a fresh cryptographically-random 32-byte seed is generated (the `ensemble init` first-run path).
  • If seed is non-nil it must be exactly identity.SeedSize bytes and is used verbatim (the `ensemble init --seed=<base64>` recovery path). The derived Dilithium + ed25519 keypairs and the address are a pure function of the seed, so the same seed regenerates the same identity on any machine.

now stamps the binding's created_at. InitIdentity refuses to overwrite an existing bundle, returning ErrIdentityExists.

The returned seed is the master secret. Callers should surface it only for a one-time backup prompt and never log it.

Types

type Config

type Config struct {
	DataDir      string // base directory for identity, contacts, etc.
	ReceiveDir   string // directory for incoming files; empty resolves to the OS Downloads folder (see ResolvedReceiveDir)
	SocketPath   string // Unix socket path for gRPC API
	TCPAddr      string // optional TCP address for gRPC (headless/remote)
	GRPCWebAddr  string // optional HTTP listen address for the gRPC-Web bridge (dev / local only)
	UIAddr       string // optional HTTP listen address for the ui service's SPA + gRPC-Web bridge (LAN / dev)
	UILocalHTTPS bool   // when true, bind a second loopback listener over HTTPS with a self-signed per-daemon cert (see internal/ui-service/local_tls.go)
	UIHTTPSAddr  string // listen address for the local-HTTPS port (default 127.0.0.1:9102 when UILocalHTTPS is true)
	AdminKey     string // hex-encoded Ed25519 public key for gRPC auth

	// TrustProxyTLS is the operator's explicit assertion that a trusted TLS
	// terminator (e.g. a reverse proxy like Traefik) fronts any non-loopback
	// plaintext gRPC bind. The daemon ships no built-in gRPC TLS, so the gRPC
	// API is served as cleartext h2c; admin-key auth proves the caller's
	// identity but leaves responses readable and streaming messages injectable
	// on-path. Without this flag, validateTransportSecurity refuses to bind
	// --api-addr / --grpc-web-addr to a non-loopback interface. See ADR-0002
	// notes / README. Settable via --trust-proxy-tls or ENSEMBLE_TRUST_PROXY_TLS.
	// A TLS terminator also protects the SPA, so this waives the UI gate below.
	TrustProxyTLS bool

	// UnsafePlaintextUI acknowledges serving the web SPA over plaintext HTTP on
	// a non-loopback interface. The SPA handles the raw 32-byte admin seed in
	// browser JS during enrolment, so an on-path attacker who injects script
	// into a plaintext response can exfiltrate it before it is zeroed. By
	// default validateUISecurity refuses a non-loopback plaintext --ui-addr;
	// this flag is the explicit "trusted LAN, no terminator" opt-in for dev
	// use (logs a loud warning). Prefer --ui-local-https or the onion. Settable
	// via --unsafe-plaintext-ui or ENSEMBLE_UNSAFE_PLAINTEXT_UI.
	UnsafePlaintextUI bool
	// Metrics is the observability master switch, default OFF. When false the
	// metrics registry is a no-op and NOTHING is collected at the source — no
	// bandwidth metering, no per-peer series, no retention. Metrics are a
	// traffic-analysis metadata store on a Tor privacy app, so the dashboard
	// ships dark until the operator opts in. Settable via --metrics or
	// ENSEMBLE_METRICS. The optional Prometheus exposition endpoint is a
	// separate, additional opt-in — this flag never opens a network port.
	Metrics bool

	// MetricsListen optionally serves the metrics registry in Prometheus
	// text-exposition format on this HTTP address (e.g. "127.0.0.1:9100").
	// A SECOND opt-in on top of Metrics — empty (the default) means no
	// listener even when Metrics is on; a local dashboard view is not the
	// same decision as opening a network port. Requires Metrics; non-loopback
	// binds additionally require TrustProxyTLS (see validateMetricsListen).
	// Settable via --metrics-listen or ENSEMBLE_METRICS_LISTEN.
	MetricsListen string

	DisableTor bool          // skip Tor startup (for testing)
	TorPath    string        // external tor binary to run instead of the embedded one (empty = embedded default)
	DisableP2P bool          // skip libp2p host startup (for testing)
	P2PPort    int           // UDP port for QUIC (0 = random)
	RTMaxAge   time.Duration // routing-table eviction window (0 = use discovery default)

	// SignalingBackend selects the signaling transport. Empty or "tor"
	// uses the Tor onion-based backend (the default). "loopback" uses the
	// same-host Unix-socket backend in internal/signaling/loopback — Tor is
	// not started under that mode. Unknown values fail validation at Start.
	SignalingBackend string

	// LoopbackDir overrides the rendezvous directory used by the loopback
	// signaling backend. Empty resolves to ${XDG_RUNTIME_DIR:-/tmp}/ensemble-loopback/
	// at Start time. Only consulted when SignalingBackend == "loopback".
	LoopbackDir string

	// MdnsIface optionally restricts the mDNS signaling backend's advertise
	// and query traffic to a single network interface (matched by name).
	// Empty = use all multicast-capable interfaces (the zeroconf default).
	// Only consulted when SignalingBackend == "mdns".
	MdnsIface string

	// SeedNodes is the bootstrap-seed onion list that wireSubsystems dials
	// when the routing table is empty at startup. Authoritative only when
	// SeedNodesSet is true; otherwise the daemon falls back to
	// discovery.DefaultSeeds(). The two-field shape lets an operator opt out
	// entirely (--seed-nodes="") without being indistinguishable from "unset
	// — please apply defaults".
	SeedNodes    []string
	SeedNodesSet bool
}

Config holds daemon startup configuration.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns a config with sensible defaults.

func (Config) ResolvedReceiveDir

func (c Config) ResolvedReceiveDir() string

ResolvedReceiveDir returns the directory incoming files are saved to: the explicit ReceiveDir override when set, otherwise the OS Downloads folder (XDG_DOWNLOAD_DIR if set, else ~/Downloads — the standard location on Linux, macOS and Windows). Falls back to <DataDir>/received only when no home directory is resolvable, so files never land somewhere unwritable.

func (Config) ResolvedSeeds

func (c Config) ResolvedSeeds() []string

ResolvedSeeds returns the effective bootstrap-seed list: the operator override (SeedNodes) when SeedNodesSet is true, otherwise the built-in discovery.DefaultSeeds list. The result is safe to mutate — both branches return a fresh slice.

type Daemon

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

Daemon manages the node lifecycle and gRPC server.

func New

func New(cfg Config) *Daemon

New creates a daemon with the given config.

func (*Daemon) APIServer

func (d *Daemon) APIServer() *api.Server

APIServer returns the daemon's gRPC service implementation. The in-process TUI's DirectBackend wires it as the command-invoker seam so slash-commands run through the same SendCommand / ListServiceCommands path the gRPC surface exposes (built-ins + augment dispatch), without a loopback.

func (*Daemon) ChatHistory

func (d *Daemon) ChatHistory() *chat.History

ChatHistory returns the daemon's chat message store, or nil if the chat service was never started (no p2p host). Used by the in-process TUI's DirectBackend to load + delete history.

func (*Daemon) MetricsRegistry

func (d *Daemon) MetricsRegistry() *metrics.Registry

MetricsRegistry returns the daemon's metrics registry. Always non-nil after Start; a no-op registry when the --metrics master flag is off, so readers (gRPC GetMetrics/StreamMetrics, Prometheus) see an empty snapshot rather than needing their own gate.

func (*Daemon) Node

func (d *Daemon) Node() *node.Node

Node returns the underlying node (for in-process TUI access).

func (*Daemon) SetAutoDialer

func (d *Daemon) SetAutoDialer(fn autoDialFn)

SetAutoDialer overrides the function used by the startup auto-dial sweep. Intended for tests: production callers should not touch this. Must be called before Start so the override is in place when the sweep launches.

func (*Daemon) Start

func (d *Daemon) Start() error

Start initializes identity, starts the node, and listens for gRPC connections.

func (*Daemon) Stop

func (d *Daemon) Stop()

Stop gracefully shuts down the daemon.

type PeerIntroductionEvent

type PeerIntroductionEvent struct {
	FromServiceAddr string
	ToAddr          string
	PeerAddr        string
	SessionID       string
	ExpiresAt       int64
	RoleHint        string
	Payload         []byte
}

PeerIntroductionEvent is the in-process payload published on the EventBus for an inbound peer introduction. Mirrors the proto fields so consumers can trust the daemon-attested from_service_addr.

type ServiceStateEvent

type ServiceStateEvent struct {
	Name     string `json:"name"`
	Version  string `json:"version"`
	State    string `json:"state"` // stopped|starting|running|backoff|blocked|errored|stopping
	Reason   string `json:"reason,omitempty"`
	PID      int    `json:"pid,omitempty"`
	Restarts int    `json:"restarts,omitempty"`
	Enabled  bool   `json:"enabled"`
}

ServiceStateEvent is the EventServiceState payload (ADR-0009): one supervised service's lifecycle change, JSON-encoded onto the Subscribe stream as a `service_state` DaemonEvent. All-strings/ints on purpose — the JSON event path must stay readable to clients without proto enums.

Jump to

Keyboard shortcuts

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