SugarSshServer
SSH server middleware framework
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 SugarCraftProgramdirectly on the supervisor's STDIN/STDOUT. Pin viaServer::withTransport(new HostSshdTransport()). Use this for inline-STDIN-reading middleware or zero-subprocess Program mounts.
What's in the box
Middleware::handle(Context $ctx, Session $session, callable $next): void.Source & demos
- Source on GitHub
- Full README
- Runnable examples
- Originally inspired by wish (Go); SugarCraft is developed as a native PHP project.
API reference
| Class | Method | Description |
|---|---|---|
| Server | new() | Start an empty middleware pipeline — this library opens no listener: the pipeline runs inside the process sshd (or your supervisor) spawns under ForceCommand |
| Server | use(Middleware) | Add middleware to the pipeline |
| Server | withTransport(Transport) | Override the active transport (default: InProcessTransport) |
| Server | withKeepalive(int) | Arm an idle keepalive beat on the server (opt-in); stored on the server, not added to the use() middleware stack |
| Server | serve(?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) |
| Context | background() | Root context — never done, not cancelable |
| Context | withValue(string $k, mixed $v) | Return a new context with $k → $v attached |
| Context | withDeadline(DateTimeImmutable) | Return a new cancelable context that is done when deadline passes |
| Context | withCancelable() | Return a new cancelable context (call cancel() to trigger) |
| Context | cancel(?Throwable) | Mark the context as canceled |
| Context | done(): bool | True when canceled or deadline-exceeded |
| Context | err(): ?Throwable | CancellationException, DeadlineExceededException, or null |
| Context | value(string $k): mixed | Walk parent chain looking for $k; null if not found |
| Session | user, term, cols, rows, clientHost, clientPort, serverHost, serverPort, tty, command, lang, sessionId, authMethod, keyFingerprint, clientVersion, serverVersion | Session 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. |
| Session | withProtocolMetadata(?string $sessionId, ?string $authMethod, ?string $keyFingerprint, ?string $clientVersion, ?string $serverVersion): self | Return 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). |
| Session | isInteractive(): bool | True when a TTY is attached |
| Session | toLogContext(): array | Array of session fields for logging |
| Session | markRefused() · refused(): bool | The 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. |
| Session | exitStatus(): ?int · recordExitStatus(int): void | The child's exit code once a spawner has run one, else null. Reading belongs to anyone; writing belongs to transports. |
| Session | withSize(int $cols, int $rows): self | Immutable clone carrying new dimensions — the resize door DefaultChannelHandler walks through; it has nothing to do with the exit path. |
| Server | EXIT_DENIED = 129 · resolveStatus(Session): int | The 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. |
| Middleware | handle(Context, Session, callable): void|PromiseInterface | All middleware receive Context first, Session second; may return void (sync) or PromiseInterface (async — transport awaits before continuing chain) |
| AsyncMiddleware | extends Middleware | Abstract 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 |
| Spawn | new(callable) | Terminal middleware for subprocess spawning (InProcess only) |
| BubbleTea | new(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. |
| PasswordAuth | new(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. |
| CertificateAuth | new(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. |
| AuthMethods | new(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. |
| KeyboardInteractive | new(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. |
| Subsystem | new() | Terminal — parses subsystem <name> from Session::command, dispatches to registered SubsystemHandler; non-subsystem requests pass through to $next |
| SubsystemHandler | handle(Context, Session): void | Interface — implement to handle a named subsystem request |
| SftpStub | new() | Example SubsystemHandler impl — stub demonstrating wiring; not a real SFTP server |
| RateLimit | new(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. |
| Logger | new(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. |
| Keepalive | new(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. |
| Transport | interface — run(Context, Session, array $stack): int | What withTransport() swaps: receives the fully ordered middleware stack and returns the session's exit status. Two implementations ship: InProcessTransport (default) and HostSshdTransport (legacy). |
| Transport\ChildSpawner | interface — runChild(Session, array $cmd, ?array $env = null): int · signalChild(int): void | The 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. |
| TransportAware | interface — setTransport(ChildSpawner): void | Middleware 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. |
| InProcessTransport | new(?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(). |
| HostSshdTransport | new() | Legacy transport — inline middleware, Program on STDIN/STDOUT |
| ChannelHandler | handlePtyReq / handleWindowChange / handleShell / handleExec / handleSignal / handleEnv / handleBreak | Interface 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. |
| ChannelMsg | abstract base | Base for all SSH channel messages (RFC 4254) |
| DefaultChannelHandler | new(?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. |
| PtyReqMsg | wantPty, term, cols, rows, widthPx, heightPx | PTY allocation request |
| WindowChangeMsg | cols, rows, widthPx, heightPx | Terminal resize (SIGWINCH equivalent) |
| ShellMsg | wantShell, subsystem | Login-shell request |
| ExecMsg | command | Exec request — raw command string |
| SignalMsg | signalName | Signal delivery (SIGINT, SIGTERM, etc.) |
| EnvMsg | name, value | Environment variable request |
| BreakMsg | breakLengthMs | Break request — duration in milliseconds (int, defaults to 0) |
| CancellationException | extends RuntimeException | Thrown when Context is canceled |
| DeadlineExceededException | extends RuntimeException | Thrown 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, defaultInProcessTransport. Selects the transport the middleware stack runs under.Server::withKeepalive(int $intervalSeconds): int. Keepalive is opt-in and off unlesswithKeepalive()is called;Server::$keepalivestays null until then.60is 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.Loggersink: string, resource or null, default$SSH_SERVER_LOGwhen set, else stderr. Where the one-line JSON session records go. Files the logger creates are0600.new RateLimit($statePath, $burst, $ratePerSec, ..., $failClosed): int, float, bool, default5,0.5,false. Per-IP token bucket. With$failClosedleft 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, default129. 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 SugarCraftProgrammounted inside a sugar-pty subprocess.run-program.php: The wrapper program thatspawn-program.phpruns 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
| Method | Summary |
|---|---|
__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.
| Method | Summary |
|---|---|
static background(): self | Root context — never done, no values, not cancelable. |
withValue(string $k, mixed $v): self | Attach a key-value pair and return a new derived Context. |
withDeadline(\DateTimeImmutable $deadline): self | Return a new derived Context with the given deadline. |
withCancelable(): self | Return a new derived Context with an active cancellation signal. |
cancel(?\Throwable $reason = null): bool | Mark this Context (and all derived contexts) as cancelled. |
done(): bool | Returns true when this Context — or any ancestor it was derived from — has been cancelled, or when a deadline in the chain has expired. |
err(): ?\Throwable | Returns the cancellation or deadline error, or null if not done. |
deadline(): ?\DateTimeImmutable | The earliest deadline in this context's chain, or null when no node carries one. |
value(string $k): mixed | Look up a value by key, walking the parent chain. |
DeadlineExceededException final class
| Method | Summary |
|---|---|
__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.
| Method | Summary |
|---|---|
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.
| Method | Summary |
|---|---|
static new(): self | |
use(Middleware $m): self | Append a middleware to the stack. |
withMiddleware(Middleware ...$ms): self | Append several middlewares at once, in order, clone-and-return — the varargs spelling of use(), mirroring the Go option-list form. |
onSession(callable $fn): self | Append a session hook to the stack without writing a class. |
withTransport(Transport $t): self | Override the active transport. Defaults to InProcessTransport when not called. |
transport(): Transport | |
withLocale(string $code): self | Arm a catalogue locale for the notices this server renders. |
withKeepalive(int $intervalSeconds = 60): self | Arm an idle keepalive beat for sessions this server serves. |
serve(?Session $session = null, ?Context $ctx = null): int | Build 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): int | The one answer to 'what code does this session leave behind?'. |
Session final class
Per-connection session metadata exposed to middleware.
| Method | Summary |
|---|---|
__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(): self | Read the current sshd environment and build a Session. |
isInteractive(): bool | |
withProtocolMetadata(?string $sessionId, ?string $authMethod, ?string $keyFingerprint, ?string $clientVersion, ?string $serverVersion): self | Create a new Session with protocol metadata populated. |
withSize(int $cols, int $rows): self | Create 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(): ?int | The child's exit code once a spawner has run one, else null. |
recordExitStatus(int $status): void | Transport-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(): bool | True when a middleware stopped this session rather than serving it. |
markRefused(): void | Say that this session was refused, so the process can exit nonzero. |
toLogContext(): array | The fields a session-start/end record is made of. |
StreamHelper final class
Opens or validates the stderr-style report stream shared by middleware.
| Method | Summary |
|---|---|
static chmodOpenedFile($stream, string $path, int $mode): void | Set 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.
| Method | Summary |
|---|---|
run(Context $ctx, Session $session, array $stack): int | Run 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.
| Method | Summary |
|---|---|
setTransport(ChildSpawner $transport): void | Receive the transport driving the current stack. |
SugarCraft\SshServer\Channel
ChannelHandler interface
Interface for handling SSH channel-level messages.
| Method | Summary |
|---|---|
cols(): int | Current columns the handler wants the spawned PTY to carry. |
rows(): int | Current rows the handler wants the spawned PTY to carry. |
handlePtyReq(PtyReqMsg $msg, Session $session): void | Handle a PTY request message. |
handleWindowChange(WindowChangeMsg $msg, Session $session): void | Handle a window-change message. |
handleShell(ShellMsg $msg, Session $session): void | Handle a shell request message. |
handleExec(ExecMsg $msg, Session $session): void | Handle an exec request message. |
handleSignal(SignalMsg $msg, Session $session): void | Handle a signal message. |
handleEnv(EnvMsg $msg, Session $session): void | Handle an environment variable request message. |
handleBreak(BreakMsg $msg, Session $session): void | Handle 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.
| Method | Summary |
|---|---|
__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): void | Apply 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): bool | May this decoded request be spawned? |
handleSignal(SignalMsg $msg, Session $session): void | |
handleEnv(EnvMsg $msg, Session $session): void | Store a peer-supplied environment variable, within the budget. |
handleBreak(BreakMsg $msg, Session $session): void | Receive 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): array | Split 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.
| Method | Summary |
|---|---|
__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.
| Method | Summary |
|---|---|
__construct(public readonly int $breakLengthMs = 0) |
EnvMsg final class
Environment channel message.
| Method | Summary |
|---|---|
__construct(public readonly string $name, public readonly string $value) |
ExecMsg final class
Exec channel message.
| Method | Summary |
|---|---|
__construct(public readonly string $command) |
PtyReqMsg final class
PTY request channel message.
| Method | Summary |
|---|---|
__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.
| Method | Summary |
|---|---|
__construct(public readonly bool $wantShell, public readonly string $subsystem = '') |
SignalMsg final class
Signal channel message.
| Method | Summary |
|---|---|
__construct(public readonly string $signalName) |
WindowChangeMsg final class
Window-change channel message.
| Method | Summary |
|---|---|
__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.
| Method | Summary |
|---|---|
handle(Context $ctx, Session $session, callable $next): PromiseInterface |
Auth final class
Username / public-key allowlist gate.
| Method | Summary |
|---|---|
__construct(array $users = [], array $keyFingerprints = [], $stderr = null, ?callable $fingerprintValidator = null, array $userKeys = []) | |
static allowingUsers(array $users): self | Gate on usernames only, constructed so it cannot be unarmed. |
static pairs(array $userKeys): self | Gate 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.
| Method | Summary |
|---|---|
__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.
| Method | Summary |
|---|---|
__construct(callable $factory) | |
setTransport(ChildSpawner $transport): void | TransportAware 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.
| Method | Summary |
|---|---|
__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.
| Method | Summary |
|---|---|
__construct(private readonly int $intervalSeconds = 60) | |
interval(): int | Get the keepalive interval in seconds. |
Logger final class
Connect / disconnect logger.
| Method | Summary |
|---|---|
__construct($target = null) | |
static auto(): self | Resolve 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): self | Append to $path, creating it 0600 when it does not exist. |
static toStream($stream): self | Write 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(): self | Explicitly 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(): string | Which 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.
| Method | Summary |
|---|---|
__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): void | Charge 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.
| Method | Summary |
|---|---|
__construct(callable $factory) | |
setTransport(ChildSpawner $transport): void | Duck-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.
| Method | Summary |
|---|---|
register(string $name, SubsystemHandler $handler): void | Register a handler for a named subsystem. |
has(string $name): bool | Returns 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.
| Method | Summary |
|---|---|
__construct(array $methods, $stdout = null, bool $announce = false) | |
handle(Context $ctx, Session $session, callable $next): void | |
static fromContext(Context $ctx): array | Read 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.
| Method | Summary |
|---|---|
__construct(callable $validate, bool $required = true, $stderr = null) | |
handle(Context $ctx, Session $session, callable $next): void |
KeyboardInteractive final class
Challenge-response keyboard-interactive authentication.
| Method | Summary |
|---|---|
__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.
| Method | Summary |
|---|---|
__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.
| Method | Summary |
|---|---|
handle(Context $ctx, Session $session): void |
SubsystemHandler interface
Handles SSH subsystem requests.
| Method | Summary |
|---|---|
handle(Context $ctx, Session $session): void | Handle 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.
| Method | Summary |
|---|---|
runChild(Session $session, array $cmd, ?array $env = null): int | Spawn $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): void | Forward 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).
| Method | Summary |
|---|---|
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.
| Method | Summary |
|---|---|
__construct(?PtySystem $system = null) | |
withSizeProvider(callable $provider): self | Returns 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): void | Begin emitting the keepalive beat: at most one per transport, replaced (not stacked) by later calls. |
setKeepaliveCallback(callable $callback): void | Register a callback to be invoked in the pump loop whenever stream_select reports no ready streams (idle timeout). |
setChannelHandler(ChannelHandler $handler): void | Set the channel handler for dispatching SSH channel messages. |
pty(): MasterPty | Returns 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): int | Spawn $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.
| Method | Summary |
|---|---|
armKeepalive(int $intervalSeconds): void | Begin emitting the keepalive beat: at most one per transport, replaced (not stacked) by later calls. |
PromiseAwait final class
Shared synchronous-promise await helper.
| Method | Summary |
|---|---|
static settle(PromiseInterface $promise, float $timeout = 30.0, ?Context $ctx = null): void | Synchronously 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: Gocontext.Context:Done()andDeadline()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
Logger → RateLimit → hello against a synthetic Session.
Spawn bash (in-process)
InProcessTransport spawning/bin/bash -l via sugar-pty. Inner shell runs echo / uname / stty size / exit.