sip

package module
v0.10.0 Latest Latest
Warning

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

Go to latest
Published: Oct 26, 2026 License: MIT Imports: 52 Imported by: 3 modules, 1 package

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

sip

Go reference

A Go server that puts a real terminal in a browser tab.

every keystroke, wheel event, drag and copy above crosses a websocket to a real pseudo-terminal, and the image is decoded in the browser from the kitty escape the program wrote

You bring a command, or a Bubble Tea model, and a browser. sip gives back a pseudo-terminal to run it on, a client that renders the result with xterm.js, and a wire between them that speaks WebTransport where the browser will and WebSocket everywhere else. The program on the far side takes its interactive code path: isatty is true, TERM means something, SIGWINCH arrives when the tab is resized, and the window size carries pixel dimensions so kitty graphics tools can size an image to the cell grid.

There are two ways in and neither is the lesser one. sip -- htop serves a command with no Go anywhere. server.Serve runs a Bubble Tea model per browser session, with a handler shaped like Wish's. Both build the same session over the same transports, so a bug in one is a bug in the other.

The client is vendored, not built. static/webterm.js is a standalone build of the webterm package, which inlines xterm.js and its fit, webgl, canvas, web-links, image and unicode-graphemes addons along with the kitty overlay, the clipboard layer, the width overrides, the transports, the buffer search and the touch layer. webterm-vendor.json names the webterm commit it was built from. The optional vtgl renderer is a second file, static/webterm-vtgl.js, which the page loads only when the vtgl renderer is chosen. The experimental worker engine is static/engine/: libghostty-vt and a WebGL2 renderer in Web Workers, loaded only when the renderer is engine. A browser that cannot run it gets the xterm.js client. With the engine, the connection also runs in a worker, with the same transports and reconnect rules, so terminal output never reaches the page's main thread. engine-vendor.json names its webterm commit. There is no build step, no bundler and no node_modules between a clone and a running server: go:embed bakes the whole client, fonts included, into one binary.

What it does

  • Runs the program on a real pseudo-terminal through xpty, so it takes its interactive path rather than the piped-output one, and tears it down by process group so a multiplexer's daemon does not outlive the session.
  • Speaks WebTransport over HTTP/3 where the browser negotiates it and falls back to WebSocket otherwise, with the same type-prefixed binary framing behind both and a /cert-hash exchange for the self-signed loopback case.
  • Draws kitty graphics through an overlay that anchors each placement to the buffer row that introduced it, so images scroll with their text instead of hanging over it, and repositions every placement on scroll and resize.
  • Decodes PNG placements in the browser with createImageBitmap. The server-side transcoder that re-emits them as raw RGBA is there for clients without a decoder and is off by default, because forwarding the compressed payload is both smaller and faster.
  • Carries pixel dimensions on resize and forwards them to TIOCSWINSZ, which is what kitten icat and ntcharts read to size an image to the grid.
  • Copies a selection to the system clipboard on Ctrl+C, and forwards OSC 52 writes from programs that set the clipboard themselves. It never answers an OSC 52 read: a remote program cannot pull your clipboard back through the terminal.
  • Sets the mouse pointer from the program, through the kitty pointer shapes protocol: a stack per screen, queries answered on the program's own stdin, and every name checked against the thirty the specification names before it reaches a CSS property.
  • Clusters graphemes to UAX 29 rather than billing per scalar, so a ZWJ family emoji takes the columns it draws in instead of eight.
  • Puts a key bar over the software keyboard on a phone, carrying the keys a phone keyboard does not have: Escape, Tab, the arrows, and Ctrl and Alt as sticky modifiers, because a touch screen cannot hold one key while pressing another. It measures the keyboard and gives the terminal what is left, and it makes a finger act like a mouse: tap to click, long press to right click, hold and drag to drag or to select.
  • Refuses to bind a non-loopback address without TLS, and refuses basic auth without it, unless told otherwise by an explicit flag that logs what it is giving up. Loopback gets a self-signed certificate generated on the spot.
  • Checks the Host header of each session handshake on a loopback bind. This stops DNS rebinding, where a web page points its own name at 127.0.0.1 and opens your terminal. A name passes only when it is localhost, the --host name, a --cert-host name or an --allow-host name. 0.0.0.0 and :: listen on loopback too, so they get the same check on plain HTTP with no password. There, every IP address passes, so the LAN address you type on a phone works. With TLS or a password they are not checked, so a machine name such as myhost.local works. sip looks up a --host name once, and the listeners bind the address it gives.
  • Composes at three layers, after Wish: ConnectMiddleware wraps the handshake, SessionMiddleware wraps the byte streams, and Middleware wraps the per-session handler. LiftHTTPMiddleware turns any func(http.Handler) http.Handler into the first of those, so chi, gorilla and otelhttp are all reusable at the door.
  • Ships as one binary. The client, the stylesheets and JetBrains Mono Nerd Font are embedded, tagged with a content ETag so a redeployed client actually takes effect.

