Documentation
¶
Overview ¶
Package remotecontrol implements the /remote-control feature: an in-process web server that lets a phone on the same LAN mirror the CLI session, inject prompts, and approve risky tool calls (see tasks/spec-remote-control.md).
This file (node #438) provides the auth substrate: a one-time, TTL-bound pairing token that a paired browser exchanges for an opaque session credential. All state is in-memory and process-scoped; nothing is persisted or logged, and Clear() wipes it on shutdown.
Index ¶
- Constants
- Variables
- func DetectRoutableIP() (string, error)
- func ListenFreePort(host string, port int) (net.Listener, int, error)
- func Render(url string) (string, error)
- type Bridge
- func (b *Bridge) Close()
- func (b *Bridge) Confirm(ctx context.Context, tool, summary string) (Decision, bool)
- func (b *Bridge) DenyAllPending() int
- func (b *Bridge) Enabled() bool
- func (b *Bridge) OnDecide(confirmID string, approve, always bool)
- func (b *Bridge) OnInput(text string)
- func (b *Bridge) OutputWriter() io.Writer
- func (b *Bridge) RemoteInput() <-chan string
- func (b *Bridge) ResolveConfirm(confirmID string, approve, always bool) bool
- type Config
- type Decision
- type Frame
- type FrameType
- type Handler
- type Server
- func (s *Server) Addr() string
- func (s *Server) Broadcast(f Frame)
- func (s *Server) HasClient() bool
- func (s *Server) SendConfirm(confirmID, tool, summary string)
- func (s *Server) SendOutput(text string)
- func (s *Server) SetHandler(h Handler)
- func (s *Server) Start() (string, error)
- func (s *Server) Stop(ctx context.Context) error
- type Sink
- type TokenStore
Constants ¶
const ( StatusConnected = "connected" StatusEnded = "ended" StatusDisconnected = "disconnected" )
Status values carried in Frame.State for FrameStatus frames.
Variables ¶
var ErrNoLAN = errors.New("remotecontrol: no routable LAN address found; are you connected to Wi-Fi?")
ErrNoLAN is returned by DetectRoutableIP when no routable, non-loopback IPv4 address can be found. Binding loopback would produce a URL the phone cannot reach, so the caller must surface this rather than fall back silently.
var ErrNotStarted = errors.New("remotecontrol: server not started")
ErrNotStarted is returned by operations that require a running server.
Functions ¶
func DetectRoutableIP ¶
DetectRoutableIP returns a routable IPv4 address suitable for embedding in the printed pairing URL — one a phone on the same Wi-Fi can actually reach.
It iterates interfaces (not bare addresses) so it can skip the ones that would yield an unreachable URL: interfaces that are down, loopback, or point-to-point (VPN utun / tunnel links, whose address the phone cannot route to). Among the rest it prefers a private LAN address (RFC1918: 10/8, 172.16/12, 192.168/16), which is what home/office Wi-Fi hands out; a non-private routable address is used only as a fallback when no private one exists. Callers that need a specific interface should override via Config.Host. It returns ErrNoLAN when nothing routable exists.
func ListenFreePort ¶
ListenFreePort binds a TCP listener on host. It first tries the requested port; if port is 0 or already in use it falls back to a kernel-assigned free port (:0). It returns the listener and the actual port bound.
func Render ¶
Render encodes url as a QR code drawn with Unicode half-block characters, suitable for scanning off a terminal by a phone camera. Two matrix rows are packed into each text line (▀ ▄ █ and space), halving the printed height.
The rendering assumes a dark-background terminal: light QR modules are drawn as bright block glyphs and dark modules as the terminal background. go-qrcode includes the mandatory quiet-zone border in its bitmap.
On any encoding error Render returns ("", err); callers should degrade gracefully by printing the URL alone (the QR is a convenience, not required).
Types ¶
type Bridge ¶
type Bridge struct {
// contains filtered or unexported fields
}
Bridge is the seam that merges the local terminal with a remote browser controlling the same REPL session. It:
- tees session output to the remote client (OutputWriter),
- surfaces remote-submitted prompts as an input channel (RemoteInput),
- routes confirmation prompts to the remote and awaits a decision (Confirm), resolvable either remotely (OnDecide) or locally (ResolveConfirm).
A nil *Bridge (deps.remote == nil) means remote control is off; callers must guard with Enabled or simply not construct one, so existing behavior is byte-identical.
Bridge implements the server Handler interface (OnInput, OnDecide).
func (*Bridge) Close ¶ added in v1.2.5
func (b *Bridge) Close()
Close closes the remote-input channel so a listener blocked in RemoteInput returns, and drops subsequent input. It is called when the remote session stops, so no listener goroutine outlives the session it was watching. Close is idempotent; OnInput after Close is a no-op rather than a panic.
func (*Bridge) Confirm ¶
Confirm requests approval for a risky tool call from the remote client and blocks until the client decides, the context is cancelled (e.g. answered locally instead), or a deadline in ctx fires. The returned bool is true only when the decision came from the remote client; on ctx cancellation it is false and the caller should fall back to the local answer.
func (*Bridge) DenyAllPending ¶ added in v1.2.5
DenyAllPending resolves every pending confirmation as a denial. It is the client-disconnect path: the controlling browser is gone, so nobody can answer, and leaving the gate parked would stall the run until the user interrupts it manually. Denials are fail-closed, the same answer an interrupted Confirm produces. It returns how many waiters were resolved.
func (*Bridge) OnDecide ¶
OnDecide implements Handler: the remote client's answer to a confirmation.
func (*Bridge) OnInput ¶
OnInput implements Handler: a remote prompt. Non-blocking so the WebSocket read goroutine is never stalled; if the buffer is full the oldest queued prompt is dropped to make room (refined in #445).
func (*Bridge) OutputWriter ¶
OutputWriter returns an io.Writer that streams everything written to it to the remote client as output frames. It is intended to be combined with the local terminal writer via io.MultiWriter, so local rendering is unchanged and the remote receives a copy. Writes never fail and never block on the network (delivery is best-effort via the sink).
func (*Bridge) RemoteInput ¶
RemoteInput exposes prompts submitted by the remote client. The REPL input loop selects on this channel alongside local stdin.
func (*Bridge) ResolveConfirm ¶
ResolveConfirm delivers a decision to a pending Confirm. It returns true if a waiting Confirm was resolved. Both the remote path (OnDecide) and the local terminal path may call it; the first delivery wins and later ones are no-ops.
type Config ¶
type Config struct {
PairTTL time.Duration // pairing-token lifetime; 0 → defaultPairTTL
Host string // LAN IP for the printed URL; "" → auto-detect
Port int // 0 → auto-pick, fall back on conflict
ConfirmTimeout time.Duration // 0 → wait forever for a remote decision
// OnClientConnect, if set, is invoked (on the WebSocket goroutine) when a
// browser pairs and connects, with the client's remote address. The REPL uses
// it to print a one-line terminal notice so the operator notices remote access
// (§7.3). It must not block for long.
OnClientConnect func(remoteAddr string)
// OnClientDisconnect, if set, is invoked when the controlling client's
// WebSocket closes. It must not block for long.
OnClientDisconnect func()
}
Config controls a remote-control server instance.
type Frame ¶
type Frame struct {
Type FrameType `json:"type"`
// Output
Text string `json:"text,omitempty"`
// Confirm
ConfirmID string `json:"confirmId,omitempty"`
Tool string `json:"tool,omitempty"`
Summary string `json:"summary,omitempty"`
// Decide
Approve bool `json:"approve,omitempty"`
Always bool `json:"always,omitempty"`
// Status
State string `json:"state,omitempty"` // connected | ended | disconnected
Reason string `json:"reason,omitempty"` // human-readable detail for State
}
Frame is a single WebSocket message. Fields are populated according to Type; unused fields are omitted from the JSON encoding.
type FrameType ¶
type FrameType string
FrameType enumerates the WebSocket message kinds exchanged between the server and the paired browser. It is the wire contract shared with the embedded SPA.
const ( // FrameOutput streams session text from server to client. FrameOutput FrameType = "output" // FrameInput carries a prompt line submitted by the client to the server. FrameInput FrameType = "input" // FrameConfirm asks the client to approve/reject a risky tool call. FrameConfirm FrameType = "confirm" // FrameDecide carries the client's approval decision back to the server. FrameDecide FrameType = "decide" // FrameStatus reports session lifecycle changes to the client. FrameStatus FrameType = "status" )
type Handler ¶
type Handler interface {
// OnInput is called when the client submits a prompt line.
OnInput(text string)
// OnDecide is called when the client answers a confirmation request.
OnDecide(confirmID string, approve, always bool)
}
Handler receives frames the browser sends. The REPL bridge implements it; tests supply a fake. Callbacks run on the WebSocket read goroutine and must not block for long.
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server is an in-process HTTP + WebSocket server that mirrors the CLI session to a single paired browser on the LAN.
func NewServer ¶
NewServer builds a server. handler may be nil (frames from the client are then ignored), which is useful for output-only smoke tests.
func (*Server) Broadcast ¶
Broadcast sends a frame to the connected client, if any. It is safe to call from any goroutine.
func (*Server) SendConfirm ¶
SendConfirm asks the client to approve a risky tool call.
func (*Server) SendOutput ¶
SendOutput streams session text to the client. It never drops bytes: the text is appended to the ring (for replay) and to the pending buffer that the pump coalesces and flushes. If pending output has grown past outputQueueMax the call blocks until the pump drains it, applying backpressure to the producer rather than discarding output (§5.4, §8.4). It returns immediately once the server is stopping so a shutting-down producer never wedges.
func (*Server) SetHandler ¶
SetHandler installs the handler that receives client frames. It exists to break the construction cycle between the server (a Bridge's Sink) and the Bridge (the server's Handler): build the server, build the Bridge with the server as Sink, then SetHandler(bridge). It must be called before Start so the WebSocket read goroutine never observes a mid-flight swap.
type Sink ¶
type Sink interface {
SendOutput(text string)
SendConfirm(confirmID, tool, summary string)
HasClient() bool
}
Sink is the subset of the server the bridge needs. *Server satisfies it. It lets the bridge stream output, request confirmations, and check connectivity without importing the HTTP layer directly (and makes the seam unit-testable).
type TokenStore ¶
type TokenStore struct {
// contains filtered or unexported fields
}
TokenStore holds the outstanding pairing tokens and issued session credentials for one remote-control session. It is safe for concurrent use by the HTTP handlers. All values are cryptographically random secrets; the store keeps only their hex string form and never logs them.
func NewTokenStore ¶
func NewTokenStore() *TokenStore
NewTokenStore returns an empty store using the wall clock.
func (*TokenStore) Clear ¶
func (s *TokenStore) Clear()
Clear wipes all pairing tokens and session credentials. It is called on server shutdown so no secret outlives the remote-control session.
func (*TokenStore) ConsumePairing ¶
func (s *TokenStore) ConsumePairing(value string) bool
ConsumePairing validates a pairing token and, on success, marks it used so it can never be redeemed again. It returns false if the token is unknown, already used, or expired. The single-use marking happens under the lock, so two concurrent /pair requests with the same token cannot both succeed.
func (*TokenStore) IssueSession ¶
func (s *TokenStore) IssueSession() (string, error)
IssueSession creates and stores a new opaque session credential (set as the golder_rc cookie after pairing) and returns its hex value.
func (*TokenStore) NewPairing ¶
func (s *TokenStore) NewPairing(ttl time.Duration) (string, error)
NewPairing mints a fresh one-time pairing token that expires after ttl and returns its hex value for embedding in the pairing URL.
func (*TokenStore) ValidateSession ¶
func (s *TokenStore) ValidateSession(cred string) bool
ValidateSession reports whether cred matches a currently-issued session credential. Comparison is constant-time to avoid leaking the credential through response timing; an empty cred is always rejected.