src

package
v1.9.0 Latest Latest
Warning

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

Go to latest
Published: May 18, 2026 License: MIT Imports: 32 Imported by: 0

Documentation

Index

Constants

View Source
const B3TTY_CONFIG_PATH = "b3tty"
View Source
const BUFFER_SIZE = 4096
View Source
const CONFIG_FILE_NAME = "conf.yaml"
View Source
const DEFAULT_AUTO_RESIZE = true
View Source
const DEFAULT_COLS = 80
View Source
const DEFAULT_CURSOR_BLINK = true
View Source
const DEFAULT_FONT_FAMILY = ""
View Source
const DEFAULT_FONT_SIZE = 14
View Source
const DEFAULT_PROFILE_NAME = "default"
View Source
const DEFAULT_ROOT = "/"
View Source
const DEFAULT_ROWS = 24
View Source
const DEFAULT_SHELL = "$SHELL"
View Source
const DEFAULT_TITLE = "b3tty"
View Source
const DEFAULT_URI = "localhost"
View Source
const DEFAULT_WORKING_DIRECTORY = "$HOME"
View Source
const DOT_CONFIG_PATH = ".config"
View Source
const LOCK_FILE_NAME = "b3tty.lock"
View Source
const MAX_REQUEST_BODY_SIZE = 4096
View Source
const TOKEN_LENGTH = 24

Variables

This section is empty.

Functions

func Bold

func Bold(s string) string

Bold returns s wrapped in bold ANSI codes when color output is enabled, and returns s unchanged when output is piped or redirected.

func BoldGreen

func BoldGreen(s string) string

BoldGreen returns s in bold green when color output is enabled.

func Debug

func Debug(msg string)

Debug logs a debug message. Output is suppressed unless SetDebug(true) has been called.

func Debugf

func Debugf(format string, args ...any)

Debugf logs a debug message. Output is suppressed unless SetDebug(true) has been called.

func DeleteProfileFromConfig added in v1.7.0

func DeleteProfileFromConfig(configPath string, name string) error

DeleteProfileFromConfig reads the existing config file at configPath, removes the named entry from the profiles section, and writes the file back. No-ops if the profiles section or the named entry is absent.

func Error

func Error(msg string)

Error logs an error message.

func Errorf

func Errorf(format string, args ...any)

Errorf logs an error message.

func Fatal

func Fatal(args ...any)

Fatal logs a fatal error message and terminates the process.

func Fatalf

func Fatalf(format string, args ...any)

Fatalf logs a fatal error message and terminates the process.

func GetBuiltinTheme added in v1.9.0

func GetBuiltinTheme(name string) (map[string]any, bool)

GetBuiltinTheme returns the color map for the named built-in theme. The second return value is false when no such theme exists.

func GetBuiltinThemeNames added in v1.9.0

func GetBuiltinThemeNames() []string

GetBuiltinThemeNames returns the sorted names of all built-in themes.

func Info

func Info(msg string)

Info logs an informational message.

func Infof

func Infof(format string, args ...any)

Infof logs an informational message.

func NewWarnLogger

func NewWarnLogger() *log.Logger

NewWarnLogger returns a *log.Logger suitable for http.Server.ErrorLog. Internal HTTP/TLS messages are routed through Warnf so the timestamp and level label appear in the same order as every other log line.

func OpenBrowser added in v1.9.0

func OpenBrowser(url string) error

OpenBrowser attempts to open url in the system default browser using the appropriate OS command. It returns an error if the command fails or the platform is unsupported.

func ReadThemeNames added in v1.6.0

func ReadThemeNames(path string) ([]string, error)

ReadThemeNames reads the config file at path and returns the names from the themes section, preserving their exact case as written in the YAML.

func RemoveLockFile added in v1.9.0

func RemoveLockFile() error

RemoveLockFile deletes the lock file. It is a no-op if the file does not exist.

func SaveProfileToConfig added in v1.7.0

func SaveProfileToConfig(configPath string, name string, p Profile) error

