daemon

package
v0.101.1 Latest Latest
Warning

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

Go to latest
Published: Sep 1, 2026 License: MIT Imports: 38 Imported by: 0

Documentation

Overview

Package daemon implements kit's remote-session transport: a daemon mode (`kit daemon`) that hosts kit sessions for paired clients, and a client mode (`kit remote --host <name>`) that attaches a local terminal to that remote session. New clients pair via `kit daemon pair` + `kit remote --pair <code>`.

The design keeps all iroh logic inside the kit-tunnel sidecar (Rust, see contrib/kit-tunnel). The Go side owns policy only: pairing codes, frame relay, PTY and terminal management. See docs in the package files.

Index

Constants

View Source
const (
	// FrameClipboardFlagFinal marks the last chunk of a clipboard transfer.
	FrameClipboardFlagFinal byte = 0x01
	// FrameClipboardFlagClear marks a "clipboard has no image" signal: the
	// client sends it when Ctrl-V found no local image. The daemon clears
	// the session clipboard file so the child's Ctrl-V sees nothing.
	FrameClipboardFlagClear byte = 0x02
)
View Source
const (
	CodeAlphabet = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"
	CodeLength   = 8
)

CodeAlphabet excludes 0/O/1/I to keep codes readable and unambiguous when read aloud or copied. 8 characters from a 32-symbol alphabet is ~40 bits of entropy. The code stays valid for the daemon's lifetime and allows multiple sessions; guessing is throttled by the tunnel's handshake backoff (which also persists across failures), so treat the code like a password for the duration of the daemon run.

Variables

View Source
var (
	// ErrClipboardTooLarge is returned by the collector when a transfer
	// exceeds clipboardMaxImageSize.
	ErrClipboardTooLarge = errors.New("clipboard image too large")
)
View Source
var ErrNoLocalDaemon = errors.New("daemon: no local daemon is running")

ErrNoLocalDaemon is returned when nothing is listening on the local socket. Callers use it to decide whether to auto-start a daemon.

Functions

func AuthorizeClient

func AuthorizeClient(pubKeyHex string) (string, error)

AuthorizeClient stores a freshly paired client's public key.

func DecodeResize

func DecodeResize(payload []byte) (cols, rows int, err error)

DecodeResize unpacks a RESIZE payload.

func DialLocal added in v0.101.0

func DialLocal(ctx context.Context) (net.Conn, error)

DialLocal connects to the local daemon's control socket.

The context bounds the dial: a socket that exists but is not being accepted on would otherwise block past the caller's deadline.

func EncodeClipboardChunks

func EncodeClipboardChunks(mediaType string, data []byte) [][]byte

EncodeClipboardChunks splits an image into FrameClipboard payloads. The first chunk carries the media type; each payload's low bit marks the final chunk.

func EncodeResize

func EncodeResize(cols, rows int) []byte

EncodeResize packs cols/rows into a RESIZE payload.

func FindTunnelBinary

func FindTunnelBinary() (string, error)

FindTunnelBinary locates the kit-tunnel sidecar, in order:

  1. KIT_TUNNEL_BIN (explicit override)
  2. next to the kit executable (task-managed output/ layout)
  3. a repo checkout build (dev convenience for `go run ./cmd/kit daemon`)
  4. the embedded copy staged into the kit build by `task build` (extracted to the user cache dir on first use)
  5. PATH

func Fingerprint

func Fingerprint(raw []byte) string

Fingerprint is the short public identity used in prompts and stores: the first 16 hex chars of SHA-256 over the raw key bytes.

func ForgetHost

func ForgetHost(name string) error

ForgetHost removes a stored host. Returns an error when unknown.

func FormatCode

func FormatCode(code string) string

FormatCode renders a code for display as XXXX-XXXX.

func GenerateCode

func GenerateCode() (string, error)

GenerateCode returns a fresh random pairing code of CodeLength characters.

func InstallSystemService

func InstallSystemService(ctx context.Context) error

InstallSystemService writes the user unit and enables + starts it. When a daemon is already running interactively, the service's own lock attempt would fail forever, so refuse here instead of creating a restart loop.

