All 42 libraries

SugarSshServer

SSH server middleware framework

inspired by charmbracelet/wish ssh force-command middleware-over-sshd

SugarSshServer code coverage

Build TUIs anyone can ssh user@host to run. Leans on the host's OpenSSH daemon (ForceCommand) rather than re-implementing the SSH wire protocol. sshd handles auth, ciphers, host keys, audit logs; blocking brute-forcers stays fail2ban's separate job.

Install

composer require sugarcraft/sugar-ssh-server

Two transports

What the supervisor PHP process does internally is pluggable via the Transport abstraction:

  • InProcessTransport (default). Allocates a sugar-pty master/slave pair, spawns the user's cmd as a subprocess with full controlling-terminal semantics (Ctrl+C → SIGINT, SIGWINCH-driven resize, job control), pumps bytes between the supervisor's STDIN/STDOUT and the sugar-pty master. Terminal middleware: Spawn.
  • HostSshdTransport (legacy, opt-in). Pre-PTY-upgrade architecture: middleware run inline in the supervisor; the terminal middleware (BubbleTea) mounts a SugarCraft Program directly on the supervisor's STDIN/STDOUT. Pin via Server::withTransport(new HostSshdTransport()). Use this for inline-STDIN-reading middleware or zero-subprocess Program mounts.

Quickstart — in-process bash

// /opt/wish/server.php — invoked by sshd ForceCommand
require '/opt/wish/vendor/autoload.php';

use SugarCraft\SshServer\Server;
use SugarCraft\SshServer\Middleware\{Logger, Auth, Spawn};
use SugarCraft\SshServer\Session;

exit(Server::new()
    ->use(Logger::toFile('/var/log/wish.jsonl'))
    ->use(new Auth(users: ['wishuser']))
    ->use(new Spawn(fn (Session $s) => [
        'cmd' => ['/bin/bash', '-l'],
        'env' => [
            'TERM' => $s->term, 'USER' => $s->user, 'HOME' => "/home/{$s->user}",
            'PATH' => '/usr/local/bin:/usr/bin:/bin',
        ],
    ]))
    ->serve());

Quickstart — host-sshd legacy

use SugarCraft\SshServer\Transport\HostSshdTransport;
use SugarCraft\SshServer\Middleware\BubbleTea;

exit(Server::new()
    ->withTransport(new HostSshdTransport())
    ->use(Logger::toFile('/var/log/wish.jsonl'))
    ->use(new Auth(users: ['wishuser']))
    ->use(new BubbleTea(fn($session) => new MyApp($session)))
    ->serve());

The wishuser in both Auth allowlists is what the sshd Match block makes true: under ForceCommand the entry script runs as the target account, so $s->user is that account on every connection, and an allowlist of human names refuses 100% of logins with exit Server::EXIT_DENIED. Per-user separation needs per-user Match blocks or authorized_keys command= entries, each running its own entry script.

What's in the box

InProcessTransport (default)sugar-pty supervisor — allocates a PTY, spawns child with controllingTerminal:true, pumps bytes, forwards SIGWINCH. Lets you mount any cmd / shell / editor.
HostSshdTransport (legacy)Pre-PTY-upgrade behavior. Middleware run inline against sshd's PTY directly. Zero subprocess overhead.
Spawn middleware (InProcess only)Terminal — produces cmd[] from Session via factory. Drives runChild() on the active transport.
BubbleTea middleware (HostSshd only)Terminal — mounts a SugarCraft Program inline reading STDIN/STDOUT. Transport-aware: throws clearly under InProcess.
Logger / Auth / RateLimitTransport-agnostic. Same composition surface under either mode.
Custom middlewareAnything implementing Middleware::handle(Context $ctx, Session $session, callable $next): void.

Source & demos

Try the quickstart →

API