SaveProfileToConfig reads the existing config file at configPath (creating it if absent), upserts the named profile in the profiles section, and writes the file back.

func SaveSettingsToConfig added in v1.8.0

func SaveSettingsToConfig(configPath string, server SettingsServerConfig, terminal SettingsTerminalConfig) error

SaveSettingsToConfig reads the existing config file at configPath (creating it if absent), updates the server and terminal sections with the provided values, and writes the file back. Existing settings not covered by the structs are preserved.

func SaveThemeToConfig added in v1.6.0

func SaveThemeToConfig(configPath string, themeName string, colors map[string]any) error

SaveThemeToConfig reads the existing config file at configPath (creating it if absent), sets the active theme name, and writes the theme's color entries to the themes section, overwriting any existing entry for that theme name.

func Serve

func Serve(ts *TerminalServer, shouldOpenBrowser bool, useTLS bool)

Serve wires up the HTTP mux and starts the server.

func SetDebug

func SetDebug(enabled bool)

SetDebug enables or disables debug-level logging.

func UpdateThemeInConfig added in v1.5.2

func UpdateThemeInConfig(configPath string, themeName string, colors map[string]any) error

UpdateThemeInConfig reads the existing config file at configPath (creating it if absent), sets the active theme name, and adds the theme's color entries to the themes section if they are not already present. Existing settings are preserved.

func ValidateConfig added in v1.3.1

func ValidateConfig(path string) error

ValidateConfig opens the YAML file at path, decodes it into typed structs with KnownFields(true) enabled, and returns a descriptive error (including the line number from the YAML parser) if any field has the wrong type or any unrecognised key is present.

func ValidatePortNumber added in v1.4.1

func ValidatePortNumber(port int) bool

ValidatePortNumber reports whether port is a valid TCP/UDP port number (1–65535).

func ValidateTheme

func ValidateTheme(t *Theme) error

ValidateTheme checks every color field in t against validateThemeColor. It returns an error naming the first invalid field and value, or nil when all fields are valid. Fields are identified by their JSON tag name.

func ValidateThemeColor added in v1.3.1

func ValidateThemeColor(s string) bool

validateThemeColor reports whether s is a valid theme color value. Valid values are an empty string (field not set), a CSS hex color with 3 or 6 hex digits (e.g. "#fff" or "#14181d"), or a string of only ASCII letters representing a named CSS color (e.g. "red" or "cornflowerblue").

func Warn

func Warn(msg string)

Warn logs a warning message.

func Warnf

func Warnf(format string, args ...any)

Warnf logs a warning message.

func WriteDefaultConfig added in v1.3.1

func WriteDefaultConfig(themeName string, colors map[string]any) error

WriteDefaultConfig writes a default theme config file to $HOME/.config/b3tty/conf.yaml.

func WriteLockFile added in v1.9.0

func WriteLockFile(port, pid int, token, protocol string) error

WriteLockFile creates or overwrites the lock file with the server's runtime values. The config directory is created if it does not exist.

Types

type CSPHeader added in v1.3.1

type CSPHeader struct {
	Name   string
	Values []string
}

CSPHeader represents a single Content-Security-Policy directive, consisting of a directive name (e.g. "script-src") and one or more source values (e.g. "self", "nonce-abc123"). Values are rendered without surrounding quotes in Add/Set but wrapped in single quotes by String() to produce valid CSP syntax.

func NewCSPHeader added in v1.3.1

func NewCSPHeader(name string, values ...string) *CSPHeader

NewCSPHeader constructs a CSPHeader with the given directive name and initial source values.

func (*CSPHeader) Add added in v1.3.1

func (ch *CSPHeader) Add(value string) *CSPHeader

Add appends a single source value to this directive. Returns the receiver for chaining. Mutations are reflected in any CSPHeaders map that holds a pointer to this CSPHeader.

func (*CSPHeader) Set added in v1.3.1

func (ch *CSPHeader) Set(values ...string) *CSPHeader