What it looks like

Every image below is a frame of the real client in a real browser, driven against a real server by scripts/demo/record-hero.mjs, which is also what regenerates the recording at the top of this page. The programs are the ones on this machine and the files are this repository's own.

a shell in the browser has just run kitten icat on this repository's banner, and the image is drawn across the cells above the next prompt at its full widthglow is running on the alternate screen with this repository's README rendered as styled markdown, scrolled part way down by a mouse wheela drag has highlighted the kitten icat command line in the scrollback, leaving the rest of the screen unselectedthe prompt at the bottom of the screen now holds the command that was selected further up, pasted back out of the system clipboard and highlighted by the shell as bracketed pastethe client's settings panel is open over the terminal with rows for transport and renderer, a font size slider, checkboxes for copy on select and cursor blink, and a status block reporting that the renderer is WebGL and the transport fell back to WebSocket
a kitty graphics placement, sent as PNG over the socket and decoded in the browser
a Bubble Tea program on the alternate screen, scrolled with a real mouse wheel
a drag selection over a command line in the scrollback, on its way to the clipboard
the same text pasted back at the prompt, out of the system clipboard Ctrl+C wrote it to
the client's own settings, reporting the renderer and the transport it actually got

Install

go get github.com/Gaurav-Gosain/sip          # library
go install github.com/Gaurav-Gosain/sip/cmd/sip@latest   # command line

Command line

sip -- htop                                   # serve a command
sip -p 8080 -- lazygit                        # on another port
sip --host 0.0.0.0 --cert s.crt --key s.key -- bash       # public, with TLS
sip --basic-user admin --basic-pass-file /run/secrets/sip --cert s.crt --key s.key -- bash
sip --font /path/to/CommitMono.ttf --font-family "Commit Mono" -- nvim

Then open http://localhost:7681. The command to run goes after --, so its own flags are never read as sip's.

flag meaning
-H, --host, -p, --port bind address and HTTP port; WebTransport uses port+1
--cert, --key TLS certificate and key
--auto-tls serve HTTPS from a self-signed certificate sip generates and keeps
--cert-dir, --cert-host, --cert-days where that certificate lives, what else it signs for, how long it lasts
--allow-insecure-no-tls permit a non-loopback bind, or basic auth, without TLS
--origin browser origin allowlist, a path.Match glob, repeatable
--allow-host extra host name a loopback server, or a 0.0.0.0 or :: server with no TLS and no password, answers to, repeatable
--allow-framing let pages of every origin frame the terminal
--frame-ancestor an origin that may frame the terminal, repeatable
--basic-user, --basic-pass-file HTTP basic auth. Only the owner of the file may have access to it (mode 600). $SIP_PASSWORD is also read, and sip removes it from the environment of the program
--max-conns, --idle-timeout concurrent session limit and idle cutoff
--renderer webgl, canvas, dom or engine (experimental); empty picks the best available
--ctrl-v-to-program send Ctrl+V to the program as a key; by default it pastes
--font, --font-family serve a font from disk instead of the embedded one
-d, --dir working directory for the wrapped command

