All 48 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

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 App\MyApp;
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.

Concepts

The server runs a middleware pipeline inside the process that sshd spawns under ForceCommand. It opens no listener of its own. What the supervisor PHP process does internally is pluggable via the Transport abstraction, and there are two transports:

  • 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.

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 reference

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)Arm an idle keepalive beat on the server (opt-in); stored on the server, not added to the use() middleware stack
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.
Auth__construct(array $users = [], array $keyFingerprints = [], $stderr = null, ?callable $fingerprintValidator = null, 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

Configuration

Each option is set on Server or on the middleware that owns it. The defaults are the values the classes ship with.

  • Server::withTransport(Transport): Transport, default InProcessTransport. Selects the transport the middleware stack runs under.
  • Server::withKeepalive(int $intervalSeconds): int. Keepalive is opt-in and off unless withKeepalive() is called; Server::$keepalive stays null until then. 60 is the argument default, not a shipped default. Once armed, it sends a NUL byte to the child's stdin when the pump loop has been idle for this many seconds. This is not an SSH-level keepalive.
  • Logger sink: string, resource or null, default $SSH_SERVER_LOG when set, else stderr. Where the one-line JSON session records go. Files the logger creates are 0600.
  • new RateLimit($statePath, $burst, $ratePerSec, ..., $failClosed): int, float, bool, default 5, 0.5, false. Per-IP token bucket. With $failClosed left false, a connection is let through when the state file cannot be read.
  • Auth::__construct(array $users, array $keyFingerprints, ...): list, default empty lists. The allowlists. With both empty, every session is admitted.
  • Server::EXIT_DENIED: int, default 129. The exit status a refused session returns to the SSH client.

Examples

Each file in examples/ runs from the library root as php examples/<name>.php. Several need an sshd ForceCommand setup to log in through, and showcase.php runs without one.

  • hello-server.php: The smallest end-to-end server: a session banner, used as a deployment smoke test.
  • spawn-bash.php: The default in-process supervisor. It spawns a login bash in a sugar-pty for each connecting user.
  • spawn-program.php: A SugarCraft Program mounted inside a sugar-pty subprocess.
  • run-program.php: The wrapper program that spawn-program.php runs as the PTY child.
  • showcase.php: Drives the middleware pipeline against a synthesised session in one process, with Logger, RateLimit and a custom middleware.

Testing

cd sugar-ssh-server
composer install
vendor/bin/phpunit

The suite boots through tests/bootstrap.php, which calls SugarCraft\Testing\LoopPin::pinStableClock() before any test arms a timer on the shared event loop. sugar-testing is a require-dev dependency.

Only methods declared in sugar-ssh-server/src, or inherited from a parent declared there, are listed. A type that extends a class outside that tree, such as \RuntimeException, does not show the methods of that class.

SugarCraft\SshServer

CancellationException final class

MethodSummary
__construct(string $reason = '')The optional reason rides the fixed text as context cancelled: <reason> — a bare throw used to be the only shape this channel could carry. Context::cancel() hands a supplied Throwable through to err() verbatim, so cancel(new CancellationException('hangup received')) is the blessed way to attach a why without defining a class of your own.

Context final class

Immutable context object carrying cancellation, deadlines, and key-value metadata across the middleware chain.

MethodSummary
static background(): selfRoot context — never done, no values, not cancelable.
withValue(string $k, mixed $v): selfAttach a key-value pair and return a new derived Context.
withDeadline(\DateTimeImmutable $deadline): selfReturn a new derived Context with the given deadline.
withCancelable(): selfReturn a new derived Context with an active cancellation signal.
cancel(?\Throwable $reason = null): boolMark this Context (and all derived contexts) as cancelled.
done(): boolReturns true when this Context — or any ancestor it was derived from — has been cancelled, or when a deadline in the chain has expired.
err(): ?\ThrowableReturns the cancellation or deadline error, or null if not done.
deadline(): ?\DateTimeImmutableThe earliest deadline in this context's chain, or null when no node carries one.
value(string $k): mixedLook up a value by key, walking the parent chain.

DeadlineExceededException final class

MethodSummary
__construct(string $reason = '')The optional reason rides the fixed text as context deadline exceeded: <reason>. With no reason the message is the plain fixed string, so anything matching on it today keeps matching.

Lang final class

Per-library translation facade for sugar-ssh-server.

Middleware interface

SSH session middleware contract.

MethodSummary
handle(Context $ctx, Session $session, callable $next)May return void (synchronous) or a \React\Promise\PromiseInterface (asynchronous). The transport will wait for the promise to settle before continuing the chain.

Server final class

SSH session entry point.

MethodSummary
static new(): self
use(Middleware $m): selfAppend a middleware to the stack.
withMiddleware(Middleware ...$ms): selfAppend several middlewares at once, in order, clone-and-return — the varargs spelling of use(), mirroring the Go option-list form.
onSession(callable $fn): selfAppend a session hook to the stack without writing a class.
withTransport(Transport $t): selfOverride the active transport. Defaults to InProcessTransport when not called.
transport(): Transport
withLocale(string $code): selfArm a catalogue locale for the notices this server renders.
withKeepalive(int $intervalSeconds = 60): selfArm an idle keepalive beat for sessions this server serves.
serve(?Session $session = null, ?Context $ctx = null): intBuild the Session from the current environment (or use the injected one) and ask the active transport to run the middleware chain. Returns when the chain finishes — for a terminal subprocess (Spawn / BubbleTea) that's when the inner process exits or the SSH client disconnects.
static resolveStatus(Session $session): intThe one answer to 'what code does this session leave behind?'.

Session final class

Per-connection session metadata exposed to middleware.

MethodSummary
__construct(public readonly string $user = '', public readonly string $clientHost = '', public readonly int $clientPort = 0, public readonly string $serverHost = '', public readonly int $serverPort = 0, public readonly string $term = 'xterm-256color', public readonly int $cols = self::DEFAULT_COLS, public readonly int $rows = self::DEFAULT_ROWS, public readonly ?string $tty = null, public readonly ?string $command = null, public readonly string $lang = 'C.UTF-8', public readonly ?string $sessionId = null, public readonly ?string $authMethod = null, public readonly ?string $keyFingerprint = null, public readonly ?string $clientVersion = null, public readonly ?string $serverVersion = null)
static fromEnvironment(): selfRead the current sshd environment and build a Session.
isInteractive(): bool
withProtocolMetadata(?string $sessionId, ?string $authMethod, ?string $keyFingerprint, ?string $clientVersion, ?string $serverVersion): selfCreate a new Session with protocol metadata populated.
withSize(int $cols, int $rows): selfCreate a new Session with a different terminal geometry, carrying every other field — protocol metadata included (parse-once/carry: rebuilds must never silently drop sessionId/authMethod/versions).
exitStatus(): ?intThe child's exit code once a spawner has run one, else null.
recordExitStatus(int $status): voidTransport-only: called by the transport loop as its child settles (see \SugarCraft\SshServer\Transport\ChildSpawner), which is the only place a child's exit code is known.
refused(): boolTrue when a middleware stopped this session rather than serving it.
markRefused(): voidSay that this session was refused, so the process can exit nonzero.
toLogContext(): arrayThe fields a session-start/end record is made of.

StreamHelper final class

Opens or validates the stderr-style report stream shared by middleware.

MethodSummary
static chmodOpenedFile($stream, string $path, int $mode): voidSet a file mode through a path name, but only while that name still resolves to the inode the caller actually opened.
static openOrValidate(mixed $stream, string $target = 'php://stderr', string $mode = 'w'): mixed

Transport interface

Pluggable strategy that decides HOW the middleware stack runs for a connected session.

MethodSummary
run(Context $ctx, Session $session, array $stack): intRun the middleware $stack against $session. Implementations choose whether to walk the stack inline (HostSshd) or set up extra plumbing (InProcess) before delegating to terminal middleware that drive the actual user-visible behaviour.

TransportAware interface

Contract for middleware that needs the active transport injected.

MethodSummary
setTransport(ChildSpawner $transport): voidReceive the transport driving the current stack.

SugarCraft\SshServer\Channel

ChannelHandler interface

Interface for handling SSH channel-level messages.

MethodSummary
cols(): intCurrent columns the handler wants the spawned PTY to carry.
rows(): intCurrent rows the handler wants the spawned PTY to carry.
handlePtyReq(PtyReqMsg $msg, Session $session): voidHandle a PTY request message.
handleWindowChange(WindowChangeMsg $msg, Session $session): voidHandle a window-change message.
handleShell(ShellMsg $msg, Session $session): voidHandle a shell request message.
handleExec(ExecMsg $msg, Session $session): voidHandle an exec request message.
handleSignal(SignalMsg $msg, Session $session): voidHandle a signal message.
handleEnv(EnvMsg $msg, Session $session): voidHandle an environment variable request message.
handleBreak(BreakMsg $msg, Session $session): voidHandle a break request message.

ChannelMsg abstract class

Base class for all SSH channel-level messages.

DefaultChannelHandler final class

Default channel handler wiring the common case: PTY + shell.

MethodSummary
__construct(private readonly ?ChildSpawner $spawner = null, ?Session $session = null, private readonly array $acceptEnv = [], private readonly ?string $shell = null, private readonly array $allowedExec = [], ?callable $execGate = null, $stderr = null)
handlePtyReq(PtyReqMsg $msg, Session $session): void
handleWindowChange(WindowChangeMsg $msg, Session $session): voidApply a peer's window change. A zero in either dimension means the sender declared nothing for it, and the current size is KEPT — the pty-req leg already resolved the session/default fallback once, and a mid-session non-declaration must not demote a known terminal to the 80×24 floor.
handleShell(ShellMsg $msg, Session $session): void
handleExec(ExecMsg $msg, Session $session): void
execAllowed(Session $session, array $argv): boolMay this decoded request be spawned?
handleSignal(SignalMsg $msg, Session $session): void
handleEnv(EnvMsg $msg, Session $session): voidStore a peer-supplied environment variable, within the budget.
handleBreak(BreakMsg $msg, Session $session): voidReceive the RFC 4254 break signal — and do nothing with it.
cols(): int
rows(): int
ptyAllocated(): ?bool
envVars(): array
shellRequested(): bool
execRequested(): bool
pendingCommand(): array
static decodeCommandString(string $command): arraySplit a command string into argv tokens.

DelegatingChannelHandler abstract class

Partial-override base for ChannelHandler: forward everything to a delegate, then override only the verbs you actually care about.

MethodSummary
__construct(protected readonly ChannelHandler $delegate)
cols(): int
rows(): int
handlePtyReq(PtyReqMsg $msg, Session $session): void
handleWindowChange(WindowChangeMsg $msg, Session $session): void
handleShell(ShellMsg $msg, Session $session): void
handleExec(ExecMsg $msg, Session $session): void
handleSignal(SignalMsg $msg, Session $session): void
handleEnv(EnvMsg $msg, Session $session): void
handleBreak(BreakMsg $msg, Session $session): void

SugarCraft\SshServer\Channel\Msg

BreakMsg final class

Break channel message.

MethodSummary
__construct(public readonly int $breakLengthMs = 0)

EnvMsg final class

Environment channel message.

MethodSummary
__construct(public readonly string $name, public readonly string $value)

ExecMsg final class

Exec channel message.

MethodSummary
__construct(public readonly string $command)

PtyReqMsg final class

PTY request channel message.

MethodSummary
__construct(public readonly bool $wantPty, public readonly string $term = '', public readonly int $cols = 80, public readonly int $rows = 24, public readonly int $widthPx = 0, public readonly int $heightPx = 0)

ShellMsg final class

Shell channel message.

MethodSummary
__construct(public readonly bool $wantShell, public readonly string $subsystem = '')

SignalMsg final class

Signal channel message.

MethodSummary
__construct(public readonly string $signalName)

WindowChangeMsg final class

Window-change channel message.

MethodSummary
__construct(public readonly int $cols, public readonly int $rows, public readonly int $widthPx = 0, public readonly int $heightPx = 0)

SugarCraft\SshServer\Middleware

AsyncMiddleware abstract class

Abstract base for middleware that needs to perform async I/O before delegating to the next handler.

MethodSummary
handle(Context $ctx, Session $session, callable $next): PromiseInterface

Auth final class

Username / public-key allowlist gate.

MethodSummary
__construct(array $users = [], array $keyFingerprints = [], $stderr = null, ?callable $fingerprintValidator = null, array $userKeys = [])
static allowingUsers(array $users): selfGate on usernames only, constructed so it cannot be unarmed.
static pairs(array $userKeys): selfGate on the name↔key pairing, constructed so it cannot be unarmed.
handle(Context $ctx, Session $session, callable $next): void

AuthRateLimitBridge final class

Turns an auth-gate refusal into a token-bucket penalty.

MethodSummary
__construct(private readonly Middleware $gate, private readonly RateLimit $rateLimit, private readonly float $penalty = 3.0)
handle(Context $ctx, Session $session, callable $next): void

BubbleTea final class

Terminal middleware that mounts a SugarCraft Program for the connected user — the legacy HostSshd-style entry point.

MethodSummary
__construct(callable $factory)
setTransport(ChildSpawner $transport): voidTransportAware seam invoked by InProcessTransport at stack-walk time. The mere presence of an injected ChildSpawner means we're under in-process mode and inline Program execution would conflict with the bytes-pump loop — so flag it for handle() to refuse.
handle(Context $ctx, Session $session, callable $next): void

ClosureMiddleware final class

A middleware that IS a closure — the one-liner door on the stack.

MethodSummary
__construct(callable $fn)
handle(Context $ctx, Session $session, callable $next)MiddlewareTypingContract: pass-through exemption — see that guard's const for why this one declaration carries no native return type.

Keepalive final class

The keepalive interval — a value, not a middleware.

MethodSummary
__construct(private readonly int $intervalSeconds = 60)
interval(): intGet the keepalive interval in seconds.

Logger final class

Connect / disconnect logger.

MethodSummary
__construct($target = null)
static auto(): selfResolve the sink from the deployment environment: the configured SSH_SERVER_LOG file when present, stderr otherwise. Prefer this over new Logger() in boot code so the resolution is visible at the call site.
static toFile(string $path): selfAppend to $path, creating it 0600 when it does not exist.
static toStream($stream): selfWrite to an already-open resource the caller keeps (a pipe into the daemon's logger, a test buffer). Not closed by this middleware.
static toStderr(): selfExplicitly choose the process error stream. Under ForceCommand that is the connecting client's extended-data channel — use it only where that is what you want (a local run, a tool, a test).
target(): stringWhich sink this instance resolved to, as a short machine-readable description: file:<path>, stderr, or stream. The client-visible hazard of stderr is why this is public.
__destruct()
handle(Context $ctx, Session $session, callable $next): void

RateLimit final class

Connection rate-limiter using token-buckets persisted to a file.

MethodSummary
__construct(private readonly string $statePath, private readonly int $burst = 5, private readonly float $ratePerSec = 0.5, $stderr = null, private readonly bool $failClosed = false, private readonly ?int $userBurst = null, private readonly ?float $userRatePerSec = null)
handle(Context $ctx, Session $session, callable $next): void
penalize(Session $session, float $tokens = 1.0): voidCharge an extra $tokens against a session's buckets without the accept/reject semantics of a connect. Intended to be called from an auth-failure hook so repeated bad credentials drain the limiter faster than connection attempts alone.

Spawn final class

Terminal middleware that spawns a child process inside the active transport's PTY supervisor.

MethodSummary
__construct(callable $factory)
setTransport(ChildSpawner $transport): voidDuck-typed seam invoked by InProcessTransport at stack-walk time so this middleware doesn't have to be aware of which transport drives the Server. Production code never calls this directly.
handle(Context $ctx, Session $session, callable $next): void

Subsystem final class

Middleware that dispatches SSH subsystem requests to a registered SubsystemHandler.

MethodSummary
register(string $name, SubsystemHandler $handler): voidRegister a handler for a named subsystem.
has(string $name): boolReturns true when a handler is registered for the given name.
handle(Context $ctx, Session $session, callable $next): void

SugarCraft\SshServer\Middleware\Auth

AuthMethods final class

Records an informational list of accepted authentication methods in Context and echoes it to the client.

MethodSummary
__construct(array $methods, $stdout = null, bool $announce = false)
handle(Context $ctx, Session $session, callable $next): void
static fromContext(Context $ctx): arrayRead the informational auth-methods list back from a Context (convenience for downstream middleware / logging). This is the list the operator declared via the constructor — it is NOT proof that any method actually authenticated the session.

CertificateAuth final class

X.509 certificate gate -- reads a certificate the deployment exports.

MethodSummary
__construct(callable $validate, bool $required = true, $stderr = null)
handle(Context $ctx, Session $session, callable $next): void

KeyboardInteractive final class

Challenge-response keyboard-interactive authentication.

MethodSummary
__construct(array $challenges, ?callable $validate = null, string $name = '', string $instruction = '', $stdout = null, $stdin = null, $stderr = null)
handle(Context $ctx, Session $session, callable $next): void

PasswordAuth final class

Password-authentication gate.

MethodSummary
__construct(callable $validate, $stderr = null)
handle(Context $ctx, Session $session, callable $next): void

SugarCraft\SshServer\Middleware\Subsystem

SftpStub final class

QUARANTINED EXAMPLE — demo wiring only, never for production use.

MethodSummary
handle(Context $ctx, Session $session): void

SubsystemHandler interface

Handles SSH subsystem requests.

MethodSummary
handle(Context $ctx, Session $session): voidHandle the subsystem request.

SugarCraft\SshServer\Transport

ChildSpawner interface

Marker interface for transports that can spawn a child process inside a controlled PTY and pump bytes on its behalf.

MethodSummary
runChild(Session $session, array $cmd, ?array $env = null): intSpawn $cmd inside a fresh PTY and pump bytes between the supervisor's STDIN/STDOUT and the master fd until the child exits, returns the exit code.
signalChild(int $signal): voidForward a signal to the live child process.

DispatchesMiddlewareStack trait

Shared middleware-stack walk owning the library's single promise settle point.

HostSshdTransport final class

Legacy transport — runs the middleware stack directly in the supervisor process. STDIN/STDOUT are the slave side of sshd's PTY (sshd allocated it for the SSH session and exposed it via the inherited file descriptors).

MethodSummary
run(Context $ctx, Session $session, array $stack): int

InProcessTransport final class

Default transport — allocates a sugar-pty master/slave pair via the injected (or factory-resolved) PtySystem, spawns the user's cmd as a subprocess with controllingTerminal: true, and pumps bytes between the supervisor's STDIN/STDOUT and the PTY master via PosixPump.

MethodSummary
__construct(?PtySystem $system = null)
withSizeProvider(callable $provider): selfReturns a clone of this transport with the given size provider — used by SIGWINCH forwarding to query the host's PTY winsize. Production code rarely needs to call this.
armKeepalive(int $intervalSeconds): voidBegin emitting the keepalive beat: at most one per transport, replaced (not stacked) by later calls.
setKeepaliveCallback(callable $callback): voidRegister a callback to be invoked in the pump loop whenever stream_select reports no ready streams (idle timeout).
setChannelHandler(ChannelHandler $handler): voidSet the channel handler for dispatching SSH channel messages.
pty(): MasterPtyReturns the active master PTY for the current session. Valid only while a session is actively being pumped — callers must not store the reference across pump-loop boundaries. Its single legitimate caller in this library is the armed keepalive beat (armKeepalive()); the accessor stays public so custom pump callbacks registered via setKeepaliveCallback() can reach the master too.
run(Context $ctx, Session $session, array $stack): int
runChild(Session $session, array $cmd, ?array $env = null, $stdin = null, $stdout = null, ?Context $ctx = null): intSpawn $cmd as a subprocess inside a fresh PTY and pump bytes between the caller's STDIN/STDOUT (or the supervisor's process stdio if those are null) and the PTY master until the child exits or one of the stdio streams hits EOF.
signalChild(int $signal): void

KeepaliveArming interface

The one pump-idle hook that \SugarCraft\SshServer\Server::withKeepalive() arms.

MethodSummary
armKeepalive(int $intervalSeconds): voidBegin emitting the keepalive beat: at most one per transport, replaced (not stacked) by later calls.

PromiseAwait final class

Shared synchronous-promise await helper.

MethodSummary
static settle(PromiseInterface $promise, float $timeout = 30.0, ?Context $ctx = null): voidSynchronously wait for a promise to settle.

Troubleshooting

The client gets exit status 129 and the child never starts

A refusal gate such as Auth or RateLimit marks the session refused, so the process exits Server::EXIT_DENIED (129) and no child is spawned. There is no disconnect packet or error body. A throttle writes its rate-limit notice to the stream it was given, and that is the first place to look.

The client gets exit status 0 and nothing ran

A stack that runs out of middleware without spawning a child answers 0, meaning there was nothing to run, not a refusal. Add a terminal middleware such as Spawn or BubbleTea to the stack. A child that ran reports its own code, which wins over both values.

->use() registers nothing

Server is immutable. use() returns a new server with the middleware appended, and the receiver stays as it was. A bare $server->use($m); with the return value discarded therefore does nothing. Write $server = $server->use($m);, or chain the calls as the examples do.

Every login is admitted

new Auth() with no users, keyFingerprints or userKeys admits every session, and KeyboardInteractive without a validator accepts any answer. RateLimit with the default failClosed: false lets the connection through when its state file cannot be read. Pass an allow-list, or use Auth::allowingUsers([...]), which throws a LogicException on an empty list, and pass failClosed: true to RateLimit.

Composer refuses to install on a host without ext-ffi

The sugar-pty dependency requires ext-ffi in its own manifest, so composer require fails on a host without it, even though this package only suggests it. Install the extension. Adding --ignore-platform-reqs=ext-ffi lets the install finish, but then only the legacy HostSshdTransport can run, because the default transport needs FFI to allocate the PTY.

runChild() throws PtyException

The default InProcessTransport throws PtyException when ext-pcntl is missing or the host cannot allocate a PTY. Install ext-pcntl. In a restricted container, grant the device /dev/ptmx and a devpts mount at /dev/pts, or keep the connection behind sshd and use HostSshdTransport, which needs none of these.

Output is cut off partway through

runChild() sets the PTY master and STDIN to non-blocking and leaves STDOUT blocking on purpose. A non-blocking STDOUT drops every byte past the pipe buffer with no error. Keep STDOUT blocking when you call runChild(), and do not add a stream_set_blocking($stdout, false) line.

One abusive client locks out a whole bastion

The ip: bucket in RateLimit keys on the direct TCP peer, so a bastion, a load balancer or a ProxyJump hop collapses many operators into one bucket. Enable the username bucket ($userBurst), or move throttling to the fronting layer. Keep the state file and its lock on a local filesystem, because flock on NFS can be silently absent.

Upstream mapping

The server is inspired by charmbracelet/wish, which is also cited in the docblocks. Other classes mirror Go concepts directly.

  • Context: Go context.Context: Done() and Deadline() semantics
  • Promise handling in the transports: charmbracelet/wish PromiseDispatch.awaitPromise
  • HostSshdTransport: sugar-ssh-server's own pre-PTY-upgrade architecture, kept for existing deployments. It has no upstream counterpart.

Changelog and versioning

The package has no separate changelog file and no release tag in the monorepo, so its history is the commit log of sugar-ssh-server/, mirrored on GitHub. One change to know about when you upgrade: Server is immutable. Before audit sugar-ssh-server-008, use() changed the server in place. It now returns a new server, so a bare $server->use($m); no longer registers anything.

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.