ClassMethodDescription
Servernew()Start an empty middleware pipeline — this library opens no listener: the pipeline runs inside the process sshd (or your supervisor) spawns under ForceCommand
Serveruse(Middleware)Add middleware to the pipeline
ServerwithTransport(Transport)Override the active transport (default: InProcessTransport)
ServerwithKeepalive(int)Add keepalive middleware with the given interval
Serverserve(?Session, ?Context)Start the server (builds a fresh root Context::background() automatically when none is passed; supply a cancellable context to make cancel-propagation reachable through the public API)
Contextbackground()Root context — never done, not cancelable
ContextwithValue(string $k, mixed $v)Return a new context with $k → $v attached
ContextwithDeadline(DateTimeImmutable)Return a new cancelable context that is done when deadline passes
ContextwithCancelable()Return a new cancelable context (call cancel() to trigger)
Contextcancel(?Throwable)Mark the context as canceled
Contextdone(): boolTrue when canceled or deadline-exceeded
Contexterr(): ?ThrowableCancellationException, DeadlineExceededException, or null
Contextvalue(string $k): mixedWalk parent chain looking for $k; null if not found
Sessionuser, term, cols, rows, clientHost, clientPort, serverHost, serverPort, tty, command, lang, sessionId, authMethod, keyFingerprint, clientVersion, serverVersionSession metadata. The last five are filled in by withProtocolMetadata() and are honest only so far as the environment is: sessionId is minted per process, authMethod is sniffed from SSH_USER_AUTH, keyFingerprint is always null today, and the two version fields read names stock OpenSSH never exports.
SessionwithProtocolMetadata(?string $sessionId, ?string $authMethod, ?string $keyFingerprint, ?string $clientVersion, ?string $serverVersion): selfReturn a new Session with protocol metadata attached. Nothing negotiates it over a wire: this library does not speak SSH, and InProcessTransport::run() calls it once with locally derived values (fresh random id, method sniffed from the environment, fingerprint hard-wired to null).
SessionisInteractive(): boolTrue when a TTY is attached
SessiontoLogContext(): arrayArray of session fields for logging
SessionmarkRefused() · refused(): boolThe refusal latch every bundled gate closes (Auth, PasswordAuth, KeyboardInteractive, CertificateAuth, RateLimit, DispatchesMiddlewareStack): mark once at the deny site and do not call $next. One-way — a refused session stays refused.
SessionexitStatus(): ?int · recordExitStatus(int): voidThe child's exit code once a spawner has run one, else null. Reading belongs to anyone; writing belongs to transports.
SessionwithSize(int $cols, int $rows): selfImmutable clone carrying new dimensions — the resize door DefaultChannelHandler walks through; it has nothing to do with the exit path.
ServerEXIT_DENIED = 129 · resolveStatus(Session): intThe single exit-status contract both transports resolve through: a recorded child status wins, else a refused session leaves 129, else 0. A ForceCommand entry script hands it to exit() so the SSH client sees the real code.
Middlewarehandle(Context, Session, callable): void|PromiseInterfaceAll middleware receive Context first, Session second; may return void (sync) or PromiseInterface (async — transport awaits before continuing chain)
AsyncMiddlewareextends MiddlewareAbstract base for promise-returning middleware — override handleAsync() to perform async I/O (LDAP, OAuth, database auth); the transport settles the promise through PromiseAwait, which enforces a 30-second ceiling and ends its own loop spin at the decision — do not await from inside a loop you already run
Spawnnew(callable)Terminal middleware for subprocess spawning (InProcess only)
BubbleTeanew(callable(Session): object)Terminal middleware for Program mount (HostSshd only). The factory's return must expose a run() method; any other value raises RuntimeException with the Lang key bubbletea.bad_factory at handle time.
Authnew(array $users, array $keyFingerprints, ?resource $stderr, ?callable $fingerprintValidator, array $userKeys)Allowlist gate. users and keyFingerprints are independent (a cross product, not a pairing) — bob with alice's key is admitted as alice. userKeys (name => that name's keys, or [Auth::ANY_KEY]) is the authoritative pairing. Empty lists arm nothing.
PasswordAuthnew(callable, ?resource)Validates (user, password) against a callback. Wrapper-only. The password arrives through SSH_PASSWORD, which this repo does not set. It is expected to reach the process from a wrapper that exports it, or from a client-supplied value an operator lets through with AcceptEnv SSH_PASSWORD; that value is peer-asserted rather than proven. Whether sshd's ForceCommand path exports it is unverified against OpenSSH. The gate does not authenticate the peer by itself. A session that delivered no variable at all is refused before the callback runs; an explicitly empty one still reaches it.
CertificateAuthnew(callable, bool $required = true, $stderr = null)Reads a client certificate from CertificateAuth::ENV_KEYS (nothing in stock OpenSSH exports them — your wrapper must). Refuses when $required and announces “checked nothing” on either path, so a silent no-op cannot masquerade as a gate.
AuthMethodsnew(list<string>, ?resource, bool $announce = false)Stores the declared list in the Context for your own middleware to read. The SSH_AUTH_METHODS publickey,password line on STDOUT is opt-in and off by default: under ForceCommand that stream is the client's data channel, so the line is text in the user's terminal. It is not an RFC 4252 banner (sshd finished authenticating before this process started) and not an auth gate; use sshd's own Banner= for a message users must see.
KeyboardInteractivenew(list<array{prompt:string,echo?:bool}|string>, ?callable $validate = null, string $name = '', string $instruction = '', $stdout = null, $stdin = null, $stderr = null)A bare-string element is a challenge with echo: true; any other shape is refused with InvalidArgumentException. Prints each prompt (and the literal echo flag) to the supervisor's STDOUT and reads a line back from STDIN. That is the whole mechanism: it is not RFC 4256 — no SSH messages are involved, and under HostSshdTransport you get sshd's own keyboard-interactive instead. Echo is a label, not terminal state: input is not hidden (the exchange announces that once when any prompt asks for silence), each answer is capped at MAX_RESPONSE_BYTES, there is no built-in deadline, and without $validate any answer passes.
Subsystemnew()Terminal — parses subsystem <name> from Session::command, dispatches to registered SubsystemHandler; non-subsystem requests pass through to $next
SubsystemHandlerhandle(Context, Session): voidInterface — implement to handle a named subsystem request
SftpStubnew()Example SubsystemHandler impl — stub demonstrating wiring; not a real SFTP server
RateLimitnew(string $statePath, int $burst = 5, float $ratePerSec = 0.5, $stderr = null, bool $failClosed = false, ?int $userBurst = null, ?float $userRatePerSec = null)Per-IP token bucket (optionally a second per-username bucket). State publishes through an atomic rename behind an exclusive lock on a stable <state-path>.lock sidecar; idle refilled buckets are pruned on every publish. A state error fails open unless failClosed: true. penalize() exists but nothing calls it — wire it yourself after a failed login.
Loggernew(string|resource|null) · auto() · toFile() · toStream() · toStderr() · target()One-line JSON session records. Sink resolution: $SSH_SERVER_LOG when set, else stderr — which under ForceCommand is the connecting client's channel, not journald. Files created here are 0600; an existing file keeps its mode.
Keepalivenew(int $intervalSeconds = 60)When the pump loop idles past the interval, writes a NUL byte to the child's stdin through the PTY master. It is not an SSH-level keepalive: it is a no-op under HostSshdTransport (sshd's own ClientAliveInterval covers that path), and a raw-mode TUI never echoes it, so nothing reaches the wire. Use it to keep a NAT mapping warm in front of a line-oriented shell, not to detect a dead client.
Transportinterface — run(Context, Session, array $stack): intWhat withTransport() swaps: receives the fully ordered middleware stack and returns the session's exit status. Two implementations ship: InProcessTransport (default) and HostSshdTransport (legacy).
Transport\ChildSpawnerinterface — runChild(Session, array $cmd, ?array $env = null): int · signalChild(int): voidThe two-method pair Spawn type-hints — the narrow contract a transport satisfies for terminal middleware. signalChild() forwards every mapped SignalMsg (SIGWINCH resizes included) to the live child; it is a no-op when no child runs, and delivery falls back to libc kill(2) over FFI rather than ext-posix. A custom spawner written from runChild alone fails at class load — implement both.
TransportAwareinterface — setTransport(ChildSpawner): voidMiddleware that needs the transport implements this. The transport calls setTransport() on every aware middleware at walk time, before the first handle(); implementations must tolerate being called twice because a Server object is reused across sessions.
InProcessTransportnew(?PtySystem $system = null)Default transport — PTY supervisor on sugar-pty. The handler is a setter, not a constructor argument: call setChannelHandler(ChannelHandler $handler) (passing a second constructor argument is silently ignored by PHP and the default handler keeps running). Also exposes withSizeProvider(), setKeepaliveCallback() and pty().
HostSshdTransportnew()Legacy transport — inline middleware, Program on STDIN/STDOUT
ChannelHandlerhandlePtyReq / handleWindowChange / handleShell / handleExec / handleSignal / handleEnv / handleBreakInterface for custom channel-level message handling (InProcessTransport only). Only WindowChangeMsg is produced by the library today — from a SIGWINCH; the other six are dispatched by your own code, not by the wire.
ChannelMsgabstract baseBase for all SSH channel messages (RFC 4254)
DefaultChannelHandlernew(?ChildSpawner, ?Session, array $acceptEnv, ?string $shell, array $allowedExec, mixed $execGate, $stderr)Default impl — tracks PTY dims, env vars, drives ChildSpawner on shell/exec. Exec is default-closed: the peer names the program, so nothing spawns unless $allowedExec holds that exact path and the optional $execGate returns exactly true. The gate is typed mixed on purpose: it is meant to be callable|null, and a value that is neither raises internally and is treated as a refusal (catch-Throwable fail-closed), never a fatal or an approval. decodeCommandString() is the public quoting tokenizer (no shell, no expansion, no globbing) and is also the right entry point for SSH_ORIGINAL_COMMAND.
PtyReqMsgwantPty, term, cols, rows, widthPx, heightPxPTY allocation request
WindowChangeMsgcols, rows, widthPx, heightPxTerminal resize (SIGWINCH equivalent)
ShellMsgwantShell, subsystemLogin-shell request
ExecMsgcommandExec request — raw command string
SignalMsgsignalNameSignal delivery (SIGINT, SIGTERM, etc.)
EnvMsgname, valueEnvironment variable request
BreakMsgbreakLengthMsBreak request — duration in milliseconds (int, defaults to 0)
CancellationExceptionextends RuntimeExceptionThrown when Context is canceled
DeadlineExceededExceptionextends RuntimeExceptionThrown when Context deadline passes

Demos.

VHS-recorded GIFs of the flagship examples — showcase (the middleware-stack tour) and spawn-bash (interactive bash through Spawn) — regenerated automatically on every push that touches the source. The remaining examples are plain CLI scripts without a tape.

Middleware pipeline

Middleware pipeline

Logger → RateLimit → hello against a synthetic Session.
Spawn bash

Spawn bash (in-process)

InProcessTransport spawning /bin/bash -l via sugar-pty. Inner shell runs echo / uname / stty size / exit.