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 BackgroundIsDark(hex string) bool
- func DecodeResize(payload []byte) (cols, rows int, err error)
- func DialLocal(ctx context.Context) (net.Conn, error)
- func EncodeClipboardChunks(mediaType string, data []byte) [][]byte
- func EncodeResize(cols, rows int) []byte
- func EncodeTerminalInfo(info TerminalInfo) ([]byte, error)
- func FindTunnelBinary() (string, error)
- func Fingerprint(raw []byte) string
- func ForgetHost(name string) error
- func FormatCode(code string) string
- func GenerateCode() (string, error)
- func HexColor(c color.Color) string
- func InstallSystemService(ctx context.Context) error
- func LoadClientIdentity() ([]byte, error)
- func LoadDaemonIdentity() ([]byte, error)
- func LocalSocketPath() (string, error)
- func NormalizeCode(raw string) (string, error)
- func RemoveSystemService(ctx context.Context) error
- func ReportSessionCwd(dir string)
- func RunClient(ctx context.Context, rw io.ReadWriter, opts AttachOptions) (err error)
- func RunHost(ctx context.Context, name string, opts AttachOptions) error
- func RunLocal(ctx context.Context, opts AttachOptions) 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 StartLocalDaemon(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 AttachOptions
- type ClientEntry
- type ClientKeyPair
- type ClipboardCollector
- type ErrSwitchHost
- type Frame
- type FrameType
- type HostEntry
- type IdentityPaths
- type PairOptions
- type PairWindowOptions
- type SessionChoice
- type SessionEntry
- type SessionPicker
- type Status
- type TerminalInfo
- 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.
const ( // RemoteSessionEnv marks a child as running inside a daemon session. RemoteSessionEnv = "KIT_REMOTE_SESSION" // RemoteBackgroundEnv holds the CLIENT terminal's background colour as // "#rrggbb", or BackgroundUnknown when that terminal was asked and did // not answer. The child prefers it over its own OSC query, which would // otherwise have to cross the PTY — and, for a remote session, the // network — before the first frame is drawn, and which the client, // being the side that owns the terminal, can answer without any of it. RemoteBackgroundEnv = "KIT_REMOTE_BACKGROUND" )
const BackgroundUnknown = "unknown"
BackgroundUnknown marks a terminal that was asked for its background colour and did not answer.
Variables ¶
var ( // ErrClipboardTooLarge is returned by the collector when a transfer // exceeds clipboardMaxImageSize. ErrClipboardTooLarge = errors.New("clipboard image too large") )
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 ¶
AuthorizeClient stores a freshly paired client's public key.
func BackgroundIsDark ¶ added in v0.101.2
BackgroundIsDark reports whether a reported background reads as dark.
The test is HSL lightness below one half, which is the test lipgloss applies to a background it queried itself. Sharing the rule means a session started from this environment variable and one started from a live query never disagree about which half of a theme to render. A value that names no colour — BackgroundUnknown among them — reports dark, matching lipgloss's own answer for a terminal that will not say.
func DecodeResize ¶
DecodeResize unpacks a RESIZE payload.
func DialLocal ¶ added in v0.101.0
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 ¶
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 EncodeTerminalInfo ¶ added in v0.101.2
func EncodeTerminalInfo(info TerminalInfo) ([]byte, error)
EncodeTerminalInfo renders a TERMINAL 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 HexColor ¶ added in v0.101.2
HexColor renders a colour as "#rrggbb". color.Color reports 16-bit premultiplied channels, so each is scaled back to 8 bits. A nil colour yields "", which callers read as "the terminal did not say".
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 LocalSocketPath ¶ added in v0.101.0
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 ¶
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 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 ¶
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 StartLocalDaemon ¶ added in v0.101.0
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 ¶
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 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.
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 ¶
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,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} // FrameTerminal describes the CLIENT's terminal to the daemon (JSON, // see TerminalInfo). A daemon owns a PTY, not a terminal, and a PTY // reports no colour depth and answers no background-colour query, so // without this a session's child describes the daemon's own // environment — under a service manager, no terminal at all. Sent // before SESSION_ATTACH so a new session's child is spawned already // describing the terminal it will be seen in. FrameTerminal FrameType = 0x0e // client -> daemon: JSON TerminalInfo // 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 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 TerminalInfo ¶ added in v0.101.2
type TerminalInfo struct {
Term string `json:"term,omitempty"`
ColorTerm string `json:"colorterm,omitempty"`
// Background is the terminal background as "#rrggbb", or
// BackgroundUnknown when the terminal was asked and did not answer.
// The two are distinct on purpose: "asked, no answer" tells the child
// not to spend its own startup asking again, where an empty value (a
// client too old to probe at all) leaves it free to try.
Background string `json:"background,omitempty"`
// Multiplexer names the terminal multiplexer the client runs inside
// ("tmux", "screen", "zellij"), or is empty for a bare terminal. A
// multiplexer's pane variables describe a process's own pane and so
// never cross the wire; without this the child probes a terminal that
// answers from behind one and then draws graphics the multiplexer
// discards. See termgfx.RemoteMultiplexerEnv.
Multiplexer string `json:"multiplexer,omitempty"`
}
TerminalInfo describes the client terminal a session is rendered in. The daemon cannot observe any of it: it owns the PTY, and a PTY answers no capability queries of its own.
Term and ColorTerm are forwarded into the child's environment the way ssh forwards TERM, so colour-depth detection sees the user's terminal. Background is the terminal's own background colour, which decides whether a theme renders its light or its dark palette; the client resolves it locally because the OSC query that answers it must otherwise cross a PTY and a network before the first frame is drawn.
func DecodeTerminalInfo ¶ added in v0.101.2
func DecodeTerminalInfo(payload []byte) (TerminalInfo, error)
DecodeTerminalInfo parses a TERMINAL payload.
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.