func LoadClientIdentity

func LoadClientIdentity() ([]byte, error)

LoadClientIdentity returns the client's signing seed, creating it on first use.

func LoadDaemonIdentity

func LoadDaemonIdentity() ([]byte, error)

LoadDaemonIdentity returns the daemon's endpoint seed, creating it on first use. The seed doubles as the iroh endpoint secret.

func LocalSocketPath added in v0.101.0

func LocalSocketPath() (string, error)

LocalSocketPath returns the path of the local control socket.

XDG_RUNTIME_DIR is preferred: it is user-private (0700), on tmpfs, and cleared on logout, which is exactly the lifetime a socket wants. The cache dir is the fallback, alongside daemon.lock and daemon.json, so all daemon state stays in one place on systems without a runtime dir.

func NormalizeCode

func NormalizeCode(raw string) (string, error)

NormalizeCode uppercases a code and strips separators/spaces. It rejects anything that is not exactly CodeLength alphabet characters.

func RemoveSystemService

func RemoveSystemService(ctx context.Context) error

RemoveSystemService stops, disables, and deletes the user unit.

func ReportSessionCwd added in v0.101.0

func ReportSessionCwd(dir string)

ReportSessionCwd records the working directory a session settled on, so the daemon can show it in the session list. It is a no-op outside a daemon-hosted session, and a best-effort write: a session list without a directory is a cosmetic loss, never a reason to fail starting up.

func RunClient added in v0.101.0

func RunClient(ctx context.Context, rw io.ReadWriter, opts AttachOptions) (err error)

RunClient drives a daemon connection for the whole client session: pick a session, attach, run, and repeat when the user switches. It returns when the user detaches, the session ends, or the connection drops.

The caller owns rw and closes it.

func RunHost

func RunHost(ctx context.Context, name string, opts AttachOptions) error

RunHost attaches the local terminal to a paired daemon by name: `kit remote --host homelab`. Authentication is by client signing key; no pairing code is involved.

The sidecar stream is handed to RunClient, which owns everything above the transport: session choice, raw mode, the input pumps and the chord table. The local socket path (kit attach) uses the same code.

func RunLocal added in v0.101.0

func RunLocal(ctx context.Context, opts AttachOptions) error

RunLocal attaches the terminal to the local daemon, starting one when none is running.

func RunPair

func RunPair(ctx context.Context, opts PairOptions) error

RunPair performs one-time pairing against a host's pairing window: it proves knowledge of the one-time code, hands the host this machine's signing public key, and stores the host under a friendly name for codeless reconnection with RunHost.

All user-facing messages go to stderr — nothing touches stdout except the eventual remote session.

func RunPairWindow

func RunPairWindow(ctx context.Context, opts PairWindowOptions) error

RunPairWindow opens a one-time pairing window: it derives an ephemeral bootstrap endpoint from a fresh code, shows the code, and — when a client presents it — asks the user to accept or reject on this terminal. On accept the client's public key joins the allowlist and the client learns this daemon's endpoint id; the code is then burned.

The window is independent of the main daemon process: pairing writes the allowlist to disk, and `kit daemon` (running or not) picks it up on the next connection attempt.

func SaveHost

func SaveHost(name string, endpointID string) error

SaveHost adds (or replaces) a paired host entry under the given name. The endpoint id must be 64 hex chars (an ed25519 public key) so a stored entry can never crash the sidecar's dial path later.

func SeedFromCode

func SeedFromCode(rawCode string) ([]byte, error)

SeedFromCode derives the 32-byte endpoint seed from a pairing code using HKDF-SHA256 with fixed salt/info. The code is normalized first so both sides agree on every input regardless of how the user typed it.

func Serve

func Serve(ctx context.Context) error

Serve runs the daemon until ctx is cancelled: bind the stable endpoint derived from the daemon identity, then host remote sessions for paired clients. Each client authenticates by signing the handshake with its pairing key; the signature is checked against the allowlist written by `kit daemon pair`. First-time clients pair through `kit daemon pair`, which runs its own short-lived bootstrap endpoint.