sip completion writes a bash, zsh, fish or powershell script. Commands, help and completion are built on spf13/cobra and rendered by charmbracelet/fang.

Library

server := sip.NewServer(sip.DefaultConfig())

err := server.Serve(ctx, func(sess sip.Session) (tea.Model, []tea.ProgramOption) {
	pty := sess.Pty()
	return model{width: pty.Width, height: pty.Height}, nil
})

Handler returns a model and its options per session. ServeWithProgram takes a ProgramHandler and hands back a *tea.Program instead, for when the program needs constructing directly:

server.ServeWithProgram(ctx, func(sess sip.Session) *tea.Program {
	return tea.NewProgram(myModel{}, sip.MakeOptions(sess)...)
})

A Session is the terminal:

type Session interface {
	Pty() Pty                            // terminal dimensions
	Context() context.Context            // cancelled when the browser goes away
	Read(p []byte) (n int, err error)
	Write(p []byte) (n int, err error)
	WindowChanges() <-chan WindowSize    // resize events
}

Config covers the rest: Host, Port, ReadOnly, MaxConnections, IdleTimeout, AllowOrigins and OriginPatterns, TLSCert and TLSKey, AutoTLS and its CertDir, CertHosts and CertValidity, BasicUsername and BasicPassword, AllowedHosts, AllowFraming and FrameAncestors, MaxPasteBytes, ResizeThrottle, MaxWindowDims and MaxWindowCells, FontPath and FontFamily, Appearance for the palette and the cursors, the touch key bar's MobileKeys, MobileRows and MobilePrefix, and the three middleware slices. Every field has a working default; sip.DefaultConfig() is a complete configuration.

Three middleware subpackages ship with it: middleware/osc52gate to allow, deny or audit outbound OSC 52 clipboard writes, middleware/recover to catch a panic while a handler builds a model, and middleware/logging for slog session start and end lines.

A Bubble Tea program can also be compiled to wasm and run with no server at all: go run ./cmd/sip-wasm-build -o web/app.wasm ./cmd/myapp builds it, and the client connects to it through the same adapter it uses for a socket.

Colours

The terminal's palette, its two cursors and the chrome around them are Config.Appearance. The zero value is sip's own Catppuccin Mocha, so a program that sets nothing looks exactly as it did before the field existed.

sip.Config{
    Appearance: sip.Appearance{
        Theme: sip.Theme{
            Foreground: "#ebdbb2",
            Background: "#282828",
            Cursor:     "#fe8019",
        }.WithANSI(sip.ANSIPalette{
            "#282828", "#cc241d", "#98971a", "#d79921",
            "#458588", "#b16286", "#689d6a", "#a89984",
            "#928374", "#fb4934", "#b8bb26", "#fabd2f",
            "#83a598", "#d3869b", "#8ec07c", "#ebdbb2",
        }),
        MouseCursor: "crosshair",
        CursorStyle: "bar",
        Title:       "Gruvbox shell",
    },
}

A theme is a patch, not a replacement: an unset colour keeps sip's own, so three colours change three colours. WithANSI takes the sixteen in index order, which is how a palette read out of kitty, ghostty, alacritty or wezterm arrives, and the named fields are xterm.js's own so an imported theme reads next to the file it came from.

The page follows the palette. The settings panel, the status pill, the scrollbar, the bell flash and the touch key bar are painted from the same colours as the terminal, so a Gruvbox terminal does not sit in a Catppuccin panel. PageBackground sets the ground behind the grid on its own, for the one case where the two should differ.

Colours are hex: #rgb, #rgba, #rrggbb or #rrggbbaa. A bad colour or an unknown cursor keyword stops the server at startup and names the field. That is deliberate. A browser drops a value it cannot parse and paints the default, which makes a typo look like sip ignoring the setting.

examples/appearance is the whole thing in one file.

Hacking the page

Everything the browser runs is embedded in sip's binary, so until this existed changing one CSS rule meant forking sip. A handful of options change the page from Go instead, and a deployment that sets none of them serves exactly what it served before they existed.

