Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions packages/server/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,23 @@
# localterm-server

## [Unreleased]

### Features

- Add xumux v0.2 binary transport (`/xumux` WebSocket endpoint)
- Binary codec for terminal message types (input, output, resize, exit, title, session-info)
- XumuxServer multiplexer with HELLO/WELCOME handshake and channel management
- WebSocketAdapter for xumux transport over WebSocket
- Per-connection local session map prevents channel-ID collisions across concurrent connections
- Backpressure enforcement on xumux channels
- Loopback security on `/xumux` endpoint

### Bug Fixes

- Exit-code null sentinel changed from -1 to INT32_MIN so real exit code -1 is preserved
- `decodeResize` returns null on short payload instead of throwing
- `session.dispose()` called in PTY exit handler to prevent resource leak

## 0.0.11

### Patch Changes
Expand Down
4 changes: 3 additions & 1 deletion packages/server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,10 @@
},
"devDependencies": {
"@types/node": "^25.5.0",
"@types/ws": "^8.18.1",
"typescript": "^5.9.3",
"vite-plus": "^0.1.12"
"vite-plus": "^0.1.12",
"ws": "^8.20.0"
},
"engines": {
"node": ">=22"
Expand Down
165 changes: 157 additions & 8 deletions packages/server/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,23 @@ import {
WS_READY_STATE_OPEN,
} from "./constants.js";
import { ServerErrorException, serverError } from "./errors.js";
import {
TERMINAL_MSG_TYPE,
decodeInput,
decodeResize,
encodeExit,
encodeOutput,
encodeSessionInfo,
encodeTitle,
} from "./protocol.js";
import { clientToServerMessageSchema } from "./schemas.js";
import { enforceLoopback, isLoopbackHost, loopbackMiddleware } from "./security.js";
import { Session } from "./session.js";
import { SessionRegistry } from "./session-registry.js";
import { resolveStaticAsset } from "./static-resolver.js";
import type { ServerToClientMessage } from "./types.js";
import { WebSocketAdapter } from "./xumux/websocket-adapter.js";
import { XumuxServer } from "./xumux/xumux-server.js";

export interface ServerOptions {
port?: number;
Expand Down Expand Up @@ -89,6 +100,7 @@ export const createServer = async (options: ServerOptions = {}): Promise<Running
}

let session: Session | null = null;
let registryId: number | null = null;

return {
onOpen(_event, ws) {
Expand All @@ -97,11 +109,8 @@ export const createServer = async (options: ServerOptions = {}): Promise<Running
return;
}
session = new Session({});
registry.register(session);
registryId = registry.registerAuto(session);

// Wire listeners BEFORE the first safeSend so any synchronous emit
// from Session (current or future) reaches the client. Today
// node-pty's data/exit are async, but this guards against drift.
const onOutput = (data: string) => safeSend(ws, { type: "output", data });
const onTitle = (title: string) => safeSend(ws, { type: "title", title });
const onExit = (code: number | null) => {
Expand Down Expand Up @@ -138,16 +147,156 @@ export const createServer = async (options: ServerOptions = {}): Promise<Running
}
},
onClose() {
if (!session) return;
registry.unregister(session);
if (!session || registryId === null) return;
registry.unregister(registryId);
session.dispose();
session = null;
registryId = null;
},
onError() {
if (!session) return;
registry.unregister(session);
if (!session || registryId === null) return;
registry.unregister(registryId);
session.dispose();
session = null;
registryId = null;
},
};
}),
);