func StartLocalDaemon added in v0.101.0

func StartLocalDaemon(ctx context.Context) error

StartLocalDaemon launches a background daemon and waits for its socket.

This is the tmux behaviour: `kit attach` on a machine with no daemon starts one rather than telling the user to. The child is fully detached (its own process group, no inherited terminal) so it outlives the terminal that spawned it — a daemon killed by the hangup of the shell that started it would defeat the point of detachable sessions.

Two clients racing to start a daemon is safe: the loser fails on the single-instance flock and both then connect to the winner's socket.

func TouchClient

func TouchClient(fp string) error

TouchClient updates last_seen after a successful authenticated handshake. Runs under the store lock so a concurrent revoke is never resurrected by a stale read-modify-write.

func TouchHost

func TouchHost(name string) error

TouchHost updates last_used after a successful connection.

func WriteDataFrames

func WriteDataFrames(w io.Writer, session uint32, b []byte) error

WriteDataFrames splits b into chunkSize DATA frames tagged with session.

func WriteFrame

func WriteFrame(w io.Writer, t FrameType, session uint32, payload []byte) error

WriteFrame writes one frame.

Types

type AttachOptions added in v0.101.0

type AttachOptions struct {
	// Name identifies the daemon in user-facing messages.
	Name string
	// Host is the saved host name this client is connected to, matching
	// the Host the picker reports for this daemon's own sessions. Empty
	// means the local daemon. It is how a cross-host choice is told apart
	// from one on this daemon, so it must be the picker's value, not a
	// display string.
	Host string
	// Reattach is the command that reattaches to this daemon, quoted in
	// the message printed after a detach.
	Reattach string
	// Pick chooses among live sessions. When nil, the client always
	// starts a new session and in-session switching is disabled.
	Pick SessionPicker
	// Target selects a session up front: zero consults Pick, and any
	// other value attaches directly.
	Target uint64
	// ForceNew skips the picker and starts a new session.
	ForceNew bool
	// Hub, when set, handles a cross-host switch request.
	Hub SessionPicker
	// HubEntries supplies sessions from other hosts for the hub picker.
	// The context bounds the queries it makes.
	HubEntries func(ctx context.Context) []SessionEntry
}

AttachOptions configures a client attach loop.

type ClientEntry

type ClientEntry struct {
	FP       string    `json:"fp"`     // Fingerprint(client public key)
	PubKey   string    `json:"pubkey"` // 64 hex chars (ed25519 public)
	Label    string    `json:"label"`  // optional note set at pairing time
	AddedAt  time.Time `json:"added_at"`
	LastSeen time.Time `json:"last_seen"`
}

ClientEntry is one paired client, as known on the host.

func ListAuthorized

func ListAuthorized() ([]ClientEntry, error)

ListAuthorized returns all paired clients, sorted by fingerprint.

func LookupClient

func LookupClient(fp string) (ClientEntry, bool, error)

LookupClient verifies a fingerprint is authorized and returns its entry.

func RevokeClient

func RevokeClient(fpOrPrefix string) (ClientEntry, error)

RevokeClient removes an authorized client by fingerprint (or by its unique short prefix). Returns the removed entry.

type ClientKeyPair

type ClientKeyPair struct {
	Seed   []byte
	Priv   ed25519.PrivateKey
	Pub    ed25519.PublicKey
	PubHex string // 64 hex chars
}

ClientKeyPair is the client's signing identity.

func NewClientKeyPair

func NewClientKeyPair(seed []byte) ClientKeyPair

NewClientKeyPair derives the full ed25519 keypair from the stored seed.

type ClipboardCollector

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

ClipboardCollector reassembles a chunked clipboard transfer.

func NewClipboardCollector

func NewClipboardCollector() *ClipboardCollector

NewClipboardCollector returns a collector for one image transfer.

func (*ClipboardCollector) Add

func (c *ClipboardCollector) Add(payload []byte) (done bool, mediaType string, data []byte, err error)