Set replaces all source values for this directive with the provided values, discarding any previously assigned values. Returns the receiver for chaining.

func (CSPHeader) String added in v1.3.1

func (ch CSPHeader) String() string

String renders the directive as a CSP-formatted string, e.g. "script-src 'self' 'nonce-abc123';". Each value is wrapped in single quotes.

type CSPHeaders added in v1.3.1

type CSPHeaders struct {
	Headers map[string]*CSPHeader
}

CSPHeaders is a collection of CSPHeader directives keyed by directive name. Directive pointers are stored in the map, so mutations via Get().Add() or Get().Set() are reflected in the CSPHeaders value without re-inserting the directive. Use String() to serialize the full policy for use in a Content-Security-Policy response header.

func GetCSPHeaders added in v1.3.1

func GetCSPHeaders() CSPHeaders

GetCSPHeaders returns the baseline Content-Security-Policy directives used by b3tty's HTTP handlers. The returned CSPHeaders value contains the following directives:

  • default-src 'none'
  • script-src 'self' 'wasm-unsafe-eval' (callers must add a per-request nonce)
  • style-src 'self' 'unsafe-inline'
  • connect-src 'self'
  • img-src 'self'
  • frame-ancestors 'none'
  • base-uri 'self'

script-src: allow same-origin module scripts plus the one inline script

that sets window.B3TTY, identified by its per-request nonce.
'wasm-unsafe-eval' is required for xterm.js which uses WebAssembly
internally; it is more targeted than 'unsafe-eval' and does not permit
JS eval().

style-src: allow same-origin stylesheets plus 'unsafe-inline' for the

dynamic <style> element the JS injects for theme background gradients.

connect-src 'self': covers same-origin fetch and ws:/wss: connections. frame-ancestors 'none': prevents the terminal from being embedded in an

iframe on any other page.

base-uri 'self': blocks <base> tag injection that could redirect relative

URLs to an attacker-controlled origin.

Callers that render HTML (e.g. displayTermHandler) should call csp.Get("script-src").Add("nonce-<value>") on the returned value to inject a per-request nonce before writing the CSP header to the response.

func NewCSPHeders added in v1.3.1

func NewCSPHeders(headers ...*CSPHeader) *CSPHeaders

NewCSPHeders constructs a CSPHeaders collection from the provided directives, keyed by each directive's Name field.

func (CSPHeaders) Add added in v1.3.1

func (chs CSPHeaders) Add(key string, header *CSPHeader) *CSPHeaders

Add inserts or replaces the directive stored under key. Returns a pointer to the (possibly updated) CSPHeaders for chaining.

func (CSPHeaders) Get added in v1.3.1

func (chs CSPHeaders) Get(key string) *CSPHeader

Get returns a pointer to the CSPHeader for the given directive name, or nil if no such directive exists. Mutating the returned pointer updates the entry in place, which is reflected in subsequent calls to String().

func (CSPHeaders) String added in v1.3.1

func (chs CSPHeaders) String() string

String serializes all directives into a single Content-Security-Policy header value, with each directive separated by a space. Directive order is not guaranteed because the underlying storage is a map.

type Client

type Client struct {
	Rows        int
	Columns     int
	AutoResize  bool
	CursorBlink bool
	FontFamily  string
	FontSize    int
	Theme       Theme
}

func NewClient

func NewClient(rows *int, columns *int, autoResize *bool, blink *bool, fontFamily *string, fontSize *int, theme *Theme) *Client

type CommandLogger added in v1.9.0

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

CommandLogger prints colorized messages without timestamps or level label prefixes. It is intended for use in CLI subcommands where output should read as clean user-facing text rather than structured server log lines. Level is indicated by color only: white for Info, yellow for Warn, red for Error and Fatal, and magenta for Debug.

func NewCommandLogger added in v1.9.0

func NewCommandLogger() *CommandLogger

NewCommandLogger returns a CommandLogger that writes to stdout with no timestamp or prefix.

func (*CommandLogger) Debug added in v1.9.0

func (c *CommandLogger) Debug(msg string)

