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(ports): review round — unforgeable ownership, app tmux, off-screen sweep

review6bad4a60a2eb
diff --git a/CLAUDE.md b/CLAUDE.md
index 50535562e..eee89bedf 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -5192,6 +5192,28 @@ project's existing ControlMaster, so the URL the tool itself printed just works
exit 1 with no output is an ANSWER, "nothing listening"), else `/proc/net/tcp{,6}` joined to
`ls -l /proc/*/fd` by socket inode (one `ls`, never a `readlink` per descriptor). No tool at all is
its own failure (`no-listener-tool`), never "no ports".
+- **The listener tools' output is attacker-influenced text — parse it as such** (review of #1063,
+ reproduced on the dev host). ss prints a holder as `("<name>",pid=N,fd=M)` with the process NAME
+ raw, and any process can rename itself: as root, a listener owned by `nobody` named
+ `vite",pid=12345` printed `users:(("vite",pid=12345",pid=219072,fd=3))`. Collecting every `pid=`
+ on the line handed that stranger's port to whichever node's tree holds 12345 (pane pids are
+ visible to every user via `ps`), and the forward then served the attacker's page on
+ `localhost:P` — where it receives the cookies of every OTHER localhost dev app (cookies are not
+ port-scoped). Two defences: each `(…)` group is parsed on its own and only its LAST
+ `,pid=N,fd=M` counts (ss cannot print `)` inside a name, so a greedy `[^)]*` cannot be steered
+ past it), and `assembleDevPorts` requires the tool's name for that pid to agree with `ps`'s
+ (prefix-tolerant: Linux comm is 15 bytes, lsof's `c` 9, macOS ps prints the full basename). The
+ `/proc` branch had the same class: GNU `ls -l` prints a NEWLINE in an fd's link target raw, so a
+ target `a\n/proc/100/fd:\nl -> socket:[999]` forged a pid header; it is `ls -lq` now. Both
+ are tested under a real `/bin/sh`, and the ss one also END TO END: a real process outside the
+ pane tree renames itself (`prctl(PR_SET_NAME)`) to name the pane's pid, real `ss` prints the
+ forged group, and the port is not attributed.
+- **The LOCAL scan asks the app's own tmux** (`tmuxBin: ptyManager.getTmuxBin()`, the resolver
+ session memory is given, quoted into the script). A bare `tmux` answered 127 on both sockets for
+ a Mac whose only tmux is the bundled one and for a Linux tmux reachable only on the login-shell
+ PATH (nix, linuxbrew) — `unreachable`, no chip ever — and a different tmux client against the
+ app's server can hit a protocol mismatch. No tmux at all is `unsupported` (plain shells own no
+ pane tree). An SSH host keeps `tmux` via the PATH append.
- **One generated script, run on BOTH machines.** `devPortsProbeCommand` is POSIX sh; a local project
runs it through `/bin/sh -c`, an SSH project over the master — one round trip carrying the panes of
both nodeterm sockets (fenced per socket with the SAME `fencedListPanesCommand`/`parseFencedPanes`
@@ -5212,7 +5234,9 @@ project's existing ControlMaster, so the URL the tool itself printed just works
debounced trailing scan 4 s after the project's agents report activity (`onHookEvent` — a dev
server is usually an agent's tool call); a slow poll (30 s local, 60 s SSH) ONLY while the window is
focused and visible — a server started by hand in a plain terminal fires no hook; and on demand when
- the chip's menu opens. Automatic scans keep a 10 s gap; concurrent ones coalesce in core. An SSH
+ the chip's menu opens. **Both automatic triggers — the hook lull AND the poll — check "someone is
+ watching" at fire time**; the hook one did not at first, so every agent turn in a backgrounded
+ window cost an exec on the host (`ps` + `ss -p` across every process's fds as root). Automatic scans keep a 10 s gap; concurrent ones coalesce in core. An SSH
project is scanned only while connected. One scan costs one `ps` plus one `ss` (a few lines) — an
exec over the master on a host, never a login.
- **Forwarding rules — each a refusal, never a guess** (`PortForwardRegistry`):
@@ -5222,17 +5246,34 @@ project's existing ControlMaster, so the URL the tool itself printed just works
address), because a server bound only to `::1` refuses `127.0.0.1`. The target is re-validated as
an IP literal — it came off another machine's command output and lands in an ssh argument.
- The local side binds `127.0.0.1` ONLY (`localForwardArgs`), never `*`: an unfinished app must not
- be published to the network the laptop is on.
+ be published to the network the laptop is on. `localFwdSpec` re-validates both ports and the
+ target at the argv site (rule 13) and throws, which the registry reports as a failed forward.
+ An IPv4-mapped bind (`::ffff:127.0.0.1`) is normalized to its IPv4 address first — it used to
+ make `forwardTarget` answer null, reported as a misleading SSH refusal (now its own
+ `unreachable-address`).
- **A taken local port is refused with the reason, never silently moved.** "Taken" means anything
answers on `127.0.0.1:P` OR `[::1]:P`, or 127.0.0.1 cannot be bound: a local app bound only to
`::1` leaves 127.0.0.1 free, the forward would succeed, and the browser's `localhost` (IPv6 first)
would show the LOCAL app under the host's name. A different local port is only ever the person's
explicit choice (a confirm naming a suggested free port, and saying the tool's printed links will
- not reach it).
+ not reach it). The facts are two connects and one bind, ordered by the pure `localPortVerdict`:
+ an answer on `::1` is busy; a bind refused with EACCES/EPERM is `local-port-denied` (a confirmed
+ privileged port on Linux as non-root — "already in use" was a lie), with a free unprivileged port
+ offered; a bind refused as IN USE may be OUR OWN master's listener — after an app crash the
+ adopted ControlPersist orphan keeps its forwards while the registry starts empty — so the
+ identical forward is re-issued: the holding master acknowledges it with 0 (measured) and it is
+ re-adopted, anything else answers 255 and it stays busy; a v4 answer we could still bind beside
+ (BSD wildcard + SO_REUSEADDR) is busy, never shadowed.
- A privileged port (< 1024, either side) is never forwarded until the person confirms it.
- Lifecycle: cancelled (`-O cancel` with the exact spec) when the node's session ends
(`PtyManager.onSessionEnded` — delete and recycle) or when a SUCCESSFUL scan no longer lists the
- host port; dropped without ssh when the project leaves `connected` (the master takes its
+ host port UNDER THE NODE THAT OWNS THE FORWARD (the same number under another node is not the
+ server the person opened). The renderer scans only the project on screen, so core re-checks on
+ its own: a sweep (`FORWARD_SWEEP_MS`, 60 s) armed ONLY while a forward is held re-scans each
+ forwarding project, skipping one reconciled within the interval — without it, a project switched
+ away from or closed (neither disconnects) kept its forwards bound after the dev server died, the
+ local port stayed taken (a local dev server silently moved to P+1), and whatever later bound the
+ host's P got the traffic; dropped without ssh when the project leaves `connected` (the master takes its
listeners with it). A failed scan cancels nothing — a failed read is never evidence. A master
rebuilt behind our back by `ControlMaster=auto` (issue #735's mechanism) carries no `-L`, so every
successful scan re-checks that the local listener is still held and forgets one that is not — the
@@ -5259,7 +5300,8 @@ project's existing ControlMaster, so the URL the tool itself printed just works
beside the node. **Mobile: follow-up** — the phone would need the port list over the relay and a
forward of its own (it has no local browser node); noted for nodeterm-ios. All three channels are
in `HOST_ONLY_CHANNELS` (a forward binds a port on the host machine's loopback).
-- **Known limits, stated:** a server that DAEMONIZES (double-fork, reparented to init) leaves the
+- **Known limits, stated:** a re-adopted orphan forward (above) is only re-claimed when the person
+ opens that port again; until then the chip does not show it as forwarded. A server that DAEMONIZES (double-fork, reparented to init) leaves the
pane tree and is not found; `ss` without `-p` information for our own processes (hidepid, a
container) finds listeners but no owner, so nothing is attributed; the Mac leg (lsof, the local
bind/connect probes under BSD socket rules) has not been run on a Mac — device checklist in the PR.
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index d03ca239e..b5b8f3909 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -206,7 +206,9 @@ anything else. Board-level fields survive every transform — `pullLinks` is one
(`core/remote-ssh/port-forward.ts`) binds `127.0.0.1` only, keeps the same port number or
refuses with the reason — a different local port is only ever the person's explicit choice — and
never forwards a port below 1024 unasked. The renderer passes a node and a port, never an address:
- core re-scans and decides the host-side target. See CLAUDE.md → Dev-server ports.
+ core re-scans and decides the host-side target. Treat `ss`/`lsof`/`ls` output as attacker-
+ influenced text: a process name is chosen by the process, so parse each owner group on its own and
+ never let a name reach a pid (see CLAUDE.md → Dev-server ports).
- **A GitHub issue reaches a pane only as a validated reference.** Issue titles and bodies are
written by strangers on public repositories, and a launch line is typed into a shell. Anything
diff --git a/src/core/dev-ports-service.test.ts b/src/core/dev-ports-service.test.ts
index bb163bf3f..ae15e70d6 100644
--- a/src/core/dev-ports-service.test.ts
+++ b/src/core/dev-ports-service.test.ts
@@ -41,7 +41,7 @@ describe('startDevPortsService', () => {
it('a local project is scanned on this machine', async () => {
const local = vi.fn(async (): Promise<DevPortsReport> => ({ ok: true, nodes: {} }))
const run = vi.fn()
- startDevPortsService({ local, remote: { isRemoteProject: () => false, run } })
+ startDevPortsService({ tmuxBin: () => null, local, remote: { isRemoteProject: () => false, run } })
await scan({ projectId: 'p' })
expect(local).toHaveBeenCalledTimes(1)
expect(run).not.toHaveBeenCalled()
@@ -50,7 +50,7 @@ describe('startDevPortsService', () => {
it('an SSH project is scanned on its host — by identity OR by the renderer\'s claim — never locally', async () => {
const local = vi.fn(async (): Promise<DevPortsReport> => ({ ok: true, nodes: { x: [] } }))
const run = vi.fn(async () => REPLY)
- startDevPortsService({ local, remote: { isRemoteProject: (id) => id === 'ssh', run } })
+ startDevPortsService({ tmuxBin: () => null, local, remote: { isRemoteProject: (id) => id === 'ssh', run } })
expect((await scan({ projectId: 'ssh' })).nodes.web[0].port).toBe(5173)
expect((await scan({ projectId: 'other', remote: true })).ok).toBe(true)
expect(local).not.toHaveBeenCalled()
@@ -58,12 +58,12 @@ describe('startDevPortsService', () => {
it('a dead master is unreachable, and with no runner a remote scope is refused, never local', async () => {
const local = vi.fn(async (): Promise<DevPortsReport> => ({ ok: true, nodes: {} }))
- startDevPortsService({ local, remote: { isRemoteProject: () => true, run: async () => null } })
+ startDevPortsService({ tmuxBin: () => null, local, remote: { isRemoteProject: () => true, run: async () => null } })
expect((await scan({ projectId: 'ssh' })).reason).toBe('unreachable')
resetPlatformForTests()
platform = fakePlatform()
initPlatform(platform)
- startDevPortsService({ local, remote: { isRemoteProject: () => true } })
+ startDevPortsService({ tmuxBin: () => null, local, remote: { isRemoteProject: () => true } })
expect((await scan({ projectId: 'ssh' })).reason).toBe('unsupported')
expect(local).not.toHaveBeenCalled()
})
@@ -75,13 +75,13 @@ describe('startDevPortsService', () => {
await new Promise((r) => setTimeout(r, 5))
return REPLY
})
- startDevPortsService({ remote: { isRemoteProject: () => true, run } })
+ startDevPortsService({ tmuxBin: () => null, remote: { isRemoteProject: () => true, run } })
await Promise.all([scan({ projectId: 'ssh' }), scan({ projectId: 'ssh' })])
expect(calls).toBe(1)
})
it('forwarding is refused for a local project, and when no registry is wired', async () => {
- startDevPortsService({
+ startDevPortsService({ tmuxBin: () => null,
remote: {
isRemoteProject: (id) => id === 'ssh',
run: async () => REPLY,
@@ -92,14 +92,14 @@ describe('startDevPortsService', () => {
resetPlatformForTests()
platform = fakePlatform()
initPlatform(platform)
- startDevPortsService({ remote: { isRemoteProject: () => true, run: async () => REPLY } })
+ startDevPortsService({ tmuxBin: () => null, remote: { isRemoteProject: () => true, run: async () => REPLY } })
expect(await fwd({ projectId: 'ssh', nodeId: 'web', port: 5173 })).toMatchObject({ ok: false, reason: 'unsupported' })
})
it('an SSH scan reports the forwards the registry holds, and reconciles them', async () => {
const sshRun = vi.fn(async (_args: string[]) => ({ code: 0, stdout: "" }))
const held = new Set<number>()
- startDevPortsService({
+ startDevPortsService({ tmuxBin: () => null,
remote: {
isRemoteProject: () => true,
run: async () => REPLY,
@@ -109,7 +109,7 @@ describe('startDevPortsService', () => {
held.add(5173)
return sshRun(args)
},
- localPortBusy: async () => false,
+ localPortState: async () => ({ v4Answers: false, v6Answers: false, bind: 'ok' as const }),
localPortHeld: async (p) => held.has(p)
}
}
diff --git a/src/core/dev-ports-service.ts b/src/core/dev-ports-service.ts
index ba54ce2c3..b2dab3569 100644
--- a/src/core/dev-ports-service.ts
+++ b/src/core/dev-ports-service.ts
@@ -17,13 +17,15 @@ import type {
} from '../shared/dev-ports'
import { collectLocalDevPorts, fetchRemoteDevPorts, type RemoteDevPortsRunner } from './dev-ports'
import {
- defaultLocalPortBusy,
+ defaultLocalPortState,
defaultLocalPortHeld,
PortForwardRegistry,
type PortForwardDeps
} from './remote-ssh/port-forward'
export interface DevPortsServiceOptions {
+ /** The app's tmux binary for the LOCAL scan — the same resolver session memory is given. */
+ tmuxBin: () => string | null
/** This machine's scan. Injectable for tests. */
local?: () => Promise<DevPortsReport>
remote?: {
@@ -32,13 +34,13 @@ export interface DevPortsServiceOptions {
run?: RemoteDevPortsRunner
/** Present ⇒ same-port forwarding is offered for SSH projects. */
forward?: Pick<PortForwardDeps, 'refForProject' | 'run'> &
- Partial<Pick<PortForwardDeps, 'localPortBusy' | 'localPortHeld'>>
+ Partial<Pick<PortForwardDeps, 'localPortState' | 'localPortHeld'>>
}
}
const unsupported = (): DevPortsReport => ({ ok: false, reason: 'unsupported', nodes: {} })
-export function startDevPortsService(opts: DevPortsServiceOptions = {}): {
+export function startDevPortsService(opts: DevPortsServiceOptions): {
registry: PortForwardRegistry | null
dispose(): void
} {
@@ -64,7 +66,7 @@ export function startDevPortsService(opts: DevPortsServiceOptions = {}): {
refForProject: fwd.refForProject,
run: fwd.run,
scan: scanRemote,
- localPortBusy: fwd.localPortBusy ?? defaultLocalPortBusy,
+ localPortState: fwd.localPortState ?? defaultLocalPortState,
localPortHeld: fwd.localPortHeld ?? defaultLocalPortHeld
})
: null
@@ -79,7 +81,7 @@ export function startDevPortsService(opts: DevPortsServiceOptions = {}): {
await registry.reconcile(query.projectId, report)
return { ...report, forwards: registry.list(query.projectId) }
}
- return (opts.local ?? (() => collectLocalDevPorts()))()
+ return (opts.local ?? (() => collectLocalDevPorts({ tmuxBin: opts.tmuxBin })))()
})
platform().handle(
@@ -111,5 +113,5 @@ export function startDevPortsService(opts: DevPortsServiceOptions = {}): {
}
)
- return { registry, dispose: (): void => {} }
+ return { registry, dispose: (): void => registry?.dispose() }
}
diff --git a/src/core/dev-ports.realsh.test.ts b/src/core/dev-ports.realsh.test.ts
index 06e1ca425..559139e91 100644
--- a/src/core/dev-ports.realsh.test.ts
+++ b/src/core/dev-ports.realsh.test.ts
@@ -87,6 +87,41 @@ EOF`,
expect(r).toEqual({ ok: true, nodes: { web: [{ port: 8080, addresses: ['127.0.0.1'], command: 'node', ephemeral: false }] } })
})
+ it('ss branch: a process NAMED like a group cannot claim a node\'s pid', async () => {
+ // 100 is the web pane's shell; 700 is a stranger's server that renamed itself.
+ const bin = fakeHost({
+ tmux: TMUX,
+ ps: `printf ' 1 0 init\\n 100 1 zsh\\n 700 1 %s\\n' 'x",pid=100'`,
+ ss: `printf '%s\\n' 'LISTEN 0 5 0.0.0.0:8000 0.0.0.0:* users:(("x",pid=100",pid=700,fd=3))'`
+ })
+ expect(parseDevPortsProbe(await probe(bin), SOCKS)).toEqual({ ok: true, nodes: {} })
+ })
+
+ it.skipIf(realSsOnAppendedPath || realLsofOnAppendedPath)(
+ '/proc branch: a newline in an fd target cannot forge a pid header',
+ async () => {
+ const proc = testTmpDir('devports-procq-')
+ fs.mkdirSync(path.join(proc, 'net'))
+ fs.writeFileSync(
+ path.join(proc, 'net/tcp'),
+ ' sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode\n' +
+ ' 0: 00000000:1F40 00000000:0000 0A 00000000:00000000 00:00000000 00000000 65534 0 999 1\n'
+ )
+ // 700 is a stranger (not under any pane); its fd target smuggles a header naming pid 100,
+ // the web pane's shell, followed by a line claiming socket 999.
+ fs.mkdirSync(path.join(proc, '700', 'fd'), { recursive: true })
+ fs.symlinkSync(`a\n${proc}/100/fd:\nl -> socket:[999]`, path.join(proc, '700/fd/4'))
+ fs.symlinkSync('socket:[999]', path.join(proc, '700/fd/3'))
+ const bin = fakeHost({
+ tmux: TMUX,
+ ps: `printf ' 1 0 init\\n 100 1 zsh\\n 700 1 evil\\n'`,
+ cat: 'exec /bin/cat "$@"',
+ ls: 'exec /bin/ls "$@"'
+ })
+ expect(parseDevPortsProbe(await probe(bin, proc), SOCKS)).toEqual({ ok: true, nodes: {} })
+ }
+ )
+
it.skipIf(realSsOnAppendedPath || realLsofOnAppendedPath)('no tool at all says so — never "no ports"', async () => {
const bin = fakeHost({ tmux: TMUX, ps: PS })
expect(parseDevPortsProbe(await probe(bin), SOCKS)).toEqual({ ok: false, reason: 'no-listener-tool', nodes: {} })
@@ -146,4 +181,43 @@ describe.skipIf(!canRunReal)('dev-ports probe end to end (real tmux, real listen
expect(r.nodes.realnode?.map((p) => p.port)).toEqual([Number(port)])
expect(r.nodes.realnode?.[0].addresses).toEqual(['127.0.0.1'])
}, 20_000)
+
+ it.skipIf(!hasTool('ss') || !hasTool('python3'))(
+ 'a REAL process outside the tree, renamed to name the pane\'s pid, is not attributed (real ss)',
+ async () => {
+ const dir = testTmpDir('devports-forge-')
+ const portFile = path.join(dir, 'port')
+ execFileSync('tmux', ['-L', SOCKET, '-f', '/dev/null', 'new-session', '-d', '-s', 'nt-victim', 'sleep 60'])
+ const panePid = execFileSync('tmux', ['-L', SOCKET, 'list-panes', '-t', '=nt-victim', '-F', '#{pane_pid}'], {
+ encoding: 'utf8'
+ }).trim()
+ const name = `x",pid=${panePid}`.slice(0, 15)
+ // A child of the TEST RUNNER — never under the pane — that renames itself and listens.
+ const py = [
+ 'import ctypes,socket,sys,time',
+ `ctypes.CDLL(None).prctl(15, ctypes.c_char_p(${JSON.stringify(name)}.encode()), 0, 0, 0)`,
+ "s=socket.socket(); s.bind(('127.0.0.1',0)); s.listen()",
+ `open(${JSON.stringify(portFile)},'w').write(str(s.getsockname()[1]))`,
+ 'time.sleep(30)'
+ ].join('\n')
+ const child = execFile('python3', ['-c', py])
+ try {
+ let port = ''
+ for (let i = 0; i < 100 && !port; i++) {
+ await new Promise((r) => setTimeout(r, 50))
+ port = fs.existsSync(portFile) ? fs.readFileSync(portFile, 'utf8') : ''
+ }
+ expect(port).not.toBe('')
+ const { stdout } = await run('/bin/sh', ['-c', devPortsProbeCommand({ sockets: [SOCKET] })])
+ // Only meaningful if ss really printed the forged name — assert the precondition.
+ expect(stdout).toContain(`"${name}"`)
+ const r = parseDevPortsProbe(stdout, [SOCKET])
+ expect(r.ok).toBe(true)
+ expect(r.nodes.victim).toBeUndefined()
+ } finally {
+ child.kill()
+ }
+ },
+ 20_000
+ )
})
diff --git a/src/core/dev-ports.test.ts b/src/core/dev-ports.test.ts
index 5a30bae23..b00408e59 100644
--- a/src/core/dev-ports.test.ts
+++ b/src/core/dev-ports.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, it } from 'vitest'
+import { describe, expect, it, vi } from 'vitest'
import {
assembleDevPorts,
collectLocalDevPorts,
@@ -32,6 +32,8 @@ describe('splitHostPort', () => {
expect(splitHostPort(':::8080')).toEqual({ address: '::', port: 8080 })
expect(splitHostPort('*:3000')).toEqual({ address: '*', port: 3000 })
expect(splitHostPort('127.0.0.53%lo:53')).toEqual({ address: '127.0.0.53', port: 53 })
+ // An IPv4-mapped bind is its IPv4 address (it used to make forwardTarget answer null).
+ expect(splitHostPort('[::ffff:127.0.0.1]:5173')).toEqual({ address: '127.0.0.1', port: 5173 })
})
it('refuses a peer column and out-of-range ports', () => {
expect(splitHostPort('0.0.0.0:*')).toBeNull()
@@ -44,22 +46,64 @@ describe('splitHostPort', () => {
describe('parseSsListeners', () => {
it('takes the local address, every owning pid and the command', () => {
const l = parseSsListeners(SS_REAL)
- expect(l[0]).toEqual({ pids: [210], address: '127.0.0.1', port: 5173, command: 'node' })
- expect(l[1]).toEqual({ pids: [210], address: '::1', port: 5173, command: 'node' })
- expect(l[3]).toEqual({ pids: [300, 301], address: '*', port: 3000, command: 'ruby' })
+ expect(l[0]).toEqual({ owners: [{ pid: 210, command: 'node' }], address: '127.0.0.1', port: 5173 })
+ expect(l[1]).toEqual({ owners: [{ pid: 210, command: 'node' }], address: '::1', port: 5173 })
+ expect(l[3]).toEqual({ owners: [{ pid: 300, command: 'ruby' }, { pid: 301, command: 'ruby' }], address: '*', port: 3000 })
// Another user's socket carries no process column: listed, but owned by nobody we know.
- expect(l[4]).toEqual({ pids: [], address: '::', port: 8080, command: '' })
+ expect(l[4]).toEqual({ owners: [], address: '::', port: 8080 })
expect(l).toHaveLength(6)
})
})
+describe('parseSsListeners — the owner column is attacker-influenced', () => {
+ // Reproduced (review of #1063): a process owned by `nobody` renamed itself `vite",pid=12345` and
+ // ss printed its name raw. Collecting every `pid=` on the line handed the port to pid 12345.
+ const forged = 'LISTEN 0 5 0.0.0.0:8000 0.0.0.0:* users:(("vite",pid=12345",pid=219072,fd=3))'
+ it('takes only the LAST pid of a group, and keeps the forged text as the name', () => {
+ expect(parseSsListeners(forged)[0].owners).toEqual([{ pid: 219072, command: 'vite",pid=12345' }])
+ })
+ it('never attributes the forged port to the node whose tree holds the named pid', () => {
+ const out = assembleDevPorts(
+ [{ session: 'nt-a', panePid: 12345, command: 'zsh' }],
+ [
+ { pid: 12345, ppid: 1, command: 'zsh' },
+ { pid: 219072, ppid: 1, command: 'vite",pid=12345' }
+ ],
+ parseSsListeners(forged)
+ )
+ expect(out).toEqual({})
+ })
+ it('a pid whose ps name disagrees with the tool\'s name is not trusted', () => {
+ const out = assembleDevPorts(
+ [{ session: 'nt-a', panePid: 100, command: 'zsh' }],
+ [
+ { pid: 100, ppid: 1, command: 'zsh' },
+ { pid: 101, ppid: 100, command: 'node' }
+ ],
+ [{ owners: [{ pid: 101, command: 'postgres' }], address: '127.0.0.1', port: 5432 }]
+ )
+ expect(out).toEqual({})
+ })
+ it('truncated names still agree (lsof prints 9 chars, macOS ps the full basename)', () => {
+ const out = assembleDevPorts(
+ [{ session: 'nt-a', panePid: 100, command: 'zsh' }],
+ [
+ { pid: 100, ppid: 1, command: 'zsh' },
+ { pid: 101, ppid: 100, command: 'com.docker.backend' }
+ ],
+ [{ owners: [{ pid: 101, command: 'com.docke' }], address: '127.0.0.1', port: 3000 }]
+ )
+ expect(out.a.map((p) => p.port)).toEqual([3000])
+ })
+})
+
describe('parseLsofListeners', () => {
it('groups n-fields under the preceding p/c', () => {
const out = parseLsofListeners('p210\ncnode\nf26\nn127.0.0.1:5173\nf27\nn[::1]:5173\np300\ncruby\nn*:3000\n')
expect(out).toEqual([
- { pids: [210], address: '127.0.0.1', port: 5173, command: 'node' },
- { pids: [210], address: '::1', port: 5173, command: 'node' },
- { pids: [300], address: '*', port: 3000, command: 'ruby' }
+ { owners: [{ pid: 210, command: 'node' }], address: '127.0.0.1', port: 5173 },
+ { owners: [{ pid: 210, command: 'node' }], address: '::1', port: 5173 },
+ { owners: [{ pid: 300, command: 'ruby' }], address: '*', port: 3000 }
])
})
})
@@ -123,10 +167,10 @@ describe('assembleDevPorts — ownership by process tree', () => {
]
it('attributes a descendant listener to its node, merges families, sorts', () => {
const out = assembleDevPorts(panes, procs, [
- { pids: [102], address: '::1', port: 5173, command: '' },
- { pids: [102], address: '127.0.0.1', port: 5173, command: 'node' },
- { pids: [102], address: '127.0.0.1', port: 4000, command: 'node' },
- { pids: [102], address: '127.0.0.1', port: 40001, command: 'node' }
+ { owners: [{ pid: 102, command: '' }], address: '::1', port: 5173 },
+ { owners: [{ pid: 102, command: 'node' }], address: '127.0.0.1', port: 5173 },
+ { owners: [{ pid: 102, command: 'node' }], address: '127.0.0.1', port: 4000 },
+ { owners: [{ pid: 102, command: 'node' }], address: '127.0.0.1', port: 40001 }
])
expect(out).toEqual({
a: [
@@ -138,14 +182,14 @@ describe('assembleDevPorts — ownership by process tree', () => {
})
it('never reports a port owned outside every nt- pane tree', () => {
const out = assembleDevPorts(panes, procs, [
- { pids: [500], address: '0.0.0.0', port: 5432, command: 'postgres' },
- { pids: [901], address: '0.0.0.0', port: 8000, command: 'python3' },
- { pids: [], address: '::', port: 8080, command: '' }
+ { owners: [{ pid: 500, command: 'postgres' }], address: '0.0.0.0', port: 5432 },
+ { owners: [{ pid: 901, command: 'python3' }], address: '0.0.0.0', port: 8000 },
+ { owners: [], address: '::', port: 8080 }
])
expect(out).toEqual({})
})
it('takes the command from ps when the listener tool did not name it', () => {
- const out = assembleDevPorts(panes, procs, [{ pids: [102], address: '127.0.0.1', port: 3000, command: '' }])
+ const out = assembleDevPorts(panes, procs, [{ owners: [{ pid: 102, command: '' }], address: '127.0.0.1', port: 3000 }])
expect(out.a[0].command).toBe('node')
})
it('survives a cyclic ppid chain', () => {
@@ -154,7 +198,7 @@ describe('assembleDevPorts — ownership by process tree', () => {
{ pid: 101, ppid: 100, command: 'node' }
]
const out = assembleDevPorts([{ session: 'nt-a', panePid: 100, command: 'zsh' }], cyclic, [
- { pids: [101], address: '127.0.0.1', port: 3000, command: 'node' }
+ { owners: [{ pid: 101, command: 'node' }], address: '127.0.0.1', port: 3000 }
])
expect(out.a.map((p) => p.port)).toEqual([3000])
})
@@ -218,8 +262,34 @@ describe('forwardTarget', () => {
describe('runners', () => {
it('local: Windows is unsupported, a throwing exec is unreachable', async () => {
- expect(await collectLocalDevPorts(async () => '', 'win32')).toEqual({ ok: false, reason: 'unsupported', nodes: {} })
- expect((await collectLocalDevPorts(async () => { throw new Error('x') }, 'linux')).reason).toBe('unreachable')
+ const tmuxBin = (): string => '/usr/bin/tmux'
+ expect(await collectLocalDevPorts({ tmuxBin, exec: async () => '', platformName: 'win32' })).toEqual({
+ ok: false,
+ reason: 'unsupported',
+ nodes: {}
+ })
+ const exec = async (): Promise<string> => {
+ throw new Error('x')
+ }
+ expect((await collectLocalDevPorts({ tmuxBin, exec, platformName: 'linux' })).reason).toBe('unreachable')
+ })
+
+ it("local: asks the APP's tmux by absolute path, quoted — never whatever `tmux` is on PATH", async () => {
+ // A Mac whose only tmux is the bundled one has none on PATH; a bare `tmux` answered 127 twice.
+ let seen = ''
+ await collectLocalDevPorts({
+ tmuxBin: () => "/Applications/node term.app/Contents/Resources/tmux/bin/tm'ux",
+ exec: async (cmd) => ((seen = cmd), ''),
+ platformName: 'darwin'
+ })
+ expect(seen).toContain(`'/Applications/node term.app/Contents/Resources/tmux/bin/tm'\\''ux' -L node-terminal list-panes`)
+ expect(seen).not.toMatch(/^tmux -L/m)
+ })
+
+ it('local: no tmux at all is unsupported (plain shells own no pane tree)', async () => {
+ const exec = vi.fn(async () => '')
+ expect((await collectLocalDevPorts({ tmuxBin: () => null, exec, platformName: 'linux' })).reason).toBe('unsupported')
+ expect(exec).not.toHaveBeenCalled()
})
it('remote: a null (dead master) is unreachable, never empty', async () => {
expect(await fetchRemoteDevPorts('p', async () => null)).toEqual({ ok: false, reason: 'unreachable', nodes: {} })
diff --git a/src/core/dev-ports.ts b/src/core/dev-ports.ts
index d654c7607..099bb1be0 100644
--- a/src/core/dev-ports.ts
+++ b/src/core/dev-ports.ts
@@ -22,6 +22,7 @@ import { execFile } from 'child_process'
import { promisify } from 'util'
import { DEV_PORT_EPHEMERAL_MIN, type DevPort, type DevPortsReport } from '../shared/dev-ports'
import { REMOTE_TMUX_PATH_DIRS } from '../shared/ssh'
+import { shellSingleQuote } from '../shared/shell-quote'
import { indexProcesses, type PaneRef } from './session-memory'
import { fencedListPanesCommand, parseFencedPanes } from './session-memory-remote'
import { TMUX_SOCKET } from './tmux-naming'
@@ -45,6 +46,15 @@ export interface DevPortsProbeOptions {
sockets?: readonly string[]
/** Root of the proc filesystem for the last-resort branch. Tests point it at a fake tree. */
procRoot?: string
+ /**
+ * An absolute tmux binary to ask. The LOCAL leg passes the app's own (`PtyManager.getTmuxBin()`,
+ * the same one session memory is given): a Mac whose only tmux is the bundled one, or a Linux
+ * box whose tmux is only on the login-shell PATH (nix, linuxbrew), has NO `tmux` on this
+ * process's PATH, so a bare `tmux` answered 127 on both sockets and the chip never appeared —
+ * and a different tmux CLIENT against the app's server can hit a protocol mismatch. Omitted on
+ * an SSH host, where the host's own tmux is found through the PATH append.
+ */
+ tmuxBin?: string
}
/**
@@ -60,10 +70,11 @@ export interface DevPortsProbeOptions {
export function devPortsProbeCommand(opts: DevPortsProbeOptions = {}): string {
const sockets = opts.sockets ?? DEV_PORT_SOCKETS
const proc = opts.procRoot ?? '/proc'
+ const tmux = opts.tmuxBin ? shellSingleQuote(opts.tmuxBin) : 'tmux'
return [
`PATH="$PATH:${REMOTE_TMUX_PATH_DIRS}:/usr/sbin:/sbin"`,
`echo '${PANES}'`,
- ...sockets.map(fencedListPanesCommand),
+ ...sockets.map((s) => fencedListPanesCommand(s, tmux)),
`echo '${PROCS}'`,
`ps -eo pid=,ppid=,comm= 2>/dev/null`,
`echo '${LISTEN}'`,
@@ -79,7 +90,10 @@ export function devPortsProbeCommand(opts: DevPortsProbeOptions = {}): string {
` echo '##VIA proc'`,
` cat '${proc}/net/tcp' '${proc}/net/tcp6' 2>/dev/null`,
` echo '${FD}'`,
- ` ls -l '${proc}'/[0-9]*/fd 2>/dev/null`,
+ // `-q`: a non-printable in a link target prints as `?`. Without it GNU ls prints a NEWLINE in
+ // an fd's target raw, and a file named `a\n/proc/100/fd:\nl -> socket:[999]` forges a pid
+ // header and hands socket 999 to pid 100 (reproduced).
+ ` ls -lq '${proc}'/[0-9]*/fd 2>/dev/null`,
` echo '##LISTENRC 0'`,
`else`,
` echo '##VIA none'`,
@@ -88,12 +102,18 @@ export function devPortsProbeCommand(opts: DevPortsProbeOptions = {}): string {
].join('\n')
}
-/** One listening socket and the pid(s) that hold it. */
+/** A process holding a listening socket, with the name the listener tool printed for it ('' when
+ * the tool names none — the /proc branch). */
+export interface SocketOwner {
+ pid: number
+ command: string
+}
+
+/** One listening socket and the process(es) that hold it. */
export interface Listener {
- pids: number[]
+ owners: SocketOwner[]
address: string
port: number
- command: string
}
export interface ProcRow {
@@ -131,12 +151,29 @@ export function splitHostPort(token: string): { address: string; port: number }
const pct = address.indexOf('%')
if (pct >= 0) address = address.slice(0, pct)
if (address === '::' || address === '') address = '::'
+ // An IPv4-mapped bind (`::ffff:127.0.0.1`) IS its IPv4 address — the /proc decoder already says
+ // so, and leaving it mapped made `forwardTarget` answer null for an ordinary loopback server.
+ const mapped = /^::ffff:(\d{1,3}(?:\.\d{1,3}){3})$/i.exec(address)
+ if (mapped) address = mapped[1]
return { address, port }
}
-/** `ss -ltnp`. The local address is the first `addr:port` token with a numeric port — the peer
- * column (`0.0.0.0:*`) never has one, which also makes this indifferent to whether the installed
- * ss prints a State column. */
+/**
+ * `ss -ltnp`. The local address is the first `addr:port` token with a numeric port — the peer
+ * column (`0.0.0.0:*`) never has one, which also makes this indifferent to whether the installed
+ * ss prints a State column.
+ *
+ * **The owner column is attacker-influenced text.** ss prints each holder as
+ * `("<name>",pid=N,fd=M)` with the process NAME raw — any process can rename itself (15 bytes of
+ * comm), and a name of `vite",pid=12345` printed `users:(("vite",pid=12345",pid=219072,fd=3))`
+ * (reproduced as root against a listener owned by `nobody`). Collecting every `pid=N` on the line
+ * handed that stranger's port to whichever node's tree holds 12345 — pane pids are visible to every
+ * user through `ps` — and the forward then served the attacker's page on `localhost`, where it
+ * reads the cookies of every other localhost dev app. So each group is parsed on its own and only
+ * the LAST `,pid=N,fd=M` before its closing `)` is the pid: ss cannot print `)` inside a name
+ * (it would end the group), so a greedy `[^)]*` cannot be steered past it. `assembleDevPorts`
+ * then cross-checks that name against `ps` for that pid.
+ */
export function parseSsListeners(text: string): Listener[] {
const out: Listener[] = []
for (const line of text.split('\n')) {
@@ -146,9 +183,11 @@ export function parseSsListeners(text: string): Listener[] {
if (hp) break
}
if (!hp) continue
- const pids = [...line.matchAll(/pid=(\d+)/g)].map((m) => Number(m[1]))
- const command = /\(\("([^"]*)",pid=/.exec(line)?.[1] ?? ''
- out.push({ pids, ...hp, command })
+ const owners: SocketOwner[] = []
+ for (const group of line.matchAll(/\("([^)]*)",pid=(\d+),fd=\d+\)/g)) {
+ owners.push({ pid: Number(group[2]), command: group[1] })
+ }
+ out.push({ owners, ...hp })
}
return out
}
@@ -170,7 +209,7 @@ export function parseLsofListeners(text: string): Listener[] {
// An established connection prints `a->b`; LISTEN never does, but be explicit.
if (val.includes('->')) continue
const hp = splitHostPort(val)
- if (hp) out.push({ pids: [pid], ...hp, command })
+ if (hp) out.push({ owners: [{ pid, command }], ...hp })
}
}
return out
@@ -249,6 +288,19 @@ export function parseProcFdSockets(text: string): Map<string, number[]> {
return out
}
+/**
+ * Does the name a listener tool printed for a pid agree with `ps`'s name for it? Defence in depth
+ * behind the per-group ss parse: a pid the tool attributes must be a process `ps` knows by that
+ * name. Prefix-tolerant, because the tools truncate differently (Linux comm is 15 bytes, lsof's
+ * default `c` field 9, macOS ps prints the full basename). A tool that names nothing ('' — the
+ * /proc branch, where the pid comes from the kernel's fd table) is not checked.
+ */
+function namesAgree(toolName: string, psName: string | undefined): boolean {
+ if (!toolName) return true
+ if (psName === undefined || psName === '') return false
+ return psName.startsWith(toolName) || toolName.startsWith(psName)
+}
+
/** `node id → ports`, from the three facts. Pure. */
export function assembleDevPorts(
panes: readonly PaneRef[],
@@ -274,8 +326,9 @@ export function assembleDevPorts(
}
const byNode = new Map<string, Map<number, DevPort>>()
for (const l of listeners) {
- const pid = l.pids.find((p) => owner.has(p))
- if (pid === undefined) continue
+ const holder = l.owners.find((o) => owner.has(o.pid) && namesAgree(o.command, commandOf.get(o.pid)))
+ if (holder === undefined) continue
+ const pid = holder.pid
const nodeId = owner.get(pid) as string
let ports = byNode.get(nodeId)
if (!ports) byNode.set(nodeId, (ports = new Map()))
@@ -287,7 +340,7 @@ export function assembleDevPorts(
ports.set(l.port, {
port: l.port,
addresses: [l.address],
- command: l.command || commandOf.get(pid) || '',
+ command: holder.command || commandOf.get(pid) || '',
ephemeral: l.port >= DEV_PORT_EPHEMERAL_MIN
})
}
@@ -342,7 +395,9 @@ export function parseDevPortsProbe(stdout: string, sockets: readonly string[] =
const sockets4 = parseProcNetTcp(bodyLines.slice(0, fdAt).join('\n'))
const owners = parseProcFdSockets(bodyLines.slice(fdAt + 1).join('\n'))
listeners = []
- for (const [inode, hp] of sockets4) listeners.push({ pids: owners.get(inode) ?? [], ...hp, command: '' })
+ for (const [inode, hp] of sockets4) {
+ listeners.push({ owners: (owners.get(inode) ?? []).map((pid) => ({ pid, command: '' })), ...hp })
+ }
} else {
return fail('unreachable')
}
@@ -370,17 +425,29 @@ export function forwardTarget(addresses: readonly string[]): string | null {
return specific ?? null
}
+export interface LocalDevPortsOptions {
+ /** The app's tmux (`PtyManager.getTmuxBin()`); null = no tmux, so there is no pane tree at all. */
+ tmuxBin: () => string | null
+ exec?: (command: string) => Promise<string>
+ platformName?: NodeJS.Platform
+}
+
/** Runs the probe on this machine. Windows has no `/bin/sh` and no tmux: honestly unsupported. */
-export async function collectLocalDevPorts(
- exec: (command: string) => Promise<string> = async (command) => {
- const { stdout } = await runAsync('/bin/sh', ['-c', command], { timeout: 15_000, maxBuffer: 16 * 1024 * 1024 })
- return stdout
- },
- platformName: NodeJS.Platform = process.platform
-): Promise<DevPortsReport> {
+export async function collectLocalDevPorts(opts: LocalDevPortsOptions): Promise<DevPortsReport> {
+ const platformName = opts.platformName ?? process.platform
if (platformName === 'win32') return fail('unsupported')
+ // No tmux means every terminal is a plain shell (PtyManager's fallback): no nt- pane tree exists
+ // to own a port. Unsupported for this run rather than a "could not look" asked every 30 s.
+ const tmuxBin = opts.tmuxBin()
+ if (!tmuxBin) return fail('unsupported')
+ const exec =
+ opts.exec ??
+ (async (command: string): Promise<string> => {
+ const { stdout } = await runAsync('/bin/sh', ['-c', command], { timeout: 15_000, maxBuffer: 16 * 1024 * 1024 })
+ return stdout
+ })
try {
- return parseDevPortsProbe(await exec(devPortsProbeCommand()))
+ return parseDevPortsProbe(await exec(devPortsProbeCommand({ tmuxBin })))
} catch {
return fail('unreachable')
}
diff --git a/src/core/remote-ssh/control-master.ts b/src/core/remote-ssh/control-master.ts
index 6ff3956c2..3315ece8d 100644
--- a/src/core/remote-ssh/control-master.ts
+++ b/src/core/remote-ssh/control-master.ts
@@ -778,6 +778,12 @@ export function hookForwardCancelArgs(conn: SshConnection, controlPath: string,
* `toAddr` must already be a validated IP literal (core/dev-ports.ts `forwardTarget`).
*/
function localFwdSpec(localPort: number, toAddr: string, remotePort: number): string {
+ // Re-validated HERE, at the argv site (CLAUDE.md rule 13), not only by the caller: the address
+ // came off another machine's command output. A throw is caught by the registry as a failed
+ // forward, never an ssh argument.
+ const okPort = (n: number): boolean => Number.isInteger(n) && n >= 1 && n <= 65535
+ const okAddr = /^\d{1,3}(\.\d{1,3}){3}$/.test(toAddr) || (/^[0-9A-Fa-f:]+$/.test(toAddr) && toAddr.includes(':'))
+ if (!okPort(localPort) || !okPort(remotePort) || !okAddr) throw new Error('invalid forward spec')
const host = toAddr.includes(':') ? `[${toAddr}]` : toAddr
return `127.0.0.1:${localPort}:${host}:${remotePort}`
}
diff --git a/src/core/remote-ssh/port-forward.test.ts b/src/core/remote-ssh/port-forward.test.ts
index aa0a53748..50180f8ee 100644
--- a/src/core/remote-ssh/port-forward.test.ts
+++ b/src/core/remote-ssh/port-forward.test.ts
@@ -1,9 +1,15 @@
-import { afterEach, describe, expect, it } from 'vitest'
+import { afterEach, describe, expect, it, vi } from 'vitest'
import net from 'net'
import type { DevPortsReport } from '../../shared/dev-ports'
import type { SshConnection } from '../../shared/ssh'
import { localForwardArgs, localForwardCancelArgs } from './control-master'
-import { canBind, canConnect, defaultLocalPortBusy, PortForwardRegistry, type PortForwardDeps } from './port-forward'
+import { canBind, canConnect, defaultLocalPortBusy, localPortVerdict, PortForwardRegistry, type PortForwardDeps } from './port-forward'
+
+const registries: PortForwardRegistry[] = []
+afterEach(() => {
+ for (const r of registries.splice(0)) r.dispose()
+ vi.useRealTimers()
+})
const conn: SshConnection = { host: 'box', user: 'me', port: 2222 }
const CP = '/tmp/cp.sock'
@@ -17,29 +23,49 @@ const vite = (addresses = ['127.0.0.1']): DevPortsReport['nodes'] => ({
function harness(over: Partial<PortForwardDeps> & { scanResult?: DevPortsReport } = {}) {
const calls: string[][] = []
+ /** Held by some OTHER local process on 127.0.0.1. */
const busy = new Set<number>()
+ /** Something listens on [::1] only. */
+ const v6 = new Set<number>()
+ /** Binding needs rights we do not have. */
+ const denied = new Set<number>()
+ /** Held by the project's master (ours, or an adopted orphan's). */
const held = new Set<number>()
let connected = true
let scanResult = over.scanResult ?? report(vite())
+ const scans: string[] = []
const deps: PortForwardDeps = {
refForProject: (id) => (connected && id === 'p' ? { conn, controlPath: CP } : undefined),
run: async (args) => {
calls.push(args)
const i = args.indexOf('-L')
const local = Number(args[i + 1].split(':')[1])
- if (args[1] === 'forward') held.add(local)
- else held.delete(local)
+ if (args[1] === 'forward') {
+ // Measured: the holding master acknowledges an identical forward with 0; a port another
+ // process holds fails the bind with 255.
+ if (busy.has(local) || denied.has(local)) return { code: 255, stdout: '' }
+ held.add(local)
+ } else held.delete(local)
return { code: 0, stdout: '' }
},
- scan: async () => scanResult,
- localPortBusy: async (p) => busy.has(p) || held.has(p),
+ scan: async (id) => (scans.push(id), scanResult),
+ localPortState: async (p) => ({
+ v4Answers: busy.has(p) || held.has(p),
+ v6Answers: v6.has(p),
+ bind: denied.has(p) ? 'denied' : busy.has(p) || held.has(p) ? 'in-use' : 'ok'
+ }),
localPortHeld: async (p) => held.has(p),
...over
}
+ const reg = new PortForwardRegistry(deps)
+ registries.push(reg)
return {
- reg: new PortForwardRegistry(deps),
+ reg,
+ scans,
calls,
busy,
+ v6,
+ denied,
held,
setScan: (r: DevPortsReport) => (scanResult = r),
disconnect: () => (connected = false)
@@ -104,7 +130,10 @@ describe('PortForwardRegistry.forward', () => {
h.busy.add(5174)
const r = await h.reg.forward({ projectId: 'p', nodeId: 'web', port: 5173 })
expect(r).toMatchObject({ ok: false, reason: 'local-port-busy', suggestedLocalPort: 5175 })
- expect(h.calls).toHaveLength(0)
+ // The only ssh call is the identical re-claim, which the master refused (someone else holds it).
+ expect(h.calls).toHaveLength(1)
+ expect(h.reg.list('p')).toEqual([])
+ h.calls.length = 0
// The explicit choice is honoured.
const chosen = await h.reg.forward({ projectId: 'p', nodeId: 'web', port: 5173, localPort: 5175 })
expect(chosen).toMatchObject({ ok: true, localPort: 5175, url: 'http://localhost:5175' })
@@ -136,6 +165,56 @@ describe('PortForwardRegistry.forward', () => {
})
})
+describe('PortForwardRegistry — local port facts (review nits)', () => {
+ it('re-claims a forward an adopted orphan master still holds, instead of "port in use"', async () => {
+ const h = harness()
+ h.held.add(5173) // the master kept it across an app restart; the registry is empty
+ expect(await h.reg.forward({ projectId: 'p', nodeId: 'web', port: 5173 })).toMatchObject({
+ ok: true,
+ localPort: 5173,
+ reused: true
+ })
+ expect(h.reg.list('p')).toEqual([{ nodeId: 'web', remotePort: 5173, localPort: 5173 }])
+ })
+
+ it('a port another process holds stays busy even after the re-claim attempt', async () => {
+ const h = harness()
+ h.busy.add(5173)
+ expect(await h.reg.forward({ projectId: 'p', nodeId: 'web', port: 5173 })).toMatchObject({
+ ok: false,
+ reason: 'local-port-busy',
+ suggestedLocalPort: 5174
+ })
+ expect(h.reg.list('p')).toEqual([])
+ })
+
+ it('a listener on ::1 only is busy — never re-claimed, never forwarded over', async () => {
+ const h = harness()
+ h.v6.add(5173)
+ expect(await h.reg.forward({ projectId: 'p', nodeId: 'web', port: 5173 })).toMatchObject({ reason: 'local-port-busy' })
+ expect(h.calls).toHaveLength(0)
+ })
+
+ it('a privileged local bind this user may not make says so, with an alternative', async () => {
+ const h = harness({ scanResult: report({ web: [{ port: 80, addresses: ['0.0.0.0'], command: 'nginx', ephemeral: false }] }) })
+ h.denied.add(80)
+ const r = await h.reg.forward({ projectId: 'p', nodeId: 'web', port: 80, allowPrivileged: true })
+ expect(r).toMatchObject({ ok: false, reason: 'local-port-denied', suggestedLocalPort: 1024 })
+ expect(h.calls).toHaveLength(0)
+ })
+
+ it('an address that is no IP literal is named as such, not as an SSH refusal', async () => {
+ const h = harness({ scanResult: report({ web: [{ port: 5173, addresses: ['localhost'], command: 'node', ephemeral: false }] }) })
+ expect(await h.reg.forward({ projectId: 'p', nodeId: 'web', port: 5173 })).toMatchObject({ reason: 'unreachable-address' })
+ })
+
+ it('the argv builder itself refuses a bad spec (validated at the interpolation site)', () => {
+ expect(() => localForwardArgs(conn, CP, 5173, '-oProxyCommand=x', 5173)).toThrow()
+ expect(() => localForwardArgs(conn, CP, 0, '127.0.0.1', 5173)).toThrow()
+ expect(() => localForwardCancelArgs(conn, CP, 5173, '127.0.0.1', 70000)).toThrow()
+ })
+})
+
describe('PortForwardRegistry lifecycle', () => {
it('cancels when a successful scan no longer lists the host port; a FAILED scan cancels nothing', async () => {
const h = harness()
@@ -185,6 +264,48 @@ describe('PortForwardRegistry lifecycle', () => {
})
})
+describe('PortForwardRegistry sweep — forwards of projects NOT on screen', () => {
+ it('cancels a forward on its own once the owning node stops listening, even if nothing scans it', async () => {
+ vi.useFakeTimers()
+ const h = harness()
+ await h.reg.forward({ projectId: 'p', nodeId: 'web', port: 5173 })
+ h.setScan(report({}))
+ await vi.advanceTimersByTimeAsync(60_000)
+ expect(h.reg.list('p')).toEqual([])
+ expect(h.calls.at(-1)?.[1]).toBe('cancel')
+ })
+
+ it('is disarmed while nothing is held — no scan runs on a timer then', async () => {
+ vi.useFakeTimers()
+ const h = harness()
+ await vi.advanceTimersByTimeAsync(180_000)
+ expect(h.scans).toEqual([])
+ await h.reg.forward({ projectId: 'p', nodeId: 'web', port: 5173 })
+ await h.reg.unforward('p', 5173)
+ const before = h.scans.length
+ await vi.advanceTimersByTimeAsync(180_000)
+ expect(h.scans.length).toBe(before)
+ })
+
+ it('skips a project the renderer reconciled within the interval', async () => {
+ vi.useFakeTimers()
+ const h = harness()
+ await h.reg.forward({ projectId: 'p', nodeId: 'web', port: 5173 })
+ await vi.advanceTimersByTimeAsync(59_000)
+ await h.reg.reconcile('p', report(vite()))
+ const before = h.scans.length
+ await vi.advanceTimersByTimeAsync(1_000)
+ expect(h.scans.length).toBe(before)
+ })
+
+ it('checks the OWNING node: the same port under another node is not the server that was opened', async () => {
+ const h = harness()
+ await h.reg.forward({ projectId: 'p', nodeId: 'web', port: 5173 })
+ await h.reg.reconcile('p', report({ other: [{ port: 5173, addresses: ['127.0.0.1'], command: 'node', ephemeral: false }] }))
+ expect(h.reg.list('p')).toEqual([])
+ })
+})
+
describe('local port probes (real sockets)', () => {
const servers: net.Server[] = []
afterEach(async () => {
@@ -207,6 +328,14 @@ describe('local port probes (real sockets)', () => {
expect(await defaultLocalPortBusy(port)).toBe(false)
})
+ it('the pure verdict orders the facts: ::1 first, then rights, then in-use, then a v4 answer', () => {
+ expect(localPortVerdict({ v4Answers: false, v6Answers: true, bind: 'in-use' })).toBe('busy')
+ expect(localPortVerdict({ v4Answers: false, v6Answers: false, bind: 'denied' })).toBe('denied')
+ expect(localPortVerdict({ v4Answers: true, v6Answers: false, bind: 'in-use' })).toBe('maybe-ours')
+ expect(localPortVerdict({ v4Answers: true, v6Answers: false, bind: 'ok' })).toBe('busy')
+ expect(localPortVerdict({ v4Answers: false, v6Answers: false, bind: 'ok' })).toBe('free')
+ })
+
it('a listener on ::1 ONLY still makes the port busy (localhost would reach it first)', async () => {
let port: number
try {
diff --git a/src/core/remote-ssh/port-forward.ts b/src/core/remote-ssh/port-forward.ts
index 05ecc087e..e84e817eb 100644
--- a/src/core/remote-ssh/port-forward.ts
+++ b/src/core/remote-ssh/port-forward.ts
@@ -38,12 +38,45 @@ export interface PortForwardDeps {
run(args: string[]): Promise<{ code: number; stdout: string }>
/** A fresh discovery of the project's host (coalesced by the caller). */
scan(projectId: string): Promise<DevPortsReport>
- /** Is anything reachable on this machine's `localhost:<port>`, or is the loopback port unbindable? */
- localPortBusy(port: number): Promise<boolean>
+ /** What this machine's `localhost:<port>` looks like right now (see `localPortVerdict`). */
+ localPortState(port: number): Promise<LocalPortState>
/** Is the loopback listener still there (i.e. can we NOT bind 127.0.0.1:<port>)? */
localPortHeld(port: number): Promise<boolean>
}
+/** The raw facts about a local port, from two connects and one bind. */
+export interface LocalPortState {
+ /** Something answers on 127.0.0.1:<port>. */
+ v4Answers: boolean
+ /** Something answers on [::1]:<port>. */
+ v6Answers: boolean
+ /** Binding 127.0.0.1:<port> ourselves: fine, EADDRINUSE, or EACCES (privileged, no rights). */
+ bind: 'ok' | 'in-use' | 'denied'
+}
+
+export type LocalPortVerdict = 'free' | 'busy' | 'denied' | 'maybe-ours'
+
+/**
+ * Pure. The order is the rule:
+ * - an answer on `::1` is BUSY whatever else is true: a browser's `localhost` tries IPv6 first, so
+ * a forward on 127.0.0.1 would show the local app under the host's name;
+ * - a bind refused for lack of rights is its own answer (the port is not in use — it cannot be
+ * ours, and "already in use" would be a lie);
+ * - a bind refused as IN USE on exactly 127.0.0.1 might be OUR master's listener from before an
+ * app restart (an adopted ControlPersist orphan keeps its forwards; the registry does not) —
+ * the caller may re-issue the identical forward, which the holding master acknowledges with 0
+ * and any other holder refuses with 255 (both measured);
+ * - something answering on 127.0.0.1 that we could still bind next to (BSD wildcard + SO_REUSEADDR)
+ * is busy, never shadowed.
+ */
+export function localPortVerdict(s: LocalPortState): LocalPortVerdict {
+ if (s.v6Answers) return 'busy'
+ if (s.bind === 'denied') return 'denied'
+ if (s.bind === 'in-use') return 'maybe-ours'
+ if (s.v4Answers) return 'busy'
+ return 'free'
+}
+
interface Held extends DevPortForward {
projectId: string
target: string
@@ -54,11 +87,61 @@ interface Held extends DevPortForward {
/** How far past the requested port the suggestion looks for a free one. */
const SUGGEST_SPAN = 100
+/**
+ * While ANY forward is held, core re-checks them on its own at this cadence. The renderer scans only
+ * the project on screen, so without this a forward of a project the person switched away from (or
+ * closed — neither disconnects) stayed bound after its dev server died: the local port stayed taken
+ * (a local dev server silently moved to P+1) and whatever later bound the host's P got the traffic.
+ * One exec per forwarding project per minute, and nothing at all while no forward is held; a
+ * project the renderer scanned within the interval is skipped.
+ */
+export const FORWARD_SWEEP_MS = 60_000
+
export class PortForwardRegistry {
private readonly held = new Map<number, Held>() // keyed by LOCAL port — unique on this machine
private readonly inFlight = new Map<string, Promise<DevPortForwardResult>>()
+ private readonly reconciledAt = new Map<string, number>()
+ private sweepTimer: ReturnType<typeof setInterval> | null = null
+ private sweeping = false
+
+ constructor(
+ private readonly d: PortForwardDeps,
+ private readonly clock: { now(): number; sweepMs: number } = { now: () => Date.now(), sweepMs: FORWARD_SWEEP_MS }
+ ) {}
+
+ /** Arm the sweep while something is held; disarm it when nothing is. */
+ private syncSweep(): void {
+ if (this.held.size > 0 && !this.sweepTimer) {
+ this.sweepTimer = setInterval(() => void this.sweep(), this.clock.sweepMs)
+ ;(this.sweepTimer as { unref?: () => void }).unref?.()
+ } else if (this.held.size === 0 && this.sweepTimer) {
+ clearInterval(this.sweepTimer)
+ this.sweepTimer = null
+ }
+ }
- constructor(private readonly d: PortForwardDeps) {}
+ /** One pass over every project that holds a forward. Exported for tests via the class. */
+ async sweep(): Promise<void> {
+ if (this.sweeping) return
+ this.sweeping = true
+ try {
+ const projects = new Set([...this.held.values()].map((h) => h.projectId))
+ for (const projectId of projects) {
+ const last = this.reconciledAt.get(projectId)
+ if (last !== undefined && this.clock.now() - last < this.clock.sweepMs) continue
+ if (!this.d.refForProject(projectId)) continue // disconnect handling drops these
+ await this.reconcile(projectId, await this.d.scan(projectId))
+ }
+ } finally {
+ this.sweeping = false
+ this.syncSweep()
+ }
+ }
+
+ dispose(): void {
+ if (this.sweepTimer) clearInterval(this.sweepTimer)
+ this.sweepTimer = null
+ }
list(projectId: string): DevPortForward[] {
return [...this.held.values()]
@@ -105,7 +188,7 @@ export class PortForwardRegistry {
const found = report.nodes[req.nodeId]?.find((p) => p.port === remotePort)
if (!found) return this.refuse('not-listening', remotePort)
const target = forwardTarget(found.addresses)
- if (!target) return this.refuse('forward-failed', remotePort)
+ if (!target) return this.refuse('unreachable-address', remotePort)
// Already forwarded for this project's port: hand back the live one, forget a dead one.
for (const h of this.held.values()) {
@@ -115,16 +198,19 @@ export class PortForwardRegistry {
return { ok: true, localPort: h.localPort, url: devPortUrl(h.localPort), reused: true }
}
this.held.delete(h.localPort)
+ this.syncSweep()
}
if ((isPrivilegedPort(remotePort) || isPrivilegedPort(localPort)) && req.allowPrivileged !== true) {
return this.refuse('privileged', remotePort, localPort)
}
- const ours = this.held.get(localPort)
- if (ours || (await this.d.localPortBusy(localPort))) {
+ if (this.held.has(localPort)) {
return this.refuse('local-port-busy', remotePort, localPort, await this.suggest(localPort))
}
+ const verdict = localPortVerdict(await this.d.localPortState(localPort))
+ if (verdict === 'busy') return this.refuse('local-port-busy', remotePort, localPort, await this.suggest(localPort))
+ if (verdict === 'denied') return this.refuse('local-port-denied', remotePort, localPort, await this.suggest(localPort))
// Re-read the ref: the scan was a round trip, and the master may have gone meanwhile.
const ref = this.d.refForProject(req.projectId)
@@ -135,7 +221,13 @@ export class PortForwardRegistry {
} catch {
code = -1
}
- if (code !== 0) return this.refuse('forward-failed', remotePort, localPort)
+ if (code !== 0) {
+ // 'maybe-ours' that the master did not acknowledge: someone else holds the port.
+ if (verdict === 'maybe-ours') {
+ return this.refuse('local-port-busy', remotePort, localPort, await this.suggest(localPort))
+ }
+ return this.refuse('forward-failed', remotePort, localPort)
+ }
this.held.set(localPort, {
projectId: req.projectId,
nodeId: req.nodeId,
@@ -145,20 +237,24 @@ export class PortForwardRegistry {
conn: ref.conn,
controlPath: ref.controlPath
})
- return { ok: true, localPort, url: devPortUrl(localPort), reused: false }
+ this.syncSweep()
+ // An acknowledged 'maybe-ours' is a forward this master already held (adopted after a restart).
+ return { ok: true, localPort, url: devPortUrl(localPort), reused: verdict === 'maybe-ours' }
}
/** The first free, non-privileged, not-ours local port after `from` — a suggestion only. */
private async suggest(from: number): Promise<number | undefined> {
- for (let p = Math.max(from + 1, 1024); p <= Math.min(from + SUGGEST_SPAN, 65535); p++) {
+ const start = Math.max(from + 1, 1024)
+ for (let p = start; p <= Math.min(start + SUGGEST_SPAN, 65535); p++) {
if (this.held.has(p)) continue
- if (!(await this.d.localPortBusy(p))) return p
+ if (localPortVerdict(await this.d.localPortState(p)) === 'free') return p
}
return undefined
}
private async cancel(h: Held): Promise<void> {
this.held.delete(h.localPort)
+ this.syncSweep()
try {
await this.d.run(localForwardCancelArgs(h.conn, h.controlPath, h.localPort, h.target, h.remotePort))
} catch {
@@ -173,17 +269,19 @@ export class PortForwardRegistry {
return true
}
- /** After a SUCCESSFUL scan of the project: cancel forwards whose host port stopped listening,
+ /** After a SUCCESSFUL scan of the project: cancel forwards whose host port its OWNING node no
+ * longer listens on (another node now on that number is not the server the person opened),
* forget forwards whose local listener vanished (a rebuilt master). A failed scan changes nothing. */
async reconcile(projectId: string, report: DevPortsReport): Promise<void> {
if (!report.ok) return
- const listening = new Set<number>()
- for (const ports of Object.values(report.nodes)) for (const p of ports) listening.add(p.port)
+ this.reconciledAt.set(projectId, this.clock.now())
for (const h of [...this.held.values()]) {
if (h.projectId !== projectId) continue
- if (!listening.has(h.remotePort)) await this.cancel(h)
+ const stillOwned = report.nodes[h.nodeId]?.some((p) => p.port === h.remotePort) === true
+ if (!stillOwned) await this.cancel(h)
else if (!(await this.d.localPortHeld(h.localPort))) this.held.delete(h.localPort)
}
+ this.syncSweep()
}
/** The node's session ended (delete, recycle): its dev server went with it. */
@@ -194,6 +292,8 @@ export class PortForwardRegistry {
/** The project's master is gone; its listeners died with it — nothing to cancel over ssh. */
projectDisconnected(projectId: string): void {
for (const h of [...this.held.values()]) if (h.projectId === projectId) this.held.delete(h.localPort)
+ this.reconciledAt.delete(projectId)
+ this.syncSweep()
}
}
@@ -212,27 +312,37 @@ export function canConnect(host: string, port: number, timeoutMs = 400): Promise
})
}
-/** Could this process bind `host:port` right now? (Released immediately.) */
-export function canBind(host: string, port: number): Promise<boolean> {
+/** Try to bind `host:port` (released immediately): ok, in use, or denied (EACCES/EPERM). */
+export function tryBind(host: string, port: number): Promise<LocalPortState['bind']> {
return new Promise((resolve) => {
const srv = net.createServer()
- srv.once('error', () => resolve(false))
- srv.listen({ host, port, exclusive: true }, () => srv.close(() => resolve(true)))
+ srv.once('error', (err: NodeJS.ErrnoException) =>
+ resolve(err.code === 'EACCES' || err.code === 'EPERM' ? 'denied' : 'in-use')
+ )
+ srv.listen({ host, port, exclusive: true }, () => srv.close(() => resolve('ok')))
})
}
-/**
- * Busy = something answers on `localhost:<port>` over either family, or 127.0.0.1 cannot be bound.
- * The ::1 connect check is the one that matters for correctness: a local app bound only to ::1
- * leaves 127.0.0.1 free, the forward would succeed, and the browser node's `localhost` (IPv6
- * first) would show the local app instead of the host's.
- */
+/** Could this process bind `host:port` right now? */
+export async function canBind(host: string, port: number): Promise<boolean> {
+ return (await tryBind(host, port)) === 'ok'
+}
+
+export async function defaultLocalPortState(port: number): Promise<LocalPortState> {
+ const [v4Answers, v6Answers, bind] = await Promise.all([
+ canConnect('127.0.0.1', port),
+ canConnect('::1', port),
+ tryBind('127.0.0.1', port)
+ ])
+ return { v4Answers, v6Answers, bind }
+}
+
+/** Busy for any reason — the old yes/no view of `defaultLocalPortState`. */
export async function defaultLocalPortBusy(port: number): Promise<boolean> {
- const [v4, v6] = await Promise.all([canConnect('127.0.0.1', port), canConnect('::1', port)])
- if (v4 || v6) return true
- return !(await canBind('127.0.0.1', port))
+ return localPortVerdict(await defaultLocalPortState(port)) !== 'free'
}
+/** The forward's own listener is still there when WE cannot bind its port — only in-use counts. */
export async function defaultLocalPortHeld(port: number): Promise<boolean> {
- return !(await canBind('127.0.0.1', port))
+ return (await tryBind('127.0.0.1', port)) === 'in-use'
}
diff --git a/src/core/session-memory-remote.ts b/src/core/session-memory-remote.ts
index 9a13d4341..0a3b176cb 100644
--- a/src/core/session-memory-remote.ts
+++ b/src/core/session-memory-remote.ts
@@ -56,7 +56,7 @@ const SWEEP_SOCKETS: readonly string[] = [TMUX_SOCKET, RMT_TMUX_SOCKET]
* /proc reads over a link we do not control, and its output is what we already parse.
*/
export function remoteSessionMemoryCommand(): string {
- const listPanes = fencedListPanesCommand
+ const listPanes = (socket: string): string => fencedListPanesCommand(socket)
return [
// tmux may live off the exec channel's PATH (Homebrew on macOS — issue #449, same append as
// remoteTmuxPathPrologue). Without this every socket answers 127 and the sweep reports
@@ -108,10 +108,10 @@ function parsePanesSection(lines: readonly string[]): { answered: number; panes:
/** One socket's fenced `list-panes` block for a generated script. Shared with the dev-ports probe
* (core/dev-ports.ts), so the two remote sweeps fence a socket — and classify its failure — the
* same way. */
-export function fencedListPanesCommand(socket: string): string {
+export function fencedListPanesCommand(socket: string, tmux = 'tmux'): string {
return [
`echo '${SOCK} ${socket}'`,
- `tmux -L ${socket} list-panes -a -F '${PANE_FMT}' 2>&1`,
+ `${tmux} -L ${socket} list-panes -a -F '${PANE_FMT}' 2>&1`,
`echo "${SOCKRC} $?"`
].join('\n')
}
diff --git a/src/main/dev-ports-wiring.test.ts b/src/main/dev-ports-wiring.test.ts
index e52320c14..81ed5aa82 100644
--- a/src/main/dev-ports-wiring.test.ts
+++ b/src/main/dev-ports-wiring.test.ts
@@ -12,6 +12,9 @@ describe('dev-ports wiring', () => {
it('the desktop registers the service with a forward leg over the project master', () => {
expect(main).toMatch(/startDevPortsService\(\{[\s\S]{0,1500}forward: \{[\s\S]{0,300}refForProject/)
})
+ it("the local scan asks the app's own tmux, like session memory (a bundled-only tmux is not on PATH)", () => {
+ expect(main).toMatch(/startDevPortsService\(\{\s*tmuxBin: \(\) => ptyManager\.getTmuxBin\(\)/)
+ })
it('a node\'s session ending cancels its forwards; a disconnect forgets the project\'s', () => {
expect(main).toMatch(/ptyManager\.onSessionEnded\(\(nodeId\) => void devPorts\.registry\?\.nodeEnded\(nodeId\)\)/)
expect(main).toMatch(/onSshProjectStatus\([\s\S]{0,200}projectDisconnected\(e\.projectId\)/)
diff --git a/src/main/index.ts b/src/main/index.ts
index d2057beda..84ef22173 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -3155,6 +3155,7 @@ app.whenReady().then(async () => {
// Dev-server ports (CLAUDE.md → Dev-server ports). Same identity predicate and the same
// exit-code-gated runner shape as session memory above; forwarding rides the project's master.
const devPorts = startDevPortsService({
+ tmuxBin: () => ptyManager.getTmuxBin(),
remote: {
isRemoteProject: sshScopePredicate({
sshProjectIds: () => workspaceStore.sshProjectIds(),
diff --git a/src/renderer/canvas/useDevPortScanner.test.tsx b/src/renderer/canvas/useDevPortScanner.test.tsx
new file mode 100644
index 000000000..582bb2473
--- /dev/null
+++ b/src/renderer/canvas/useDevPortScanner.test.tsx
@@ -0,0 +1,53 @@
+// @vitest-environment jsdom
+// Review of #1063: a hook lull used to scan even with the window in the background — an exec on the
+// host per agent turn while nobody looked. The hook trigger is now gated on "someone is watching".
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
+import { createRoot, type Root } from 'react-dom/client'
+import { act } from 'react'
+
+const scanDevPorts = vi.fn(async () => {})
+vi.mock('../state/devPorts', () => ({ scanDevPorts, devPortsAvailable: () => true }))
+const hookSubs = new Map<string, () => void>()
+vi.mock('../state/agentStatus', () => ({
+ useAgentStatus: { getState: () => ({ onHookEvent: (id: string, cb: () => void) => (hookSubs.set(id, cb), () => hookSubs.delete(id)) }) }
+}))
+vi.mock('../state/projects', () => ({ useProjects: (sel: (s: unknown) => unknown) => sel({ getProject: () => ({}) }) }))
+vi.mock('../state/sshConn', () => ({ useSshConn: (sel: (s: unknown) => unknown) => sel({ byProject: {} }) }))
+
+const { useDevPortScanner } = await import('./useDevPortScanner')
+
+function Probe(): null {
+ useDevPortScanner('p', 'n1')
+ return null
+}
+
+let root: Root
+let focused = true
+beforeEach(() => {
+ vi.useFakeTimers()
+ scanDevPorts.mockClear()
+ vi.spyOn(document, 'hasFocus').mockImplementation(() => focused)
+ root = createRoot(document.createElement('div'))
+ act(() => root.render(<Probe />))
+ scanDevPorts.mockClear() // the mount scan
+})
+afterEach(() => {
+ act(() => root.unmount())
+ vi.useRealTimers()
+ vi.restoreAllMocks()
+})
+
+describe('useDevPortScanner — hook trigger', () => {
+ it('scans after a hook lull while the window is focused', async () => {
+ focused = true
+ hookSubs.get('n1')!()
+ await vi.advanceTimersByTimeAsync(4_000)
+ expect(scanDevPorts).toHaveBeenCalledWith('p', false, 'hook')
+ })
+ it('does NOT scan after a hook lull while the window is in the background', async () => {
+ focused = false
+ hookSubs.get('n1')!()
+ await vi.advanceTimersByTimeAsync(4_000)
+ expect(scanDevPorts).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/renderer/canvas/useDevPortScanner.ts b/src/renderer/canvas/useDevPortScanner.ts
index 5c302f090..d0ed892f0 100644
--- a/src/renderer/canvas/useDevPortScanner.ts
+++ b/src/renderer/canvas/useDevPortScanner.ts
@@ -2,12 +2,17 @@
// rules live in lib/devPorts.ts; this is only the wiring: mount, window focus, a debounced trailing
// scan after the project's agents report activity, and a slow poll while the window is focused.
import { useEffect } from 'react'
-import { DEV_PORTS_HOOK_DEBOUNCE_MS, pollIntervalMs } from '../lib/devPorts'
+import { DEV_PORTS_HOOK_DEBOUNCE_MS, pollIntervalMs, scanWhileWatching } from '../lib/devPorts'
import { devPortsAvailable, scanDevPorts } from '../state/devPorts'
import { useAgentStatus } from '../state/agentStatus'
import { useProjects } from '../state/projects'
import { useSshConn } from '../state/sshConn'
+/** Is someone looking? Read at FIRE time: a hook lull while the window is in the background must
+ * not become an exec on the host (the focus event re-scans when the person comes back). */
+const watching = (): boolean =>
+ scanWhileWatching(document.visibilityState === 'visible', document.hasFocus())
+
/**
* @param terminalIdsSig the project's terminal node ids joined with `,` — a primitive, so a canvas
* edit that does not add or remove a terminal does not re-run the effects.
@@ -19,7 +24,6 @@ export function useDevPortScanner(projectId: string, terminalIdsSig: string): vo
useEffect(() => {
if (!eligible) return
- const watching = (): boolean => document.visibilityState === 'visible' && document.hasFocus()
void scanDevPorts(projectId, remote, 'mount')
const timer = setInterval(() => {
if (watching()) void scanDevPorts(projectId, remote, 'poll')
@@ -39,7 +43,7 @@ export function useDevPortScanner(projectId: string, terminalIdsSig: string): vo
if (debounce) clearTimeout(debounce)
debounce = setTimeout(() => {
debounce = null
- void scanDevPorts(projectId, remote, 'hook')
+ if (watching()) void scanDevPorts(projectId, remote, 'hook')
}, DEV_PORTS_HOOK_DEBOUNCE_MS)
}
const subscribe = useAgentStatus.getState().onHookEvent
diff --git a/src/renderer/components/PortsChip.tsx b/src/renderer/components/PortsChip.tsx
index 976cdb180..1332a5416 100644
--- a/src/renderer/components/PortsChip.tsx
+++ b/src/renderer/components/PortsChip.tsx
@@ -75,7 +75,7 @@ export const PortsChip = memo(function PortsChip({
})
return
}
- if (result.reason === 'local-port-busy' && result.suggestedLocalPort !== undefined) {
+ if ((result.reason === 'local-port-busy' || result.reason === 'local-port-denied') && result.suggestedLocalPort !== undefined) {
const alt = result.suggestedLocalPort
setPending({
port: req.port,
diff --git a/src/renderer/lib/devPorts.ts b/src/renderer/lib/devPorts.ts
index d023e2fe0..3d9a24cc0 100644
--- a/src/renderer/lib/devPorts.ts
+++ b/src/renderer/lib/devPorts.ts
@@ -18,6 +18,11 @@ export const DEV_PORTS_HOOK_DEBOUNCE_MS = 4_000
/** No automatic scan closer than this to the previous one; an explicit refresh ignores it. */
export const DEV_PORTS_MIN_GAP_MS = 10_000
+/** The automatic triggers (hook lull, poll) run only while the window is visible AND focused. */
+export function scanWhileWatching(visible: boolean, focused: boolean): boolean {
+ return visible && focused
+}
+
export type ScanReason = 'mount' | 'focus' | 'hook' | 'poll' | 'user'
export function shouldScan(reason: ScanReason, now: number, lastStartedAt: number | undefined): boolean {
diff --git a/src/shared/dev-ports.ts b/src/shared/dev-ports.ts
index 7eca0c4ec..cf77d9905 100644
--- a/src/shared/dev-ports.ts
+++ b/src/shared/dev-ports.ts
@@ -70,7 +70,11 @@ export type DevPortForwardRefusal =
| 'not-listening'
| 'privileged'
| 'local-port-busy'
+ /** This computer refuses to let the app listen on the port (below 1024 without admin rights). */
+ | 'local-port-denied'
| 'forward-failed'
+ /** The server is bound to something that is not a plain IP literal — nothing to aim at. */
+ | 'unreachable-address'
export type DevPortForwardResult =
| { ok: true; localPort: number; url: string; reused: boolean }
@@ -116,7 +120,11 @@ export function forwardRefusalText(
return `Port ${port} is a privileged port (below 1024).`
case 'local-port-busy':
return `Port ${localPort} is already in use on this computer, so it cannot be forwarded to the same number.`
+ case 'local-port-denied':
+ return `This computer does not let the app listen on port ${localPort} (ports below 1024 need administrator rights here).`
case 'forward-failed':
return `The SSH connection refused to forward port ${port}.`
+ case 'unreachable-address':
+ return `Port ${port} is bound to an address this app cannot forward to.`
}
}