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(ssh): verify the reverse hook tunnel end-to-end; start hookServer first

enesd3bf09042bfb
diff --git a/src/main/index.ts b/src/main/index.ts
index 1a2a18ee7..a9f60b554 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -612,6 +612,14 @@ app.whenReady().then(async () => {
return result.canceled || result.filePaths.length === 0 ? null : result.filePaths[0]
})
+ // The hook server starts BEFORE the window exists: an SSH project the renderer auto-reconnects
+ // on load calls remoteHooks.setup with getHook()'s LIVE port/token, and a start racing behind
+ // that connect hands it port 0 — setup then bails fail-open and, on a reused live-orphan
+ // ControlMaster, the master keeps serving a PREVIOUS app run's `-R` hook forward: every remote
+ // hook POST dies against a dead port with zero symptoms beyond "statuses stay idle". The
+ // listeners (setListener/setRawListener/setControlHandler) attach later, which the server
+ // tolerates — early hook POSTs are simply dropped, never mis-routed.
+ await hookServer.start()
const win = createWindow()
// Flip `quitting` before quitAndInstall so the window's close-event actually closes (not hides);
// quitAndInstall closes all windows then calls app.quit(), which our hide-on-close would block.
@@ -1028,7 +1036,6 @@ app.whenReady().then(async () => {
target.webContents.send(IPC.agentControl, { requestId, sourceNodeId: nodeId, verb, args })
})
})
- await hookServer.start()
initMediaProtocol()
initContextLink(ptyManager)
diff --git a/src/main/remote-ssh/remote-hooks.test.ts b/src/main/remote-ssh/remote-hooks.test.ts
index 5aab30a6e..b277916a4 100644
--- a/src/main/remote-ssh/remote-hooks.test.ts
+++ b/src/main/remote-ssh/remote-hooks.test.ts
@@ -3,14 +3,18 @@ import { RemoteHooks } from './remote-hooks'
const conn = { host: 'h', user: 'u' }
-function mk() {
+function mk(opts: { verifyAnswers?: string[] } = {}) {
const calls: { args: string[]; stdin?: string }[] = []
+ // Tunnel-verify curl answers, consumed in order (default: healthy on the first try).
+ const verifyAnswers = [...(opts.verifyAnswers ?? ['204'])]
const run = vi.fn(async (args: string[], stdin?: string) => {
calls.push({ args, stdin })
const joined = args.join(' ')
// resolve the remote $HOME probe → absolute remote paths build from this.
if (joined.includes('$HOME')) return { code: 0, stdout: '/home/u' }
if (joined.includes('cat /home/u/.claude/settings.json')) return { code: 0, stdout: '{}' }
+ // the end-to-end tunnel verification curl (runs in ARGS, unlike the script's stdin curl).
+ if (joined.includes('%{http_code}')) return { code: 0, stdout: verifyAnswers.shift() ?? '204' }
return { code: 0, stdout: '' }
})
return { rh: new RemoteHooks({ run }), calls, run }
@@ -48,6 +52,46 @@ describe('RemoteHooks.setup', () => {
expect(joined.some((j) => j.includes('~/'))).toBe(false)
})
+ it('verifies the tunnel end-to-end and heals a stale forward with one rebind', async () => {
+ // First verify sees a dead target (a reused live-orphan master serving a previous run's
+ // forward — the field case that killed remote statuses for hours); the rebind fixes it.
+ const { rh, calls } = mk({ verifyAnswers: ['000', '204'] })
+ const res = await rh.setup('p1', conn, '/s.sock', { port: 51234, token: 'tok', version: '1' })
+ expect(res?.endpointPath).toBe('/home/u/.nodeterm/hook-endpoint-p1.env')
+ const joined = calls.map((c) => c.args.join(' '))
+ expect(joined.filter((j) => j.includes('-O forward')).length).toBe(2)
+ // The retry clears our own possibly-registered spec before rebinding.
+ expect(joined.some((j) => j.includes('-O cancel'))).toBe(true)
+ // The verify curl runs on the HOST through the sock with the fresh token.
+ expect(joined.some((j) => j.includes('--unix-socket') && j.includes('x-nodeterm-hook-token: tok'))).toBe(true)
+ })
+
+ it('refuses to advertise a tunnel that never verifies — no endpoint file, null result', async () => {
+ const { rh, calls } = mk({ verifyAnswers: ['000', '000'] })
+ const res = await rh.setup('p1', conn, '/s.sock', { port: 51234, token: 'tok', version: '1' })
+ expect(res).toBeNull()
+ // The endpoint file must NOT be written: sessions would source a socket that answers nothing.
+ expect(calls.map((c) => c.args.join(' ')).some((j) => j.includes('hook-endpoint-p1.env'))).toBe(false)
+ })
+
+ it('a failed -O forward bind is retried, never trusted', async () => {
+ const calls: { args: string[] }[] = []
+ let forwards = 0
+ const run = vi.fn(async (args: string[]) => {
+ calls.push({ args })
+ const joined = args.join(' ')
+ if (joined.includes('$HOME')) return { code: 0, stdout: '/home/u' }
+ if (joined.includes('-O forward')) return { code: ++forwards === 1 ? 1 : 0, stdout: '' }
+ if (joined.includes('%{http_code}')) return { code: 0, stdout: '204' }
+ if (joined.includes('cat /home/u/.claude/settings.json')) return { code: 0, stdout: '{}' }
+ return { code: 0, stdout: '' }
+ })
+ const rh = new RemoteHooks({ run })
+ const res = await rh.setup('p1', conn, '/s.sock', { port: 51234, token: 'tok', version: '1' })
+ expect(res?.endpointPath).toBe('/home/u/.nodeterm/hook-endpoint-p1.env')
+ expect(forwards).toBe(2)
+ })
+
it('gives two different projects (or a browse) distinct endpoint files — no shared clobber', async () => {
const a = await mk().rh.setup('proj', conn, '/s', { port: 1, token: 't', version: '1' })
const { rh, calls } = mk()
diff --git a/src/main/remote-ssh/remote-hooks.ts b/src/main/remote-ssh/remote-hooks.ts
index bea063c48..325f3a955 100644
--- a/src/main/remote-ssh/remote-hooks.ts
+++ b/src/main/remote-ssh/remote-hooks.ts
@@ -45,7 +45,12 @@ export class RemoteHooks {
controlPath: string,
hook: { port: number; token: string; version: string }
): Promise<{ endpointPath: string } | null> {
- if (!hook.port || !hook.token) return null
+ if (!hook.port || !hook.token) {
+ // Not just fail-open noise: on a reused live-orphan ControlMaster this leaves the master
+ // serving a PREVIOUS app run's forward (dead port) with nothing ever rebinding it.
+ console.warn('[remote-hooks] hook server not ready at connect — remote agents run without hooks')
+ return null
+ }
try {
// 0. resolve the remote $HOME once → build all remote paths absolute (no unexpanded ~).
const { code, stdout } = await this.r.run(childArgs(conn, controlPath, 'printf %s "$HOME"'))
@@ -61,11 +66,34 @@ export class RemoteHooks {
// silently → no status badge / context meter / subagent cards / session-name sync on ANY SSH
// node. A per-project file means each session sources ITS OWN project's live sock.
const endpoint = `${remoteDir}/hook-endpoint-${projectId}.env`
- // 1. reverse unix-socket forward (stale socket → remove first so -R can bind).
- await this.r.run(childArgs(conn, controlPath, `mkdir -p ${remoteDir} && rm -f ${sock}`))
- await this.r.run(hookForwardArgs(conn, controlPath, sock, hook.port))
+ // 1. reverse unix-socket forward, VERIFIED end-to-end before anything advertises it.
+ // A reused live-orphan master (app relaunch; ControlMaster children outlive the app) can
+ // carry a stale forward from the previous run — same path, DEAD port. sshd even serves
+ // several listeners for one path across rm+rebind cycles (observed in the field: two fds
+ // on one sshd). Binding is therefore not evidence of a working tunnel; only an HTTP
+ // answer from THIS app run's hook server is. Field case: every remote hook POST died
+ // against a dead port for hours — no badges, no context meter — with zero symptoms,
+ // because every step here was silently fail-open.
+ let verified = false
+ for (let attempt = 0; attempt < 2 && !verified; attempt++) {
+ if (attempt > 0) {
+ // Our own spec may already be registered (a reconnect this run) — clear it first.
+ await this.r.run(hookForwardCancelArgs(conn, controlPath, sock, hook.port)).catch(() => {})
+ }
+ await this.r.run(childArgs(conn, controlPath, `mkdir -p ${remoteDir} && rm -f ${sock}`))
+ const fwd = await this.r.run(hookForwardArgs(conn, controlPath, sock, hook.port))
+ if (fwd.code !== 0) continue
+ verified = await this.verifyTunnel(conn, controlPath, sock, hook.token)
+ }
+ if (!verified) {
+ console.warn(
+ `[remote-hooks] reverse hook tunnel failed verification for ${projectId} — remote agents run without status hooks`
+ )
+ return null
+ }
this.specs.set(projectId, { sock, port: hook.port })
- // 2. remote endpoint file (0600 via umask).
+ // 2. remote endpoint file (0600 via umask) — written only after the tunnel proved live,
+ // so sessions are never pointed at a socket that answers nothing.
await this.r.run(
childArgs(conn, controlPath, `umask 077; cat > ${endpoint}`),
remoteEndpointFileContents(sock, hook.token, hook.version)
@@ -193,6 +221,30 @@ export class RemoteHooks {
}
}
+ /**
+ * Prove the forward reaches THIS app run: POST through the remote sock with the fresh token
+ * and require the hook server's own 204 — the same transport (`curl --unix-socket`) the
+ * managed hook script uses, run ON the host. `000`/curl-fail = the listener's target is dead
+ * (a stale forward from a previous run). No `payload` field is sent, so the server records
+ * nothing (its listener path needs one).
+ */
+ private async verifyTunnel(
+ conn: SshConnection,
+ controlPath: string,
+ sock: string,
+ token: string
+ ): Promise<boolean> {
+ try {
+ const cmd =
+ `curl -s -m 5 -o /dev/null -w '%{http_code}' -X POST --unix-socket ${posixQuote(sock)} ` +
+ `-H ${posixQuote(`x-nodeterm-hook-token: ${token}`)} http://localhost/hook/verify --data nodeId=verify`
+ const r = await this.r.run(childArgs(conn, controlPath, cmd))
+ return r.code === 0 && r.stdout.trim() === '204'
+ } catch {
+ return false
+ }
+ }
+
async teardown(projectId: string, conn: SshConnection, controlPath: string): Promise<void> {
const spec = this.specs.get(projectId)
this.specs.delete(projectId)