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(windows): serve dev-server -L port forwards over the native SSH transport

review25cbd8c76a36
diff --git a/src/core/remote-ssh/native/native-invoke.test.ts b/src/core/remote-ssh/native/native-invoke.test.ts
index 700dbe9f4..698be0266 100644
--- a/src/core/remote-ssh/native/native-invoke.test.ts
+++ b/src/core/remote-ssh/native/native-invoke.test.ts
@@ -12,6 +12,8 @@ import {
exitMasterArgs,
hookForwardArgs,
hookForwardCancelArgs,
+ localForwardArgs,
+ localForwardCancelArgs,
masterArgs
} from '../control-master'
import type { SshConnection } from '../../../shared/ssh'
@@ -26,6 +28,8 @@ let port: number
let clients: Connection[] = []
/** Remote socket path → the server-side client that asked for it (to push a connection back). */
const streamForwards = new Map<string, Connection>()
+/** Every direct-tcpip open the server saw, as `addr:port`. */
+const tcpipOpens: string[] = []
beforeAll(async () => {
dir = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-native-inv-'))
@@ -48,6 +52,17 @@ beforeAll(async () => {
}
reject?.()
})
+ // direct-tcpip (`-L`): dial the destination on this loopback "host" and splice.
+ client.on('tcpip', (accept, reject, info) => {
+ tcpipOpens.push(`${info.destIP}:${info.destPort}`)
+ const out = net.connect({ host: info.destIP, port: info.destPort })
+ out.once('error', () => reject?.())
+ out.once('connect', () => {
+ const ch = accept()
+ ch.on('error', () => out.destroy())
+ ch.pipe(out).pipe(ch)
+ })
+ })
client.on('session', (accept) => {
accept().on('exec', (a, _r, info) => {
const ch = a()
@@ -195,6 +210,100 @@ describe('native-invoke', () => {
}
})
+ describe('-O forward -L (dev-server port forwarding)', () => {
+ const echo = (): Promise<{ srv: net.Server; port: number }> =>
+ new Promise((r) => {
+ const srv = net.createServer((s) => s.pipe(s))
+ srv.listen(0, '127.0.0.1', () => r({ srv, port: (srv.address() as AddressInfo).port }))
+ })
+ const freePort = (): Promise<number> =>
+ new Promise((r) => {
+ const s = net.createServer()
+ s.listen(0, '127.0.0.1', () => {
+ const p = (s.address() as AddressInfo).port
+ s.close(() => r(p))
+ })
+ })
+ const roundTrip = (lport: number, text: string): Promise<string> =>
+ new Promise((resolve, reject) => {
+ const c = net.connect({ host: '127.0.0.1', port: lport })
+ let got = ''
+ c.on('data', (d) => {
+ got += d.toString()
+ if (got.length >= text.length) {
+ c.end()
+ resolve(got)
+ }
+ })
+ c.on('error', reject)
+ c.write(text)
+ })
+ const canListen = (p: number): Promise<boolean> =>
+ new Promise((r) => {
+ const s = net.createServer()
+ s.once('error', () => r(false))
+ s.listen(p, '127.0.0.1', () => s.close(() => r(true)))
+ })
+
+ it('carries a local loopback connection to the host port, built and parsed by the real builders', async () => {
+ const { srv, port: remotePort } = await echo()
+ try {
+ const m = mux()
+ await runSshArgv(m, childArgs(conn(), CP(), 'true'))
+ const lport = await freePort()
+ const fwd = await runSshArgv(m, localForwardArgs(conn(), CP(), lport, '127.0.0.1', remotePort))
+ expect(fwd.code).toBe(0)
+ expect(await roundTrip(lport, 'hello dev server')).toBe('hello dev server')
+ expect(tcpipOpens).toContain(`127.0.0.1:${remotePort}`)
+ // A duplicate is acknowledged again (the registry's 'maybe-ours' adoption depends on it).
+ expect((await runSshArgv(m, localForwardArgs(conn(), CP(), lport, '127.0.0.1', remotePort))).code).toBe(0)
+ expect(await canListen(lport)).toBe(false)
+ // Cancel frees the port; a cancel of what is not held is not an error.
+ expect((await runSshArgv(m, localForwardCancelArgs(conn(), CP(), lport, '127.0.0.1', remotePort))).code).toBe(0)
+ expect(await canListen(lport)).toBe(true)
+ expect((await runSshArgv(m, localForwardCancelArgs(conn(), CP(), lport, '127.0.0.1', remotePort))).code).toBe(0)
+ } finally {
+ srv.close()
+ }
+ })
+
+ it('a port someone else holds is OpenSSH\'s "Port forwarding failed", exit 255', async () => {
+ const m = mux()
+ await runSshArgv(m, childArgs(conn(), CP(), 'true'))
+ const foreign = net.createServer()
+ await new Promise<void>((r) => foreign.listen(0, '127.0.0.1', () => r()))
+ const busy = (foreign.address() as AddressInfo).port
+ try {
+ const r = await runSshArgv(m, localForwardArgs(conn(), CP(), busy, '127.0.0.1', 1))
+ expect(r.code).toBe(255)
+ expect(r.stderr.toString()).toMatch(/Port forwarding failed/)
+ } finally {
+ foreign.close()
+ }
+ })
+
+ it('without a master it fails like ssh; a dropped or exited master releases its listeners', async () => {
+ const m = mux()
+ const lport = await freePort()
+ const none = await runSshArgv(m, localForwardArgs(conn(), CP(), lport, '127.0.0.1', 1))
+ expect(none.code).toBe(255)
+ expect(none.stderr.toString()).toMatch(/Control socket connect/)
+
+ await runSshArgv(m, childArgs(conn(), CP(), 'true'))
+ expect((await runSshArgv(m, localForwardArgs(conn(), CP(), lport, '127.0.0.1', 1))).code).toBe(0)
+ expect(await canListen(lport)).toBe(false)
+ for (const c of clients) c.end() // the host drops the connection
+ for (let i = 0; i < 50 && !(await canListen(lport)); i++) await new Promise((r) => setTimeout(r, 20))
+ expect(await canListen(lport)).toBe(true)
+
+ const lport2 = await freePort()
+ await runSshArgv(m, childArgs(conn(), CP(), 'true'))
+ expect((await runSshArgv(m, localForwardArgs(conn(), CP(), lport2, '127.0.0.1', 1))).code).toBe(0)
+ expect((await runSshArgv(m, exitMasterArgs(conn(), CP()))).code).toBe(0)
+ expect(await canListen(lport2)).toBe(true)
+ })
+ })
+
it('an argv the parser refuses is a named exit 255, not a guess', async () => {
const r = await runSshArgv(mux(), ['-L', '1:h:2', '[email protected]'])
expect(r.code).toBe(255)
diff --git a/src/core/remote-ssh/native/native-invoke.ts b/src/core/remote-ssh/native/native-invoke.ts
index 6f4ad0147..281b15dc1 100644
--- a/src/core/remote-ssh/native/native-invoke.ts
+++ b/src/core/remote-ssh/native/native-invoke.ts
@@ -53,13 +53,15 @@ export async function runSshArgv(
return (await mux.exit(cp)) ? result(0, '', 'Exit request sent.\n') : result(255, '', `${noMasterMessage(cp)}\n`)
case 'forward':
try {
- await mux.forward(cp, p.forward)
+ if (p.forward.kind === 'local') await mux.forwardLocal(cp, p.forward)
+ else await mux.forward(cp, p.forward)
return result(0, '', '')
} catch (e) {
return result(255, '', `${(e as Error).message}\n`)
}
case 'cancel':
- await mux.cancel(cp, p.forward)
+ if (p.forward.kind === 'local') await mux.cancelLocal(cp, p.forward)
+ else await mux.cancel(cp, p.forward)
return result(0, '', '')
}
}
diff --git a/src/core/remote-ssh/native/native-mux.ts b/src/core/remote-ssh/native/native-mux.ts
index f3ab57917..5459da84e 100644
--- a/src/core/remote-ssh/native/native-mux.ts
+++ b/src/core/remote-ssh/native/native-mux.ts
@@ -33,7 +33,7 @@ import net from 'net'
import type { Duplex } from 'stream'
import fs from 'fs'
import { Client, createAgent, utils, type Channel, type ClientChannel, type ConnectConfig, type UNIXConnectionDetails, type ParsedKey, type SFTPWrapper } from 'ssh2'
-import type { ParsedSsh, ReverseForward, SshOptions, SshTarget } from './ssh-argv'
+import type { LocalForward, ParsedSsh, ReverseForward, SshOptions, SshTarget } from './ssh-argv'
import { parseProxyJump, type HostQuery, type JumpSpec, type ResolvedHost } from './ssh-config'
import { acceptNewHostKey } from './known-hosts'
import { addKeyToAgent, type AgentAddResult } from './agent-add'
@@ -84,6 +84,9 @@ interface Conn {
alive: boolean
closed: Promise<string>
forwards: Map<string, ReverseForward>
+ /** `-L` listeners this connection holds, by spec (see `localForwardKey`). They close with it,
+ * as an OpenSSH master's listeners die with the master process. */
+ localForwards: Map<string, LocalListener>
target: SshTarget
options: SshOptions
/** Channels open on this connection right now. */
@@ -96,6 +99,30 @@ interface Conn {
ownsJumps: boolean
}
+interface LocalListener {
+ server: net.Server
+ /** Accepted connections, destroyed with the listener (a cancel ends what it was carrying). */
+ sockets: Set<net.Socket>
+}
+
+/** OpenSSH's mux reply for a local forward it could not set up (`mux_client_forward`). */
+export const LOCAL_FORWARD_FAILED = 'mux_client_forward: forwarding request failed: Port forwarding failed'
+
+function localForwardKey(f: LocalForward): string {
+ return `${f.bindHost}:${f.localPort}:${f.toHost}:${f.toPort}`
+}
+
+function closeLocalListener(l: LocalListener): void {
+ l.server.close()
+ for (const s of l.sockets) s.destroy()
+ l.sockets.clear()
+}
+
+function closeLocalForwards(c: Conn): void {
+ for (const l of c.localForwards.values()) closeLocalListener(l)
+ c.localForwards.clear()
+}
+
/** How deep a first hop's own ProxyJump may recurse before we call it a loop. */
const MAX_JUMP_DEPTH = 8
@@ -174,6 +201,7 @@ export class NativeMux {
if (!c) return false
this.conns.delete(controlPath)
c.alive = false
+ closeLocalForwards(c)
c.client.end()
this.endOverflow(controlPath)
await Promise.race([c.closed, new Promise((r) => setTimeout(r, 2000))])
@@ -185,6 +213,7 @@ export class NativeMux {
for (const [cp, c] of this.conns) {
this.conns.delete(cp)
c.alive = false
+ closeLocalForwards(c)
c.client.end()
this.endOverflow(cp)
}
@@ -415,6 +444,70 @@ export class NativeMux {
)
}
+ /**
+ * `-O forward -L 127.0.0.1:<port>:<addr>:<port>`: a loopback listener here whose every accepted
+ * connection rides a direct-tcpip channel of the shared connection to `addr:port` on the host.
+ * A spec this connection already holds is acknowledged again, as an OpenSSH master acknowledges a
+ * duplicate forward — the port registry's adoption of a forward that survived a renderer reload
+ * ('maybe-ours') depends on that. A port someone else holds is OpenSSH's "Port forwarding failed".
+ */
+ async forwardLocal(controlPath: string, fwd: LocalForward): Promise<void> {
+ const conn = this.conns.get(controlPath)
+ if (!conn?.alive) throw new Error(noMasterMessage(controlPath))
+ await conn.ready
+ const key = localForwardKey(fwd)
+ if (conn.localForwards.has(key)) return
+ const sockets = new Set<net.Socket>()
+ const server = net.createServer((sock) => {
+ sockets.add(sock)
+ sock.once('close', () => sockets.delete(sock))
+ sock.on('error', () => sock.destroy())
+ sock.pause()
+ if (!conn.alive) return void sock.destroy()
+ conn.client.forwardOut(sock.remoteAddress ?? '127.0.0.1', sock.remotePort ?? 0, fwd.toHost, fwd.toPort, (err, ch) => {
+ if (err) {
+ this.deps.log?.(`[native-ssh] -L ${fwd.localPort}: channel open failed to ${fwd.toHost}:${fwd.toPort}: ${err.message}`)
+ return void sock.destroy()
+ }
+ ch.on('error', () => sock.destroy())
+ ch.once('close', () => sock.destroy())
+ sock.once('close', () => ch.close())
+ sock.pipe(ch).pipe(sock)
+ sock.resume()
+ })
+ })
+ await new Promise<void>((resolve, reject) => {
+ server.once('error', (e: NodeJS.ErrnoException) => {
+ this.deps.log?.(`[native-ssh] -L ${fwd.localPort}: ${e.code ?? e.message}`)
+ reject(new Error(LOCAL_FORWARD_FAILED))
+ })
+ // `exclusive`: never share the handle with a cluster worker; the port is ours alone.
+ server.listen({ host: fwd.bindHost, port: fwd.localPort, exclusive: true }, () => resolve())
+ })
+ // The connection may have gone (or another call won the same spec) while we were listening.
+ if (!conn.alive || conn.localForwards.has(key)) {
+ server.close()
+ if (!conn.alive) throw new Error(noMasterMessage(controlPath))
+ return
+ }
+ server.on('error', (e) => this.deps.log?.(`[native-ssh] -L ${fwd.localPort}: ${e.message}`))
+ conn.localForwards.set(key, { server, sockets })
+ }
+
+ /** `-O cancel -L …`: close the listener and what it carries. Not held = not an error (as ssh). */
+ async cancelLocal(controlPath: string, fwd: LocalForward): Promise<void> {
+ const conn = this.conns.get(controlPath)
+ const key = localForwardKey(fwd)
+ const l = conn?.localForwards.get(key)
+ if (!conn || !l) return
+ conn.localForwards.delete(key)
+ await new Promise<void>((resolve) => {
+ l.server.close(() => resolve())
+ for (const s of l.sockets) s.destroy()
+ l.sockets.clear()
+ })
+ }
+
// ---------------------------------------------------------------------------------------------
/** Drain an exec channel into an ExecResult (stdin written, timeout enforced). */
@@ -462,6 +555,7 @@ export class NativeMux {
alive: true,
closed,
forwards: new Map(),
+ localForwards: new Map(),
target,
options,
channels: 0,
@@ -476,6 +570,7 @@ export class NativeMux {
})
client.on('close', () => {
conn.alive = false
+ closeLocalForwards(conn)
// The jump connections belong to the target connection: they end with it.
if (conn.ownsJumps) for (const j of conn.jumps) j.end()
if (this.conns.get(controlPath) === conn) {
diff --git a/src/core/remote-ssh/native/ssh-argv.test.ts b/src/core/remote-ssh/native/ssh-argv.test.ts
index 638f572b3..e2d5e7241 100644
--- a/src/core/remote-ssh/native/ssh-argv.test.ts
+++ b/src/core/remote-ssh/native/ssh-argv.test.ts
@@ -7,6 +7,8 @@ import {
masterRoundTripArgs,
hookForwardArgs,
hookForwardCancelArgs,
+ localForwardArgs,
+ localForwardCancelArgs,
scpArgs,
scpDownArgs,
remoteTmuxPtyArgs,
@@ -71,6 +73,34 @@ describe('parseSshArgv reads back every builder in control-master.ts', () => {
expect(parseSshArgv(hookForwardCancelArgs(plain, CP, '/r.sock', 1))).toMatchObject({ op: 'cancel' })
})
+ it('local (-L) forwards, IPv4 and bracketed IPv6, for forward and cancel', () => {
+ expect(parseSshArgv(localForwardArgs(plain, CP, 5173, '10.0.0.7', 3000))).toMatchObject({
+ kind: 'control',
+ op: 'forward',
+ forward: { kind: 'local', bindHost: '127.0.0.1', localPort: 5173, toHost: '10.0.0.7', toPort: 3000 }
+ })
+ expect(parseSshArgv(localForwardCancelArgs(plain, CP, 8080, '::1', 8080))).toMatchObject({
+ op: 'cancel',
+ forward: { kind: 'local', localPort: 8080, toHost: '::1', toPort: 8080 }
+ })
+ expect(parseSshArgv(hookForwardArgs(plain, CP, '/r.sock', 1))).toMatchObject({ forward: { kind: 'reverse' } })
+ })
+
+ it('refuses every -L the builders never emit', () => {
+ const fwd = (spec: string): string[] => ['-O', 'forward', '-L', spec, '-o', `ControlPath=${CP}`, 'a@b']
+ expect(() => parseSshArgv(fwd('0.0.0.0:80:127.0.0.1:80'))).toThrow(/-L 0\.0\.0\.0/)
+ expect(() => parseSshArgv(fwd('8080:127.0.0.1:80'))).toThrow(/-L/)
+ expect(() => parseSshArgv(fwd('127.0.0.1:80:localhost:80'))).toThrow(/-L/)
+ expect(() => parseSshArgv(fwd('127.0.0.1:80:::1:80'))).toThrow(/-L/)
+ expect(() => parseSshArgv(fwd('127.0.0.1:80:999.0.0.1:80'))).toThrow(/-L/)
+ expect(() => parseSshArgv(fwd('127.0.0.1:0:127.0.0.1:80'))).toThrow(/-L port/)
+ expect(() =>
+ parseSshArgv(['-O', 'forward', '-L', '127.0.0.1:1:127.0.0.1:2', '-R', '/r.sock:127.0.0.1:3', 'a@b'])
+ ).toThrow(/-L with -R/)
+ expect(() => parseSshArgv(['-L', '127.0.0.1:1:127.0.0.1:2', 'a@b'])).toThrow(/-L outside/)
+ expect(() => parseSshArgv(['-O', 'check', '-L', '127.0.0.1:1:127.0.0.1:2', 'a@b'])).toThrow(/-L with -O check/)
+ })
+
it('interactive pty', () => {
const p = parseSshArgv(remoteTmuxPtyArgs(plain, CP, 'nt-node-1', '~/proj'))
expect(p.kind).toBe('exec')
@@ -81,6 +111,7 @@ describe('parseSshArgv reads back every builder in control-master.ts', () => {
it('refuses what it does not know, naming it', () => {
expect(() => parseSshArgv(['-L', '8080:localhost:80', 'a@b'])).toThrow(UnsupportedSshArgv)
+ expect(() => parseSshArgv(['-D', '1080', 'a@b'])).toThrow(/-D/)
expect(() => parseSshArgv(['-o', 'ProxyCommand=nc %h %p', 'a@b'])).toThrow(/ProxyCommand/)
expect(() => parseSshArgv(['-o', 'BatchMode=maybe', 'a@b'])).toThrow(/BatchMode/)
expect(() => parseSshArgv(['-O', 'stop', 'a@b'])).toThrow(/-O stop/)
diff --git a/src/core/remote-ssh/native/ssh-argv.ts b/src/core/remote-ssh/native/ssh-argv.ts
index 8c2984188..db6350bdf 100644
--- a/src/core/remote-ssh/native/ssh-argv.ts
+++ b/src/core/remote-ssh/native/ssh-argv.ts
@@ -42,6 +42,21 @@ export interface ReverseForward {
localPort: number
}
+/**
+ * `-L 127.0.0.1:<port>:<addr>:<port>` — the only -L shape the builders produce (localFwdSpec in
+ * control-master.ts): a loopback listener here, a direct-tcpip channel to `toHost:toPort` there.
+ */
+export interface LocalForward {
+ bindHost: '127.0.0.1'
+ localPort: number
+ /** An IP literal, brackets already stripped from an IPv6 one. */
+ toHost: string
+ toPort: number
+}
+
+/** What `-O forward|cancel` names: a reverse (`-R`) or a local (`-L`) forward. */
+export type ForwardSpec = ({ kind: 'reverse' } & ReverseForward) | ({ kind: 'local' } & LocalForward)
+
export type ParsedSsh =
| { kind: 'master'; target: SshTarget; options: SshOptions; background: boolean }
| { kind: 'control'; op: 'check' | 'exit'; target: SshTarget; options: SshOptions }
@@ -50,7 +65,7 @@ export type ParsedSsh =
op: 'forward' | 'cancel'
target: SshTarget
options: SshOptions
- forward: ReverseForward
+ forward: ForwardSpec
}
| { kind: 'exec'; target: SshTarget; options: SshOptions; tty: boolean; command?: string }
@@ -143,6 +158,20 @@ function parseReverse(spec: string): ReverseForward {
return { remoteSocket: m[1], localHost: m[2], localPort: parsePort(m[3], '-R port') }
}
+/**
+ * `127.0.0.1:<port>:<ipv4|[ipv6]>:<port>`, and nothing else. Re-validated here, at the parse site
+ * (CLAUDE.md rule 13), even though localFwdSpec already checked it: a bind address other than
+ * loopback would publish a dev server to the LAN, and a hostname target is not something any
+ * builder emits.
+ */
+function parseLocal(spec: string): LocalForward {
+ const m = /^127\.0\.0\.1:(\d+):(\d{1,3}(?:\.\d{1,3}){3}|\[[0-9A-Fa-f:]*:[0-9A-Fa-f:]*\]):(\d+)$/.exec(spec)
+ if (!m) throw new UnsupportedSshArgv(`-L ${spec}`)
+ const toHost = m[2].startsWith('[') ? m[2].slice(1, -1) : m[2]
+ if (!toHost.includes(':') && toHost.split('.').some((o) => Number(o) > 255)) throw new UnsupportedSshArgv(`-L ${spec}`)
+ return { bindHost: '127.0.0.1', localPort: parsePort(m[1], '-L port'), toHost, toPort: parsePort(m[3], '-L port') }
+}
+
/**
* Parse an ssh argv (without the program). The remote command is every argument after the
* destination joined with single spaces — exactly what OpenSSH sends to the server, which runs it
@@ -157,6 +186,7 @@ export function parseSshArgv(argv: string[]): ParsedSsh {
let tty = false
let op: string | undefined
let reverse: ReverseForward | undefined
+ let local: LocalForward | undefined
let i = 0
const need = (flag: string): string => {
const v = argv[++i]
@@ -185,6 +215,9 @@ export function parseSshArgv(argv: string[]): ParsedSsh {
case '-R':
reverse = parseReverse(need(a))
break
+ case '-L':
+ local = parseLocal(need(a))
+ break
case '-p':
t.port = parsePort(need(a), '-p')
break
@@ -207,15 +240,20 @@ export function parseSshArgv(argv: string[]): ParsedSsh {
if (rest.length) throw new UnsupportedSshArgv(`command with -O ${op}`)
if (op === 'check' || op === 'exit') {
if (reverse) throw new UnsupportedSshArgv(`-R with -O ${op}`)
+ if (local) throw new UnsupportedSshArgv(`-L with -O ${op}`)
return { kind: 'control', op, target, options: o }
}
if (op === 'forward' || op === 'cancel') {
- if (!reverse) throw new UnsupportedSshArgv(`-O ${op} without -R`)
- return { kind: 'control', op, target, options: o, forward: reverse }
+ // One forward per call, as every builder emits; both at once has no single answer.
+ if (reverse && local) throw new UnsupportedSshArgv(`-L with -R`)
+ if (local) return { kind: 'control', op, target, options: o, forward: { kind: 'local', ...local } }
+ if (!reverse) throw new UnsupportedSshArgv(`-O ${op} without -R or -L`)
+ return { kind: 'control', op, target, options: o, forward: { kind: 'reverse', ...reverse } }
}
throw new UnsupportedSshArgv(`-O ${op}`)
}
if (reverse) throw new UnsupportedSshArgv('-R outside -O forward/cancel')
+ if (local) throw new UnsupportedSshArgv('-L outside -O forward/cancel')
if (master) {
if (!noCommand || rest.length || tty) throw new UnsupportedSshArgv('-M without -N, or with a command')
return { kind: 'master', target, options: o, background }