dgclient

package
v0.0.0-...-8023560 Latest Latest
Warning

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

Go to latest
Published: Jun 1, 2025 License: MIT Imports: 14 Imported by: 0

README

dgclient

A Go client library for connecting to dgamelaunch-style SSH servers with modular view interfaces and comprehensive authentication support.


Installation

go get github.com/opd-ai/go-gamelaunch-client/pkg/dgclient

Features

SSH Connection Management
  • Multiple Authentication Methods - Password, SSH key (RSA, Ed25519, ECDSA), and SSH agent authentication
  • Automatic Reconnection - Exponential backoff with configurable retry limits and delay intervals
  • Connection Health Monitoring - Real-time status tracking with graceful error recovery
  • Session Persistence - Maintains game state across temporary network interruptions
  • Host Key Verification - Secure host key validation with known_hosts support
Terminal Emulation and PTY Handling
  • Full PTY Support - Complete pseudo-terminal implementation with proper signal handling
  • Dynamic Terminal Resizing - Automatic resize propagation to remote sessions
  • ANSI Escape Sequence Processing - Complete support for color codes, cursor movement, and screen control
  • Screen Buffer Management - Efficient memory handling with configurable buffer sizes
  • Terminal Type Detection - Automatic TERM environment variable configuration
Modular View Architecture
  • Pluggable View Interface - Clean abstraction for custom display implementations
  • Multiple View Backends - Terminal UI (tcell), web interface, and custom implementations
  • View State Synchronization - Efficient state updates with change detection
  • Concurrent View Support - Multiple simultaneous view connections to single client
  • View Configuration - Flexible options for terminal dimensions and rendering preferences
Authentication System
  • AuthMethod Interface - Extensible authentication framework for custom methods
  • Key-Based Authentication - Support for encrypted and unencrypted private keys
  • SSH Agent Integration - Automatic agent discovery with fallback authentication
  • Password Authentication - Secure password handling with memory clearing
  • Multi-Factor Support - Keyboard-interactive authentication for complex login flows
Session Management
  • Game Server Integration - Seamless connection to dgamelaunch-style servers
  • Game Selection Automation - Programmatic game launching and menu navigation
  • Session State Tracking - Connection status monitoring with detailed error reporting
  • Resource Management - Proper cleanup of SSH connections and terminal resources
  • Concurrent Session Handling - Multiple simultaneous connections with independent state
Configuration and Flexibility
  • Comprehensive Client Options - Configurable timeouts, buffer sizes, and connection parameters
  • Environment Variable Support - Standard SSH environment variable handling
  • Debug and Logging - Detailed logging with configurable verbosity levels
  • Error Context - Rich error information with operation context and recovery suggestions
  • Performance Tuning - Adjustable polling intervals and buffer management
Network Resilience
  • Connection Recovery - Automatic detection and recovery from network failures
  • Timeout Management - Configurable timeouts for different operation types
  • Keepalive Support - SSH keepalive packets to maintain long-running connections
  • Bandwidth Optimization - Efficient data transfer with compression support
  • IPv4/IPv6 Support - Dual-stack networking with preference configuration
Developer Experience
  • Clean API Design - Intuitive interfaces with comprehensive documentation
  • Example Implementations - Reference implementations for common use cases
  • Testing Infrastructure - Mock implementations and test utilities for development
  • Error Handling Patterns - Consistent error wrapping with actionable messages
  • Thread Safety - Safe concurrent usage with proper synchronization
Integration Capabilities
  • Library Integration - Easy embedding in larger applications with minimal dependencies
  • CLI Tool Foundation - Solid base for command-line tool development
  • GUI Framework Support - Compatible with various Go GUI frameworks through view interface
  • Service Integration - Suitable for daemon and service implementations
  • Monitoring Integration - Metrics and health check endpoints for operational monitoring

Architecture

The dgclient package implements a layered architecture designed for modularity and extensibility:

Connection Layer: Manages SSH connections with authentication, host key verification, and connection lifecycle. Handles network failures with automatic reconnection and maintains session state across interruptions.

Session Layer: Provides PTY management with terminal emulation, handling resize events and maintaining screen buffer state. Processes ANSI escape sequences and manages terminal input/output streams.

View Layer: Defines the View interface for pluggable display backends, enabling integration with terminal UIs, web interfaces, or custom rendering systems. Supports multiple concurrent views with independent state management.

Authentication Layer: Implements the AuthMethod interface with support for password, key-based, and SSH agent authentication. Provides secure credential handling with proper memory management and cleanup.

