The Hard Part of a Browser SSH Terminal Is Closing It
A browser terminal looks like a straightforward UI feature: xterm.js in browser <ββWebSocketββ> SSH PTY on VPS Most tutorials implement it in fifty lines. Upgrade a WebSocket, connect an SSH client, pipe stdin
A browser terminal looks like a straightforward UI feature:
xterm.js in browser <ββWebSocketββ> SSH PTY on VPS
Most tutorials implement it in fifty lines. Upgrade a WebSocket, connect an SSH client, pipe stdin in one direction, pipe stdout in the other.
The hard part is not opening the shell.
The hard part is everything that happens while that WebSocket stays open:
- What happens if another browser tab opens a WebSocket using the user's cookie?
- What happens if an administrator removes that user from the team while their bash session is still open?
- What happens if the user closes the tab while the SSH handshake is still connecting?
- What happens if someone leaves an interactive root prompt idle for six hours?
- What happens if someone pastes 50 KB of text or sends a 10,000-column resize frame?
These questions shaped the WebSocket terminal handler in Nitrobase.
Nitrobase has only recently launched and is still in Beta. Providing a host or container shell from a web panel creates real operational risk, so the terminal handler is designed around explicit boundaries rather than treating the WebSocket as a thin pipe.
Browsers do not enforce CORS on WebSocket upgrades
A standard cross-origin fetch() is blocked by browsers unless the server opts in with CORS headers.
WebSocket upgrades behave differently. Any third-party page can attempt:
new WebSocket("wss://your-panel.example.com/api/servers/<id>/terminal");
If the user is signed in to your panel, the browser automatically attaches the session cookie to that WebSocket handshake. Without an explicit origin check, a malicious website could connect to your panel's shell endpoint on the user's behalfβan attack known as Cross-Site WebSocket Hijacking (CSWSH).
Nitrobase checks Origin before accepting the upgrade:
WebSocket upgrade request
|
+--> Origin header missing or malformed --> 403 Forbidden
|
+--> Origin host != Host / X-Forwarded-Host --> 403 Forbidden
|
+--> Origin host matches --> check cookie + RBAC
Browsers always attach the Origin header on WebSocket upgrades and client JavaScript cannot forge it, so comparing Origin against the target Host (or proxy-forwarded X-Forwarded-Host) closes cross-site upgrades before any session lookup or SSH work runs.
Opening a session is an HTTP check; keeping it open is a state problem
On normal HTTP API routes, revoking a user's session or changing their team role takes effect on the very next request.
A WebSocket terminal is different. Once upgraded, it can stay connected for hours without issuing another HTTP request.
Imagine a realistic team scenario:
14:00 User opens a host shell as a Team Operator (allowed)
14:05 Admin removes User from the team (or drops terminal permission)
14:06 Browser WebSocket is STILL connected to bash on the VPS
Checking permissions only during upgrade leaves that shell alive until the user voluntarily closes the tab.
Nitrobase registers every open terminal socket (and live SSE stream) with an in-process live connection registry (trackLiveConnection). Each tracked entry records the sessionId, userId, active teamId, and required permission (server.terminal for host shells, app.terminal for container shells):
- Immediate revocation hooks: Signing out or revoking a session notifies matching live connections immediately.
- Periodic re-validation backstop: Every 30 seconds, the registry validates active sessions and team permissions in bulk against the database.
When a session expires or the member loses the server.terminal or app.terminal permission, Nitrobase writes a localized banner directly into the terminal stream, tears down the remote PTY/executor, and closes the WebSocket with custom close codes (4403 for team access changed, 4401 for session ended).
Closing a tab mid-handshake leaks remote shells
Connecting to a remote VPS over SSH takes timeβnetwork latency, key authentication, and spawning a PTY on the server all happen asynchronously after the WebSocket open event fires.
If the user refreshes the page or closes the browser tab 200 milliseconds after clicking "Terminal," the WebSocket close event fires before executor.shell() finishes resolving:
t=0ms WS open -> start async SSH connect + PTY spawn
t=150ms User closes tab -> WS close fires (session doesn't exist yet!)
t=400ms SSH connect finishes -> PTY spawns -> nobody is listening!
Without explicit tracking, that orphaned bash or docker exec -it process sits open on the managed server indefinitely.
Nitrobase sets a closed flag on the connection state when close fires and checks it at two checkpoints inside the async setup path:
- right after
getExecutor(target.server)resolves; - right after
executor.shell(...)resolves.
If state.closed became true while awaiting either step, teardown() immediately closes both the shell session and the underlying SSH executor.
Input frames, pastes, and resize dimensions are untrusted
Even an authenticated terminal user should not be able to crash a PTY process or hang the server with malformed WebSocket frames.
Nitrobase validates and bounds every frame in parseTerminalMessage():
| Control | Limit / Behavior | Why it exists |
|---|---|---|
| Per-frame input cap |
4 KiB (4096 UTF-16 code units) |
Oversized frames are dropped whole with a terminal notice rather than buffered infinitely |
| Client paste chunking | chunkTerminalInput() |
Splits large pastes into ordered frames under 4 KiB, preserving UTF-16 surrogate pairs and accounting for JSON escape expansion (up to 6x for control chars) |
| Terminal resize bounds |
cols: 10..500, rows: 5..200
|
Prevents negative, NaN, or giant resize payloads from reaching the PTY |
| Idle timeout | TERMINAL_IDLE_TIMEOUT_MS |
Closes unattended shells; reset by real input frames, never by background resize events |
Notice that last distinction: browser windows resize when a laptop docks or splits screen. Resetting the idle timer on resize frames could keep an abandoned terminal open accidentally, so only interactive input resets it.
Also, if a user starts typing commands while the SSH session is still connecting (t=100ms), message awaits state.ready so those initial keystrokes are queued cleanly and delivered once the PTY is readyβor discarded if the connection failed.
Container shells vs. host shells are separate permissions
Not every teammate who needs to inspect an application container should get a login shell on the underlying VPS host.
Nitrobase splits terminal access into two endpoints and two distinct RBAC permissions:
-
/api/servers/:serverId/terminal(server.terminal): Opens a host shell on the managed VPS. -
/api/apps/:appId/terminal?service=...(app.terminal): Runs a trusteddocker exec -itcommand directly inside a specific service container rather than dropping the user onto the VPS root prompt.
Both endpoints share the exact same createTerminalHandler() boundary, origin checks, live revocation tracking, idle timer, and audit trail. Every session records both an open audit event and a close audit event containing the end reason (closed, TERMINAL_IDLE, TERMINAL_ACCESS_CHANGED, or TERMINAL_SESSION_ENDED).
What a browser terminal still does not protect against
A terminal guard controls who can open and keep a shell over HTTP/WebSocket.
Once an authorized operator has an active host shell or container shell, they hold whatever privileges the underlying SSH user or container user possesses. Origin checks and live revocation do not restrict what commands an authorized user runs inside their session, nor do they replace least-privilege container users or host-level SSH key management.
My WebSocket terminal checklist
Before shipping an interactive shell in a web control plane, these are the boundaries I verify:
- [ ] Does the WebSocket upgrade validate
OriginagainstHost/X-Forwarded-Host? - [ ] Are permissions verified both at
upgradeand again insideopen? - [ ] Does revoking a session or changing a team role immediately terminate already-open terminals?
- [ ] Does disconnecting while SSH is still connecting clean up the newly spawned PTY instead of leaking it?
- [ ] Are client-supplied
rowsandcolsclamped to sensible integer bounds? - [ ] Are WebSocket input frames size-bounded, with large pastes chunked safely on the client?
- [ ] Are idle shells closed automatically, without letting
resizeevents keep them alive? - [ ] Are both terminal start and terminal close (with reason) written to the audit log?
Connecting xterm.js to an SSH stream gets you a working demo in an afternoon. Building the teardown and revocation path around it is what makes it safe to leave in production.
Nitrobase source code: https://github.com/AydenGroup/nitrobase
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes β full credit and traffic to the original publisher.