Documentation
¶
Overview ¶
Package sip serves Bubble Tea applications through a web browser.
Sip provides a way to make any Bubble Tea TUI application accessible through a web browser with full terminal emulation, mouse support, and hardware-accelerated rendering via xterm.js and its WebGL renderer.
Basic usage:
server := sip.NewServer(sip.DefaultConfig())
server.Serve(context.Background(), func(sess sip.Session) (tea.Model, []tea.ProgramOption) {
pty := sess.Pty()
return myModel{width: pty.Width, height: pty.Height}, nil
})
Or with a ProgramHandler for more control:
server.ServeWithProgram(ctx, func(sess sip.Session) *tea.Program {
return tea.NewProgram(myModel{}, sip.MakeOptions(sess)...)
})
Index ¶
- Constants
- func AssetDigest(name string) (string, error)
- func AssetNames() []string
- func Assets() fs.FS
- func CertPaths(dir string) (certFile, keyFile string, err error)
- func DefaultCertDir() (string, error)
- func MakeOptions(sess Session) []tea.ProgramOption
- func RemoteAddrFromContext(ctx context.Context) string
- func RemoveManagedCert(dir string) error
- func RunBrowser(model tea.Model, opts ...tea.ProgramOption) error
- func SetLogLevel(level log.Level)
- func WithIdentity(ctx context.Context, id Identity) context.Context
- func WithRemoteAddr(ctx context.Context, addr string) context.Context
- type ANSIPalette
- type Appearance
- type BrowserProgram
- func (p *BrowserProgram) Kill()
- func (p *BrowserProgram) Printf(t string, args ...any)
- func (p *BrowserProgram) Println(args ...any)
- func (p *BrowserProgram) Quit()
- func (p *BrowserProgram) ReleaseTerminal() error
- func (p *BrowserProgram) RestoreTerminal() error
- func (p *BrowserProgram) Run() (tea.Model, error)
- func (p *BrowserProgram) Send(msg tea.Msg)
- func (p *BrowserProgram) Wait()
- type Capability
- type CertInfo
- type CertOptions
- type Color
- type CommandHandler
- type Config
- type ConnectError
- type ConnectHandler
- type ConnectMiddleware
- type Handler
- type Identity
- type ManagedCert
- type Middleware
- type MobileKey
- type MobileMouse
- type MobilePrefix
- type MobileRow
- type OptionsMessage
- type PageAPI
- type ProgramHandler
- type Pty
- type ResizeMessage
- type Route
- type Server
- type Session
- type SessionIO
- type SessionMiddleware
- type SizeMessage
- type Theme
- type WindowResizer
- type WindowSize
Constants ¶
const ( MsgInput = '0' // Terminal input (client → server) MsgOutput = '1' // Terminal output (server → client) MsgResize = '2' // Resize terminal MsgPing = '3' // Ping MsgPong = '4' // Pong MsgTitle = '5' // Set window title MsgOptions = '6' // Configuration options MsgClose = '7' // Session closed (server → client) MsgKittyKbd = '8' // Kitty keyboard protocol flags )
Message types for WebSocket/WebTransport communication.
const DefaultCertValidity = 365 * 24 * time.Hour
DefaultCertValidity is how long a managed certificate is good for.
A year, because the cost of a self-signed certificate is not generating it, it is walking to every phone and accepting the browser warning again. A shorter life would spend that cost repeatedly for no gain: nothing revokes these and nothing consults a CRL.
One thing does care about the length. Chrome accepts a WebTransport serverCertificateHashes handshake only for certificates valid under 14 days, which is why the ephemeral loopback certificate in cert.go is 10 days. A managed certificate is served over HTTPS to a browser that has been told to trust it, so it trades that path (WebTransport falls back to WebSocket over the same TLS) for not expiring every fortnight. Pass a shorter Validity to get it back.
const MaxMessageSize = 1 << 20
MaxMessageSize is the maximum allowed message size (1 MiB).
const SelfSignedWarning = `` /* 657-byte string literal not displayed */
SelfSignedWarning is what a user is going to see in the browser, said before they see it.
Nobody reads a warning they were not warned about: an unexplained "Your connection is not private" on a tool that just told them everything worked reads as the tool being broken, and the next move is either giving up or turning TLS off for good. Both are worse than the warning.
Variables ¶
This section is empty.
Functions ¶
func AssetDigest ¶ added in v0.8.0
AssetDigest returns the SHA-256 of a shipped asset, hex encoded.
It is the answer to "is my override stale". An override is a copy of a file that sip goes on developing, and nothing in an upgrade tells a consumer that the original moved on. Pin the digest of the file you copied in a test of your own:
func TestOverrideIsCurrent(t *testing.T) {
got, err := sip.AssetDigest("terminal.css")
if err != nil { t.Fatal(err) }
if got != "12056d40…" {
t.Fatal("sip's terminal.css changed; re-check static/terminal.css against it")
}
}
The test fails on the upgrade that changed the file, which is the only moment at which the answer is useful.
func AssetNames ¶ added in v0.8.0
func AssetNames() []string
AssetNames lists every file Assets holds, sorted.
func Assets ¶ added in v0.8.0
Assets returns the client files sip ships, rooted so the names match the URLs under /static/: "terminal.css", "fonts/JetBrainsMonoNerdFontMono-Regular.woff2".
Read from it to derive an override from the file sip actually serves, instead of guessing at its content.
func CertPaths ¶ added in v0.6.0
CertPaths reports where the managed keypair lives without touching the filesystem, for a caller that wants to name the paths in a config file or a unit file before anything has been generated.
func DefaultCertDir ¶ added in v0.6.0
DefaultCertDir is where sip keeps a managed keypair: a "sip" directory inside the user's config directory ($XDG_CONFIG_HOME/sip on Linux, ~/Library/Application Support/sip on macOS, %AppData%\sip on Windows).
func MakeOptions ¶
func MakeOptions(sess Session) []tea.ProgramOption
MakeOptions returns tea.ProgramOptions configured for the web session. On Unix, this uses the PTY slave file for proper raw mode support. On Windows, this uses the Session's Reader/Writer interface with pipes.
func RemoteAddrFromContext ¶ added in v0.3.0
RemoteAddrFromContext returns the remote address attached to ctx, or "" if none.
func RemoveManagedCert ¶ added in v0.6.0
RemoveManagedCert deletes the managed keypair. Missing files are not an error: the postcondition is that there is no managed certificate.
func RunBrowser ¶ added in v0.3.0
func RunBrowser(model tea.Model, opts ...tea.ProgramOption) error
RunBrowser executes the model with the appropriate runtime for the build target. On native this is a regular tea.Program; on wasm this installs the JavaScript bridge that the sip web frontend speaks to.
The same main.go works on both targets when wrapped in this helper.
func SetLogLevel ¶
SetLogLevel sets the logging verbosity for the sip package.
func WithIdentity ¶ added in v0.3.0
WithIdentity returns a derived context carrying id. Passing nil returns ctx unchanged.
Types ¶
type ANSIPalette ¶ added in v0.8.0
type ANSIPalette [16]Color
ANSIPalette is the sixteen ANSI colours in index order, 0 to 15: the eight normal colours then the eight bright ones.
It exists because that is the shape a palette arrives in. A theme read out of kitty, ghostty, alacritty or wezterm is an indexed list, and so is the palette a Go program already holds for its own rendering, so the alternative is sixteen hand-written assignments per theme and a silent swap the first time colour 5 lands in BrightMagenta.
type Appearance ¶ added in v0.8.0
type Appearance struct {
// Theme is the terminal's palette. Unset colours keep sip's built-in
// Catppuccin Mocha, so a theme is a patch, not a replacement.
//
// The chrome follows it: the settings panel, the status indicator, the
// scrollbar and the touch key bar are all painted from the palette
// rather than from a second set of colours, because a Gruvbox terminal
// in a Catppuccin panel is what a second set of colours produces the
// first time one of them is updated alone.
Theme Theme
// MouseCursor is the CSS cursor over the terminal. Empty keeps "text",
// which is what a terminal shows because its main gesture is selecting
// text.
//
// It also replaces the arrow xterm switches to while a program is
// reading the mouse: a deployment that names a cursor means it in both
// states, and a cursor that changes under a program the user is
// clicking through reads as a glitch.
//
// A program running in the terminal may name its own shape through
// the kitty pointer shapes protocol, and that wins while it is set.
// This is what a pop back to an empty stack restores, and what
// ?__default__ reports. See pointershapes.go.
//
// Accepts a CSS cursor keyword: the thirty the protocol names, plus
// "none", "auto", "context-menu" and "all-scroll". The last four are a
// deployment's to choose and a program's to do without: a kiosk that
// hides the pointer is reasonable, a program that hides the user's
// pointer is a program the user cannot then click away from.
MouseCursor string
// CursorStyle is the text cursor's shape: "block", "bar" or
// "underline". Empty keeps "block". A program that sets its own shape
// through DECSCUSR still wins, as it does in any terminal.
CursorStyle string
// CursorInactiveStyle is the text cursor's shape while the terminal
// does not hold focus: "outline", "block", "bar", "underline" or
// "none". Empty keeps "outline", which is the hollow box that tells a
// user the keyboard is somewhere else.
CursorInactiveStyle string
// CursorBlink starts the text cursor blinking. Off by default because
// a blinking cursor is a permanent animation, so an idle terminal
// repaints forever and a laptop notices.
//
// This sets the default, not the answer: a user who has picked one in
// the settings panel keeps their choice.
CursorBlink bool
// Scrollback is how many lines above the screen the browser keeps.
// 0 keeps the default, 5000. Each line costs memory in the browser,
// not on the server.
Scrollback int
// FontSize is the terminal's font size in CSS pixels. 0 keeps the
// default, 14. Like CursorBlink this is the default and not the
// answer: the settings panel's slider still wins, and a narrow touch
// screen still starts a point smaller until the user picks a size.
FontSize int
// Title is the page title before the program sets one, and what the
// tab falls back to when a program clears it. Empty keeps "Sip".
//
// A program's own title sequence still wins while it is running: this
// is what the tab says during the second before the session connects,
// which for a deployment with several sip tabs open is the whole
// difference between them.
Title string
// Favicon is the tab icon, as a relative path, an http(s) URL or a
// data: URI. Empty ships no icon, which is what sip does today.
//
// A data: URI is the one that needs no second route into the page, so
// a deployment can carry its icon in the same Go file as the palette.
Favicon string
// PageBackground is the ground behind the terminal: the letterbox left
// by a grid that does not divide evenly into the window, and the page
// before the terminal is drawn.
//
// Empty follows Theme.Background, which is what a deployment setting a
// light theme wants and would otherwise have to say twice. Set it only
// to make the two differ.
PageBackground Color
}
Appearance is how the page looks: the terminal's palette, its two cursors, and the small amount of chrome around it.
Everything here was a constant in static/terminal.js until a deployment asked for its own colours and its own mouse cursor and there was no answer but a fork. The zero value is exactly what sip rendered before this existed, field by field, so a program that sets nothing sees no change at all.
It travels to the browser twice, from one producer. The page is built before the session handshake, so the values are seeded into window.__sipConfig at index render, which is also what lets the font be loaded before the terminal measures its cell box; the same blob is then sent over MsgOptions on connect, which is what reaches a page sip did not render and what re-applies on a reconnect. A missing or partial blob leaves the built-in defaults standing.
func (Appearance) IsZero ¶ added in v0.8.0
func (a Appearance) IsZero() bool
IsZero reports whether nothing about the appearance is configured.
func (Appearance) Validate ¶ added in v0.8.0
func (a Appearance) Validate() error
Validate reports the first setting the browser would not understand.
The server refuses to start on one rather than passing it on, because every one of these fails silently in a browser: an unparseable colour, an unknown cursor keyword and a bad favicon URL all leave the page looking exactly as it did before the option was added, which is indistinguishable from sip having ignored it.
type BrowserProgram ¶ added in v0.3.0
type BrowserProgram struct {
// contains filtered or unexported fields
}
BrowserProgram wraps a BubbleTea program for either native or browser (wasm) execution. On native builds it delegates to a standard tea.Program.
func NewBrowserProgram ¶ added in v0.3.0
func NewBrowserProgram(model tea.Model, opts ...tea.ProgramOption) *BrowserProgram
NewBrowserProgram returns a BrowserProgram that runs the model with a native tea.Program. On `GOOS=js GOARCH=wasm` this same call (built from run_js.go) returns a wasm-bridged program instead.
func (*BrowserProgram) Kill ¶ added in v0.3.0
func (p *BrowserProgram) Kill()
func (*BrowserProgram) Printf ¶ added in v0.3.0
func (p *BrowserProgram) Printf(t string, args ...any)
func (*BrowserProgram) Println ¶ added in v0.3.0
func (p *BrowserProgram) Println(args ...any)
func (*BrowserProgram) Quit ¶ added in v0.3.0
func (p *BrowserProgram) Quit()
func (*BrowserProgram) ReleaseTerminal ¶ added in v0.3.0
func (p *BrowserProgram) ReleaseTerminal() error
func (*BrowserProgram) RestoreTerminal ¶ added in v0.3.0
func (p *BrowserProgram) RestoreTerminal() error
func (*BrowserProgram) Send ¶ added in v0.3.0
func (p *BrowserProgram) Send(msg tea.Msg)
func (*BrowserProgram) Wait ¶ added in v0.3.0
func (p *BrowserProgram) Wait()
type Capability ¶ added in v0.8.0
type Capability string
Capability names one thing a page script is allowed to do through window.sip.
The list is short on purpose. Each name is a different kind of harm, so a deployment can answer "what may this page do" without reading sip's client: watching the terminal is not typing into it, repainting it is not reading what a program printed, and none of those is ending the session.
const ( // CapObserve lets the page watch the terminal: sip.on, sip.off, // sip.size and sip.status. // // It reads the grid's shape and the transport, never its contents, // with one exception worth knowing: the title event carries a string // the program chose. See docs/extending.md. CapObserve Capability = "observe" // CapInput lets the page type: sip.send and sip.input.paste. // // This is the strongest one. Anything that can call it can run a // command in the user's shell, so grant it only to a page whose every // script you ship yourself. CapInput Capability = "input" // CapAppearance lets the page repaint: sip.appearance.get, set and // reset. It reaches the palette, the font, both cursors, the // scrollback, the tab title and the tab icon. // // It changes nothing about the session, so it is the capability to // reach for when a page wants a theme switcher and nothing else. CapAppearance Capability = "appearance" // CapView lets the page move the viewport and clear the scrollback: // sip.view. // // Clearing throws away what the user has scrolled back to, so it is // destructive in a small way. It cannot read anything. CapView Capability = "view" // CapRead lets the page read what the program printed: sip.selection // and sip.search. // // Search is a read as much as the selection is. A page that can ask // "is this string on the screen" can learn the screen one answer at a // time, so the two travel together. CapRead Capability = "read" // CapClipboard lets the page copy the selection to the system // clipboard: sip.clipboard.copySelection. // // The text does not pass through the script, so this is not CapRead. // It is its own capability because it writes to something outside the // page that the user owns. CapClipboard Capability = "clipboard" // CapConnection lets the page restart the session: // sip.connection.reconnect. // // A reconnect ends the running session and starts a new one. The // program the user was running dies with it. CapConnection Capability = "connection" )
func AllCapabilities ¶ added in v0.8.0
func AllCapabilities() []Capability
AllCapabilities returns every capability sip defines.
Pass it to PageAPI.Grant for a page whose scripts you write and ship yourself. Do not pass it to reach one call: a grant is a promise about every script in the document, not about the line you are writing.
func DefaultCapabilities ¶ added in v0.8.0
func DefaultCapabilities() []Capability
DefaultCapabilities returns what a deployment that sets no PageAPI grants.
type CertInfo ¶
CertInfo holds generated certificate information.
func GenerateSelfSignedCert ¶
GenerateSelfSignedCert generates a self-signed TLS certificate for WebTransport. The certificate is valid for 10 days (Chrome requires < 14 days for serverCertificateHashes).
type CertOptions ¶ added in v0.6.0
type CertOptions struct {
// Dir is the directory holding the keypair. Empty means DefaultCertDir.
Dir string
// Hosts are extra DNS names and IP addresses to put in the SAN, on top
// of the ones discovered from the machine. A name that parses as an IP
// becomes an IP SAN; everything else becomes a DNS SAN.
Hosts []string
// BindHost is the address the server will listen on, if known. It is
// covered by the SAN even when it is not an address of this machine
// (a name resolved by a router's DNS, say).
BindHost string
// Validity is how long the certificate lasts. 0 means
// DefaultCertValidity.
Validity time.Duration
}
CertOptions configures a managed certificate.
type Color ¶ added in v0.8.0
type Color string
Color is a colour the browser understands, written as CSS hex: "#rgb", "#rgba", "#rrggbb" or "#rrggbbaa".
The empty string means "leave the default alone". That is what makes a partial palette work: a deployment that sets three colours gets three colours changed and keeps the other thirteen, rather than thirteen black cells from a struct nobody finished filling in.
Only hex is accepted. A browser drops a colour it cannot parse and paints the default instead, with nothing in the console, so "rebeccapurple" or a stray "0x" would reach the page and look like the option was ignored. Appearance.Validate refuses it at the server instead, where the deployment can see it.
type CommandHandler ¶ added in v0.1.8
type CommandHandler struct {
// contains filtered or unexported fields
}
CommandHandler creates command sessions for each browser connection.
type Config ¶
type Config struct {
// Host to bind to (default: "localhost"). It takes no port; the port
// goes in Port. A name is looked up once
// when the server starts. Both listeners bind the address it gives,
// and the checks read that address. A name whose addresses are of
// more than one kind (loopback and network, say) is refused, and so
// is a name for a link-local IPv6 address. Give that address with its
// zone, such as fe80::1%eth0.
Host string
// Port to listen on (default: "7681")
Port string
// ReadOnly disables input from clients when true
ReadOnly bool
// MaxConnections limits concurrent connections (0 = unlimited)
MaxConnections int
// IdleTimeout closes sessions with no inbound bytes for the given
// duration (0 = disabled). Inbound = client → PTY only.
IdleTimeout time.Duration
// AllowOrigins is the legacy alias for OriginPatterns. Both are
// merged. Empty means same-origin only.
AllowOrigins []string
// OriginPatterns is an allowlist of additional browser origins
// permitted to connect. Each entry is a path.Match shell glob, NOT
// a regex (e.g. "https://app.example.com", "*.example.com").
OriginPatterns []string
// TLSCert path to TLS certificate (enables HTTPS)
TLSCert string
// TLSKey path to TLS private key
TLSKey string
// AutoTLS serves HTTPS from a self-signed keypair sip manages for the
// user, generating one on first use and reusing it after that. It is
// ignored when TLSCert and TLSKey are set.
//
// It exists because the alternative people actually reached for was
// AllowInsecureNoTLS, permanently. Binding a LAN address is what you do
// to reach a terminal from a phone, that bind is refused without TLS,
// and until now nothing in sip helped with the certificate, so the
// documented path ended at "obtain a certificate somehow".
//
// The certificate signs for itself, so the first visit from any browser
// shows a warning. See SelfSignedWarning for what to tell the user, and
// say it: a warning nobody was warned about reads as a broken tool.
AutoTLS bool
// CertDir overrides where AutoTLS keeps its keypair. Empty uses
// DefaultCertDir.
CertDir string
// CertHosts are extra DNS names and IP addresses AutoTLS puts in the
// certificate's SAN. The bind address, the loopback names, the
// machine's hostname and its interface addresses are covered already;
// this is for a name only some other resolver knows about.
CertHosts []string
// CertValidity is how long an AutoTLS certificate lasts.
// 0 means DefaultCertValidity.
CertValidity time.Duration
// Debug enables verbose logging
Debug bool
// BasicUsername / BasicPassword enable HTTP Basic Auth on every
// HTTP request (handshake + static assets). Empty disables auth.
BasicUsername string
BasicPassword string
// AllowInsecureNoTLS lets BasicAuth or non-loopback hosts run
// without TLS. Default false (refuses to start). Use only for
// development behind a trusted reverse proxy that terminates TLS.
AllowInsecureNoTLS bool
// MaxPasteBytes caps the size of a single inbound message
// (typically a bracketed-paste payload). 0 = default 1 MiB.
MaxPasteBytes int
// ResizeThrottle coalesces rapid inbound resize messages into the
// most recent value. 0 = default 16ms.
ResizeThrottle time.Duration
// MaxWindowDims caps the terminal size a client can ask for. A resize
// over the cap is clamped to it. 0 in either dimension uses the
// default, 2048 columns by 1024 rows.
MaxWindowDims WindowSize
// MaxWindowCells caps columns times rows. A resize over the cap keeps
// its columns and loses rows until it fits. 0 uses the default,
// 250000 cells.
//
// The cap exists because memory grows with the cell count. A Bubble
// Tea program costs about 230 bytes per cell, so the default bounds a
// session near 60 MB. Without it one 2048x2048 resize took a server
// from 17 MB to 970 MB.
MaxWindowCells int
// InitialResizeTimeout is the maximum time to wait for the
// client's initial Resize message after WS upgrade or WT CONNECT.
// 0 = default 10s.
InitialResizeTimeout time.Duration
// WriteTimeout bounds how long a single output write to the client
// may block before the session is torn down. A stalled-but-alive
// client (stopped reading, socket buffers full) otherwise pins the
// output goroutine and its connection slot indefinitely. 0 = default
// 30s. Negative disables the deadline.
WriteTimeout time.Duration
// FontPath is an optional filesystem path to a custom font (.ttf,
// .otf, .woff, .woff2). When set, the file is served at
// /static/fonts/custom and registered as a @font-face named
// FontFamily. Empty uses the embedded JetBrains Mono Nerd Font.
FontPath string
// FontFamily is the CSS font-family used by the terminal. Used in
// conjunction with FontPath when present, otherwise overrides the
// default for the embedded font stack. Empty defaults to
// "JetBrainsMono Nerd Font Mono".
FontFamily string
// Appearance is how the page looks: the terminal's palette, its two
// cursors and the chrome around them. The zero value renders exactly
// what sip rendered before the field existed; see Appearance.
Appearance Appearance
// CtrlVToProgram sends a plain Ctrl+V to the program as a key, for
// vim's block select (Ctrl+Q also starts one) and a shell's
// literal-next. By default Ctrl+V is a browser paste chord, like
// Ctrl+Shift+V and Shift+Insert, because a program's own paste key
// reads the server's clipboard and not the user's. On macOS Ctrl+V
// always goes to the program and Cmd+V pastes.
CtrlVToProgram bool
// Renderer selects the client-side terminal renderer: "webgl",
// "canvas" or "dom". Empty means "auto", which prefers WebGL and
// falls back to canvas and then the DOM. "engine" is the experimental
// worker engine (libghostty-vt and a WebGL2 renderer in Web Workers);
// a browser that cannot run it gets "auto". A user's saved setting and
// a ?renderer= query param both override this.
Renderer string
// ExtraCSS is appended to the page's stylesheets, after sip's own, so
// an ordinary rule wins on cascade order alone.
//
// Reach for this first. It survives a sip upgrade, because sip is
// still serving its own stylesheet underneath and only the rules named
// here are the deployment's. Replacing terminal.css through StaticFS
// does not: the copy stops at the version it was taken from.
//
// It is served as a file at /static/sip-extra.css, so it revalidates
// and shows up in the browser's developer tools like any other
// stylesheet.
//
// It is not the place for the palette or the cursors. Those are
// Appearance, which the terminal reads as options rather than as CSS,
// and which also reaches the chrome around the grid.
ExtraCSS string
// ExtraJS is a classic script run after sip's client, before the
// terminal opens, at /static/sip-extra.js.
//
// It talks to the page through window.sip. What that page API answers
// is PageAPI's question, not this one. See docs/extending.md.
ExtraJS string
// PageAPI bounds what a page script may do through window.sip.
//
// The zero value grants what sip granted before the field existed: the
// events, the grid size and sip.send. Everything else is opt-in, one
// capability at a time. See PageAPI and docs/extending.md.
PageAPI PageAPI
// StaticFS replaces client files one at a time. A name in it wins over
// sip's own copy, and a name missing from it falls through, so
// replacing one stylesheet does not mean vendoring the rest.
//
// Names match the URLs under /static/: "terminal.css", "index.html",
// "fonts/MyFont.woff2". A file with a name sip does not ship is served
// too, which is how a page gets a logo or a second font.
//
// Use it when a rule cannot reach what it needs to change. A replaced
// file is a fork of that file: sip goes on developing the original and
// nothing in an upgrade tells the deployment that it moved. Pin
// AssetDigest in a test if you keep one.
//
// Two names are config, not files, and a file cannot claim them:
// sip-extra.css and sip-extra.js.
StaticFS fs.FS
// Routes serve a deployment's own URLs beside the terminal: a favicon,
// a web app manifest, a page of its own. Every route is behind the
// same Basic Auth as the rest of the server.
//
// A route that names one of sip's own paths is refused at startup
// rather than allowed to break the terminal.
Routes []Route
// MobileKeys replaces the client's default touch key bar with a key
// set of the deployment's own. Empty keeps the default, which is the
// keys a phone keyboard lacks and every terminal program understands
// (Escape, Tab, sticky Ctrl and Alt, the arrows, some punctuation).
//
// Set it when the program being served has chords worth a button:
// sip has no way to know what those are. The bar is only built on a
// touch device, so this has no effect on a desktop.
//
// It is the one-row shorthand for MobileRows, which wins when both are
// set.
MobileKeys []MobileKey
// MobileRows lays the touch key bar out in more than one strip, for a
// key set that has outgrown a single one. Rows are drawn top to bottom
// and the typing row conventionally goes last, nearest the thumb that
// is already on the software keyboard.
MobileRows []MobileRow
// MobilePrefix declares the leader chord this deployment is driven by:
// tmux's Ctrl+B, screen's Ctrl+A, emacs's Ctrl+X. A phone cannot hold a
// modifier while pressing a letter, so without this every binding in a
// leader-driven program is unreachable from a touch device, which is
// most of what such a program can do.
//
// It powers two kinds of button, and neither exists without it:
// MobileKey.Prefix arms the chord so the second half can be typed on
// the software keyboard, and MobileKey.Prefixed sends the leader and a
// key together in one tap.
MobilePrefix MobilePrefix
// DisableMobileKeyBar suppresses the touch key bar entirely, for a
// program that draws touch controls of its own. The software
// keyboard's share of the window is still measured and reserved.
DisableMobileKeyBar bool
// MobileMouse tunes what a finger on the terminal does. The zero
// value is the working default; see MobileMouse for what it means and
// for the two switches that turn parts of it off.
MobileMouse MobileMouse
// AllowedHosts adds host names that a session handshake may carry in
// its Host header.
//
// On a loopback bind, sip refuses a handshake whose Host is not a
// loopback address, localhost, a name under .localhost, the bind host,
// a CertHosts entry or an AllowedHosts entry. This stops DNS
// rebinding, where a web page points its own name at 127.0.0.1 and
// opens a session on this machine. Add the public name here when a
// reverse proxy on the same machine forwards the client's Host.
//
// An unspecified bind (0.0.0.0, ::) listens on loopback too, so it
// gets the same check when the server has no TLS and no password.
// There, every IP address in Host also passes, because a rebinding
// page always sends a name. A browser that opens the server by its
// LAN address works with no change. Add each name that browsers use
// for this machine, such as myhost.local. With TLS or a password, an
// unspecified bind is not checked: a rebound name is not in the
// certificate, and a rebinding page does not know the password. A
// user name with an empty password does not count.
//
// A "*" entry turns the check off. A bind to one network address is
// not checked.
AllowedHosts []string
// AllowFraming lets every origin put the page in a frame. By default
// the page carries Content-Security-Policy: frame-ancestors 'self'
// and X-Frame-Options: SAMEORIGIN, so only a page of the same origin
// can frame it. A framed terminal takes the keys the user types into
// it, so set this only when any site may embed the terminal. To allow
// some sites, use FrameAncestors.
AllowFraming bool
// FrameAncestors adds origins that may put the page in a frame, such
// as "https://app.example.com". Each entry is a CSP source expression.
// The page then carries frame-ancestors 'self' and the entries, and no
// X-Frame-Options, because that header cannot name an origin.
// AllowFraming overrides it.
FrameAncestors []string
// ConnectMiddleware extends the layer-1 chain. Built-in basic auth
// + connection-limit middleware are appended after the user chain
// so they run innermost (last).
ConnectMiddleware []ConnectMiddleware
// SessionMiddleware extends the layer-2 chain. The first
// middleware is the outermost wrapper.
SessionMiddleware []SessionMiddleware
// HandlerMiddleware extends the layer-3 chain that wraps the
// user's Handler. The first middleware is outermost (sees calls
// first).
HandlerMiddleware []Middleware
// EnableKittyTranscoder runs every PTY → client byte stream through the
// server-side kitty graphics PNG → RGBA transcoder.
//
// The client's kitty overlay decodes PNG itself through
// createImageBitmap, so this is off by default and the raw APC stream
// is forwarded untouched (keeping PNG payloads compressed end to end).
// Enable it only to force server-side transcoding as a fallback.
EnableKittyTranscoder bool
}
Config holds the web server configuration.
func ConfigFromContext ¶ added in v0.3.0
ConfigFromContext returns a read-only copy of the Config attached to ctx, or the zero value if none.
func DefaultConfig ¶
func DefaultConfig() Config
DefaultConfig returns sensible default configuration.
type ConnectError ¶ added in v0.3.0
type ConnectError struct {
Status int // HTTP status code on WS path; mapped to QUIC code on WT path
Headers http.Header // Headers to write on WS path before body (ignored on WT)
Body string // Body to write on WS path (ignored on WT)
WTCode uint32 // Override the default WS-status → QUIC-code mapping
Cause error // Optional underlying error
}
ConnectError is returned by ConnectHandler implementations to control the rejection response. A plain error returned from a ConnectHandler is treated as &ConnectError{Status: http.StatusInternalServerError}.
func (*ConnectError) Error ¶ added in v0.3.0
func (e *ConnectError) Error() string
func (*ConnectError) Unwrap ¶ added in v0.3.0
func (e *ConnectError) Unwrap() error
func (*ConnectError) WTErrorCode ¶ added in v0.3.0
func (e *ConnectError) WTErrorCode() uint32
WTErrorCode returns the QUIC error code used when closing a WebTransport session in response to this ConnectError. Default mapping: 4xx → 0x01, 5xx → 0x02, anything else → 0x00.
type ConnectHandler ¶ added in v0.3.0
ConnectHandler is invoked at the handshake boundary for both WebSocket upgrades and WebTransport CONNECTs. Returning a non-nil error rejects the connection; returning *ConnectError gives full control over the rejection response.
A middleware that approves the connection MUST call next(r). The framework's terminal handler captures the *http.Request as last seen, which is how context updates propagate to layer 2 / layer 3.
type ConnectMiddleware ¶ added in v0.3.0
type ConnectMiddleware func(next ConnectHandler) ConnectHandler
ConnectMiddleware decorates a ConnectHandler.
func LiftHTTPMiddleware ¶ added in v0.3.0
func LiftHTTPMiddleware(mw func(http.Handler) http.Handler) ConnectMiddleware
LiftHTTPMiddleware adapts a standard func(http.Handler) http.Handler into a ConnectMiddleware so existing net/http middleware (chi, gorilla, otelhttp, prometheus, tollbooth, …) can run on the sip handshake boundary.
Outcomes:
- Lifted middleware calls next: adapter invokes the sip ConnectHandler chain and returns its result.
- Lifted middleware writes a response and does NOT call next: adapter returns errResponseWritten so the framework stops without writing again.
Lifted middleware MUST NOT inspect the response after next returns — there is no response after upgrade. Must call next.ServeHTTP synchronously; goroutine dispatch is undefined.
type Handler ¶
type Handler func(sess Session) (tea.Model, []tea.ProgramOption)
Handler is the function Bubble Tea apps implement to hook into sip. This will create a new tea.Program for every browser connection and start it with the tea.ProgramOptions returned.
type Identity ¶ added in v0.3.0
type Identity interface {
String() string
}
Identity is the minimal contract for authenticated subjects produced by ConnectMiddleware. The interface is intentionally tiny so any auth implementation can satisfy it cheaply.
type ManagedCert ¶ added in v0.6.0
type ManagedCert struct {
// CertFile and KeyFile are the PEM paths. KeyFile is 0600.
CertFile string
KeyFile string
// DNSNames and IPs are the subject alternative names. A browser
// rejects the certificate outright for an address that is in neither,
// whatever the user has agreed to trust.
DNSNames []string
IPs []string
NotBefore time.Time
NotAfter time.Time
// Fingerprint is the SHA-256 of the DER, colon-separated and upper
// case: the same form browsers show in their certificate viewer, so a
// suspicious user can compare the two.
Fingerprint string
}
ManagedCert describes the keypair sip keeps for a deployment: where it is, what it covers and how long it lasts.
func CreateManagedCert ¶ added in v0.6.0
func CreateManagedCert(opts CertOptions) (*ManagedCert, error)
CreateManagedCert generates a keypair and writes it to the cert directory, replacing whatever was there. The key is written 0600 inside a 0700 directory.
func EnsureManagedCert ¶ added in v0.6.0
func EnsureManagedCert(opts CertOptions) (cert *ManagedCert, created bool, err error)
EnsureManagedCert returns the existing managed certificate, generating one when there is none, when it has expired, or when it does not cover the address the server is about to bind. It reports whether it generated one, so a caller can say so and show the browser warning only when it is news.
func LoadManagedCert ¶ added in v0.6.0
func LoadManagedCert(dir string) (*ManagedCert, error)
LoadManagedCert reads the managed certificate's metadata. It returns an error wrapping fs.ErrNotExist when there is none, which is a normal state and not a failure: callers test it with errors.Is.
func (*ManagedCert) Covers ¶ added in v0.6.0
func (c *ManagedCert) Covers(host string) bool
Covers reports whether host is in the certificate's SAN. A browser will refuse the connection when it is not, so this is what a caller checks before telling a user to point a phone at an address.
func (*ManagedCert) Expired ¶ added in v0.6.0
func (c *ManagedCert) Expired() bool
Expired reports whether the certificate is outside its validity window.
func (*ManagedCert) ExpiresWithin ¶ added in v0.6.0
func (c *ManagedCert) ExpiresWithin(d time.Duration) bool
ExpiresWithin reports whether the certificate runs out inside d.
type Middleware ¶ added in v0.3.0
Middleware decorates a Handler. Matches the shape of charmbracelet/wish bubbletea.Middleware.
type MobileKey ¶ added in v0.5.0
type MobileKey struct {
// Label is the text on the button. Keep it short: a row is a single
// strip on a phone screen.
Label string `json:"label"`
// Title is the tooltip and the accessible name.
Title string `json:"title,omitempty"`
// Key is a KeyboardEvent key name ("Escape", "Tab", "ArrowLeft",
// "Home", "PageUp") or a literal character ("/", "|"). Ignored when
// Mod is set.
Key string `json:"key,omitempty"`
// Code is the KeyboardEvent code ("KeyC", "Backslash"). The default
// client-side encoder works from Key alone and ignores this; it is
// carried for a page that supplies an encoder of its own, since a
// keymap encoder derives the character from the code and the shift
// state rather than from the key name.
Code string `json:"code,omitempty"`
// Mod makes this a sticky modifier instead of a key: "ctrl" or
// "alt".
Mod string `json:"mod,omitempty"`
// Ctrl, Alt and Shift are modifiers the button carries itself, on
// top of whatever the bar has armed. A "^C" button is
// {Label: "^C", Key: "c", Ctrl: true}.
Ctrl bool `json:"ctrl,omitempty"`
Alt bool `json:"alt,omitempty"`
Shift bool `json:"shift,omitempty"`
// Prefix makes this the leader button: it sends Config.MobilePrefix
// and stays lit until the next key goes out, so a chord with no button
// of its own can be finished on the software keyboard. The button is
// left out of the bar when no prefix is configured, rather than
// arming a chord that would never be sent.
Prefix bool `json:"prefix,omitempty"`
// Prefixed sends Config.MobilePrefix and then this key in one tap,
// with the Ctrl, Alt and Shift this button declares, so a chord whose
// second half is itself modified is still one button:
//
// {Label: "prev", Key: "o", Ctrl: true, Prefixed: true} tmux Ctrl+B Ctrl+O
//
// The bar's own sticky modifiers are cleared rather than folded in: a
// chord is a fixed sequence and the user pressed one button, so a
// latched Ctrl must not turn this into a different chord. With no
// prefix configured it sends the key on its own.
Prefixed bool `json:"prefixed,omitempty"`
// Narrow gives the button less horizontal padding, for a
// single-character label.
Narrow bool `json:"narrow,omitempty"`
// ID names the button so a page script can mark its state through the
// controller's setState.
ID string `json:"id,omitempty"`
}
MobileKey is one button on the client's touch key bar. It is handed to the browser as-is, so the field names match what webterm's key bar reads.
A key sends input:
sip.MobileKey{Label: "esc", Title: "Escape", Key: "Escape"}
sip.MobileKey{Label: "|", Title: "Pipe", Key: "|", Narrow: true}
A modifier is sticky instead: one tap arms it for the next keystroke, a second locks it until tapped off, because a touch screen cannot hold a key down while pressing another.
sip.MobileKey{Label: "ctrl", Title: "Ctrl", Mod: "ctrl"}
A chord is two buttons or one, and both need MobilePrefix set:
sip.MobileKey{Label: "pfx", Title: "Prefix, then a key", Prefix: true}
sip.MobileKey{Label: "split", Title: "Split the pane", Key: "%", Prefixed: true}
A button is a keystroke and nothing more. If the program has no binding for the key, tapping it does what typing that key does, which for an unbound chord is nothing at all. sip cannot know a deployment's keymap, so it never pretends to: a button reports no success it did not have.
func DefaultMobileKeys ¶ added in v0.6.0
func DefaultMobileKeys() []MobileKey
DefaultMobileKeys returns the key bar's built-in typing row: the keys a phone keyboard does not have, or hides two layers deep, in priority order because whatever comes first is what a narrow phone shows without scrolling.
It exists for a deployment that declares MobileRows and wants its own chords above this row rather than instead of it. Leaving both MobileKeys and MobileRows unset gets the same set without naming it.
type MobileMouse ¶ added in v0.7.0
type MobileMouse struct {
// Disable turns the whole thing off: a finger sends no mouse reports
// and the terminal behaves as it did before this existed. For a
// program that reads a click as something destructive, or that means
// to handle touch itself from a page script.
Disable bool
// DisableTap keeps the drag but stops a tap becoming a click and a
// long press becoming a right click.
DisableTap bool
// DisableDrag keeps the tap but stops a press-hold-then-move becoming
// a drag, leaving that gesture as a pan.
DisableDrag bool
// LongPressMs is how long a finger must sit still before moving it
// off becomes a drag rather than a pan. 0 means the default, 450.
LongPressMs int
// SlopPx is how far a finger may wander in CSS pixels and still count
// as sitting still. 0 means the default, 10.
SlopPx int
// DisableHint drops the two things that teach the drag: the ring drawn
// under a finger once it has held long enough that moving it is a
// drag, and the one-line hint shown the first time a finger pans the
// terminal instead. For a page that explains its gestures itself.
DisableHint bool
}
MobileMouse is what a finger on the terminal does.
A touch device has no mouse, and xterm.js's own touch handling stops at turning a pan into wheel reports: a tap, a long press and a press-hold-drag all reach the program as nothing at all. The client fills that in by synthesizing the mouse events the browser would have synthesized, so whatever mouse mode and encoding the program asked for is what it gets:
tap press and release button 1, which is how a program
is clicked and how the cursor is placed
long press press and release button 3, the right click
press, hold, drag press at the origin, motion, release, which is how a
split is pulled or a region selected
pan wheel reports, as before
With the program in no mouse mode at all the same gestures drive xterm's selection instead, so a finger selects text.
The zero value is all of it, on, with the defaults below. It costs a desktop nothing: none of it installs without a touch screen.
type MobilePrefix ¶ added in v0.6.0
type MobilePrefix struct {
Key string `json:"key,omitempty"`
Code string `json:"code,omitempty"`
Ctrl bool `json:"ctrl,omitempty"`
Alt bool `json:"alt,omitempty"`
Shift bool `json:"shift,omitempty"`
}
MobilePrefix is a leader chord: the key held with its modifiers that a program waits on before reading the next key as a command.
tmux, screen: sip.MobilePrefix{Key: "b", Code: "KeyB", Ctrl: true}
rebound tmux: sip.MobilePrefix{Key: "a", Code: "KeyA", Ctrl: true}
emacs: sip.MobilePrefix{Key: "x", Code: "KeyX", Ctrl: true}
Zero value means no prefix, which is what a program without a leader wants and what every deployment that predates this field already has.
func (MobilePrefix) IsZero ¶ added in v0.6.0
func (p MobilePrefix) IsZero() bool
IsZero reports whether no prefix chord is configured.
type MobileRow ¶ added in v0.6.0
type MobileRow struct {
// Label is the row's accessible name.
Label string `json:"label,omitempty"`
// Keys are the buttons, left to right.
Keys []MobileKey `json:"keys"`
// Collapsible lets the user fold this row away with a control pinned
// to the right of the bar, and remembers the answer. Two rows over a
// software keyboard cost about three rows of terminal on a phone, and
// a user who only types never touches the chord row. Leave the typing
// row un-collapsible: it is why the bar exists.
Collapsible bool `json:"collapsible,omitempty"`
}
MobileRow is one strip of the touch key bar.
type OptionsMessage ¶
type OptionsMessage struct {
ReadOnly bool `json:"readOnly"`
Appearance *clientAppearance `json:"appearance,omitempty"`
// MaxCols, MaxRows and MaxCells are the size caps. The client clamps
// its grid the same way before it asks, so it never draws rows the
// PTY does not have. The MsgResize the server sends back is still the
// authority.
MaxCols int `json:"maxCols"`
MaxRows int `json:"maxRows"`
MaxCells int `json:"maxCells"`
}
OptionsMessage is sent to configure the terminal.
Appearance is a pointer and omitted when nothing is configured, so a deployment that configures none gets no appearance key at all.
type PageAPI ¶ added in v0.8.0
type PageAPI struct {
// Grant adds capabilities to the default set.
Grant []Capability
// Revoke removes capabilities. It is applied after Grant, so a
// capability named in both is revoked.
//
// Revoke CapInput for a page that restyles the terminal and must not
// type into it. That is the split worth making: a theme switcher has
// no business holding a keystroke primitive.
Revoke []Capability
}
PageAPI bounds what a deployment's own page script may do through window.sip.
The zero value is the default set, so a deployment that says nothing gets what sip granted before this option existed. Grant adds to that set and Revoke takes away from it, which is why neither field needs a "none" value: Revoke everything and the page gets nothing.
cfg.PageAPI.Grant = []sip.Capability{sip.CapAppearance, sip.CapRead}
cfg.PageAPI.Revoke = []sip.Capability{sip.CapInput}
Read docs/extending.md before granting anything. The short version: the capability list bounds sip's own API and nothing else. Every script in the document shares one JavaScript context, so a grant is made to the page, not to the script you had in mind. A deployment that needs a real boundary puts the terminal in an iframe.
func (PageAPI) Validate ¶ added in v0.8.0
Validate reports the first capability name sip does not define.
The server refuses to start on one. A misspelled capability is silent otherwise: Grant drops it and the page goes on being denied, which reads exactly like sip ignoring the option. Appearance.Validate refuses a bad colour for the same reason.
type ProgramHandler ¶
ProgramHandler allows creating custom tea.Program instances. Use this for more control over program initialization. Make sure to use MakeOptions to properly configure I/O.
type Pty ¶
Pty represents pseudo-terminal information.
WidthPx and HeightPx are the canvas dimensions in pixels reported by the browser. They are populated when the client sends widthPx/heightPx in its resize message. Zero means the client did not report pixel dimensions.
type ResizeMessage ¶
type ResizeMessage struct {
Cols int `json:"cols"`
Rows int `json:"rows"`
WidthPx int `json:"widthPx,omitempty"`
HeightPx int `json:"heightPx,omitempty"`
}
ResizeMessage is sent when the terminal should be resized.
WidthPx and HeightPx are optional canvas dimensions in pixels. When non-zero the server populates the PTY's TIOCSWINSZ ws_xpixel/ws_ypixel fields, which kitty graphics tools (e.g. kitten icat) read to size images.
type Route ¶ added in v0.8.0
type Route struct {
// Pattern is where the route is served. It must not be one of sip's
// own paths, and the server reports which one it clashed with.
Pattern string
// Handler answers the request.
Handler http.Handler
}
Route serves a consumer's own URL alongside the terminal.
Pattern is an http.ServeMux pattern, so a trailing slash makes it a subtree:
sip.Route{Pattern: "/favicon.ico", Handler: http.HandlerFunc(myIcon)}
sip.Route{Pattern: "/brand/", Handler: http.StripPrefix("/brand/", http.FileServerFS(brand))}
Every route is behind the same Basic Auth as the rest of the server. Sip cannot tell which of a consumer's URLs is safe to publish, so it treats them all as private, the way it treats the static assets.
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server represents the web terminal server.
func (*Server) Serve ¶
Serve starts the server and serves the Bubble Tea application. The handler is called for each new browser session to create a model. This method blocks until the context is cancelled.
func (*Server) ServeCommand ¶ added in v0.1.8
ServeCommand starts the server and runs the specified command for each connection. This is used by the CLI to wrap arbitrary commands and expose them via the browser.
func (*Server) ServeWithProgram ¶
func (s *Server) ServeWithProgram(ctx context.Context, handler ProgramHandler) error
ServeWithProgram starts the server with a custom ProgramHandler. Use this for more control over tea.Program creation.
type Session ¶
type Session interface {
// Pty returns the pseudo-terminal information for this session.
Pty() Pty
// Context returns the session's context, which is cancelled when the
// session ends.
Context() context.Context
// Read reads input from the web terminal.
Read(p []byte) (n int, err error)
// Write writes output to the web terminal.
Write(p []byte) (n int, err error)
// Fd returns the file descriptor for TTY detection.
// Required for Bubble Tea to properly detect terminal mode.
Fd() uintptr
// PtySlave returns the underlying PTY slave file for direct I/O.
// Bubble Tea requires the actual *os.File to set raw mode properly.
PtySlave() *os.File
// WindowChanges returns a channel that receives window size changes.
WindowChanges() <-chan WindowSize
}
Session represents a web terminal session, similar to ssh.Session in Wish. It provides access to terminal dimensions and other session metadata.
type SessionIO ¶ added in v0.3.0
type SessionIO interface {
OutputReader() io.Reader
InputWriter() io.Writer
Resize(cols, rows int)
Done() <-chan struct{}
Context() context.Context
Close() error
}
SessionIO is the subset of session capabilities exposed to SessionMiddleware. It is the wrappable shape — middleware overrides OutputReader / InputWriter to filter byte streams.
type SessionMiddleware ¶ added in v0.3.0
SessionMiddleware decorates an internalSession to allow filtering of I/O streams (OutputReader / InputWriter) and lifecycle events. Compose using Go's interface-embedding idiom:
type myMW struct{ sip.SessionIO }
func (m *myMW) OutputReader() io.Reader { ... wrap m.SessionIO.OutputReader() ... }
SessionMiddleware values are applied in install order; the first middleware installed is the outermost wrapper.
type SizeMessage ¶ added in v0.8.5
type SizeMessage struct {
Cols int `json:"cols"`
Rows int `json:"rows"`
AskedCols int `json:"askedCols"`
AskedRows int `json:"askedRows"`
}
SizeMessage is a MsgResize from the server to the client. The server sends it when it clamped the size the client asked for. It carries the size the PTY got, and the size that was asked for, so a client that has asked again since can tell the answer is stale.
type Theme ¶ added in v0.8.0
type Theme struct {
// Foreground and Background are the default text and ground colours,
// used for every cell a program does not colour itself.
Foreground Color `json:"foreground,omitempty"`
Background Color `json:"background,omitempty"`
// Cursor is the text cursor's colour and CursorAccent is the colour of
// the character underneath it, which is why a block cursor needs both:
// with only the first set, the glyph under the block keeps the
// foreground colour and disappears into it.
Cursor Color `json:"cursor,omitempty"`
CursorAccent Color `json:"cursorAccent,omitempty"`
// SelectionBackground and SelectionForeground paint selected text.
// SelectionInactiveBackground paints it while the terminal does not
// hold focus, so a user can see what they selected before clicking
// away.
SelectionBackground Color `json:"selectionBackground,omitempty"`
SelectionForeground Color `json:"selectionForeground,omitempty"`
SelectionInactiveBackground Color `json:"selectionInactiveBackground,omitempty"`
// The eight normal ANSI colours, indices 0 to 7.
Black Color `json:"black,omitempty"`
Red Color `json:"red,omitempty"`
Green Color `json:"green,omitempty"`
Yellow Color `json:"yellow,omitempty"`
Blue Color `json:"blue,omitempty"`
Magenta Color `json:"magenta,omitempty"`
Cyan Color `json:"cyan,omitempty"`
White Color `json:"white,omitempty"`
// The eight bright ANSI colours, indices 8 to 15. A palette that calls
// index 5 "purple" rather than "magenta" means this one.
BrightBlack Color `json:"brightBlack,omitempty"`
BrightRed Color `json:"brightRed,omitempty"`
BrightGreen Color `json:"brightGreen,omitempty"`
BrightYellow Color `json:"brightYellow,omitempty"`
BrightBlue Color `json:"brightBlue,omitempty"`
BrightMagenta Color `json:"brightMagenta,omitempty"`
BrightCyan Color `json:"brightCyan,omitempty"`
BrightWhite Color `json:"brightWhite,omitempty"`
}
Theme is the terminal's palette: the sixteen ANSI colours plus the foreground, background, cursor and selection colours that a terminal theme carries alongside them.
The field names and their JSON tags are xterm.js's own, because the struct is handed to the browser as-is and given straight to xterm's theme option. Keeping the names is what makes an imported theme readable next to the file it came from.
Every field is optional. An unset colour keeps sip's default, so this is a patch over the built-in palette rather than a replacement for it. The zero Theme changes nothing.
func (Theme) ANSI ¶ added in v0.8.0
func (t Theme) ANSI() ANSIPalette
ANSI returns the sixteen ANSI colours in index order. An unset slot comes back empty.
func (Theme) Validate ¶ added in v0.8.0
Validate reports the first colour that is not hex. It is called for you when the server starts; call it yourself to check a theme as it is read from a file, where the offending line is still in hand.
func (Theme) WithANSI ¶ added in v0.8.0
func (t Theme) WithANSI(p ANSIPalette) Theme
WithANSI returns a copy of the theme with the sixteen ANSI colours taken from an indexed palette. An empty entry leaves that slot as it was, so a caller can fill the sixteen from a file and the rest by name:
th := sip.Theme{Background: "#282828", Foreground: "#ebdbb2"}.WithANSI(pal)
type WindowResizer ¶ added in v0.3.0
type WindowResizer interface {
ResizeWindow(size WindowSize)
}
WindowResizer is an optional capability for sessions that can apply pixel dimensions in addition to character dimensions. Sessions implementing this interface receive ResizeWindow calls; others fall back to Resize(cols, rows).
type WindowSize ¶
WindowSize represents a terminal window size change.
WidthPx and HeightPx are optional canvas dimensions in pixels. When non-zero they are forwarded to the PTY's TIOCSWINSZ ws_xpixel/ws_ypixel fields, which kitty graphics tools (e.g. kitten icat) read to size images.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
sip
command
Command sip wraps any CLI command and exposes it through a web browser.
|
Command sip wraps any CLI command and exposes it through a web browser. |
|
sip-wasm-build
command
sip-wasm-build compiles a Go package to WebAssembly, injecting js/wasm stubs into BubbleTea v2 at build time so a sip-rendered BubbleTea app can run entirely in the browser.
|
sip-wasm-build compiles a Go package to WebAssembly, injecting js/wasm stubs into BubbleTea v2 at build time so a sip-rendered BubbleTea app can run entirely in the browser. |
|
examples
|
|
|
appearance
command
Example: serve a shell with the deployment's own colours and cursor.
|
Example: serve a shell with the deployment's own colours and cursor. |
|
hackable
command
A deployment that changes how sip's page looks and behaves without forking sip.
|
A deployment that changes how sip's page looks and behaves without forking sip. |
|
simple
command
Simple example showing how to serve a Bubble Tea app through the browser.
|
Simple example showing how to serve a Bubble Tea app through the browser. |
|
middleware
|
|
|
logging
Package logging provides a layer-3 Middleware that records session start and end events via slog.
|
Package logging provides a layer-3 Middleware that records session start and end events via slog. |
|
osc52gate
Package osc52gate provides a SessionMiddleware that filters OSC 52 clipboard-write escape sequences in the outbound byte stream (server → client).
|
Package osc52gate provides a SessionMiddleware that filters OSC 52 clipboard-write escape sequences in the outbound byte stream (server → client). |
|
recover
Package recover provides a layer-3 Middleware that catches panics raised during Handler construction.
|
Package recover provides a layer-3 Middleware that catches panics raised during Handler construction. |
|
Package wasm provides a bridge for running BubbleTea programs in the browser.
|
Package wasm provides a bridge for running BubbleTea programs in the browser. |