Add consumes one FrameClipboard payload. On the final chunk it returns the complete image; the collector must then be discarded.

type ErrSwitchHost added in v0.101.0

type ErrSwitchHost struct {
	// Host is the saved name of the daemon to connect to.
	Host string
	// Session is the logical session to attach to on that daemon.
	Session uint64
}

ErrSwitchHost reports that the user chose a session on a different daemon. The client speaks to exactly one daemon, so honouring the choice means the caller dials the new host and starts a fresh client; a SessionChoice.Host that this connection cannot reach must never be attached by ID alone, because every daemon numbers its sessions from 1 and the ID would silently resolve to a different session here.

func (*ErrSwitchHost) Error added in v0.101.0

func (e *ErrSwitchHost) Error() string

type Frame

type Frame struct {
	Type    FrameType
	Session uint32
	Payload []byte
}

Frame is one relayed message. Session 0 is used on the client side (the dial tunnel rewrites ids in both directions) and in tests.

func ReadFrame

func ReadFrame(r io.Reader) (Frame, error)

ReadFrame reads one frame. Returns io.EOF when the reader ends cleanly on a frame boundary (peer closed).

type FrameType

type FrameType byte

Frame types shared with contrib/kit-tunnel/src/main.rs (protocol v1). Data/resize/bye are relayed end-to-end by the tunnel, multiplexed by session id; ping/pong are reserved for a future keepalive; the 0x1x handshake/session frames never cross the tunnel boundary — the serve-side tunnel emits SESSION_OPEN/CLOSED on its stdout to introduce and retire sessions to the Go daemon.

const (
	FrameData   FrameType = 0x01
	FrameResize FrameType = 0x02
	FrameBye    FrameType = 0x03
	FramePing   FrameType = 0x04
	FramePong   FrameType = 0x05

	// Client -> daemon clipboard image transfer (chunked; see
	// internal/daemon/clipboard.go for the payload layout). Relayed by the
	// sidecar verbatim like DATA/RESIZE; consumed by the daemon, never
	// written to the session PTY.
	FrameClipboard FrameType = 0x06

	// Session lifecycle (additive, relayed verbatim by the sidecar like
	// CLIPBOARD). Sessions are LOGICAL: they outlive client connections,
	// so a client can detach (Ctrl+X d) and later reattach, and several
	// clients can attach to the same session (shared tmux-style view).
	// Wire session ids are per sidecar connection; the daemon maps them to
	// logical sessions.
	FrameSessionDetach    FrameType = 0x07 // client -> daemon: unbind me, keep the session
	FrameSessionList      FrameType = 0x08 // client -> daemon: list live sessions (payload empty)
	FrameSessionListReply FrameType = 0x09 // daemon -> client: JSON [{id,clients,started,cwd,name}]
	FrameSessionAttach    FrameType = 0x0a // client -> daemon: {logical id u64 BE}
	FrameSessionAttachAck FrameType = 0x0b // daemon -> client: {logical id u64 BE, ok 0|1}
	// FrameSessionRedraw asks the daemon to make the session's child
	// repaint. A client that has just attached inherits a screen the child
	// already drew, so without this the terminal stays blank until the
	// next keystroke. The daemon nudges the PTY size, which is what makes
	// a full-screen TUI redraw; doing it daemon-side keeps the two size
	// changes off the network, where the round trip made the old
	// client-side version of this trick unreliable.
	FrameSessionRedraw FrameType = 0x0c // client -> daemon: repaint (payload empty)
	// FrameSessionRename sets a session's display name so a list of many
	// sessions stays readable.
	FrameSessionRename FrameType = 0x0d // client -> daemon: {id u64 BE, name UTF-8}

	// Tunnel -> daemon session lifecycle (serve side only).
	FrameSessionOpen   FrameType = 0x16
	FrameSessionClosed FrameType = 0x17

	// Pairing-model control frames on the tunnel stdio (protocol v1 in
	// the sidecar). They never cross the iroh connection; they are the
	// daemon<->sidecar consultation channel that keeps all policy in Go.
	//
	// Reconnect authentication (main endpoint):
	//   AUTH_REQUEST  sidecar->daemon {c_nonce, s_nonce, client_pub}  (8+8+32)
	//   AUTH_PAYLOAD  sidecar->daemon {signature}                     (64)
	//   AUTH_DECISION daemon->sidecar {0|1}
	// Pairing (bootstrap endpoint):
	//   PAIR_REQUEST  sidecar->daemon {c_nonce, client_pub}           (8+32)
	//   PAIR_DECISION daemon->sidecar {0|1, host_endpoint_id?}        (1 or 33)
	//   PAIR_CANCEL   sidecar->daemon {corr}                          (8)
	FrameAuthRequest  FrameType = 0x30
	FrameAuthPayload  FrameType = 0x31
	FrameAuthDecision FrameType = 0x32
	FramePairRequest  FrameType = 0x40
	FramePairDecision FrameType = 0x41
	// FramePairCancel withdraws a pending pairing question: the client
	// behind it disconnected, so the prompt on the host's terminal is
	// stale and must not block the window.
	FramePairCancel FrameType = 0x42
)