func (*CommandLogger) Debugf added in v1.9.0

func (c *CommandLogger) Debugf(format string, args ...any)

func (*CommandLogger) Error added in v1.9.0

func (c *CommandLogger) Error(msg string)

func (*CommandLogger) Errorf added in v1.9.0

func (c *CommandLogger) Errorf(format string, args ...any)

func (*CommandLogger) Fatal added in v1.9.0

func (c *CommandLogger) Fatal(msg string)

func (*CommandLogger) Fatalf added in v1.9.0

func (c *CommandLogger) Fatalf(format string, args ...any)

func (*CommandLogger) Info added in v1.9.0

func (c *CommandLogger) Info(msg string)

func (*CommandLogger) Infof added in v1.9.0

func (c *CommandLogger) Infof(format string, args ...any)

func (*CommandLogger) Warn added in v1.9.0

func (c *CommandLogger) Warn(msg string)

func (*CommandLogger) Warnf added in v1.9.0

func (c *CommandLogger) Warnf(format string, args ...any)

type LockFile added in v1.9.0

type LockFile struct {
	Port     int    `json:"port"`
	PID      int    `json:"pid"`
	Token    string `json:"token"`
	Protocol string `json:"protocol"`
}

LockFile holds the runtime state written when a b3tty server starts. It lets other b3tty subcommands locate the running server and construct authenticated URLs without the user having to supply port or token.

func ReadLockFile added in v1.9.0

func ReadLockFile() (*LockFile, error)

ReadLockFile reads and parses the lock file. It returns (nil, nil) when the file does not exist, indicating no server is running.

type Profile

type Profile struct {
	Root             string
	WorkingDirectory string
	Shell            string
	Title            string
	Commands         []string
}

func NewProfile

func NewProfile(shell string, wd string, root string, title string, commands []string) Profile

func (*Profile) ApplyToCommand

func (p *Profile) ApplyToCommand(cmd *exec.Cmd) (*exec.Cmd, error)

ApplyToCommand applies the Profile's settings to the given exec.Cmd. It sets the working directory based on the Profile's WorkingDirectory field, expanding $HOME and ~ to the user's home directory. If a custom shell is specified in the Profile, it replaces the last argument of the command with the custom shell. Returns the modified exec.Cmd and any error encountered.

func (*Profile) ParseCommands

func (p *Profile) ParseCommands() ([][]string, error)

ParseCommands processes the Profile Commands and returns a slice of string slices. Each command in the Commands slice is trimmed of whitespace and split into arguments.

Returns:

  • [][]string: A slice of string slices, where each inner slice represents a parsed command with its arguments.
  • error: An error if any occurs during the parsing process, nil otherwise.

type Server

type Server struct {
	Uri      string
	Port     int
	NoAuth   bool
	FirstRun bool
	TLS
}

func NewServer

func NewServer(uri *string, port *int, noAuth *bool, tls *TLS) *Server

func (*Server) Addr

func (s *Server) Addr() url.URL

type SettingsServerConfig added in v1.9.0

type SettingsServerConfig struct {
	Port      int  `json:"port"`
	NoAuth    bool `json:"noAuth"`
	NoBrowser bool `json:"noBrowser"`
}

SettingsServerConfig holds the subset of server settings exposed via the Settings overlay. These fields require a server restart to take effect.

type SettingsTerminalConfig added in v1.9.0

type SettingsTerminalConfig struct {
	FontFamily  string `json:"fontFamily"`
	FontSize    int    `json:"fontSize"`
	CursorBlink bool   `json:"cursorBlink"`
	AutoResize  bool   `json:"autoResize"`
	Rows        int    `json:"rows"`
	Columns     int    `json:"columns"`
}

SettingsTerminalConfig holds the terminal settings exposed via the Settings overlay. Font and cursor fields apply to the live session; auto-resize, rows, and columns only persist to the config file.

type TLS

type TLS struct {
	Enabled      bool
	CertFilePath string
	KeyFilePath  string
}

