Documentation
¶
Overview ¶
Package server serves the rite.1 protocol: a read-only filesystem and commands that a ritesh client in the browser mounts over a WebSocket.
The wire contract is docs/protocol.md and the embedded JSON Schema (Schema). Conformance is checked against the shared traces in protocol/.
A Server is an http.Handler. Give it the origins that may connect and a way to turn a token into a principal, mount what clients may read, register what they may run, and route the WebSocket endpoint to it:
srv := server.New(server.Options{
Authenticate: authenticate,
Origins: []string{"https://example.dev"},
})
srv.Mount("/", fsys)
srv.Command(server.Command{Name: "hello", Run: hello})
http.Handle("/rite", srv)
Security ¶
The server decides what runs: a client names a registered command and sends argv, stdin, and signals. Clients never write to a mount.
A connection is refused unless its Origin header names a listed origin by exact scheme, host, and port. Behind a proxy, set the request's RemoteAddr to the client's address before the server sees it: the limit on connections that have not authenticated counts by it.
Paths from clients are checked before they reach a file system: a path with "..", an empty segment, or NUL is refused. Symbolic links are resolved by the server for file systems that report them (fs.ReadLinkFS, which os.DirFS, os.Root, and fstest.MapFS implement), and a link that leaves its mount is refused. Between that check and the open, the directory can change; for files on disk, os.Root closes that gap in the operating system and is the file system to mount.
Commands are Go functions, and Go cannot stop one. KILL, the output limit, and the time limit cancel the command's context and drop its output; a command that ignores its context keeps its goroutine and its process slot until it returns.
Example ¶
package main
import (
"context"
"errors"
"fmt"
"net/http"
"testing/fstest"
"github.com/jarrodb/ritesh/server"
)
func main() {
srv := server.New(server.Options{
Authenticate: func(_ context.Context, token string) (server.Principal, error) {
if token != "let-me-in" {
return server.Principal{}, errors.New("unknown token")
}
return server.Principal{ID: "user-1"}, nil
},
Origins: []string{"https://example.dev"},
Limits: server.DefaultLimits,
})
srv.Mount("/", fstest.MapFS{"readme.txt": {Data: []byte("hello\n")}})
srv.Command(server.Command{
Name: "whoami",
Summary: "print who you are",
Usage: "whoami",
Run: func(_ context.Context, p *server.Proc) int {
_, _ = fmt.Fprintln(p.Stdout, p.Principal.ID)
return 0
},
})
srv.OnSession(func(s server.Session) {
_ = s.Notify("info", "connected as "+s.Principal().ID)
})
mux := http.NewServeMux()
mux.Handle("/rite", srv)
// http.ListenAndServe(":8080", mux)
}
Output:
Index ¶
Examples ¶
Constants ¶
const ( // CapToolSchema from a client asks for the schemas of tool commands; from // the server it says the descriptors carry them. CapToolSchema = "tool.schema" // CapToolJSON and CapToolJSONL say tool commands take --json and --jsonl. CapToolJSON = "tool.json" CapToolJSONL = "tool.jsonl" )
The capabilities of rite.hello that concern tool commands.
const ( StdioTTY = "tty" StdioPipe = "pipe" )
The kinds of stdio in TTY.
const Protocol = "rite.1"
Protocol is the WebSocket subprotocol this package speaks.
Variables ¶
var ( // ErrInterrupted means the client sent INT. ErrInterrupted = errors.New("server: process interrupted") // ErrKilled means the client sent KILL or the process passed a limit. ErrKilled = errors.New("server: process killed") // ErrDisconnected means the connection ended. ErrDisconnected = errors.New("server: client disconnected") )
Causes of a process's context ending, read with context.Cause.
var ( // ErrNotConnected means the session has no connection, or has expired. ErrNotConnected = errors.New("server: session is not connected") // ErrLevel means the level is not info, warn, or error. ErrLevel = errors.New("server: level must be info, warn, or error") // ErrTooLarge means the text does not fit in one message. ErrTooLarge = errors.New("server: text exceeds the message limit") )
Errors from Session.Notify.
var DefaultLimits = defaultLimits()
DefaultLimits holds the default of every limit.
var Schema []byte
Schema is the rite.1 JSON Schema (2020-12), copied from protocol/ by the repository's sync script and checked for drift in CI.
Functions ¶
This section is empty.
Types ¶
type Candidate ¶
type Candidate struct {
// Value replaces the word being completed.
Value string `json:"value"`
// Display is shown in place of Value in the menu.
Display string `json:"display,omitempty"`
Description string `json:"description,omitempty"`
// Suffix is appended after Value: nil for the client's default, a space.
Suffix *string `json:"suffix,omitempty"`
}
Candidate is one completion.
type Command ¶
type Command struct {
// Name is what the client types. It is matched against argv[0].
Name string
Summary string
Usage string
// Flags describes the command's flags, keyed by their canonical name.
// The server does not parse them: Run receives argv as the client sent it.
Flags map[string]Flag
Subcommands map[string]Subcommand
// Run executes the command and returns its exit code, 0 to 255. It must
// return soon after ctx ends: the context is cancelled when the client
// interrupts or kills the process, when a limit is passed, and when the
// connection ends. context.Cause tells which. After an interrupt the
// command chooses its code, 130 by convention.
Run func(ctx context.Context, p *Proc) int
// Complete returns candidates for argv[index], the word the client is
// completing. When it is nil the server completes the command's flags.
Complete func(ctx context.Context, argv []string, index int) []Candidate
// Schemas make the command a tool command: it takes --json and --jsonl,
// and its schemas go to clients that send the tool.schema capability.
// The tool package fills them.
Schemas *Schemas
}
Command is something a client can run. Name, Summary, Usage, Flags, and Subcommands are sent to the client in rite.hello, which renders --help and man from them.
type Flag ¶
type Flag struct {
Long string `json:"long,omitempty"`
Short string `json:"short,omitempty"`
// Type defaults to FlagBoolean.
Type FlagType `json:"type"`
Repeat bool `json:"repeat,omitempty"`
Description string `json:"description,omitempty"`
}
Flag describes one flag of a command. Long and Short are spelled without their dashes.
type Limits ¶
type Limits struct {
// MaxMessageBytes is the largest message either side may send.
// Reported in rite.hello. The floor is 1024.
MaxMessageBytes int
// MaxProcs is the number of processes a session may run at once.
// Reported in rite.hello.
MaxProcs int
// MaxOutputBytes is what one process may write to stdout and stderr
// together. A process that passes it is killed, and proc.stderr says why.
// Reported in rite.hello.
MaxOutputBytes int64
// IdleTimeout closes a connection, with code 1000 and reason "idle",
// once no message has passed in either direction and no process has run
// for this long. Pings do not count. Reported in rite.hello as
// idleSeconds.
IdleTimeout time.Duration
// PingInterval is the time between WebSocket pings. Keep it below the
// idle timeout of any proxy in front of the server.
PingInterval time.Duration
// MessagesPerSecond is the rate of client messages on one connection.
// One second's worth may arrive at once. Past it the connection closes
// with 4029.
MessagesPerSecond int
// SessionsPerPrincipal is the number of sessions, connected or within
// their resume window, one principal may hold. A new session past it
// replaces the principal's oldest disconnected one, or closes with 4029
// when all are connected.
SessionsPerPrincipal int
// PreAuthPerAddress is the number of connections from one address that
// may wait for rite.hello at once. Past it a connection closes with 4029.
PreAuthPerAddress int
// ProcWallTime is how long one process may run before it is killed.
ProcWallTime time.Duration
// MaxStdinBytes is the stdin a process may leave unread. A process whose
// buffer passes it is killed, and proc.stderr says why.
MaxStdinBytes int
// MaxArgs and MaxArgBytes bound argv in proc.start and proc.complete.
MaxArgs int
MaxArgBytes int
// MaxEnvVars and MaxEnvBytes bound env in proc.start. The bytes count
// names and values.
MaxEnvVars int
MaxEnvBytes int
// MaxPathBytes bounds a path or cwd.
MaxPathBytes int
// MaxReadBytes bounds the bytes one fs.read returns.
MaxReadBytes int64
// MaxListEntries bounds the entries one fs.list returns.
MaxListEntries int
}
Limits bounds what one client can make the server do. A zero or negative field takes its default, the value DefaultLimits starts with.
type Options ¶
type Options struct {
// Authenticate turns the token of a rite.hello into a principal. Its
// context carries the values of the upgrade request's context, so a
// middleware can pass what it knows of the client. An error closes the
// connection as unauthorized (4001), which the client does not retry. A context that ran out closes it as a server error
// (4500), which the client does. The server never logs the token.
// Without Authenticate every connection is refused.
Authenticate func(ctx context.Context, token string) (Principal, error)
// Origins lists the origins that may connect, each as scheme://host or
// scheme://host:port. The Origin header must name one of them exactly;
// there are no patterns. A request without an Origin is refused.
Origins []string
// Limits bounds each client. Zero fields take their defaults.
Limits Limits
// Logger receives the server's logs. Nil discards them.
Logger *slog.Logger
// MOTD, when set, is shown by the client after it connects.
MOTD string
}
Options configures a Server.
type Principal ¶
type Principal struct {
// ID names the principal. Sessions are bound to it, and the limit on
// sessions counts by it. It must not be empty.
ID string
// Attrs carries what the host wants its commands to know, such as a
// tenant or a role. The server does not read it.
Attrs map[string]string
}
Principal is who a token authenticated.
type Proc ¶
type Proc struct {
// Args is argv. Args[0] is the name the command was called by.
Args []string
// Env holds the variables the client's host allows it to send.
Env map[string]string
// Cwd is the client's working directory relative to the remote's root,
// "" for the root or for a directory outside the remote.
Cwd string
// Stdin returns io.EOF when the client closes it and an error when the
// process's context ends.
Stdin io.Reader
// Stdout and Stderr send each Write to the client as one notification, so
// wrap them in a bufio.Writer for many small writes. Bytes that are not
// UTF-8 are replaced with U+FFFD. Writes block while the client is slow
// and fail once the process is killed.
Stdout, Stderr io.Writer
TTY TTY
Principal Principal
// contains filtered or unexported fields
}
Proc is one run of a command.
type Schemas ¶ added in v0.3.0
type Schemas struct {
Input, Output json.RawMessage
// Event is nil for a tool without events.
Event json.RawMessage
}
Schemas are the JSON Schemas of a tool command, each a JSON object.
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server serves rite.1 to browsers. It is an http.Handler: route the WebSocket endpoint to it. Sessions live in process memory, so run one replica or pin clients to one.
func New ¶
New returns a server with no mounts and no commands. It panics when an entry of Options.Origins is not an origin.
func (*Server) Broadcast ¶ added in v0.4.0
Broadcast sends term.notify to every connected session, as Notify does, and returns how many it reached. A connection whose outgoing queue is full is skipped rather than waited on, so one slow client delays no other.
func (*Server) Close ¶
Close ends every connection and waits for their handlers to return. New connections are refused afterwards. Commands are cancelled, not waited for.
func (*Server) Command ¶
Command registers a command. Commands are reported to clients in the order they were registered. Command panics on an empty or repeated name, a nil Run, an unknown flag type, or a schema that is not a JSON object.
func (*Server) Mount ¶
Mount serves fsys, read-only, at path under the remote's root: "/" for the root itself. For files on disk pass os.OpenRoot(dir) and its FS method, which the operating system confines to dir. Mount panics on a path that is not clean or is already mounted.
type Session ¶
type Session struct {
// contains filtered or unexported fields
}
Session is a handle on one client session. It stays valid across the client's reconnects and for ten minutes after a disconnect.
type Subcommand ¶
Subcommand describes one subcommand of a command.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
rite-world
command
Command rite-world serves protocol/world.json over rite.1 on a local port, for the client-to-server interop test (packages/ritesh/test/interop).
|
Command rite-world serves protocol/world.json over rite.1 on a local port, for the client-to-server interop test (packages/ritesh/test/interop). |
|
Package tool defines a tool once and serves it to people and agents: as a command in a shell (CLI), as a rite command over rite.1, and as an MCP tool.
|
Package tool defines a tool once and serves it to people and agents: as a command in a shell (CLI), as a rite command over rite.1, and as an MCP tool. |