type HostEntry

type HostEntry struct {
	Name       string    `json:"name"`
	EndpointID string    `json:"endpoint_id"` // 64 hex chars (ed25519 public key)
	HostFP     string    `json:"host_fp"`     // Fingerprint(EndpointID)
	AddedAt    time.Time `json:"added_at"`
	LastUsed   time.Time `json:"last_used"`
}

HostEntry is one paired daemon, as known on the client.

func GetHost

func GetHost(name string) (HostEntry, error)

GetHost returns the stored entry for name.

func ListHosts

func ListHosts() ([]HostEntry, error)

ListHosts returns all paired hosts, sorted by name.

type IdentityPaths

type IdentityPaths struct {
	DaemonSeed string // daemon endpoint seed (~/.config/kit/daemon/identity.key)
	ClientSeed string // client signing seed (~/.config/kit/remote/identity.key)
}

IdentityPaths resolves the key file locations under ~/.config/kit.

type PairOptions

type PairOptions struct {
	// Name pre-selects the saved host name (skips the interactive prompt).
	Name string
	// Code is the one-time pairing code shown by 'kit daemon pair'.
	Code string
}

PairOptions controls `kit remote --pair`. Code is required; all other fields are optional.

type PairWindowOptions

type PairWindowOptions struct {
	// Code forces a specific pairing code instead of a random one.
	// Intended for tests.
	Code string
	// Prompt overrides the interactive accept/reject decision (tests).
	// When nil, the decision is made on the terminal; a non-TTY stdin
	// always denies. Implementations should return false when ctx ends.
	Prompt func(ctx context.Context, fp string) bool
	// Window bounds the pairing window. Zero means the default (10 min).
	Window time.Duration
}

PairWindowOptions controls `kit daemon pair`. Zero values are valid.

type SessionChoice added in v0.101.0

type SessionChoice struct {
	// ID is the logical session to attach to. Zero means "start a new
	// session" unless Cancel is set.
	ID uint64
	// Host names the daemon the session belongs to, for the multi-host
	// picker. Empty means the daemon currently connected.
	Host string
	// Cancel reports that the user dismissed the picker.
	Cancel bool
}

SessionChoice is what a picker returns.

type SessionEntry added in v0.101.0

type SessionEntry struct {
	ID      uint64
	Clients int
	Started time.Time
	Cwd     string
	Name    string
	// Host is the saved host name a session belongs to. Empty for the
	// local daemon; set by the hub when several daemons are listed at once.
	Host string
}

SessionEntry describes one live session on a daemon, as reported by the session list. It is the daemon's own type so the picker can be supplied by the caller: the UI layer converts to its own view model, which keeps internal/daemon free of a dependency on internal/ui.

func ListHostSessions added in v0.101.0

func ListHostSessions(ctx context.Context, name string, timeout time.Duration) ([]SessionEntry, error)

ListHostSessions queries one paired host's live sessions without attaching, for the multi-host picker. The whole exchange is bounded by timeout: an unreachable host must not stall a picker that has other hosts to show.