type TermConfig

type TermConfig struct {
	TLS                bool     `json:"tls"`
	CursorBlink        bool     `json:"cursorBlink"`
	FontFamily         string   `json:"fontFamily"`
	FontSize           int      `json:"fontSize"`
	Rows               int      `json:"rows"`
	Columns            int      `json:"columns"`
	AutoResize         bool     `json:"autoResize"`
	Theme              Theme    `json:"theme"`
	Uri                string   `json:"uri"`
	Port               int      `json:"port"`
	Debug              bool     `json:"debug"`
	HasBackgroundImage bool     `json:"backgroundImage"`
	ThemeNames         []string `json:"themeNames"`
	AllThemeNames      []string `json:"allThemeNames"`
	BuiltinThemeNames  []string `json:"builtinThemeNames"`
	ProfileNames       []string `json:"profileNames"`
	ActiveTheme        string   `json:"activeTheme"`
}

func NewTermConfig

func NewTermConfig(srv *Server, clnt *Client, thm *Theme, themeNames []string, allThemeNames []string, builtinThemeNames []string, profileNames []string, activeTheme string) *TermConfig

type TerminalServer

type TerminalServer struct {
	Client         *Client
	Server         *Server
	Profiles       map[string]Profile
	Themes         map[string]Theme
	Token          string
	OrgCols        uint16
	OrgRows        uint16
	ProfileName    string
	StartupProfile string
	ActiveTheme    string
	ConfigFile     string
	FailedAttempts int
	FirstRun       bool
	NoBrowser      bool
	BackoffMu      sync.Mutex
	WSClients      map[*websocket.Conn]*wsClient
	WSClientsMu    sync.Mutex
	// AuthSleep is the function used to pause on auth failures. It defaults to
	// time.Sleep and can be replaced in tests with a no-op to avoid real delays.
	AuthSleep func(time.Duration)
}

TerminalServer bundles all mutable per-session state used by the HTTP handlers, making them independent of package-level globals and straightforward to test.

type Theme

type Theme struct {
	Foreground          string `json:"foreground,omitempty"`
	Background          string `json:"background,omitempty"`
	Cursor              string `json:"cursor,omitempty"`
	CursorAccent        string `json:"cursorAccent,omitempty"`
	SelectionForeground string `json:"selectionForeground,omitempty"`
	SelectionBackground string `json:"selectionBackground,omitempty"`
	Black               string `json:"black,omitempty"`
	BrightBlack         string `json:"brightBlack,omitempty"`
	Red                 string `json:"red,omitempty"`
	BrightRed           string `json:"brightRed,omitempty"`
	Yellow              string `json:"yellow,omitempty"`
	BrightYellow        string `json:"brightYellow,omitempty"`
	Green               string `json:"green,omitempty"`
	BrightGreen         string `json:"brightGreen,omitempty"`
	Blue                string `json:"blue,omitempty"`
	BrightBlue          string `json:"brightBlue,omitempty"`
	Magenta             string `json:"magenta,omitempty"`
	BrightMagenta       string `json:"brightMagenta,omitempty"`
	Cyan                string `json:"cyan,omitempty"`
	BrightCyan          string `json:"brightCyan,omitempty"`
	White               string `json:"white,omitempty"`
	BrightWhite         string `json:"brightWhite,omitempty"`
	// BackgroundImage is a server-side file path and is intentionally excluded
	// from JSON serialization to avoid exposing local paths to the browser.
	BackgroundImage string `json:"-"`
}

func (*Theme) MapToTheme

func (tm *Theme) MapToTheme(m map[string]any)

MapToTheme maps the key-value pairs from the given map to the corresponding fields of the Theme struct. It uses reflection to set the values of the struct fields based on the map keys. The map keys are expected to be in a format that can be converted to the struct field names. Only string values from the map are set to the corresponding struct fields.

Parameters:

  • m: A map[string]any containing the theme properties to be set.

Note: This method modifies the Theme struct in-place.

Jump to

Keyboard shortcuts

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