The package serves as the foundation for both CLI tools and GUI applications, providing reliable SSH connectivity to dgamelaunch servers while maintaining compatibility with traditional terminal-based roguelike games. The modular design enables custom implementations while ensuring robust connection management and comprehensive error handling.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// Connection errors
	ErrConnectionFailed     = errors.New("connection failed")
	ErrAuthenticationFailed = errors.New("authentication failed")
	ErrHostKeyMismatch      = errors.New("host key mismatch")
	ErrConnectionTimeout    = errors.New("connection timeout")

	// Session errors
	ErrPTYAllocationFailed = errors.New("PTY allocation failed")
	ErrSessionNotStarted   = errors.New("session not started")
	ErrInvalidTerminalSize = errors.New("invalid terminal size")

	// View errors
	ErrViewNotSet     = errors.New("view not set")
	ErrViewInitFailed = errors.New("view initialization failed")

	// Game errors
	ErrGameNotFound        = errors.New("game not found")
	ErrGameSelectionFailed = errors.New("game selection failed")
)

Functions

This section is empty.

Types

type AgentAuth

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

AgentAuth implements SSH agent-based authentication

func (*AgentAuth) GetSSHAuthMethod

func (a *AgentAuth) GetSSHAuthMethod() (ssh.AuthMethod, error)

func (*AgentAuth) Name

func (a *AgentAuth) Name() string

type AuthError

type AuthError struct {
	Method string
	Err    error
}

AuthError wraps authentication-specific errors

func (*AuthError) Error

func (e *AuthError) Error() string

func (*AuthError) Unwrap

func (e *AuthError) Unwrap() error

type AuthMethod

type AuthMethod interface {
	// GetSSHAuthMethod returns the underlying SSH auth method
	GetSSHAuthMethod() (ssh.AuthMethod, error)

	// Name returns a human-readable name for the auth method
	Name() string
}

AuthMethod defines the interface for SSH authentication methods

func NewAgentAuth

func NewAgentAuth() AuthMethod

NewAgentAuth creates a new SSH agent authentication method

func NewInteractiveAuth

func NewInteractiveAuth(callback func(name, instruction string, questions []string, echos []bool) ([]string, error)) AuthMethod

NewInteractiveAuth creates a new interactive authentication method

func NewKeyAuth

func NewKeyAuth(keyPath, passphrase string) AuthMethod

NewKeyAuth creates a new key authentication method

func NewPasswordAuth

func NewPasswordAuth(password string) AuthMethod

NewPasswordAuth creates a new password authentication method

type Client

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

Client manages connections to dgamelaunch servers

func NewClient

func NewClient(config *ClientConfig) *Client

NewClient creates a new dgamelaunch client

func (*Client) Close

func (c *Client) Close() error

Close closes the client and cleans up resources

func (*Client) Connect

func (c *Client) Connect(host string, port int, auth AuthMethod) error

Connect establishes a connection to the dgamelaunch server

func (*Client) ConnectWithConn

func (c *Client) ConnectWithConn(conn net.Conn, auth AuthMethod) error

ConnectWithConn establishes a connection to the dgamelaunch server using an existing net.Conn

func (*Client) Disconnect

func (c *Client) Disconnect() error

Disconnect closes the connection to the server

func (*Client) IsConnected

func (c *Client) IsConnected() bool

IsConnected returns true if the client is connected

func (*Client) ListGames

func (c *Client) ListGames() ([]GameInfo, error)

ListGames returns available games by querying the dgamelaunch server

func (*Client) Reconnect

func (c *Client) Reconnect(auth AuthMethod) error

Reconnect attempts to reconnect to the server

func (*Client) Run

func (c *Client) Run(ctx context.Context) error

Run starts the main game loop with automatic reconnection support

func (*Client) SelectGame

func (c *Client) SelectGame(gameName string) error

SelectGame sends commands to select a specific game

func (*Client) SetView

func (c *Client) SetView(view View) error

SetView sets the view for rendering game output

type ClientConfig

type ClientConfig struct {
	// SSH client configuration
	SSHConfig *ssh.ClientConfig

	// Connection settings
	ConnectTimeout    time.Duration
	KeepAliveInterval time.Duration

	// Retry settings
	MaxReconnectAttempts int
	ReconnectDelay       time.Duration

	// Terminal settings
	DefaultTerminal string

	// Debug options
	Debug bool
}

ClientConfig contains configuration for the client

func DefaultClientConfig

func DefaultClientConfig() *ClientConfig

DefaultClientConfig returns a client configuration with sensible defaults

type ConnectionError

type ConnectionError struct {
	Host string
	Port int
	Err  error
}

ConnectionError wraps connection-specific errors with additional context

func (*ConnectionError) Error

func (e *ConnectionError) Error() string

func (*ConnectionError) Unwrap

func (e *ConnectionError) Unwrap() error

type GameInfo

type GameInfo struct {
	Name        string
	Description string
	Command     string
	Available   bool
}

GameInfo contains information about an available game

type HostKeyCallback