ctx cancels the query early. The picker queries every paired host at once, and each query is a sidecar process, so a caller that gives up must be able to take them down without waiting out the timeout.

func ListLocalSessions added in v0.101.0

func ListLocalSessions(ctx context.Context) ([]SessionEntry, error)

ListLocalSessions reports the local daemon's live sessions without attaching. Returns ErrNoLocalDaemon when nothing is running, so a caller can distinguish "no daemon" from "a daemon with no sessions".

type SessionPicker added in v0.101.0

type SessionPicker func(ctx context.Context, entries []SessionEntry, input *os.File) (SessionChoice, error)

SessionPicker presents live sessions and returns the user's choice. It runs with the terminal in cooked mode and owns the screen while it runs.

input is the terminal input the picker must read from. The client keeps a single reader on os.Stdin for its whole life, so a picker that opened its own would race it for keystrokes.

ctx cancels the picker. It is the one blocking call in an attached client that the user cannot always end from the keyboard, so it has to honour the same cancellation as the session loop around it.

type Status

type Status struct {
	// Running is true when a live process holds the daemon lock.
	Running bool
	// State is the daemon's last persisted snapshot, nil when none exists.
	// For a stopped daemon this is stale data from a previous run.
	State *daemonState
}

Status describes a kit daemon on this machine (per user).

func ReadStatus

func ReadStatus() Status

ReadStatus reports whether a daemon currently holds the lock. Probing is a non-blocking exclusive flock: acquiring it means no daemon is alive.

type Tunnel

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

Tunnel is a running kit-tunnel sidecar process. Its stdout carries the relayed frames; its stderr carries "STATUS ..." lifecycle lines.

func StartTunnel

func StartTunnel(ctx context.Context, opts TunnelOptions) (*Tunnel, error)

StartTunnel launches the sidecar with the given options. Status lines are parsed from stderr; frames flow on stdin/stdout.

func (*Tunnel) Close

func (t *Tunnel) Close()

Close shuts the tunnel down in stages: closing stdin lets the process flush any pending BYE frame to the remote peer and exit on its own; only after a grace period do we kill it. An immediate kill would drop the BYE on the wire and leave the peer waiting on a silent connection.

func (*Tunnel) Exited

func (t *Tunnel) Exited() <-chan error

Exited returns a channel that receives the process exit error once.

func (*Tunnel) LastStatuses

func (t *Tunnel) LastStatuses() string

LastStatuses returns the trailing stderr lines for diagnostics.

func (*Tunnel) StatusCh

func (t *Tunnel) StatusCh() <-chan string

StatusCh exposes the raw status channel for event loops.

func (*Tunnel) Stdin

func (t *Tunnel) Stdin() io.WriteCloser

Stdin is the frame destination for data flowing toward the remote peer.

func (*Tunnel) Stdout

func (t *Tunnel) Stdout() io.ReadCloser

Stdout is the frame source for data flowing from the remote peer.

func (*Tunnel) WaitAnyStatus

func (t *Tunnel) WaitAnyStatus(ctx context.Context, timeout time.Duration, want ...string) (string, error)

WaitAnyStatus blocks until the tunnel reports any of the wanted statuses (matched on the first field), the process exits, or ctx is done. A timeout of zero or less means no deadline. Returns the matched status line.

func (*Tunnel) WaitStatus

func (t *Tunnel) WaitStatus(ctx context.Context, want string, timeout time.Duration) (string, error)

WaitStatus blocks until the tunnel reports a status line whose first field is want, the process exits, or the timeout elapses. A timeout of zero or less means no deadline.

type TunnelOptions

type TunnelOptions struct {
	Mode string
	Args []string // public flags after the mode
	Env  []string // KEY=VALUE pairs (secret seeds) added to the child env
}

TunnelOptions describes one sidecar invocation. Args carry the mode's public flags (e.g. "--timeout", "30"); Env carries key material — argv is world-readable via ps, the child environment is not.

Jump to

Keyboard shortcuts

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