sip.Config{
    ExtraCSS: `#connection-status { border-color: #a6e3a1; }`,
    ExtraJS:  `sip.on('connect', (e) => console.log('on', e.transport));`,
    PageAPI:  sip.PageAPI{Grant: []sip.Capability{sip.CapAppearance}},
    StaticFS: myAssets,                       // wins over sip's files, name by name
    Routes: []sip.Route{
        {Pattern: "/manifest.webmanifest", Handler: http.HandlerFunc(manifest)},
    },
}

Reach for them in that order. ExtraCSS and ExtraJS add to what sip serves, so an upgrade carries every fix to the files underneath. StaticFS replaces a file, which is a fork of that one file: sip names the replaced files at startup and sip.AssetDigest lets a test of yours fail on the upgrade that moved the original.

window.sip is what a page script may rely on: on, off, send, size, and the events ready, connect, disconnect, resize and title. There is no handle to the xterm.js terminal in it, on purpose. Sip may change what renders the grid, and a promise it plans to break is worse than no promise.

Config.PageAPI decides what else that script may do. sip.claim() hands over a theme switcher, a search box, the selection, the clipboard and a reconnect button, one capability at a time. Every one of them is off unless you grant it, and the default is what window.sip answered before the option existed. Read docs/extending.md before granting any of them: it carries the threat model, including the part a capability list cannot do.

examples/hackable is all of it in one file, and docs/extending.md argues each option and says what is deliberately missing.

Phones

A phone keyboard has no Escape, no Tab, no Ctrl and no arrows, which is most of what a terminal is driven with, and when it opens it covers the bottom half of the terminal it was opened for. On a touch device sip puts a scrolling key bar above the keyboard with those keys on it, measures how much of the window the keyboard is actually covering, and reserves it so the grid is refitted to what is left rather than being hidden behind it. Ctrl and Alt are sticky: one tap arms the modifier for the next keystroke, a second locks it until tapped off.

The default key set assumes nothing about what is running, because sip serves arbitrary programs. A library caller that knows better can replace it:

srv, _ := sip.New(sip.Config{
    MobileKeys: []sip.MobileKey{
        {Label: "esc", Title: "Escape", Key: "Escape"},
        {Label: "ctrl", Title: "Ctrl", Mod: "ctrl"},
        {Label: "^C", Title: "Interrupt", Key: "c", Ctrl: true},
        {Label: "/", Title: "Search", Key: "/", Narrow: true},
    },
})

Key is a KeyboardEvent key name or a literal character, Mod makes the button a sticky modifier instead, and DisableMobileKeyBar leaves the strip out for a program that draws touch controls of its own while keeping the keyboard-aware layout.

Leader chords

tmux, screen, zellij and emacs are all driven by a leader: press Ctrl+B, let go, then press a letter. A touch screen cannot hold a modifier while pressing another key, so on a phone every one of those bindings is unreachable, which for those programs is most of what they can do.

Declare the leader and the chords are buttons:

sip.Config{
    MobilePrefix: sip.MobilePrefix{Key: "b", Code: "KeyB", Ctrl: true},

    MobileRows: []sip.MobileRow{{
        Label:       "tmux",
        Collapsible: true,
        Keys: []sip.MobileKey{
            {Label: "pfx", Title: "Prefix, then a key", Prefix: true},
            {Label: "new", Title: "New window", Key: "c", Prefixed: true},
            {Label: "next", Title: "Next window", Key: "n", Prefixed: true},
            {Label: "split", Title: "Split", Key: "%", Prefixed: true},
            {Label: "zoom", Title: "Zoom the pane", Key: "z", Prefixed: true},
            {Label: "detach", Title: "Detach", Key: "d", Prefixed: true},
        },
    }, {
        Label: "keys",
        Keys:  sip.DefaultMobileKeys(),
    }},
}

