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
- Variables
- func AuthorizeClient(pubKeyHex string) (string, error)
- func DecodeResize(payload []byte) (cols, rows int, err error)
- func EncodeClipboardChunks(mediaType string, data []byte) [][]byte
- func EncodeResize(cols, rows int) []byte
- func FindTunnelBinary() (string, error)
- func Fingerprint(raw []byte) string
- func ForgetHost(name string) error
- func FormatCode(code string) string
- func GenerateCode() (string, error)
- func InstallSystemService(ctx context.Context) error
- func LoadClientIdentity() ([]byte, error)
- func LoadDaemonIdentity() ([]byte, error)
- func NormalizeCode(raw string) (string, error)
- func RemoveSystemService(ctx context.Context) error
- func RunHost(ctx context.Context, name string) error
- func RunPair(ctx context.Context, opts PairOptions) error
- func RunPairWindow(ctx context.Context, opts PairWindowOptions) error
- func SaveHost(name string, endpointID string) error
- func SeedFromCode(rawCode string) ([]byte, error)
- func Serve(ctx context.Context) error
- func TouchClient(fp string) error
- func TouchHost(name string) error
- func WriteDataFrames(w io.Writer, session uint32, b []byte) error
- func WriteFrame(w io.Writer, t FrameType, session uint32, payload []byte) error
- type ClientEntry
- type ClientKeyPair
- type ClipboardCollector
- type Frame
- type FrameType
- type HostEntry
- type IdentityPaths
- type PairOptions
- type PairWindowOptions
- type Status
- type Tunnel
- func (t *Tunnel) Close()
- func (t *Tunnel) Exited() <-chan error
- func (t *Tunnel) LastStatuses() string
- func (t *Tunnel) StatusCh() <-chan string
- func (t *Tunnel) Stdin() io.WriteCloser
- func (t *Tunnel) Stdout() io.ReadCloser
- func (t *Tunnel) WaitAnyStatus(ctx context.Context, timeout time.Duration, want ...string) (string, error)
- func (t *Tunnel) WaitStatus(ctx context.Context, want string, timeout time.Duration) (string, error)
- type TunnelOptions
Constants ¶
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 )
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 ¶
var ( // ErrClipboardTooLarge is returned by the collector when a transfer // exceeds clipboardMaxImageSize. ErrClipboardTooLarge = errors.New("clipboard image too large") )
Functions ¶
func AuthorizeClient ¶
AuthorizeClient stores a freshly paired client's public key.
func DecodeResize ¶
DecodeResize unpacks a RESIZE payload.
func EncodeClipboardChunks ¶
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 ¶
EncodeResize packs cols/rows into a RESIZE payload.
func FindTunnelBinary ¶
FindTunnelBinary locates the kit-tunnel sidecar, in order:
- KIT_TUNNEL_BIN (explicit override)
- next to the kit executable (task-managed output/ layout)
- a repo checkout build (dev convenience for `go run ./cmd/kit daemon`)
- the embedded copy staged into the kit build by `task build` (extracted to the user cache dir on first use)
- PATH
func Fingerprint ¶
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 ¶
ForgetHost removes a stored host. Returns an error when unknown.
func FormatCode ¶
FormatCode renders a code for display as XXXX-XXXX.
func GenerateCode ¶
GenerateCode returns a fresh random pairing code of CodeLength characters.
func InstallSystemService ¶
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 ¶
LoadClientIdentity returns the client's signing seed, creating it on first use.
func LoadDaemonIdentity ¶
LoadDaemonIdentity returns the daemon's endpoint seed, creating it on first use. The seed doubles as the iroh endpoint secret.
func NormalizeCode ¶
NormalizeCode uppercases a code and strips separators/spaces. It rejects anything that is not exactly CodeLength alphabet characters.
func RemoveSystemService ¶
RemoveSystemService stops, disables, and deletes the user unit.
func RunHost ¶
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 remote daemon shows its directory picker inside this terminal, then the session TUI takes over.
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 ¶
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 ¶
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 ¶
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 TouchClient ¶
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 WriteDataFrames ¶
WriteDataFrames splits b into chunkSize DATA frames tagged with session.
Types ¶
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.
type Frame ¶
Frame is one relayed message. Session 0 is used on the client side (the dial tunnel rewrites ids in both directions) and in tests.
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}] FrameSessionAttach FrameType = 0x0a // client -> daemon: {logical id u64 BE} FrameSessionAttachAck FrameType = 0x0b // daemon -> client: {logical id u64 BE, ok 0|1} // 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.
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 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) LastStatuses ¶
LastStatuses returns the trailing stderr lines for diagnostics.
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.