type HostKeyCallback interface {
	Check(hostname string, remote net.Addr, key ssh.PublicKey) error
}

HostKeyCallback defines host key verification behavior

func NewKnownHostsCallback

func NewKnownHostsCallback(path string) (HostKeyCallback, error)

NewKnownHostsCallback creates a new known hosts callback

type InputEvent

type InputEvent struct {
	Type InputEventType
	Data []byte
	Key  string // For special keys
}

InputEvent represents a user input event

type InputEventType

type InputEventType int

InputEventType defines types of input events

const (
	InputEventTypeKey InputEventType = iota
	InputEventTypeResize
	InputEventTypePaste
)

type InsecureHostKeyCallback

type InsecureHostKeyCallback struct{}

InsecureHostKeyCallback accepts any host key (NOT FOR PRODUCTION)

func (*InsecureHostKeyCallback) Check

func (i *InsecureHostKeyCallback) Check(hostname string, remote net.Addr, key ssh.PublicKey) error

type InteractiveAuth

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

InteractiveAuth implements keyboard-interactive authentication

func (*InteractiveAuth) GetSSHAuthMethod

func (i *InteractiveAuth) GetSSHAuthMethod() (ssh.AuthMethod, error)

func (*InteractiveAuth) Name

func (i *InteractiveAuth) Name() string

type KeyAuth

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

KeyAuth implements key-based authentication

func (*KeyAuth) GetSSHAuthMethod

func (k *KeyAuth) GetSSHAuthMethod() (ssh.AuthMethod, error)

func (*KeyAuth) Name

func (k *KeyAuth) Name() string

type KnownHostsCallback

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

KnownHostsCallback uses a known_hosts file for verification

func (*KnownHostsCallback) Check

func (k *KnownHostsCallback) Check(hostname string, remote net.Addr, key ssh.PublicKey) error

type PasswordAuth

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

PasswordAuth implements password-based authentication

func (*PasswordAuth) GetSSHAuthMethod

func (p *PasswordAuth) GetSSHAuthMethod() (ssh.AuthMethod, error)

func (*PasswordAuth) Name

func (p *PasswordAuth) Name() string

type ResizeEvent

type ResizeEvent struct {
	Width  int
	Height int
}

ResizeEvent contains terminal resize information

type Session

type Session interface {
	// RequestPTY requests a pseudo-terminal
	RequestPTY(term string, h, w int) error

	// WindowChange notifies the server of terminal size changes
	WindowChange(h, w int) error

	// StdinPipe returns a pipe for writing to the session
	StdinPipe() (io.WriteCloser, error)

	// StdoutPipe returns a pipe for reading from the session
	StdoutPipe() (io.Reader, error)

	// StderrPipe returns a pipe for reading stderr from the session
	StderrPipe() (io.Reader, error)

	// Start starts the session with the given command
	Start(cmd string) error

	// Shell starts an interactive shell session
	Shell() error

	// Wait waits for the session to finish
	Wait() error

	// Signal sends a signal to the remote process
	Signal(sig ssh.Signal) error

	// Close closes the session
	Close() error
}

Session wraps an SSH session with PTY support

func NewSSHSession

func NewSSHSession(session *ssh.Session) Session

NewSSHSession creates a new Session from an ssh.Session

type View

type View interface {
	// Init initializes the view
	Init() error

	// Render displays the provided data
	Render(data []byte) error

	// Clear clears the display
	Clear() error

	// SetSize updates the view dimensions
	SetSize(width, height int) error

	// GetSize returns current dimensions
	GetSize() (width, height int)

	// HandleInput reads and returns user input
	// Returns nil, io.EOF when input stream is closed
	HandleInput() ([]byte, error)

	// Close cleans up resources
	Close() error
}

View defines the interface for rendering game output and handling input

type ViewFactory

type ViewFactory interface {
	CreateView(opts ViewOptions) (View, error)
}

ViewFactory creates View instances

type ViewFactoryFunc

type ViewFactoryFunc func(opts ViewOptions) (View, error)

ViewFactoryFunc is an adapter to allow functions to be used as ViewFactory

func (ViewFactoryFunc) CreateView

func (f ViewFactoryFunc) CreateView(opts ViewOptions) (View, error)

type ViewOptions

type ViewOptions struct {
	// Terminal type (e.g., "xterm-256color", "vt100")
	TerminalType string

	// Initial dimensions
	InitialWidth  int
	InitialHeight int

	// Color support
	ColorEnabled bool

	// Unicode support
	UnicodeEnabled bool

	// Custom configuration
	Config map[string]interface{}
}

ViewOptions contains configuration for view creation

func DefaultViewOptions

func DefaultViewOptions() ViewOptions

DefaultViewOptions returns sensible defaults for view creation

Jump to

Keyboard shortcuts

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