app.get(
"/xumux",
upgradeWebSocket((context) => {
const blocked = enforceLoopback(context);
if (blocked) {
return { onOpen: (_event, ws) => ws.close(WS_CLOSE_POLICY_VIOLATION, "forbidden") };
}

let xumux: XumuxServer | null = null;
// Per-connection session map: channelId → session.
// Channel IDs are only unique within a single xumux connection, so using
// the global registry (keyed by channelId) would cause collisions when two
// concurrent connections both open channel 1. This local map is scoped to
// the current WebSocket connection closure.
const connectionSessions = new Map<number, Session>();
// Parallel map of channelId → global registry auto-ID for size tracking.
const connectionRegistryIds = new Map<number, number>();

return {
onOpen(_event, ws) {
const adapter = new WebSocketAdapter(ws);
xumux = new XumuxServer(adapter, {
onOpenChannel: (channelId) => {
if (registry.size() >= MAX_CONCURRENT_SESSIONS) {
xumux?.closeChannel(channelId);
return;
}
const session = new Session({});
const globalId = registry.registerAuto(session);
connectionSessions.set(channelId, session);
connectionRegistryIds.set(channelId, globalId);

const sessionInfoPayload = encodeSessionInfo({
shell: session.shell,
shellName: session.shellBaseName,
pid: session.pid,
cwd: session.cwd,
});
xumux?.sendToChannel(channelId, TERMINAL_MSG_TYPE.SESSION_INFO, sessionInfoPayload);

const cleanupChannel = (disposeSes: boolean) => {
connectionSessions.delete(channelId);
const gid = connectionRegistryIds.get(channelId);
if (gid !== undefined) {
registry.unregister(gid);
connectionRegistryIds.delete(channelId);
}
if (disposeSes) session.dispose();
};

session.on("output", (data) => {
if (adapter.bufferedAmount > WS_BACKPRESSURE_THRESHOLD_BYTES) {
xumux?.closeChannel(channelId);
cleanupChannel(true);
return;
}
xumux?.sendToChannel(channelId, TERMINAL_MSG_TYPE.OUTPUT, encodeOutput(data));
});
session.on("title", (title) => {
xumux?.sendToChannel(channelId, TERMINAL_MSG_TYPE.TITLE, encodeTitle(title));
});
session.on("exit", (code) => {
Comment thread
vercel[bot] marked this conversation as resolved.
xumux?.sendToChannel(channelId, TERMINAL_MSG_TYPE.EXIT, encodeExit(code));
xumux?.closeChannel(channelId);
// dispose() must be called here: onCloseChannel won't fire for
// server-initiated closes, so this is the only cleanup path.
cleanupChannel(true);
});
Comment thread
cursor[bot] marked this conversation as resolved.
},
onCloseChannel: (channelId) => {
const session = connectionSessions.get(channelId);
if (!session) return;
connectionSessions.delete(channelId);
const gid = connectionRegistryIds.get(channelId);
if (gid !== undefined) {
registry.unregister(gid);
connectionRegistryIds.delete(channelId);
}
session.dispose();
},
onChannelMessage: (event) => {
const session = connectionSessions.get(event.channelId);
if (!session) return;
if (event.type === TERMINAL_MSG_TYPE.INPUT) {
session.write(decodeInput(event.payload));
} else if (event.type === TERMINAL_MSG_TYPE.RESIZE) {
const dims = decodeResize(event.payload);
if (dims) session.resize(dims.cols, dims.rows);
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Binary xumux path lacks input size validation

Medium Severity

The /xumux binary onChannelMessage handler passes decodeInput and decodeResize results directly to session.write() and session.resize() without any bounds validation. The JSON /ws path enforces MAX_INPUT_BYTES (64 KB), MAX_COLS (1000), and MAX_ROWS (1000) via zod schemas. The binary path allows arbitrarily large input payloads and resize dimensions up to 65535 (uint16 max), creating an inconsistent security posture between the two transport paths.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 3ce56b7. Configure here.

},
});
},
onMessage(event) {
if (!xumux) return;
const raw = event.data;
let bytes: Uint8Array;
if (raw instanceof Uint8Array) {
bytes = raw;
} else if (raw instanceof ArrayBuffer) {
bytes = new Uint8Array(raw);
} else if (typeof raw === "string") {
bytes = new TextEncoder().encode(raw);
} else if (ArrayBuffer.isView(raw)) {
bytes = new Uint8Array(raw.buffer, raw.byteOffset, raw.byteLength);
} else if (typeof Blob !== "undefined" && raw instanceof Blob) {
void raw.arrayBuffer().then((buffer) => {
xumux?.onMessage(new Uint8Array(buffer));
});
return;
Comment thread
cursor[bot] marked this conversation as resolved.
} else {
return;
}
xumux.onMessage(bytes);
},
onClose() {
if (!xumux) return;
xumux.close();
xumux = null;
// Dispose any sessions that didn't get an explicit CLOSE_CHANNEL
// (e.g. client disconnected mid-session).
for (const [, session] of connectionSessions) session.dispose();
for (const [, gid] of connectionRegistryIds) registry.unregister(gid);
connectionSessions.clear();
connectionRegistryIds.clear();
},
onError() {
if (!xumux) return;
xumux.close();
xumux = null;
for (const [, session] of connectionSessions) session.dispose();
for (const [, gid] of connectionRegistryIds) registry.unregister(gid);
connectionSessions.clear();
connectionRegistryIds.clear();
},
};
}),
Expand Down
93 changes: 93 additions & 0 deletions packages/server/src/protocol.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,96 @@ export {
} from "./schemas.js";
export type { ClientToServerMessage, ServerToClientMessage } from "./types.js";
export type { ServerError, ServerErrorCode, ServerErrorKind } from "./errors.js";

export const TERMINAL_MSG_TYPE = {
INPUT: 0x01,
OUTPUT: 0x02,
RESIZE: 0x03,
EXIT: 0x04,
TITLE: 0x05,
SESSION_INFO: 0x06,
} as const;

export type TerminalMsgType = (typeof TERMINAL_MSG_TYPE)[keyof typeof TERMINAL_MSG_TYPE];

const textEncoder = new TextEncoder();
const textDecoder = new TextDecoder();

// INT32_MIN (0x80000000) — impossible as a real exit code on POSIX (0-255) or Windows (0-4294967295).
const EXIT_CODE_NULL_SENTINEL = -2147483648;

export const encodeInput = (data: string): Uint8Array => textEncoder.encode(data);

export const decodeInput = (payload: Uint8Array): string => textDecoder.decode(payload);

export const encodeOutput = (data: string): Uint8Array => textEncoder.encode(data);

export const decodeOutput = (payload: Uint8Array): string => textDecoder.decode(payload);

export const encodeResize = (cols: number, rows: number): Uint8Array => {
const buffer = new Uint8Array(4);
const view = new DataView(buffer.buffer);
view.setUint16(0, cols, false);
view.setUint16(2, rows, false);
return buffer;
};

export const decodeResize = (payload: Uint8Array): { cols: number; rows: number } | null => {
if (payload.length < 4) return null;
const view = new DataView(payload.buffer, payload.byteOffset, payload.byteLength);
return { cols: view.getUint16(0, false), rows: view.getUint16(2, false) };
};

export const encodeExit = (code: number | null): Uint8Array => {
const buffer = new Uint8Array(4);
const view = new DataView(buffer.buffer);
view.setInt32(0, code ?? EXIT_CODE_NULL_SENTINEL, false);
return buffer;
};

export const decodeExit = (payload: Uint8Array): number | null => {
if (payload.length < 4) throw new Error("exit payload must be 4 bytes");
const view = new DataView(payload.buffer, payload.byteOffset, payload.byteLength);
const raw = view.getInt32(0, false);
return raw === EXIT_CODE_NULL_SENTINEL ? null : raw;
};

export const encodeTitle = (title: string): Uint8Array => textEncoder.encode(title);

export const decodeTitle = (payload: Uint8Array): string => textDecoder.decode(payload);

export interface SessionInfo {
shell: string;
shellName: string;
pid: number;
cwd: string;
}

export const encodeSessionInfo = (info: SessionInfo): Uint8Array =>
textEncoder.encode(JSON.stringify(info));

export const decodeSessionInfo = (payload: Uint8Array): SessionInfo =>
JSON.parse(textDecoder.decode(payload)) as SessionInfo;

export {
XUMUX_CHANNEL_CONTROL,
XUMUX_CHANNEL_MAX,
XUMUX_CHANNEL_MIN,
XUMUX_CTRL_CHANNEL_ACK,
XUMUX_CTRL_CLOSE_CHANNEL,
XUMUX_CTRL_HELLO,
XUMUX_CTRL_OPEN_CHANNEL,
XUMUX_CTRL_PING,
XUMUX_CTRL_PONG,
XUMUX_CTRL_WELCOME,
XUMUX_FRAME_HEADER_BYTES,
XUMUX_VERSION,
} from "./xumux/index.js";
export { decodeFrame, encodeFrame, WebSocketAdapter, XumuxServer } from "./xumux/index.js";
export type {
WebSocketLike,
XumuxChannelEvent,
XumuxFrame,
XumuxServerEvents,
XumuxTransport,
} from "./xumux/index.js";
24 changes: 18 additions & 6 deletions packages/server/src/session-registry.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,34 @@
import type { Session } from "./session.js";

export class SessionRegistry {
private readonly sessions = new Set<Session>();
private readonly sessions = new Map<number, Session>();
private nextAutoId = -1;

register(session: Session): void {
this.sessions.add(session);
register(channelId: number, session: Session): void {
this.sessions.set(channelId, session);
}

unregister(session: Session): void {
this.sessions.delete(session);
registerAuto(session: Session): number {
const autoId = this.nextAutoId;
this.nextAutoId -= 1;
this.sessions.set(autoId, session);
return autoId;
}

unregister(channelId: number): void {
this.sessions.delete(channelId);
}

getByChannelId(channelId: number): Session | undefined {
return this.sessions.get(channelId);
}

size(): number {
return this.sessions.size;
}

disposeAll(): void {
for (const session of this.sessions) {
for (const session of this.sessions.values()) {
session.dispose();
}
this.sessions.clear();
Expand Down
15 changes: 15 additions & 0 deletions packages/server/src/xumux/constants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
export const XUMUX_VERSION = 2;

export const XUMUX_CHANNEL_CONTROL = 0x0000;
export const XUMUX_CHANNEL_MIN = 0x0001;
export const XUMUX_CHANNEL_MAX = 0xfffe;

export const XUMUX_FRAME_HEADER_BYTES = 3;

export const XUMUX_CTRL_HELLO = 0x01;
export const XUMUX_CTRL_WELCOME = 0x02;
export const XUMUX_CTRL_OPEN_CHANNEL = 0x03;
export const XUMUX_CTRL_CHANNEL_ACK = 0x04;
export const XUMUX_CTRL_CLOSE_CHANNEL = 0x05;
export const XUMUX_CTRL_PING = 0x06;
export const XUMUX_CTRL_PONG = 0x07;
Loading