### Listen Function for SSH Test Server Source: https://pkg.go.dev/github.com/charmbracelet/wish/@v1.4.7/testsession The `Listen` function starts a test SSH server, primarily for testing purposes. It takes a `testing.TB` interface and an `*ssh.Server` instance as input, returning the address string of the started server. ```Go func Listen(tb testing.TB, srv *ssh.Server) string ``` -------------------------------- ### Function: Listen Source: https://pkg.go.dev/github.com/charmbracelet/wish/testsession The `Listen` function starts a test SSH server. It takes a `testing.TB` interface for test reporting and an `*ssh.Server` instance, returning the address string where the server is listening. ```Go func Listen(tb testing.TB, srv *ssh.Server) string ``` -------------------------------- ### Function: New Source: https://pkg.go.dev/github.com/charmbracelet/wish/testsession The `New` function initializes a local SSH server with a given configuration and immediately returns a client session connected to it. This utility automatically handles the cleanup and closing of resources after the test. It requires a `testing.TB` for test reporting, an `*ssh.Server` instance, and a `*gossh.ClientConfig` for client setup. ```Go func New(tb testing.TB, srv *ssh.Server, cfg *gossh.ClientConfig) *gossh.Session ``` -------------------------------- ### SystemD Commands for Service Management Source: https://pkg.go.dev/github.com/charmbracelet/wish/@v1.4 These shell commands demonstrate how to manage a SystemD service. `sudo systemctl daemon-reload` is necessary after modifying a unit file, and `sudo systemctl start myapp` (or restart/stop) is used to control the service lifecycle. ```Bash # need to run this every time you change the unit file sudo systemctl daemon-reload # start/restart/stop/etc: sudo systemctl start myapp ``` -------------------------------- ### MiddlewareWithProgramHandler Function (Go) Source: https://pkg.go.dev/github.com/charmbracelet/wish/@v1.4.7/bubbletea MiddlewareWithProgramHandler provides access to the underlying tea.Program and allows specifying a minimum supported color profile. This is particularly useful for creating custom middlewares that need to interact directly with the tea.Program, for example, to send messages using p.Send(). It's crucial to set tea.WithInput and tea.WithOutput to the ssh.Session for proper functionality, ideally using MakeOptions. ```Go func MiddlewareWithProgramHandler(handler ProgramHandler, profile termenv.Profile) wish.Middleware ``` -------------------------------- ### SystemD Service Unit for Wish Application Source: https://pkg.go.dev/github.com/charmbracelet/wish/@v1.4 This SystemD unit file defines a service for a Wish application, ensuring it starts after the network is available, runs as a specific user and group, and restarts automatically on failure. It serves as a template for deploying Wish applications as system services. ```SystemD Unit [Unit] Description=My App After=network.target [Service] Type=simple User=myapp Group=myapp WorkingDirectory=/home/myapp/ ExecStart=/usr/bin/myapp Restart=on-failure [Install] WantedBy=multi-user.target ``` -------------------------------- ### MiddlewareWithProgramHandler Function (Go) Source: https://pkg.go.dev/github.com/charmbracelet/wish/bubbletea MiddlewareWithProgramHandler provides access to the underlying tea.Program instance and allows specifying a minimum supported color profile. This is particularly useful for creating custom middlewares that need to interact directly with the tea.Program, for example, to send messages using p.Send(). It is crucial to set tea.WithInput and tea.WithOutput to the ssh.Session for proper functionality, ideally using MakeOptions. ```go func MiddlewareWithProgramHandler(handler ProgramHandler, profile termenv.Profile) wish.Middleware ``` -------------------------------- ### Manage SystemD Service for Wish Application Source: https://pkg.go.dev/github.com/charmbracelet/wish/index These Bash commands are used to manage a SystemD service. They allow reloading the daemon after unit file changes, and starting, restarting, or stopping the Wish application service. ```Bash # need to run this every time you change the unit file sudo systemctl daemon-reload # start/restart/stop/etc: sudo systemctl start myapp ``` -------------------------------- ### Get Cmd Environment Variables Source: https://pkg.go.dev/github.com/charmbracelet/wish/@v1.4 Returns the environment variables slice from the underlying `exec.Cmd` instance wrapped by `*Cmd`. ```Go func (c *Cmd) Environ() []string ``` -------------------------------- ### Get Cmd Environment Variables (Go) Source: https://pkg.go.dev/github.com/charmbracelet/wish/index Returns the environment variables slice (`[]string`) associated with the underlying `exec.Cmd` instance wrapped by `Cmd`. This allows inspection of the command's execution environment. ```Go func (c *Cmd) Environ() []string ``` -------------------------------- ### Handler Type Definition (APIDOC) Source: https://pkg.go.dev/github.com/charmbracelet/wish/bubbletea Handler is the primary function signature that Bubble Tea applications must implement to hook into the SSH Middleware provided by wish. For each new SSH connection, this handler will be invoked to create a new tea.Program, which is then started using the tea.Model and tea.ProgramOption slice returned. ```APIDOC type Handler func(sess ssh.Session) (tea.Model, []tea.ProgramOption) ``` -------------------------------- ### New Function for SSH Client Session Source: https://pkg.go.dev/github.com/charmbracelet/wish/@v1.4.7/testsession The `New` function initiates a local SSH server with a specified configuration and establishes a client session to it. It accepts a `testing.TB` interface, an `*ssh.Server` instance, and a `*gossh.ClientConfig`, automatically handling the closure of all resources upon completion. ```Go func New(tb testing.TB, srv *ssh.Server, cfg *gossh.ClientConfig) *gossh.Session ``` -------------------------------- ### Go: Create New RateLimiter Instance Source: https://pkg.go.dev/github.com/charmbracelet/wish/ratelimiter Provides the `NewRateLimiter` constructor function, which initializes a `RateLimiter` with a specified rate, burst capacity, and maximum number of cached entries. This function internally manages an LRU cache of `rate.Limiter` instances, using the remote IP address as the key for efficient rate limiting per client. ```Go func NewRateLimiter(r rate.Limit, burst int, maxEntries int) RateLimiter ``` -------------------------------- ### Go scp Package Overview and Middleware Function Source: https://pkg.go.dev/github.com/charmbracelet/wish/scp Provides an overview of the `scp` package, which offers SCP middleware for the `wish` library, and details the main `Middleware` function for initializing SCP operations. ```APIDOC Package: scp Description: Provides a SCP middleware for wish. Functions: Middleware(rh CopyToClientHandler, wh CopyFromClientHandler) wish.Middleware Description: Initializes the SCP middleware with read and write handlers. Parameters: rh: A CopyToClientHandler for server-to-client transfers. wh: A CopyFromClientHandler for client-to-server transfers. Returns: wish.Middleware ``` -------------------------------- ### BubbleTeaHandler Type Definition (APIDOC) Source: https://pkg.go.dev/github.com/charmbracelet/wish/bubbletea BubbleTeaHandler is a deprecated type alias for the Handler function signature. It defines how Bubble Tea applications integrate with the SSH Middleware, creating a new tea.Program for each connection and starting it with the returned tea.ProgramOptions. ```APIDOC type BubbleTeaHandler = Handler ``` -------------------------------- ### activeterm Go Package API Reference Source: https://pkg.go.dev/github.com/charmbracelet/wish/activeterm Comprehensive API documentation for the `activeterm` Go package, detailing its overview, indexed functions, and specific function behaviors like `Middleware`. ```APIDOC Package activeterm Overview: Package activeterm provides a middleware to block inactive PTYs. Index: func Middleware() wish.Middleware Functions: func Middleware() wish.Middleware Description: Middleware will exit 1 connections trying with no active terminals. ``` -------------------------------- ### Manage Git Repository Existence and Initialization Source: https://pkg.go.dev/github.com/charmbracelet/wish/git Provides functionality to ensure a specified directory is a valid Git repository, initializing it as a bare repository if it doesn't exist or isn't a Git repo. ```Go func EnsureRepo(dir, repo string) error ``` ```APIDOC EnsureRepo(dir, repo string) error dir: string - The directory path to check or create the repository in. repo: string - The name or path of the repository within the directory. Returns: error - An error if the operation fails, otherwise nil. ``` -------------------------------- ### BubbleTeaHandler Type Definition (Go) Source: https://pkg.go.dev/github.com/charmbracelet/wish/@v1.4.7/bubbletea BubbleTeaHandler is a deprecated type alias for Handler. It defines the function signature that Bubble Tea applications should implement to integrate with the SSH Middleware. This handler is responsible for creating a new tea.Program for each connection and starting it with the returned tea.ProgramOptions. ```Go type BubbleTeaHandler = Handler // nolint: revive ``` -------------------------------- ### charmbracelet/wish Go Package API Reference Source: https://pkg.go.dev/github.com/charmbracelet/wish/index Comprehensive API documentation for the `charmbracelet/wish` Go package, detailing functions, types, and methods for building SSH servers and managing SSH sessions. Includes options for server configuration, command execution, and middleware patterns. ```APIDOC charmbracelet/wish Package Functions: func WithTrustedUserCAKeys(path string) ssh.Option Description: Authorize certificates signed with a given CA public key. Parameters: path (string): Path to the CA keys. Returns: ssh.Option func WithVersion(version string) ssh.Option Description: Sets the server version. Parameters: version (string): The version string. Returns: ssh.Option func WriteString(s ssh.Session, v string) (int, error) Description: Writes the given string to the session's STDOUT. Parameters: s (ssh.Session): The SSH session. v (string): The string to write. Returns: (int, error) - number of bytes written, error. Types: type Cmd struct { ... } Description: Wraps *exec.Cmd and ssh.Pty for command execution. Methods: func (c *Cmd) Environ() []string Description: Returns the underlying exec.Cmd environment. Returns: []string func (c *Cmd) Run() error Description: Runs the program and waits for it to finish. Returns: error func (c *Cmd) SetDir(dir string) Description: Sets the underlying exec.Cmd dir. Parameters: dir (string): The directory path. func (c *Cmd) SetEnv(env []string) Description: Sets the underlying exec.Cmd env. Parameters: env ([]string): The environment variables. func (*Cmd) SetStderr(io.Writer) Description: Conforms with tea.ExecCommand for stderr. Parameters: writer (io.Writer): The writer for stderr. func (*Cmd) SetStdin(io.Reader) Description: Conforms with tea.ExecCommand for stdin. Parameters: reader (io.Reader): The reader for stdin. func (*Cmd) SetStdout(io.Writer) Description: Conforms with tea.ExecCommand for stdout. Parameters: writer (io.Writer): The writer for stdout. Associated Functions: func Command(s ssh.Session, name string, args ...string) *Cmd Description: Sets stdin, stdout, and stderr to the current session's PTY. Parameters: s (ssh.Session): The SSH session. name (string): The command name. args (...string): Command arguments. Returns: *Cmd func CommandContext(ctx context.Context, s ssh.Session, name string, args ...string) *Cmd Description: Like Command but includes a context. Parameters: ctx (context.Context): The context. s (ssh.Session): The SSH session. name (string): The command name. args (...string): Command arguments. Returns: *Cmd type Middleware func(next ssh.Handler) ssh.Handler Description: Function that takes an ssh.Handler and returns an ssh.Handler. Parameters: next (ssh.Handler): The next handler in the chain. Returns: ssh.Handler ``` -------------------------------- ### Go: MakeOptions Function API Source: https://pkg.go.dev/github.com/charmbracelet/wish/@v1.4.7/bubbletea Documents the `MakeOptions` function, which generates `tea.ProgramOption` slices for Bubble Tea programs, adapting to SSH session PTY types for input and output handling. ```Go func MakeOptions(sess ssh.Session) []tea.ProgramOption ``` -------------------------------- ### Middleware Function (Go) Source: https://pkg.go.dev/github.com/charmbracelet/wish/@v1.4.7/bubbletea Middleware takes a Handler and integrates the SSH session's input and output with a tea.Program. It also automatically captures window resize events and forwards them to the tea.Program as tea.WindowSizeMsgs, ensuring the application adapts to terminal size changes. ```Go func Middleware(handler Handler) wish.Middleware ``` -------------------------------- ### API Reference: charmbracelet/wish/logging Go Package Source: https://pkg.go.dev/github.com/charmbracelet/wish/@v1.4.7/logging Detailed API documentation for the `logging` package, outlining the `Middleware` and `MiddlewareWithLogger` functions for connection logging in Go applications. ```APIDOC Package: logging Functions: func Middleware() wish.Middleware Description: Provides basic connection logging. Connects are logged with the remote address, invoked command, TERM setting, window dimensions, client version, and if the auth was public key based. Disconnect will log the remote address and connection duration. It will use charmbracelet/log.StandardLog() by default. Returns: wish.Middleware func MiddlewareWithLogger(logger Logger) wish.Middleware Description: Provides basic connection logging. Connects are logged with the remote address, invoked command, TERM setting, window dimensions, client version, and if the auth was public key based. Disconnect will log the remote address and connection duration. Parameters: logger: Logger - The custom logger interface to use. Returns: wish.Middleware ``` -------------------------------- ### Function: NewClientSession Source: https://pkg.go.dev/github.com/charmbracelet/wish/testsession The `NewClientSession` function establishes a new client session to a specified SSH server address. It takes a `testing.TB` for test reporting, the server's address string, and a `*gossh.ClientConfig` for client configuration, returning the new `*gossh.Session` and any potential error. ```Go func NewClientSession(tb testing.TB, addr string, config *gossh.ClientConfig) (*gossh.Session, error) ``` -------------------------------- ### Go `ratelimiter` Package API Reference Source: https://pkg.go.dev/github.com/charmbracelet/wish/ratelimiter Comprehensive API documentation for the `ratelimiter` Go package, detailing its variables, functions, and interfaces for implementing rate limiting middleware in `charmbracelet/wish`. It outlines the structure and usage of `ErrRateLimitExceeded`, `Middleware`, `RateLimiter`, and `NewRateLimiter`. ```APIDOC Package: ratelimiter Variables: ErrRateLimitExceeded: errors.New("rate limit exceeded, please try again later") Description: Error returned when the connection was denied due to rate limit being exceeded. Functions: Middleware(limiter RateLimiter) wish.Middleware Description: Provides a new rate limiting Middleware. Parameters: limiter: RateLimiter Returns: wish.Middleware NewRateLimiter(r rate.Limit, burst int, maxEntries int) RateLimiter Description: Returns a new RateLimiter that allows events up to rate rate, permits bursts of at most burst tokens and keeps a cache of maxEntries limiters. Parameters: r: rate.Limit burst: int maxEntries: int Returns: RateLimiter Types: RateLimiter interface Description: Implementations should check if a given session is allowed to proceed or not, returning an error if they aren't. Methods: Allow(s ssh.Session) error Description: Checks if a given session is allowed to proceed. Parameters: s: ssh.Session Returns: error ``` -------------------------------- ### Package API Documentation Structure Source: https://pkg.go.dev/github.com/charmbracelet/wish/@v1.4.7/comment Provides an overview of the `comment` package's API documentation, including sections for Index, Constants, Variables, Functions, and Types, as presented in the module's documentation. ```APIDOC Package: comment Index: func Middleware(comment string) wish.Middleware Constants: (This section is empty.) Variables: (This section is empty.) Functions: func Middleware(comment string) wish.Middleware Middleware prints a comment at the end of the session. Types: (This section is empty.) ``` -------------------------------- ### Go Package Function: MakeOptions Source: https://pkg.go.dev/github.com/charmbracelet/wish/bubbletea Documents the `MakeOptions` function, which generates Bubble Tea program options suitable for an SSH session, taking into account possible Emulated or Allocated PTYs for correct input and output handling. ```Go func MakeOptions(sess ssh.Session) []tea.ProgramOption ``` ```APIDOC MakeOptions: Signature: func MakeOptions(sess ssh.Session) []tea.ProgramOption Description: Returns the tea.WithInput and tea.WithOutput program options taking into account possible Emulated or Allocated PTYs. Parameters: sess: ssh.Session - The SSH session to derive options from. Returns: []tea.ProgramOption - A slice of Bubble Tea program options configured for the session. ``` -------------------------------- ### Go `charmbracelet/wish/logging` Package API Index Source: https://pkg.go.dev/github.com/charmbracelet/wish/logging A comprehensive index of the public functions and types available within the `charmbracelet/wish/logging` Go package, primarily focusing on middleware for connection logging. ```APIDOC func Middleware() wish.Middleware func MiddlewareWithLogger(logger Logger) wish.Middleware func StructuredMiddleware() wish.Middleware func StructuredMiddlewareWithLogger(logger *log.Logger, level log.Level) wish.Middleware type Logger ``` -------------------------------- ### Initialize a New Go Rate Limiter Source: https://pkg.go.dev/github.com/charmbracelet/wish/@v1.4.7/ratelimiter This function creates a new `RateLimiter` instance configured with a specific rate limit, burst capacity, and a cache size for storing individual IP-based limiters. It uses an LRU cache to manage `*rate.Limiter` objects keyed by remote IP addresses. ```Go func NewRateLimiter(r rate.Limit, burst int, maxEntries int) RateLimiter ``` ```APIDOC Function: NewRateLimiter Signature: func NewRateLimiter(r rate.Limit, burst int, maxEntries int) RateLimiter Description: Returns a new RateLimiter that allows events up to rate rate, permits bursts of at most burst tokens and keeps a cache of maxEntries limiters. Internally, it creates a LRU Cache of *rate.Limiter, in which the key is the remote IP address. Parameters: r: rate.Limit - The maximum rate of events. burst: int - The maximum burst of tokens allowed. maxEntries: int - The maximum number of limiters to keep in the cache. Returns: RateLimiter - A new RateLimiter instance. ``` -------------------------------- ### Middleware Function (Go) Source: https://pkg.go.dev/github.com/charmbracelet/wish/bubbletea Middleware takes a Handler function and integrates the SSH session's input and output streams with a tea.Program. It also automatically captures and forwards window resize events from the SSH client to the tea.Program as tea.WindowSizeMsgs, ensuring the UI adapts correctly. ```go func Middleware(handler Handler) wish.Middleware ``` -------------------------------- ### Go: StructuredMiddleware Function Signature Source: https://pkg.go.dev/github.com/charmbracelet/wish/@v1.4.7/logging The function signature for `StructuredMiddleware`, which provides basic connection logging in a structured form. It returns a `wish.Middleware`. ```Go func StructuredMiddleware() wish.Middleware ``` -------------------------------- ### APIDOC: Logger Interface Source: https://pkg.go.dev/github.com/charmbracelet/wish/@v1.4.7/logging API documentation for the `Logger` interface. This interface defines the contract for a basic logger, requiring a `Printf` method for formatted output. It enables flexibility in integrating different logging backends. ```APIDOC type Logger interface Description: Logger is the interface that wraps the basic Log method. Methods: Printf(format string, v ...interface{}) Description: Formats and prints a log message using the provided format string and arguments. Parameters: format: string - The format string for the log message. v: ...interface{} - The arguments to be formatted according to the format string. ``` -------------------------------- ### API Interface: CopyFromClientHandler Source: https://pkg.go.dev/github.com/charmbracelet/wish/scp Interface for handling files being copied from the client to the server. Implementations must provide methods for creating directories (`Mkdir`) and writing files (`Write`) on the server side. ```APIDOC CopyFromClientHandler Interface: Mkdir(session: ssh.Session, dirEntry: *DirEntry) -> error session: The SSH session context. dirEntry: The directory entry to create. Write(session: ssh.Session, fileEntry: *FileEntry) -> (int64, error) session: The SSH session context. fileEntry: The file entry to write. Returns: The number of bytes written and an error, if any. ``` -------------------------------- ### Go Git Package Functions API Documentation Source: https://pkg.go.dev/github.com/charmbracelet/wish/@v1.4.7/git API documentation for key functions in the `git` package, detailing their purpose, parameters, and behavior. These functions facilitate Git repository operations and SSH session interactions. ```APIDOC func EnsureRepo(dir, repo string) error dir: string - The directory where the repository should exist or be created. repo: string - The name or path of the repository. Returns: error - An error if the repository cannot be ensured. Description: Ensures a Git repository exists at the specified path. If the path doesn't exist, it's created. If it's not a Git repo, it's initialized as a bare repository. ``` ```APIDOC func Fatal(s ssh.Session, v ...interface{}) s: ssh.Session - The SSH session to print to. v: ...interface{} - Variadic arguments to be printed to the session. Description: Prints a message to the SSH session's STDOUT as a Git response and exits with status 1. This function is typically used to terminate an SSH session with an error message, mimicking a Git command's error output. ``` -------------------------------- ### NewFileSystemHandler Function Source: https://pkg.go.dev/github.com/charmbracelet/wish/scp Creates and returns a new SCP Handler instance based on the given root directory path. ```Go func NewFileSystemHandler(root string) Handler ``` -------------------------------- ### Go scp Package Handler Types and Constructors Source: https://pkg.go.dev/github.com/charmbracelet/wish/scp Documents the various handler interfaces (`CopyToClientHandler`, `CopyFromClientHandler`, `Handler`) and their associated constructor functions (`NewFSReadHandler`, `NewFileSystemHandler`) used for managing SCP client-to-server and server-to-client file transfers. ```APIDOC Types: CopyToClientHandler: Interface for handling data transfer from server to client. Functions: NewFSReadHandler(fsys fs.FS) CopyToClientHandler Description: Creates a new handler for reading files from a file system to send to the client. Parameters: fsys: The file system (fs.FS) to read from. Returns: CopyToClientHandler CopyFromClientHandler: Interface for handling data transfer from client to server. Handler: General interface for SCP operations. Functions: NewFileSystemHandler(root string) Handler Description: Creates a new file system handler rooted at a specified path. Parameters: root: The root directory (string) for file operations. Returns: Handler ``` -------------------------------- ### Go: StructuredMiddlewareWithLogger Function with Custom Logger Source: https://pkg.go.dev/github.com/charmbracelet/wish/logging This function is similar to `StructuredMiddleware` but allows specifying a custom `log.Logger` and `log.Level`. It provides structured connection logging, capturing details like remote address, invoked command, terminal settings, window dimensions, client version, and authentication method. Disconnects are also logged with remote address and connection duration. ```Go func StructuredMiddlewareWithLogger(logger *log.Logger, level log.Level) wish.Middleware ``` -------------------------------- ### Charmbracelet Wish Go API Reference Source: https://pkg.go.dev/github.com/charmbracelet/wish/index This section provides an index and overview of the public functions, types, and methods available in the Charmbracelet Wish Go library. It outlines the core components for configuring SSH servers, handling authentication, and managing SSH sessions. ```APIDOC Functions: Error(s, v) Errorf(s, f, v) Errorln(s, v) Fatal(s, v) Fatalf(s, f, v) Fatalln(s, f, v) NewServer(ops) Print(s, v) Printf(s, f, v) Println(s, v) WithAddress(addr) WithAuthorizedKeys(path) WithBanner(banner) WithBannerHandler(h) WithHostKeyPEM(pem) WithHostKeyPath(path) WithIdleTimeout(d) WithKeyboardInteractiveAuth(h) WithMaxTimeout(d) WithMiddleware(mw) WithPasswordAuth(p) WithPublicKeyAuth(h) WithSubsystem(key, h) WithTrustedUserCAKeys(path) WithVersion(version) WriteString(s, v) Types: type Cmd Command(s, name, args) CommandContext(ctx, s, name, args) (c) Environ() (c) Run() (c) SetDir(dir) (c) SetEnv(env) SetStderr() SetStdin() SetStdout() type Middleware ``` -------------------------------- ### Go Package Directory Listing and Synopses for charmbracelet/wish Source: https://pkg.go.dev/github.com/charmbracelet/wish/@v1.4 This section outlines the various sub-packages available within the `github.com/charmbracelet/wish` Go module, primarily focusing on middleware components for SSH applications. Each entry describes the package's core functionality. ```APIDOC Package accesscontrol: Synopsis: Provides a middleware that allows you to restrict the commands the user can execute. Package activeterm: Synopsis: Provides a middleware to block inactive PTYs. Package bubbletea: Synopsis: Provides middleware for serving bubbletea apps over SSH. Package comment: Synopsis: (No synopsis provided) Package elapsed: Synopsis: (No synopsis provided) Package git: Synopsis: (No synopsis provided) Package logging: Synopsis: (No synopsis provided) Package ratelimiter: Synopsis: Provides basic rate limiting functionality as a with middleware. Package recover: Synopsis: (No synopsis provided) Package scp: Synopsis: Provides a SCP middleware for wish. Package testsession: Synopsis: Provides utilities to test SSH sessions. ``` -------------------------------- ### APIDOC: Middleware Function Reference Source: https://pkg.go.dev/github.com/charmbracelet/wish/@v1.4.7/ratelimiter API documentation for the `Middleware` function, which creates a new rate limiting middleware. It requires an implementation of the `RateLimiter` interface. ```APIDOC func Middleware(limiter RateLimiter) wish.Middleware limiter: RateLimiter - An implementation of the RateLimiter interface to apply rate limiting logic. returns: wish.Middleware - A new rate limiting middleware. ``` -------------------------------- ### Create Command for SSH Session (Go) Source: https://pkg.go.dev/github.com/charmbracelet/wish/index Creates a new `*Cmd` instance, configuring its standard input, output, and error streams to the current SSH session's PTY. If the session does not have a PTY, it defaults to the session itself. The session's context is used for the underlying `exec.Command`. ```Go func Command(s ssh.Session, name string, args ...string) *Cmd ``` -------------------------------- ### Go: StructuredMiddleware Function for Basic Connection Logging Source: https://pkg.go.dev/github.com/charmbracelet/wish/logging This function provides a basic connection logging middleware for `charmbracelet/wish`. It logs connection details such as remote address, command, terminal settings, window dimensions, client version, and authentication method. Disconnect events log the remote address and duration. By default, it uses `charmbracelet/log.Default()` at the Info level. ```Go func StructuredMiddleware() wish.Middleware ``` -------------------------------- ### API Interface: CopyToClientHandler Source: https://pkg.go.dev/github.com/charmbracelet/wish/scp Interface for handling files being copied from the server to the client. It includes methods for server-side globbing, recursive directory walking, and creating directory and file entries for client-side transfer. ```APIDOC CopyToClientHandler Interface: Glob(session: ssh.Session, pattern: string) -> ([]string, error) session: The SSH session context. pattern: The glob pattern to match. Returns: A slice of matched paths. WalkDir(session: ssh.Session, path: string, walkFunc: fs.WalkDirFunc) -> error session: The SSH session context. path: The root path to start walking. walkFunc: The function to call for each entry during traversal. NewDirEntry(session: ssh.Session, path: string) -> (*DirEntry, error) session: The SSH session context. path: The path for the new directory entry. Returns: A new DirEntry. NewFileEntry(session: ssh.Session, path: string) -> (*FileEntry, func() error, error) session: The SSH session context. path: The path for the new file entry. Returns: A new FileEntry, an optional closing function, and an error. ``` -------------------------------- ### APIDOC: wish.Middleware StructuredMiddlewareWithLogger Source: https://pkg.go.dev/github.com/charmbracelet/wish/@v1.4.7/logging API documentation for the `StructuredMiddlewareWithLogger` function. This middleware provides structured connection logging, allowing specification of a custom logger instance and log level. It logs similar details to `StructuredMiddleware` but offers more control over logging behavior. ```APIDOC func StructuredMiddlewareWithLogger(logger *log.Logger, level log.Level) wish.Middleware Description: Provides basic connection logging in a structured form, allowing custom logger and log level. Connects are logged with the remote address, invoked command, TERM setting, window dimensions, client version, and if the auth was public key based. Disconnect will log the remote address and connection duration. Parameters: logger: *log.Logger - The logger instance to use for logging. level: log.Level - The log level to apply for messages. Returns: wish.Middleware - A middleware function for structured logging. ``` -------------------------------- ### SCP Package API Reference Source: https://pkg.go.dev/github.com/charmbracelet/wish/@v1.4.7/scp Detailed API reference for the `scp` Go package, including its main functions, types, and their associated methods. This covers the core components for implementing SCP middleware with `charmbracelet/wish`. ```APIDOC Package scp: Overview: Package scp provides a SCP middleware for wish. Functions: Middleware(rh CopyToClientHandler, wh CopyFromClientHandler) wish.Middleware Types: type AppendableEntry type CopyFromClientHandler type CopyToClientHandler func NewFSReadHandler(fsys fs.FS) CopyToClientHandler type DirEntry func (e *DirEntry) Append(entry Entry) func (e *DirEntry) Write(w io.Writer) error type Entry type FileEntry func (e *FileEntry) Write(w io.Writer) error type Handler func NewFileSystemHandler(root string) Handler type Info func GetInfo(cmd []string) Info type Op type RootEntry func (e *RootEntry) Append(entry Entry) func (e *RootEntry) Write(w io.Writer) error ``` -------------------------------- ### Go: StructuredMiddlewareWithLogger Function Signature Source: https://pkg.go.dev/github.com/charmbracelet/wish/@v1.4.7/logging The function signature for `StructuredMiddlewareWithLogger`, which provides connection logging with a custom logger and log level. It returns a `wish.Middleware`. ```Go func StructuredMiddlewareWithLogger(logger *log.Logger, level log.Level) wish.Middleware ``` -------------------------------- ### Go Interface: CopyFromClientHandler Source: https://pkg.go.dev/github.com/charmbracelet/wish/@v1.4.7/scp Defines an interface for handling files being copied *from* the client *to* the server via SCP. Implementations must provide methods for creating directories (`Mkdir`) and writing file contents (`Write`). ```APIDOC type CopyFromClientHandler interface { // Mkdir should created the given dir. // Note that this usually shouldn't use os.MkdirAll and the like. Mkdir(ssh.Session, *DirEntry) error // Write should write the given file. Write(ssh.Session, *FileEntry) (int64, error) } ``` -------------------------------- ### Go Function: Create Read-Only File System Handler Source: https://pkg.go.dev/github.com/charmbracelet/wish/scp Constructs a read-only `CopyToClientHandler` from a given `fs.FS` (file system) interface. This allows serving files from any Go `fs.FS` implementation via SCP, providing a convenient way to expose file system content. ```Go func NewFSReadHandler(fsys fs.FS) CopyToClientHandler ``` -------------------------------- ### Wish Package Types API Reference Source: https://pkg.go.dev/github.com/charmbracelet/wish/@v1.4 This section details the key types and their associated methods within the Charmbracelet Wish Go package. It includes the `Cmd` type, which facilitates command execution within the SSH session, and the `Middleware` type, used for extending server functionality. ```APIDOC Types: type Cmd: Command(s, name, args) CommandContext(ctx, s, name, args) (c) Environ() (c) Run() (c) SetDir(dir) (c) SetEnv(env) SetStderr() SetStdin() SetStdout() type Middleware ``` -------------------------------- ### Go `Middleware()` Function for Basic Connection Logging Source: https://pkg.go.dev/github.com/charmbracelet/wish/logging Provides basic connection logging for `wish` middleware. It logs connection details like remote address, invoked command, TERM setting, window dimensions, client version, and authentication method. Disconnects log the remote address and connection duration. Defaults to `charmbracelet/log.StandardLog()`. ```Go func Middleware() wish.Middleware ``` -------------------------------- ### NewClientSession Function for SSH Client Connection Source: https://pkg.go.dev/github.com/charmbracelet/wish/@v1.4.7/testsession The `NewClientSession` function is responsible for creating a new client session. It connects to a given network address using a provided `*gossh.ClientConfig`, returning the new `*gossh.Session` and any potential error. ```Go func NewClientSession(tb testing.TB, addr string, config *gossh.ClientConfig) (*gossh.Session, error) ``` -------------------------------- ### APIDOC: wish.Middleware StructuredMiddleware Source: https://pkg.go.dev/github.com/charmbracelet/wish/@v1.4.7/logging API documentation for the `StructuredMiddleware` function. This middleware logs connection details like remote address, command, TERM setting, window dimensions, client version, and authentication type on connect, and remote address and duration on disconnect. It uses `charmbracelet/log.Default()` and `Info` level by default. ```APIDOC func StructuredMiddleware() wish.Middleware Description: Provides basic connection logging in a structured form. Connects are logged with the remote address, invoked command, TERM setting, window dimensions, client version, and if the auth was public key based. Disconnect will log the remote address and connection duration. It will use the charmbracelet/log.Default() and Info level by default. Returns: wish.Middleware - A middleware function for structured logging. ``` -------------------------------- ### Go func Middleware for Git Server Integration Source: https://pkg.go.dev/github.com/charmbracelet/wish/@v1.4.7/git The `Middleware` function integrates Git server functionality into an `ssh.Server`. It specifies the directory for Git repositories and accepts a `Hooks` implementation. This `Hooks` implementation is used for per-repository access checks based on the SSH session's public key, and its `Push` and `Fetch` methods are invoked upon successful command completion. ```Go func Middleware(repoDir string, gh Hooks) wish.Middleware ``` -------------------------------- ### Go Logger Interface for Panic Recovery Middleware Source: https://pkg.go.dev/github.com/charmbracelet/wish/@v1.4.7/recover This Go interface defines the contract for a logger used by the `MiddlewareWithLogger` function. It requires a `Printf` method, enabling flexible integration with various logging implementations that conform to this signature. ```Go type Logger interface { Printf(format string, v ...interface{}) } ``` -------------------------------- ### API Interface: Entry Source: https://pkg.go.dev/github.com/charmbracelet/wish/scp Defines the basic `Entry` interface for SCP items, requiring only a `Write` method to output the entry in SCP format to an `io.Writer`. This serves as a fundamental building block for SCP data. ```APIDOC Entry Interface: Write(w: io.Writer) -> error w: The writer to which the current entry should be written in SCP format. ``` -------------------------------- ### Go Interface: CopyToClientHandler Source: https://pkg.go.dev/github.com/charmbracelet/wish/@v1.4.7/scp Defines an interface for handling files being copied *from* the server *to* the client via SCP. It includes methods for server-side globbing, recursive directory walking, and providing directory/file entries for transfer. ```APIDOC type CopyToClientHandler interface { // Glob should be implemented if you want to provide server-side globbing // support. // // A minimal implementation to disable it is to return `[]string{s}, nil`. // // Note: if your other functions expect a relative path, make sure that // your Glob implementation returns relative paths as well. Glob(ssh.Session, string) ([]string, error) // WalkDir must be implemented if you want to allow recursive copies. WalkDir(ssh.Session, string, fs.WalkDirFunc) error // NewDirEntry should provide a *DirEntry for the given path. NewDirEntry(ssh.Session, string) (*DirEntry, error) // NewFileEntry should provide a *FileEntry for the given path. // Users may also provide a closing function. NewFileEntry(ssh.Session, string) (*FileEntry, func() error, error) } ``` -------------------------------- ### Create System User for Wish Application Source: https://pkg.go.dev/github.com/charmbracelet/wish/index This Bash command creates a new system user and group with a home directory. It's recommended for running Wish applications securely under a dedicated, unprivileged user. ```Bash useradd --system --user-group --create-home myapp ``` -------------------------------- ### Run Cmd and Wait (Go) Source: https://pkg.go.dev/github.com/charmbracelet/wish/index Executes the program represented by the `Cmd` instance and waits for its completion. This method blocks until the command finishes, returning an error if the execution fails. ```Go func (c *Cmd) Run() error ``` -------------------------------- ### Go scp Package Entry Types and Methods Source: https://pkg.go.dev/github.com/charmbracelet/wish/scp Details the different entry types (`AppendableEntry`, `DirEntry`, `FileEntry`, `Entry`, `RootEntry`) used to represent files and directories within SCP transfers, along with their associated methods for appending entries and writing content. ```APIDOC Types: AppendableEntry: Interface for entries that can have other entries appended to them. DirEntry: Represents a directory entry in an SCP transfer. Methods: (e *DirEntry) Append(entry Entry) Description: Appends a new entry to the directory. Parameters: entry: The Entry to append. (e *DirEntry) Write(w io.Writer) error Description: Writes the directory entry's metadata to the provided writer. Parameters: w: The io.Writer to write to. Returns: error Entry: General interface for an SCP entry (file or directory). FileEntry: Represents a file entry in an SCP transfer. Methods: (e *FileEntry) Write(w io.Writer) error Description: Writes the file entry's metadata to the provided writer. Parameters: w: The io.Writer to write to. Returns: error RootEntry: Represents the root directory entry for an SCP transfer. Methods: (e *RootEntry) Append(entry Entry) Description: Appends a new entry to the root directory. Parameters: entry: The Entry to append. (e *RootEntry) Write(w io.Writer) error Description: Writes the root directory entry's metadata to the provided writer. Parameters: w: The io.Writer to write to. Returns: error ``` -------------------------------- ### APIDOC: RateLimiter Interface and Constructor Reference Source: https://pkg.go.dev/github.com/charmbracelet/wish/@v1.4.7/ratelimiter API documentation for the `RateLimiter` interface and its associated constructor `NewRateLimiter`. The interface defines how to check if an SSH session is allowed, while the constructor provides a way to create a concrete rate limiter instance. ```APIDOC type RateLimiter interface { Allow(s ssh.Session) error s: ssh.Session - The SSH session to check for allowance. returns: error - An error if the session is not allowed (e.g., ErrRateLimitExceeded), nil otherwise. } func NewRateLimiter(r rate.Limit, burst int, maxEntries int) RateLimiter r: rate.Limit - The rate limit (e.g., rate.Every(time.Second / 10)). burst: int - The maximum burst size, allowing temporary spikes above the rate limit. maxEntries: int - The maximum number of entries to keep in the rate limiter's internal map, preventing unbounded memory usage. returns: RateLimiter - A new RateLimiter instance. ``` -------------------------------- ### Go Struct: FileEntry Source: https://pkg.go.dev/github.com/charmbracelet/wish/@v1.4.7/scp Represents a file entry in the SCP context, including its name, path, file mode, size, and an `io.Reader` for its content. It encapsulates all necessary information for a single file transfer. ```APIDOC type FileEntry struct { Name string Filepath string Mode fs.FileMode Size int64 Reader io.Reader Atime int64 Mtime int64 } ``` -------------------------------- ### API Struct: FileEntry and Method Source: https://pkg.go.dev/github.com/charmbracelet/wish/scp Represents a file entry in SCP, including its name, path, file mode, size, and an `io.Reader` for its content. It provides a method for writing the file's metadata and content to an `io.Writer`. ```APIDOC FileEntry Struct: Name: string Filepath: string Mode: fs.FileMode Size: int64 Reader: io.Reader Atime: int64 Mtime: int64 Methods: Write(w: io.Writer) -> error w: The writer to which the file entry and its content should be written in SCP format. ``` -------------------------------- ### GetInfo Function Source: https://pkg.go.dev/github.com/charmbracelet/wish/scp Retrieves and returns information about the SCP operation from a given command string array. ```Go func GetInfo(cmd []string) Info ``` -------------------------------- ### RootEntry Write Method Source: https://pkg.go.dev/github.com/charmbracelet/wish/scp Recursively writes all the children entries of the RootEntry to the provided io.Writer, returning an error if the write operation fails. ```Go func (e *RootEntry) Write(w io.Writer) error ``` -------------------------------- ### Go: Git Authorization and Notification Hooks Interface Source: https://pkg.go.dev/github.com/charmbracelet/wish/git Defines the `Hooks` interface for implementing custom Git authorization and post-command notifications. It includes methods for authenticating repository access (`AuthRepo`), and handling successful push (`Push`) and fetch (`Fetch`) operations, allowing for flexible integration with external systems. ```Go type Hooks interface { AuthRepo(string, ssh.PublicKey) AccessLevel Push(string, ssh.PublicKey) Fetch(string, ssh.PublicKey) } ``` -------------------------------- ### API Struct: DirEntry and Methods Source: https://pkg.go.dev/github.com/charmbracelet/wish/scp Represents a directory entry in SCP, including its name, path, file mode, and timestamps. It can contain child entries and provides methods for appending new entries and writing the directory structure to an `io.Writer`. ```APIDOC DirEntry Struct: Children: []Entry Name: string Filepath: string Mode: fs.FileMode Atime: int64 Mtime: int64 Methods: Append(entry: Entry) entry: The entry to append to the directory or its children. Write(w: io.Writer) -> error w: The writer to which the directory entry and all its contents (recursively) should be written in SCP format. ``` -------------------------------- ### Create Read-Only File System Handler in Go Source: https://pkg.go.dev/github.com/charmbracelet/wish/@v1.4.7/scp Constructs a read-only `CopyToClientHandler` from a given `fs.FS` (file system) interface. This allows serving files from any standard Go file system implementation via the SCP protocol. ```Go func NewFSReadHandler(fsys fs.FS) CopyToClientHandler ``` -------------------------------- ### Go: Git Server Middleware Function Source: https://pkg.go.dev/github.com/charmbracelet/wish/git Provides a `wish.Middleware` function to add Git server capabilities to an `ssh.Server`. It manages repositories in a specified directory and uses a `Hooks` implementation for access control and post-command notifications. ```Go func Middleware(repoDir string, gh Hooks) wish.Middleware ``` -------------------------------- ### Go `MiddlewareWithLogger()` Function with Custom Logger Source: https://pkg.go.dev/github.com/charmbracelet/wish/logging Extends basic connection logging by allowing a custom `Logger` interface to be provided. It logs connection details such as remote address, invoked command, TERM setting, window dimensions, client version, and authentication method. Disconnects log the remote address and connection duration. ```Go func MiddlewareWithLogger(logger Logger) wish.Middleware ``` -------------------------------- ### Create Command with Context for SSH Session (Go) Source: https://pkg.go.dev/github.com/charmbracelet/wish/index Similar to `Command`, this function creates a `*Cmd` but allows specifying a `context.Context` for the underlying command execution. It sets the command's I/O to the SSH session's PTY or the session itself if no PTY is present. ```Go func CommandContext(ctx context.Context, s ssh.Session, name string, args ...string) *Cmd ``` -------------------------------- ### Create System User for Wish Application Source: https://pkg.go.dev/github.com/charmbracelet/wish/@v1.4 This command creates a new system user and group named `myapp` with a home directory. It is a recommended practice for running Wish applications securely as dedicated services, isolating them from other system processes. ```Bash useradd --system --user-group --create-home myapp ``` -------------------------------- ### Run Cmd and Wait for Completion Source: https://pkg.go.dev/github.com/charmbracelet/wish/@v1.4 Executes the program represented by the `*Cmd` instance and waits for its completion, returning any error encountered during execution. ```Go func (c *Cmd) Run() error ``` -------------------------------- ### Info Struct Definition Source: https://pkg.go.dev/github.com/charmbracelet/wish/scp Provides detailed information about the current SCP operation, including whether it's an SCP session, if it's recursive, the server path, and the operation kind. ```Go type Info struct { // Ok is true if the current session is a SCP. Ok bool // Recursive is true if its a recursive SCP. Recursive bool // Path is the server path of the scp operation. Path string // Op is the SCP operation kind. Op Op } ``` -------------------------------- ### Go: Create Rate Limiting Middleware Function Source: https://pkg.go.dev/github.com/charmbracelet/wish/@v1.4.7/ratelimiter Provides the signature for the `Middleware` function, which constructs a new rate limiting middleware for the `wish` SSH server. It takes a `RateLimiter` implementation as input. ```Go func Middleware(limiter RateLimiter) wish.Middleware ``` -------------------------------- ### Go: Logger Interface Definition for Logging Operations Source: https://pkg.go.dev/github.com/charmbracelet/wish/logging This Go interface defines a basic contract for logging. Any type implementing this interface must provide a `Printf` method, allowing for formatted output of log messages. It serves as a flexible way to integrate various logging backends with the `charmbracelet/wish` logging middleware. ```Go type Logger interface { Printf(format string, v ...interface{}) } ``` -------------------------------- ### Create New File System Handler in Go Source: https://pkg.go.dev/github.com/charmbracelet/wish/@v1.4.7/scp Provides a constructor function `NewFileSystemHandler` that returns an SCP `Handler` instance. This handler is configured to operate on a specified root directory, facilitating file system-based SCP operations. ```Go func NewFileSystemHandler(root string) Handler ``` -------------------------------- ### Create New SSH Server Instance Source: https://pkg.go.dev/github.com/charmbracelet/wish/@v1.4 Initializes and returns a new SSH server instance. By default, it accepts all incoming connections and creates a new ed25519 SSH key pair if one doesn't exist. Various options can be passed to configure the server behavior. ```APIDOC func NewServer(ops ...ssh.Option) (*ssh.Server, error) Description: Returns a default SSH server with the provided Middleware. Details: A new SSH key pair of type ed25519 will be created if one does not exist. By default this server will accept all incoming connections, password and public key. ``` -------------------------------- ### MiddlewareWithColorProfile Function (Go) Source: https://pkg.go.dev/github.com/charmbracelet/wish/@v1.4.7/bubbletea MiddlewareWithColorProfile allows developers to specify the minimum required color profile for their Bubble Tea program. If the client's terminal supports fewer colors than the specified profile, the profile will be forced. This should be used with caution as it can override client settings. ```Go func MiddlewareWithColorProfile(handler Handler, profile termenv.Profile) wish.Middleware ``` -------------------------------- ### Go: Implement `wish` Rate Limiting Middleware Source: https://pkg.go.dev/github.com/charmbracelet/wish/ratelimiter Defines the `Middleware` function, which constructs and returns a new rate limiting middleware for `charmbracelet/wish`. It takes a `RateLimiter` interface implementation, allowing custom rate limiting logic to be integrated into the SSH server. ```Go func Middleware(limiter RateLimiter) wish.Middleware ``` -------------------------------- ### Go scp Package Info and Op Types Source: https://pkg.go.dev/github.com/charmbracelet/wish/scp Describes the `Info` type for parsing SCP command-line arguments and the `Op` type for representing SCP operation types, crucial for understanding and controlling SCP transfer behavior. ```APIDOC Types: Info: Represents parsed information from an SCP command. Functions: GetInfo(cmd []string) Info Description: Parses SCP command-line arguments into an Info struct. Parameters: cmd: The command-line arguments (slice of strings). Returns: Info Op: Represents the type of SCP operation (e.g., send, receive). ```