MobilePrefix is whatever your leader is: Ctrl+A for a rebound tmux, Ctrl+X for emacs. A Prefixed key is one tap for the whole chord: the leader goes out, then the key with whatever Ctrl, Alt and Shift the button declares, so {Key: "o", Ctrl: true, Prefixed: true} is tmux's Ctrl+B Ctrl+O in one tap. The bar's own sticky modifiers are cleared rather than folded in, because Ctrl+B Ctrl+C is a different chord from Ctrl+B C and the user pressed one button. The Prefix button is for everything you did not give a button to: tap it and it lights up, then type the second half on the software keyboard.

Rows are drawn top to bottom and the typing row goes last, nearest the thumb that is already on the keyboard. A Collapsible row can be folded away by a control pinned to the right of the bar, which gives its height back to the terminal, and the choice is remembered.

A button is a keystroke and nothing more. If the program has no binding for the key, tapping it does exactly what typing that key does, which for an unbound chord is nothing at all: sip cannot know your keymap, so it never reports a success it did not have. The one case it will not fake is a Prefix button with no MobilePrefix set, which would light up and arm a chord that is never sent; that button is left out of the bar, and a Prefixed key with no prefix sends itself bare.

A finger is a mouse

xterm.js's own touch handling stops at turning a pan into scroll, so on a phone a tap, a long press and a drag reach the program as nothing at all: not a click, not a cursor placed, not a selection. sip fills that in.

gesture what the program gets
tap a click, and the software keyboard
long press a right click
press, hold, then drag a press, motion and a release: pull a split, move a window, select a region
pan scroll, as before

It is expressed as the mouse events a browser would have synthesized, not as bytes, so whichever mouse mode and encoding your program asked for is what it gets, and a program that asked for no mouse reporting at all gets the other useful thing for free: the same press-hold-drag selects text.

The zero value is all of it, on, and none of it installs without a touch screen. Config.MobileMouse turns parts off and retunes the hold:

sip.Config{
    MobileMouse: sip.MobileMouse{DisableTap: true, LongPressMs: 600},
}

The floating settings gear is draggable on a desktop and remembers where it was left, because it floats over whatever the program is drawing and there is no corner that is free of every program. On a phone it is not a floating control at all: it moves into the key bar.

TLS

sip refuses a non-loopback bind without TLS. Binding a LAN address is exactly what you do to reach a terminal from your phone, so that refusal is in the common path, and until it had an answer the answer people found was --allow-insecure-no-tls, permanently.

sip --host 0.0.0.0 --auto-tls -- bash

That generates a keypair on first use, keeps it in your user config directory, and reuses it afterwards. Run it at a terminal without --auto-tls and sip asks first; run it from a script, a container or a systemd unit and it does not ask, because there is nobody to answer, so what those get is the same refusal with a message naming the flag. Nothing here turns the requirement off.

sip cert            # where it is, what it covers, when it expires, its fingerprint
sip cert new        # generate or replace one
sip cert rm         # delete it
sip cert path       # just the path, for a unit file (--key for the key's)

The certificate signs for itself, so the first visit from any browser shows a warning: "Your connection is not private", NET::ERR_CERT_AUTHORITY_INVALID, or "Potential Security Risk Ahead". That is expected. Choose Advanced, then Proceed. The connection is encrypted either way; what the browser cannot do is vouch for who is on the other end. To stop seeing it, copy the .crt to the device and install it as a trusted certificate: on Android under Settings, Encryption & credentials, Install a certificate, CA certificate; on iOS open the file, install the profile, then enable it under About, Certificate Trust Settings. sip cert prints all of this with the fingerprint to compare against.

It signs for localhost, this machine's hostname and hostname.local, and every non-loopback address on every interface, so the LAN address you actually type works. --cert-host adds names only your router's DNS knows. A certificate that stops covering the address being bound, which is what a moved DHCP lease looks like, is regenerated rather than served into a name mismatch the browser will not let you click through.

The private key is written 0600 inside a 0700 directory, and its path is printed by sip cert path --key and nowhere else. Everywhere else it could appear is a terminal that may be shared or recorded, which is the thing sip is for.

Clipboard

Two independent paths, and which one you need depends on the program.

Selection, which works everywhere and needs no configuration: drag to select and press Ctrl+C. Double-click takes a word, triple-click a line. When a program holds the mouse, as tmux, vim and htop do with mouse mode on, hold Shift while dragging to bypass mouse reporting and select the screen text instead. "Copy on select" in the settings panel copies on release. Ctrl+Shift+C is not the path to rely on: both Chromium and Firefox reserve it for devtools and it never reaches the page.

OSC 52, for programs that set the clipboard themselves: sip forwards the escape to the browser, which writes it to the system clipboard. tmux does not emit OSC 52 under its default set-clipboard external, so add set -g set-clipboard on to your tmux.conf, at every level if you nest it. On a secure origin, meaning https or http on localhost, the write is immediate; on a plain-http LAN address the browser blocks the async clipboard API and sip falls back to a legacy copy that runs on your next click or keypress. Serving over https is how to get gesture-free clipboard writes.

  • Bubble Tea, the TUI framework the library mode serves
  • Wish, SSH for Bubble Tea apps, and the model for sip's handler and middleware API
  • webterm, the embeddable browser terminal sip vendors as its client
  • TUIOS, the terminal window manager sip was extracted from
  • xterm.js, which parses the VT stream and owns input, selection and scrollback
  • ttyd, the same idea in C

License

MIT. See LICENSE.

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

View Source
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.

View Source
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.

View Source
const MaxMessageSize = 1 << 20

MaxMessageSize is the maximum allowed message size (1 MiB).

View Source
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

func AssetDigest(name string) (string, error)

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

func Assets() fs.FS

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

func CertPaths(dir string) (certFile, keyFile string, err error)

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

func DefaultCertDir() (string, error)

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

func RemoteAddrFromContext(ctx context.Context) string

RemoteAddrFromContext returns the remote address attached to ctx, or "" if none.

func RemoveManagedCert added in v0.6.0

func RemoveManagedCert(dir string) error

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

func SetLogLevel(level log.Level)

SetLogLevel sets the logging verbosity for the sip package.

func WithIdentity added in v0.3.0

func WithIdentity(ctx context.Context, id Identity) context.Context

WithIdentity returns a derived context carrying id. Passing nil returns ctx unchanged.

func WithRemoteAddr added in v0.3.0

func WithRemoteAddr(ctx context.Context, addr string) context.Context

WithRemoteAddr returns a derived context carrying the client's remote address. Empty addr 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) Run added in v0.3.0

func (p *BrowserProgram) Run() (tea.Model, 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

type CertInfo struct {
	TLSConfig *tls.Config
	DER       []byte
	Hash      [32]byte
}

CertInfo holds generated certificate information.

func GenerateSelfSignedCert

func GenerateSelfSignedCert(_ string) (*CertInfo, error)

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.

func (Color) IsZero added in v0.8.0

func (c Color) IsZero() bool

IsZero reports whether the colour is unset.

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

func ConfigFromContext(ctx context.Context) Config

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

type ConnectHandler func(r *http.Request) error

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.

func IdentityFromContext added in v0.3.0

func IdentityFromContext(ctx context.Context) (Identity, bool)

IdentityFromContext returns the Identity attached to ctx, if any.

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

type Middleware func(next Handler) Handler

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

func (p PageAPI) Validate() error

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

type ProgramHandler func(sess Session) *tea.Program

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

type Pty struct {
	Width    int
	Height   int
	WidthPx  int
	HeightPx int
}

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 NewServer

func NewServer(config Config) *Server

NewServer creates a new web terminal server with the given configuration.

func (*Server) Serve

func (s *Server) Serve(ctx context.Context, handler Handler) error

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

func (s *Server) ServeCommand(ctx context.Context, name string, args []string, dir string) error

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

type SessionMiddleware func(SessionIO) SessionIO

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) IsZero added in v0.8.0

func (t Theme) IsZero() bool

IsZero reports whether no colour is set.

func (Theme) Validate added in v0.8.0

func (t Theme) Validate() error

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

type WindowSize struct {
	Width    int
	Height   int
	WidthPx  int
	HeightPx int
}

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.

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.

Jump to

Keyboard shortcuts

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