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(hooks): preserve endpoint ownership across local servers and tunnels

enesbd895ba14cbe
diff --git a/CLAUDE.md b/CLAUDE.md
index f108819c7..96597992d 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -2005,15 +2005,31 @@ else, and its context links must keep classifying across restarts).
"control endpoint unreachable" — in the field, a reviewer launch silently dropped. Now shared,
one definition. Two server-side halves in `hook-server.ts`: a FAILED `listen()` un-wedges the
singleton (it used to leave `this.server` set, making every retry a silent no-op at port 0)
- and both `stop()` and the failed-start path delete `hook-endpoint.env` — publication reflects
- listener liveness; a crash skips that, which is exactly what the client walk exists for. An
- HTTP answer of any code is authoritative: only a dead transport (curl 000/'') fails over, so a
- 403/400 is never re-sent to another instance. The walk is skipped under
- `CODEX_SANDBOX_NETWORK_DISABLED` (#367 — the sandbox denies every connect, the hint is the
- right diagnosis) and the final error now distinguishes "no endpoint anywhere" from "an
+ and `stop()` deletes only the endpoint contents this run published — a failed start cannot
+ erase another owner's advertisement. A crash skips cleanup, which is why clients still walk
+ the candidates.
+ HTTP 421 means the bearer belongs to a different endpoint and is rejected BEFORE dispatch;
+ it joins dead transport (curl 000/'') in the bounded discovery walk. A node-identity 403/400
+ remains final and is never re-sent to another instance. The walk is skipped under
+ `CODEX_SANDBOX_NETWORK_DISABLED` for transport failures (#367); an explicit 421 proves
+ transport worked and still permits discovery. The final error distinguishes "no endpoint
+ anywhere" from "an
advertised endpoint that is not listening" (`STALE_ENDPOINT_HINT`). Desktop quit calls
`hookServer.stop()` on the second before-quit pass, after the flush window.
+ - **Hook endpoint ownership (#826):** startup first probes every transport in an existing
+ endpoint advertisement and preserves a live or uncertain owner. The local Unix listener probes its socket before
+ cleanup. Only `ECONNREFUSED` plus the same device/inode permits removal; a live listener,
+ non-socket, symlink or uncertain probe refuses startup without replacing its endpoint.
+ Endpoint writes are atomic and stop removes only the run's own advertised contents. SSH setup
+ never removes a socket before binding: every forward gets a fresh random path, while discovery
+ is stable per project + installation identity hash. Only a verified replacement is advertised;
+ then this run cancels its previous forward. Existing legacy endpoint files are left intact and
+ upgraded clients can discover the new file. A reused tunnel that loses bearer verification
+ emits hook-only health updates: the desktop shows a warning and clears it after repair, without
+ reconnecting terminals. These changes share the core listener in Desktop and Server Edition;
+ the mobile wire protocol and node-identity rules are unchanged.
+
Enforcement is dated (`NODE_IDENTITY_STRICT_AFTER`, 2026-10-13, read through `isStrictInstant` so a
clock years ahead cannot enter strict mode early) with a `settings.hookIdentityStrict` escape hatch
in Settings → Agents. **Trust on first proof latches a node the moment it authenticates, so it
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 0223794bd..6c84426be 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -364,6 +364,13 @@ on the host too: we shipped the hook bearer that way and any other account on th
it and open a terminal running an arbitrary command. Pass secrets by 0600 file or by **stdin**
(`curl --config -`), and never add an argv fallback. See `docs/node-identity.md`.
+**A hook socket path is not ownership proof.** Never unlink a live listener to bind a hook
+socket, or overwrite an advertisement whose socket/TCP listener still answers. Local stale cleanup requires `ECONNREFUSED` and an unchanged socket inode; regular files,
+symlinks and uncertain probes are preserved. SSH setup allocates a fresh socket and publishes an
+installation-qualified endpoint only after bearer verification. A wrong bearer answers 421 before
+any handler runs; only that explicit wrong-owner response (or transport failure) permits endpoint
+failover. A node-identity 403 stays final. Test with disposable sockets, never a running user's tunnel.
+
**Both raw listeners change together** — `src/main/index.ts` and `src/server/agent-status.ts`. A new
field on a hook event that reaches only the desktop leaves the Server Edition quietly without the
feature, and the boundary tests can only tell you an import is wrong, never that a field is missing.
diff --git a/src/core/agents/hook-endpoint-failover-sh.ts b/src/core/agents/hook-endpoint-failover-sh.ts
index d6c585393..dca53cee0 100644
--- a/src/core/agents/hook-endpoint-failover-sh.ts
+++ b/src/core/agents/hook-endpoint-failover-sh.ts
@@ -106,6 +106,7 @@ export const HOOK_ENDPOINT_FALLBACK_SH = [
'nt_adopt() {',
' NODETERM_HOOK_SOCK=""',
' NODETERM_HOOK_PORT=""',
+ ' NODETERM_HOOK_TOKEN=""',
' NODETERM_NODE_TOKEN_DIR=""',
// stdout swallowed for the same reason as the endpoint source at the top of every client (#186):
// in the managed script's perm-wait branch this runs in the FOREGROUND of a hook whose stdout
diff --git a/src/core/agents/hook-server.recovery.test.ts b/src/core/agents/hook-server.recovery.test.ts
index 4850c26ee..ef41a78d5 100644
--- a/src/core/agents/hook-server.recovery.test.ts
+++ b/src/core/agents/hook-server.recovery.test.ts
@@ -53,7 +53,7 @@ afterAll(() => {
})
describe('hook server start/stop lifecycle (issue #445)', () => {
- it('a failed listen leaves the singleton retryable and drops the stale endpoint file', async () => {
+ it('a failed listen leaves the singleton retryable and preserves an advertisement it did not publish', async () => {
// The file a previous app run left behind — it advertises a port nothing listens on.
const ep = hookServer.endpointFilePath()
fs.mkdirSync(path.dirname(ep), { recursive: true })
@@ -64,8 +64,8 @@ describe('hook server start/stop lifecycle (issue #445)', () => {
// The singleton is back in the clean never-started state, not wedged with a dead Server…
expect(hookServer.getPort()).toBe(0)
expect(hookServer.getToken()).toBe('')
- // …and the stale advertisement is gone rather than pointing clients at the dead port.
- expect(fs.existsSync(ep)).toBe(false)
+ // A failed boot never takes ownership of a previous advertisement, even a stale one.
+ expect(fs.readFileSync(ep, 'utf8')).toContain("NODETERM_HOOK_TOKEN='stale'")
// A retry — same process, no app restart — comes up and re-advertises.
await hookServer.start()
diff --git a/src/core/agents/hook-server.sock.test.ts b/src/core/agents/hook-server.sock.test.ts
index 6d5be30f5..8baadb30f 100644
--- a/src/core/agents/hook-server.sock.test.ts
+++ b/src/core/agents/hook-server.sock.test.ts
@@ -13,7 +13,7 @@ import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import { promisify } from 'node:util'
-import { hookServer } from './hook-server'
+import { HookServer, hookServer } from './hook-server'
import { nodeAuthToken } from './node-auth-token'
import { parseEndpointEnv } from './hook-endpoint-parse'
import { initPlatform, resetPlatformForTests } from '../platform'
@@ -102,26 +102,19 @@ describe('hook server unix-socket listener', () => {
received = []
const sock = hookServer.getSockPath()
expect((await post({ sock }, 'list', {})).status).toBe('403')
- expect((await post({ sock }, 'list', { 'X-Nodeterm-Hook-Token': 'wrong' })).status).toBe('403')
+ expect((await post({ sock }, 'list', { 'X-Nodeterm-Hook-Token': 'wrong' })).status).toBe('421')
expect(received).toEqual([])
})
- it('rebinds cleanly over a stale socket file left by a crash', async () => {
+ it('refuses a second live owner without touching its socket or endpoint', async () => {
const sock = hookServer.getSockPath()
- hookServer.stop()
- expect(fs.existsSync(sock)).toBe(false) // stop() unlinked its own socket
- // A crash skips stop(): fake the leftover. Anything occupying the path blocks bind with
- // EADDRINUSE unless the server unlinks first — the StreamLocalBindUnlink lesson.
- fs.mkdirSync(path.dirname(sock), { recursive: true })
- fs.writeFileSync(sock, '')
- await hookServer.start()
- hookServer.setControlHandler(async (cmd) => {
- received.push({ verb: cmd.verb, nodeId: cmd.nodeId, verified: cmd.verified })
- return { ok: true, message: `did ${cmd.verb}` }
- })
- expect(hookServer.getSockPath()).toBe(sock)
- const reply = await post({ sock }, 'list', { 'X-Nodeterm-Hook-Token': hookServer.getToken() })
- expect(reply).toEqual({ status: '200', body: 'did list\n' })
+ const endpoint = fs.readFileSync(hookServer.endpointFilePath(), 'utf8')
+ const other = new HookServer()
+ await expect(other.start()).rejects.toThrow('hook-endpoint-owned')
+ other.stop()
+ expect(fs.readFileSync(hookServer.endpointFilePath(), 'utf8')).toBe(endpoint)
+ expect(await post({ sock }, 'list', { 'X-Nodeterm-Hook-Token': hookServer.getToken() }))
+ .toEqual({ status: '200', body: 'did list\n' })
})
})
diff --git a/src/core/agents/hook-server.ts b/src/core/agents/hook-server.ts
index c23386d7e..ce1e5f406 100644
--- a/src/core/agents/hook-server.ts
+++ b/src/core/agents/hook-server.ts
@@ -1,9 +1,11 @@
import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'http'
import { randomUUID, timingSafeEqual } from 'crypto'
-import { writeFileSync, mkdirSync, chmodSync, unlinkSync } from 'fs'
+import { readFileSync, mkdirSync, chmodSync, unlinkSync } from 'fs'
+import { assertHookEndpointAvailable, clearStaleHookSocket, HookSocketOwnedError } from './hook-socket-owner'
import { homedir } from 'os'
import path from 'path'
import { platform } from '../platform'
+import { writeFileAtomic } from '../fs-atomic'
import { hookSockPath } from './hook-sock-path'
import { canControlCanvas, type AgentId } from '../../shared/agents/config'
import { normalizeFor, type NormalizedAgentEvent } from '../../shared/agents/normalize'
@@ -266,8 +268,9 @@ export function verifiedRefusalFor(verb: string): string {
return MESSAGING_CONTROL_REFUSAL
}
-class HookServer {
+export class HookServer {
private server: Server | null = null
+ private starting: Promise<void> | null = null
/**
* The unix-domain twin of the loopback TCP listener (issue #367). Same HTTP handler, same
* bearer + per-node token auth — the whole identity machinery is transport-agnostic (nothing
@@ -350,6 +353,7 @@ class HookServer {
| null = null
private codexIdentityListener: ((e: CodexIdentityEvent) => void) | null = null
private endpointPath = ''
+ private publishedEndpoint = ''
private nodeAuthSecret: Buffer | null = null
/**
* `settings.hookIdentityStrict`, read LIVE (a getter, not a snapshot) so flipping it in Settings
@@ -547,7 +551,18 @@ class HookServer {
}
async start(): Promise<void> {
+ if (this.starting) return this.starting
if (this.server) return
+ this.starting = this.startOwnedEndpoint()
+ try {
+ await this.starting
+ } finally {
+ this.starting = null
+ }
+ }
+
+ private async startOwnedEndpoint(): Promise<void> {
+ await assertHookEndpointAvailable(this.endpointFilePath())
this.token = randomUUID()
// ONE handler, shared verbatim by the TCP and the unix-socket listeners: every gate (bearer,
// per-node verdict, verified-only verbs) runs identically on both transports.
@@ -560,8 +575,16 @@ class HookServer {
return
}
if (!this.tokenMatches(req.headers['x-nodeterm-hook-token'])) {
- res.writeHead(403)
- res.end()
+ if (!req.headers['x-nodeterm-hook-token']) {
+ res.writeHead(403)
+ res.end()
+ return
+ }
+ res.writeHead(421, { 'Content-Type': 'text/plain; charset=utf-8' })
+ res.end(
+ 'hook-endpoint-wrong-owner: This endpoint does not own the presented bearer. ' +
+ 'Retry after endpoint discovery; this is not an unsupported capability.\n'
+ )
return
}
req.setTimeout(SLOWLORIS_MS, () => req.destroy())
@@ -798,8 +821,8 @@ class HookServer {
// before the bind, so leaving it set makes every later start() a silent early-return with
// port 0 — while a previous run's endpoint file keeps advertising a dead port to every
// tmux session on the machine. Reset to the clean never-started state so start() can be
- // retried without restarting the app, and drop the stale advertisement (the file reflects
- // listener liveness; a client that still holds the path fails over — see the sh shims).
+ // retried without restarting the app. Only an advertisement this run actually published
+ // may be removed; a file found on disk can belong to a different live instance.
this.server?.close()
this.server = null
this.port = 0
@@ -818,13 +841,21 @@ class HookServer {
this.server!.listen(0, '127.0.0.1', onOk)
})
// Second leg, then ONE endpoint write that advertises whatever actually came up. A failed
- // socket bind must not cost the TCP endpoint file (or the boot).
- await this.startUnixListener(handler)
- this.writeEndpointFile()
+ // unavailable transport can fall back to TCP, but a different owner must refuse the boot.
+ try {
+ await this.startUnixListener(handler)
+ } catch (e) {
+ this.server?.close()
+ this.server = null
+ this.port = 0
+ this.token = ''
+ throw e // Never publish over the listener whose ownership check refused this boot.
+ }
+ await this.writeEndpointFile()
}
- /** Bind the unix-socket twin (see `unixServer`). Never throws — a socket that cannot bind is
- * simply not advertised, and everything keeps running on loopback TCP. */
+ /** Bind the Unix twin. Transport unavailability can degrade to TCP; ownership conflicts throw
+ * so a second instance cannot replace the first instance's endpoint advertisement. */
private async startUnixListener(
handler: (req: IncomingMessage, res: ServerResponse) => Promise<void>
): Promise<void> {
@@ -839,15 +870,8 @@ class HookServer {
// mode is what actually keeps other local users off the socket (the file chmod below only
// lands after listen, and the socket is world-connectable for that instant otherwise).
chmodSync(dir, 0o700)
- // A stale socket file BLOCKS bind with EADDRINUSE even when nothing is listening — the
- // StreamLocalBindUnlink lesson from the SSH reverse tunnels. Unlink-then-bind is safe here:
- // the path is ours alone (0700 dir, digest-keyed fallback), so anything at it is our own
- // leftover from a crash.
- try {
- unlinkSync(p)
- } catch {
- /* nothing stale to clear */
- }
+ // A filesystem path is not proof of ownership: another live instance may hold it.
+ await clearStaleHookSocket(p)
const srv = createServer(handler)
await new Promise<void>((resolve, reject) => {
const onErr = (e: Error): void => {
@@ -867,6 +891,7 @@ class HookServer {
this.unixServer = srv
this.sockPath = p
} catch (e) {
+ if (e instanceof HookSocketOwnedError || (e as NodeJS.ErrnoException).code === 'EADDRINUSE') throw e
console.warn('[agent-hooks] unix hook socket unavailable, staying TCP-only', e)
this.unixServer = null
this.sockPath = ''
@@ -1098,12 +1123,11 @@ class HookServer {
// The managed script sources this file at invocation to get the LIVE port/token.
// tmux sessions outlive the app, so env-baked coords go stale after a restart.
- private writeEndpointFile(): void {
+ private async writeEndpointFile(): Promise<void> {
try {
const p = this.endpointFilePath()
mkdirSync(path.dirname(p), { recursive: true })
- writeFileSync(
- p,
+ const contents =
// Every value is `posixQuote`d: the managed script SOURCES this file (`. "$file"`) under
// /bin/sh, so an unquoted space or shell metachar in a path or token would break the source
// (issue #351: macOS userDataDir lives under "Application Support" — the space made sh try
@@ -1122,11 +1146,15 @@ class HookServer {
// `[ -n "$NODETERM_HOOK_SOCK" ]` — so advertising it moves local hook traffic off the
// TCP port; the PORT line stays above for sessions holding a pre-socket script. Quoted
// like every other value (#351/#358): macOS data dirs carry a space.
- (this.sockPath ? `NODETERM_HOOK_SOCK=${posixQuote(this.sockPath)}\n` : ''),
+ (this.sockPath ? `NODETERM_HOOK_SOCK=${posixQuote(this.sockPath)}\n` : '')
+ await writeFileAtomic(
+ p,
+ contents,
// 0o600: this file holds the bearer token — owner read/write only so another local user
// can't read it and forge hook events.
- { encoding: 'utf8', mode: 0o600 }
+ { mode: 0o600 }
)
+ this.publishedEndpoint = contents
} catch (e) {
console.warn('[agent-hooks] could not write endpoint file', e)
}
@@ -1141,7 +1169,10 @@ class HookServer {
*/
private removeEndpointFile(): void {
try {
+ // A failed/unstarted instance must not erase another run's advertisement.
+ if (!this.publishedEndpoint || readFileSync(this.endpointFilePath(), 'utf8') !== this.publishedEndpoint) return
unlinkSync(this.endpointFilePath())
+ this.publishedEndpoint = ''
} catch {
/* nothing to remove — or no booted platform to name the path (tests); both are fine */
}
@@ -1197,7 +1228,7 @@ class HookServer {
this.unixServer?.close()
this.unixServer = null
// Unlink so the NEXT bind is clean even if close() lost the race with process exit; the
- // startup unlink above is still the backstop for a crash that skipped this entirely.
+ // startup probe can reclaim a confirmed stale socket after a crash.
if (this.sockPath) {
try {
unlinkSync(this.sockPath)
diff --git a/src/core/agents/hook-socket-owner.test.ts b/src/core/agents/hook-socket-owner.test.ts
new file mode 100644
index 000000000..5e853e6e4
--- /dev/null
+++ b/src/core/agents/hook-socket-owner.test.ts
@@ -0,0 +1,71 @@
+import { afterEach, describe, expect, it } from 'vitest'
+import { execFileSync } from 'child_process'
+import { createServer } from 'net'
+import { createServer as createHttpServer } from 'http'
+import fs from 'fs'
+import os from 'os'
+import path from 'path'
+import { assertHookEndpointAvailable, clearStaleHookSocket } from './hook-socket-owner'
+
+const dirs: string[] = []
+function fixture(): string {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-owner-'))
+ dirs.push(dir)
+ return path.join(dir, 'hook.sock')
+}
+afterEach(() => { for (const dir of dirs.splice(0)) fs.rmSync(dir, { recursive: true, force: true }) })
+
+describe('hook endpoint advertisement ownership', () => {
+ it.each([204, 421])('preserves a live advertised owner answering %s, independently of the new bind path', async (status) => {
+ const file = fixture()
+ const server = createHttpServer((_req, res) => { res.writeHead(status); res.end() })
+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve))
+ const address = server.address() as { port: number }
+ const contents = `NODETERM_HOOK_PORT='${address.port}'\nNODETERM_HOOK_TOKEN='old-owner'\n`
+ fs.writeFileSync(file, contents)
+ try {
+ await expect(assertHookEndpointAvailable(file)).rejects.toThrow('hook-endpoint-owned')
+ expect(fs.readFileSync(file, 'utf8')).toBe(contents)
+ } finally { await new Promise<void>((resolve) => server.close(() => resolve())) }
+ })
+
+ it('allows an absent file but preserves an unreadable ownership record', async () => {
+ const file = fixture()
+ await expect(assertHookEndpointAvailable(file)).resolves.toBeUndefined()
+ fs.writeFileSync(file, 'not an endpoint')
+ await expect(assertHookEndpointAvailable(file)).rejects.toThrow('hook-endpoint-owned')
+ expect(fs.readFileSync(file, 'utf8')).toBe('not an endpoint')
+ })
+})
+
+describe.skipIf(process.platform === 'win32')('hook socket ownership (POSIX sockets)', () => {
+ it('preserves a live listener, even if it never speaks HTTP', async () => {
+ const sock = fixture()
+ const server = createServer((client) => client.end())
+ await new Promise<void>((resolve) => server.listen(sock, resolve))
+ try {
+ const inode = fs.lstatSync(sock).ino
+ await expect(clearStaleHookSocket(sock)).rejects.toThrow('hook-endpoint-owned')
+ expect(fs.lstatSync(sock).ino).toBe(inode)
+ } finally { await new Promise<void>((resolve) => server.close(() => resolve())) }
+ })
+
+ it('clears a real socket left by a crashed disposable process', async () => {
+ const sock = fixture()
+ execFileSync(process.execPath, ['-e', "require('net').createServer().listen(process.argv[1], () => process.exit(0))", sock])
+ expect(fs.lstatSync(sock).isSocket()).toBe(true)
+ await clearStaleHookSocket(sock)
+ expect(fs.existsSync(sock)).toBe(false)
+ })
+
+ it('preserves regular files and symlinks at the intended socket path', async () => {
+ const sock = fixture()
+ fs.writeFileSync(sock, 'not ours')
+ await expect(clearStaleHookSocket(sock)).rejects.toThrow('hook-endpoint-owned')
+ expect(fs.readFileSync(sock, 'utf8')).toBe('not ours')
+ const link = `${sock}.link`
+ fs.symlinkSync(sock, link)
+ await expect(clearStaleHookSocket(link)).rejects.toThrow('hook-endpoint-owned')
+ expect(fs.lstatSync(link).isSymbolicLink()).toBe(true)
+ })
+})
diff --git a/src/core/agents/hook-socket-owner.ts b/src/core/agents/hook-socket-owner.ts
new file mode 100644
index 000000000..ca3866c9e
--- /dev/null
+++ b/src/core/agents/hook-socket-owner.ts
@@ -0,0 +1,77 @@
+import { lstatSync, readFileSync, unlinkSync } from 'fs'
+import { createConnection } from 'net'
+import { request } from 'http'
+import { parseEndpointEnv } from './hook-endpoint-parse'
+
+export class HookSocketOwnedError extends Error {
+ constructor() {
+ super(
+ 'hook-endpoint-owned: Another listener may own this hook endpoint; its advertisement was left unchanged.'
+ )
+ }
+}
+
+/** An old advertisement can point at a tunnel, even when our local bind path is different.
+ * Inspect it as data, never source it. Only a failed connect proves that it is safe to replace. */
+export async function assertHookEndpointAvailable(file: string): Promise<void> {
+ let env: Record<string, string>
+ try {
+ env = parseEndpointEnv(readFileSync(file, 'utf8'))
+ } catch (e) {
+ if ((e as NodeJS.ErrnoException).code === 'ENOENT') return
+ throw new HookSocketOwnedError()
+ }
+ const port = Number(env.NODETERM_HOOK_PORT)
+ const targets = [
+ ...(env.NODETERM_HOOK_SOCK ? [{ socketPath: env.NODETERM_HOOK_SOCK }] : []),
+ ...(Number.isInteger(port) && port > 0 && port <= 65535 ? [{ host: '127.0.0.1', port }] : [])
+ ]
+ if (!targets.length) throw new HookSocketOwnedError()
+ for (const target of targets) {
+ const stale = await new Promise<boolean>((resolve) => {
+ const req = request({
+ ...target,
+ path: '/verify',
+ method: 'POST',
+ timeout: 500,
+ headers: { 'X-Nodeterm-Hook-Token': env.NODETERM_HOOK_TOKEN ?? '' }
+ })
+ const finish = (value: boolean): void => {
+ req.destroy()
+ resolve(value)
+ }
+ req.once('response', () => finish(false))
+ req.once('timeout', () => finish(false))
+ req.once('error', (e: NodeJS.ErrnoException) => finish(e.code === 'ECONNREFUSED' || e.code === 'ENOENT'))
+ req.end()
+ })
+ if (!stale) throw new HookSocketOwnedError()
+ }
+}
+
+/** Only ECONNREFUSED proves a leftover socket. Timeouts and permission errors prove nothing. */
+export async function clearStaleHookSocket(sock: string): Promise<void> {
+ let before
+ try {
+ before = lstatSync(sock)
+ } catch (e) {
+ if ((e as NodeJS.ErrnoException).code === 'ENOENT') return
+ throw e
+ }
+ if (!before.isSocket()) throw new HookSocketOwnedError()
+ const stale = await new Promise<boolean>((resolve) => {
+ const client = createConnection(sock)
+ const finish = (value: boolean): void => {
+ client.destroy()
+ resolve(value)
+ }
+ client.once('connect', () => finish(false))
+ client.once('error', (e: NodeJS.ErrnoException) => finish(e.code === 'ECONNREFUSED'))
+ client.setTimeout(500, () => finish(false))
+ })
+ if (!stale) throw new HookSocketOwnedError()
+ // Do not delete a replacement that appeared while connect was in flight.
+ const after = lstatSync(sock)
+ if (before.dev !== after.dev || before.ino !== after.ino) throw new HookSocketOwnedError()
+ unlinkSync(sock)
+}
diff --git a/src/core/agents/hooks/managed-script.test.ts b/src/core/agents/hooks/managed-script.test.ts
index ddd8a1634..14fe9c57d 100644
--- a/src/core/agents/hooks/managed-script.test.ts
+++ b/src/core/agents/hooks/managed-script.test.ts
@@ -55,7 +55,7 @@ describe('buildManagedScript', () => {
expect((s.match(/\n *curl -sS/g) ?? []).length).toBe(4)
// The two answered POSTs are wrapped in a `{ … ; rm … } &` group that self-deletes the payload
// temp file, so `nt_hook_headers |` there is preceded by `{ ` — match either form.
- expect((s.match(/\n *(\{ )?nt_hook_headers \|/g) ?? []).length).toBe(4)
+ expect((s.match(/\n *(\{ |nt_code=\$\()?nt_hook_headers \|/g) ?? []).length).toBe(4)
expect((s.match(/--config -/g) ?? []).length).toBe(4)
})
@@ -1042,7 +1042,7 @@ describe('managed script presents the per-node token', () => {
// different secret): if it survived the fallback — because the dir was not cleared, or because
// the read happened once at the top — the server would see a foreign kid and label the event
// `legacy`, i.e. verified:false. Only a genuine re-read produces verified:true.
- it.skipIf(!shAvailable)('re-reads the token from the endpoint it FELL BACK to', async () => {
+ it.skipIf(!shAvailable).each(['dead', 'wrong-owner'])('re-reads the token after a %s endpoint', async (primary) => {
const home = newHome('home-failover')
const primaryTokens = tokenDirWith('tokens-primary', {
[NODE]: nodeAuthToken(FOREIGN_SECRET, NODE)
@@ -1051,7 +1051,7 @@ describe('managed script presents the per-node token', () => {
const dead = join(home, '.nodeterm', 'hook-endpoint-dead.env')
writeFileSync(
dead,
- `NODETERM_HOOK_SOCK=${join(home, '.nodeterm', 'nothing-listens-here.sock')}\nNODETERM_HOOK_TOKEN=dead\nNODETERM_HOOK_VERSION=2\nNODETERM_NODE_TOKEN_DIR=${primaryTokens}\n`,
+ `NODETERM_HOOK_SOCK=${primary === 'dead' ? join(home, '.nodeterm', 'nothing-listens-here.sock') : hookServer.getSockPath()}\nNODETERM_HOOK_TOKEN=dead\nNODETERM_HOOK_VERSION=2\nNODETERM_NODE_TOKEN_DIR=${primaryTokens}\n`,
'utf8'
)
const live = join(home, '.nodeterm', 'hook-endpoint-live.env')
diff --git a/src/core/agents/hooks/managed-script.ts b/src/core/agents/hooks/managed-script.ts
index 2917a7c08..59dbaa35a 100644
--- a/src/core/agents/hooks/managed-script.ts
+++ b/src/core/agents/hooks/managed-script.ts
@@ -272,26 +272,27 @@ export function buildManagedScript(
' if [ -n "$NODETERM_HOOK_SOCK" ]; then',
// The pipeline\'s exit status IS curl\'s (POSIX: the status of a pipeline is its last command),
// which is what nt_send_request below reads to decide whether to fail over.
- ' nt_hook_headers |',
- ` curl -sS -X POST --unix-socket "$NODETERM_HOOK_SOCK" "http://localhost/hook/${agentId}" \\`,
+ ' nt_code=$(nt_hook_headers |',
+ ` curl -sS -o /dev/null -w '%{http_code}' -X POST --unix-socket "$NODETERM_HOOK_SOCK" "http://localhost/hook/${agentId}" \\`,
' --connect-timeout 0.5 --max-time 1.5 --config - \\',
' -H "Content-Type: application/x-www-form-urlencoded" \\',
' --data-urlencode "nodeId=${NODETERM_NODE_ID}" \\',
' --data-urlencode "version=${NODETERM_HOOK_VERSION}" \\',
' --data-urlencode "nodeterm_pending_id=${nt_pending}" \\',
- ' --data-urlencode "payload@${nt_payload_arg}" >/dev/null 2>&1',
+ ' --data-urlencode "payload@${nt_payload_arg}" 2>/dev/null) || return 1',
' elif [ -n "$NODETERM_HOOK_PORT" ]; then',
- ' nt_hook_headers |',
- ` curl -sS -X POST "http://127.0.0.1:\${NODETERM_HOOK_PORT}/hook/${agentId}" \\`,
+ ' nt_code=$(nt_hook_headers |',
+ ` curl -sS -o /dev/null -w '%{http_code}' -X POST "http://127.0.0.1:\${NODETERM_HOOK_PORT}/hook/${agentId}" \\`,
' --connect-timeout 0.5 --max-time 1.5 --config - \\',
' -H "Content-Type: application/x-www-form-urlencoded" \\',
' --data-urlencode "nodeId=${NODETERM_NODE_ID}" \\',
' --data-urlencode "version=${NODETERM_HOOK_VERSION}" \\',
' --data-urlencode "nodeterm_pending_id=${nt_pending}" \\',
- ' --data-urlencode "payload@${nt_payload_arg}" >/dev/null 2>&1',
+ ' --data-urlencode "payload@${nt_payload_arg}" 2>/dev/null) || return 1',
' else',
' return 1',
' fi',
+ ' [ "$nt_code" != "421" ]',
'}',
'# Request POST with a BOUNDED fallback walk. On a failed primary POST, try the OTHER endpoint',
'# files in most-likely-alive order (nt_candidates) — at most $nt_fallback_max of them — and stop',
diff --git a/src/core/canvas-control-core.ts b/src/core/canvas-control-core.ts
index 61d41670b..75b3a4856 100644
--- a/src/core/canvas-control-core.ts
+++ b/src/core/canvas-control-core.ts
@@ -758,8 +758,8 @@ nt_control_post() {
--data-urlencode "nodeId=\${NODETERM_NODE_ID}" "$@" 2>/dev/null)
fi
}
-# An answer from the server — any HTTP code — is authoritative; only a dead transport fails over.
-nt_reached() { [ -n "$nt_code" ] && [ "$nt_code" != "000" ]; }
+# Only a dead transport or an explicit wrong-owner (421) answer permits failover; 403 stays final.
+nt_reached() { [ -n "$nt_code" ] && [ "$nt_code" != "000" ] && [ "$nt_code" != "421" ]; }
nt_had_transport=""
nt_control_post "$@"
@@ -770,8 +770,9 @@ nt_control_post "$@"
# to it. Before this walk the hook script healed itself and this shim died on the SAME stale file —
# "control endpoint unreachable" with the requested verb silently dropped. Skipped under a codex
# sandbox: there the sandbox denies EVERY connect (issue #367), so each candidate would burn a
-# doomed curl and the sandbox hint below is already the right diagnosis.
-if ! nt_reached && [ -z "$CODEX_SANDBOX_NETWORK_DISABLED" ]; then
+# doomed curl and the sandbox hint below is already the right diagnosis. A 421 is different:
+# it proves the transport worked and the wrong owner rejected this request before dispatch.
+if ! nt_reached && { [ "$nt_code" = "421" ] || [ -z "$CODEX_SANDBOX_NETWORK_DISABLED" ]; }; then
nt_list=$(nt_candidates "$NODETERM_HOOK_ENDPOINT")
if [ -n "$nt_list" ]; then
nt_n=0
diff --git a/src/core/context-link-core.ts b/src/core/context-link-core.ts
index ed3abc456..bd9cf4813 100644
--- a/src/core/context-link-core.ts
+++ b/src/core/context-link-core.ts
@@ -245,8 +245,8 @@ nt_ctx_post() {
--data-urlencode "nodeId=\${NODETERM_NODE_ID}" "$@" 2>/dev/null)
fi
}
-# An answer from the server — any HTTP code — is authoritative; only a dead transport fails over.
-nt_reached() { [ -n "$nt_code" ] && [ "$nt_code" != "000" ]; }
+# Only a dead transport or an explicit wrong-owner (421) answer permits failover; 403 stays final.
+nt_reached() { [ -n "$nt_code" ] && [ "$nt_code" != "000" ] && [ "$nt_code" != "421" ]; }
nt_had_transport=""
nt_ctx_post "$@"
@@ -256,8 +256,8 @@ nt_ctx_post "$@"
# creation, so an app quit/restart leaves it posting at a dead port while a live endpoint file sits
# right next to it. Skipped under a codex sandbox: connect() is denied wholesale there (issue
# #367), so each candidate would burn a doomed curl and the sandbox hint below is already the
-# right diagnosis.
-if ! nt_reached && [ -z "$CODEX_SANDBOX_NETWORK_DISABLED" ]; then
+# right diagnosis. A 421 proves transport worked and still permits discovery.
+if ! nt_reached && { [ "$nt_code" = "421" ] || [ -z "$CODEX_SANDBOX_NETWORK_DISABLED" ]; }; then
nt_list=$(nt_candidates "$NODETERM_HOOK_ENDPOINT")
if [ -n "$nt_list" ]; then
nt_n=0
diff --git a/src/main/canvas-control-shim.failover.test.ts b/src/main/canvas-control-shim.failover.test.ts
index f8ed8c62a..92401e8bb 100644
--- a/src/main/canvas-control-shim.failover.test.ts
+++ b/src/main/canvas-control-shim.failover.test.ts
@@ -11,6 +11,7 @@ import os from 'node:os'
import path from 'node:path'
import { promisify } from 'node:util'
import { CONTROL_SHIM_SCRIPT, CONTROL_UNREACHABLE_MSG } from '../core/canvas-control-core'
+import { CONTEXT_SHIM_SCRIPT } from '../core/context-link-core'
import { STALE_ENDPOINT_HINT } from '../core/agents/hook-endpoint-failover-sh'
import { hookServer } from '../core/agents/hook-server'
import { nodeAuthToken } from '../core/agents/node-auth-token'
@@ -127,22 +128,43 @@ describe('canvas-control shim endpoint failover (issue #445)', () => {
expect(err?.stderr).toContain(STALE_ENDPOINT_HINT)
})
- it('an HTTP answer from the server is authoritative — no failover on a 4xx', async () => {
- // Wrong bearer → the REAL server answers 403. A live candidate exists, but an answered
- // request must never be re-sent elsewhere: the server's refusal is the result.
+ it('keeps an actual node-identity 403 final even when another endpoint could accept it', async () => {
+ const secret = Buffer.alloc(32, 21)
+ hookServer.setNodeAuthSecret(secret)
+ const tokens = path.join(dir, 'forged-tokens')
+ fs.mkdirSync(tokens)
+ fs.writeFileSync(path.join(tokens, 'node-1'), nodeAuthToken(secret, 'another-node'))
+ const endpoint = path.join(dir, 'forged.env')
+ fs.writeFileSync(endpoint, `NODETERM_HOOK_PORT='${hookServer.getPort()}'\nNODETERM_HOOK_TOKEN='${hookServer.getToken()}'\nNODETERM_NODE_TOKEN_DIR='${tokens}'\n`)
+ received = []
+ try {
+ await expect(callShim(['list'], { NODETERM_HOOK_ENDPOINT: endpoint })).rejects.toMatchObject({ code: 1 })
+ expect(received).toEqual([])
+ } finally { hookServer.clearNodeAuthSecretForTests() }
+ })
+
+ it('the context shim also recovers from a wrong owner', async () => {
+ const contextShim = path.join(dir, 'context.sh')
+ fs.writeFileSync(contextShim, CONTEXT_SHIM_SCRIPT)
+ hookServer.setContextLinkHandler(async () => 'linked fixture')
+ const result = await run('/bin/sh', [contextShim, 'list'], {
+ env: { PATH: process.env.PATH, HOME: home, NODETERM_NODE_ID: 'node-1', NODETERM_CANVAS_CONTROL: '1',
+ NODETERM_HOOK_PORT: String(hookServer.getPort()), NODETERM_HOOK_TOKEN: 'wrong' }
+ })
+ expect(result.stdout).toContain('linked fixture')
+ })
+
+ it.each(['', '1'])('a wrong-owner response discovers the live endpoint (sandbox marker %s)', async (sandbox) => {
+ // A 421 proves that transport worked, even inside a sandbox with an allowed Unix socket.
+ // Discovery may retry because the first server rejected the bearer before dispatch.
const answeredEndpoint = path.join(dir, 'answered-endpoint.env')
fs.writeFileSync(
answeredEndpoint,
`NODETERM_HOOK_PORT='${hookServer.getPort()}'\nNODETERM_HOOK_TOKEN='wrong-bearer'\n`
)
received = []
- const err = await callShim(['list'], { NODETERM_HOOK_ENDPOINT: answeredEndpoint }).then(
- () => null,
- (e: { code: number; stderr: string }) => e
- )
- expect(err?.code).toBe(1)
- // No stale-endpoint diagnosis — the server was reached — and no fallback POST landed.
- expect(err?.stderr ?? '').not.toContain(STALE_ENDPOINT_HINT)
- expect(received).toEqual([])
+ const result = await callShim(['list'], { NODETERM_HOOK_ENDPOINT: answeredEndpoint, CODEX_SANDBOX_NETWORK_DISABLED: sandbox })
+ expect(result.stdout.trim()).toBe('did list')
+ expect(received).toEqual([{ verb: 'list', nodeId: 'node-1', verified: false }])
})
})
diff --git a/src/main/canvas-control-shim.test.ts b/src/main/canvas-control-shim.test.ts
index 5d776b8f7..0e090bf18 100644
--- a/src/main/canvas-control-shim.test.ts
+++ b/src/main/canvas-control-shim.test.ts
@@ -171,7 +171,7 @@ describe('canvas-control shim', () => {
expect(received.length).toBe(before)
})
- it('rejects a wrong token (the server answers 403, the shim exits non-zero)', async () => {
+ it('rejects a wrong token (the server answers wrong-owner 421, the shim exits non-zero)', async () => {
await expect(callShim(['list'], { NODETERM_HOOK_TOKEN: 'wrong' })).rejects.toMatchObject({
code: 1
})
diff --git a/src/main/remote-ssh/remote-hooks.test.ts b/src/main/remote-ssh/remote-hooks.test.ts
index 802183d7b..b2892d426 100644
--- a/src/main/remote-ssh/remote-hooks.test.ts
+++ b/src/main/remote-ssh/remote-hooks.test.ts
@@ -1,9 +1,12 @@
+import { createHash } from 'crypto'
import { execFileSync } from 'child_process'
import { describe, expect, it, vi } from 'vitest'
import { RemoteHooks, openCodeInstructionsTarget } from './remote-hooks'
import { isSafeRemoteHome } from '../../core/remote-safety'
import { hookServer } from '../../core/agents/hook-server'
+const ownerT = createHash('sha256').update('t').digest('hex').slice(0, 16)
+const owner = createHash('sha256').update('tok').digest('hex').slice(0, 16)
const conn = { host: 'h', user: 'u' }
function harness(
@@ -50,10 +53,10 @@ describe('RemoteHooks.setup', () => {
// real project OR a transient folder-picker browse — has its own reverse-tunnel socket, so a
// shared file let the last writer (often a short-lived browse whose tunnel then died) point
// every session at a dead socket, silently killing hook delivery for all real projects.
- expect(res?.endpointPath).toBe('/home/u/.nodeterm/hook-endpoint-p1.env')
+ expect(res?.endpointPath).toBe(`/home/u/.nodeterm/hook-endpoint-p1-${owner}.env`)
const joined = calls.map((c) => c.args.join(' '))
// reverse forward binds the ABSOLUTE remote socket (no unexpanded ~).
- expect(joined.some((j) => j.includes('-O forward') && j.includes('/home/u/.nodeterm/hook-p1.sock:127.0.0.1:51234'))).toBe(true)
+ expect(joined.some((j) => j.includes('-O forward') && /\/home\/u\/.nodeterm\/hook-[a-f0-9]{20}\.sock:127.0.0.1:51234/.test(j))).toBe(true)
// Endpoint bearer goes to a private, invocation-owned temp and is then published atomically.
const endpointWrite = calls.find((c) => (c.stdin ?? '').includes("NODETERM_HOOK_TOKEN='tok'"))
const endpointTemp = endpointWrite?.cmd.match(
@@ -62,7 +65,7 @@ describe('RemoteHooks.setup', () => {
expect(endpointTemp).toBeTruthy()
expect(endpointWrite?.cmd).toContain(`chmod 600 -- ${endpointTemp}`)
expect(endpointWrite?.cmd).toContain(
- `mv -f -- ${endpointTemp} '/home/u/.nodeterm/hook-endpoint-p1.env'`
+ `mv -f -- ${endpointTemp} '/home/u/.nodeterm/hook-endpoint-p1-${owner}.env'`
)
expect(endpointWrite?.cmd).toContain(`rm -f -- ${endpointTemp}`)
expect(
@@ -70,7 +73,7 @@ describe('RemoteHooks.setup', () => {
(c) =>
// Values are single-quoted (issue #351) so a spaced remote path sources cleanly.
(c.stdin ?? '').includes("NODETERM_HOOK_TOKEN='tok'") &&
- (c.stdin ?? '').includes("NODETERM_HOOK_SOCK='/home/u/.nodeterm/hook-p1.sock'")
+ /NODETERM_HOOK_SOCK='\/home\/u\/.nodeterm\/hook-[a-f0-9]{20}\.sock'/.test(c.stdin ?? '')
)
).toBe(true)
// managed script written to the absolute path + config merged with the guarded command.
@@ -89,6 +92,24 @@ describe('RemoteHooks.setup', () => {
expect(joined.some((j) => j.includes('~/'))).toBe(false)
})
+ it('isolates installations with the same project id and allocates a fresh bind on reconnect', async () => {
+ const a = harness()
+ const b = harness()
+ try {
+ hookServer.setNodeAuthSecret(Buffer.alloc(32, 1))
+ const first = await a.rh.setup('p1', conn, '/s', { port: 1, token: 'a', version: '2' })
+ const again = await a.rh.setup('p1', conn, '/s', { port: 1, token: 'a', version: '2' })
+ hookServer.setNodeAuthSecret(Buffer.alloc(32, 2))
+ const other = await b.rh.setup('p1', conn, '/s', { port: 2, token: 'b', version: '2' })
+ expect(first).toEqual(again) // stable discovery within one installation
+ expect(first?.endpointPath).not.toBe(other?.endpointPath)
+ const binds = [...a.calls, ...b.calls].filter((c) => c.args.includes('forward'))
+ expect(new Set(binds.map((c) => c.args[c.args.indexOf('-R') + 1].split(':')[0])).size).toBe(3)
+ const firstSpec = binds[0].args[binds[0].args.indexOf('-R') + 1]
+ expect(a.calls.some((c) => c.args.includes('cancel') && c.args.includes(firstSpec))).toBe(true)
+ } finally { hookServer.clearNodeAuthSecretForTests() }
+ })
+
it('installs codex too — hooks.json merge PLUS the config.toml trust write', async () => {
const { rh, calls } = harness()
const res = await rh.setup('p1', conn, '/s.sock', { port: 51234, token: 'tok', version: '1' })
@@ -141,7 +162,7 @@ describe('RemoteHooks.setup', () => {
// forward — the field case that killed remote statuses for hours); the rebind fixes it.
const { rh, calls } = harness({ 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')
+ expect(res?.endpointPath).toBe(`/home/u/.nodeterm/hook-endpoint-p1-${owner}.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.
@@ -173,11 +194,11 @@ describe('RemoteHooks.setup', () => {
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)
+ expect(calls.map((c) => c.args.join(' ')).some((j) => j.includes('hook-endpoint-p1-'))).toBe(false)
})
it('does not advertise an endpoint whose atomic credential publish returns non-zero', async () => {
- const { rh, calls } = harness({ failCodeOn: 'hook-endpoint-p1.env' })
+ const { rh, calls } = harness({ failCodeOn: 'hook-endpoint-p1-' })
const res = await rh.setup('p1', conn, '/s.sock', {
port: 51234,
token: 'tok',
@@ -202,7 +223,7 @@ describe('RemoteHooks.setup', () => {
})
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(res?.endpointPath).toBe(`/home/u/.nodeterm/hook-endpoint-p1-${owner}.env`)
expect(forwards).toBe(2)
})
@@ -210,16 +231,16 @@ describe('RemoteHooks.setup', () => {
const a = await harness().rh.setup('proj', conn, '/s', { port: 1, token: 't', version: '1' })
const { rh, calls } = harness()
const b = await rh.setup('ssh-browse-xyz', conn, '/s', { port: 2, token: 't', version: '1' })
- expect(a?.endpointPath).toBe('/home/u/.nodeterm/hook-endpoint-proj.env')
- expect(b?.endpointPath).toBe('/home/u/.nodeterm/hook-endpoint-ssh-browse-xyz.env')
+ expect(a?.endpointPath).toBe(`/home/u/.nodeterm/hook-endpoint-proj-${ownerT}.env`)
+ expect(b?.endpointPath).toBe(`/home/u/.nodeterm/hook-endpoint-ssh-browse-xyz-${ownerT}.env`)
// the browse writes ITS OWN endpoint file, never the real project's.
const joined = calls.map((c) => c.args.join(' '))
expect(
joined.some(
- (j) => j.includes('cat > ') && j.includes("hook-endpoint-ssh-browse-xyz.env'")
+ (j) => j.includes('cat > ') && j.includes(`hook-endpoint-ssh-browse-xyz-${ownerT}.env'`)
)
).toBe(true)
- expect(joined.some((j) => j.includes('hook-endpoint-proj.env'))).toBe(false)
+ expect(joined.some((j) => j.includes('hook-endpoint-proj-'))).toBe(false)
})
})
@@ -246,12 +267,12 @@ describe('RemoteHooks.setup — a hostile remote $HOME', () => {
it('quotes every path it builds from $HOME, so a home with a space still installs', async () => {
const { rh, conn, runs } = harness({ responses: { $HOME: '/Users/Enes K' } })
const res = await rh.setup('p1', conn, '/s.sock', { port: 51234, token: 'tok', version: '1' })
- expect(res?.endpointPath).toBe('/Users/Enes K/.nodeterm/hook-endpoint-p1.env')
+ expect(res?.endpointPath).toBe(`/Users/Enes K/.nodeterm/hook-endpoint-p1-${owner}.env`)
const joined = runs.map((r) => r.cmd)
expect(joined.some((j) => j.includes(`mkdir -p '/Users/Enes K/.nodeterm'`))).toBe(true)
expect(
joined.some(
- (j) => j.includes('cat > ') && j.includes("/Users/Enes K/.nodeterm/hook-endpoint-p1.env'")
+ (j) => j.includes('cat > ') && j.includes(`/Users/Enes K/.nodeterm/hook-endpoint-p1-${owner}.env'`)
)
).toBe(true)
expect(joined.some((j) => j.includes(`cat > '/Users/Enes K/.claude/settings.json'`))).toBe(true)
@@ -534,7 +555,7 @@ describe('RemoteHooks.teardown', () => {
// cancels using the SAME absolute sock path stored at setup.
expect(
run.mock.calls.some(
- ([a]) => a.join(' ').includes('-O cancel') && a.join(' ').includes('/home/u/.nodeterm/hook-p1.sock:127.0.0.1:51234')
+ ([a]) => a.join(' ').includes('-O cancel') && /hook-[a-f0-9]{20}\.sock:127.0.0.1:51234/.test(a.join(' '))
)
).toBe(true)
})
@@ -885,7 +906,7 @@ describe('RemoteHooks.setup — the host $HOME is data, not truth', () => {
it('installs hooks for a host whose $HOME is not spelled in ASCII', async () => {
const { rh, calls } = harness({ responses: { 'printf %s "$HOME"': '/home/gökhan' } })
const res = await rh.setup('p1', conn, '/s.sock', { port: 51234, token: 'tok', version: '1' })
- expect(res?.endpointPath).toBe('/home/gökhan/.nodeterm/hook-endpoint-p1.env')
+ expect(res?.endpointPath).toBe(`/home/gökhan/.nodeterm/hook-endpoint-p1-${owner}.env`)
const joined = calls.map((c) => c.args.join(' '))
expect(joined.some((j) => j.includes(`cat > '/home/gökhan/.claude/settings.json'`))).toBe(true)
})
@@ -943,7 +964,7 @@ describe('RemoteHooks.setup — install concurrency', () => {
await Promise.resolve()
h.releaseAll()
}
- await expect(done).resolves.toEqual({ endpointPath: '/home/u/.nodeterm/hook-endpoint-p1.env' })
+ await expect(done).resolves.toEqual({ endpointPath: `/home/u/.nodeterm/hook-endpoint-p1-${ownerT}.env` })
})
it('the TUNNEL and the ENDPOINT FILE are both complete before any agent install starts', async () => {
@@ -969,7 +990,7 @@ describe('RemoteHooks.setup — install concurrency', () => {
// catches its own errors today — this is the guard for the next one that forgets.)
const { rh } = harness({ failOn: '.grok' })
const res = await rh.setup('p1', conn, '/s.sock', { port: 1, token: 't', version: '1' })
- expect(res?.endpointPath).toBe('/home/u/.nodeterm/hook-endpoint-p1.env')
+ expect(res?.endpointPath).toBe(`/home/u/.nodeterm/hook-endpoint-p1-${ownerT}.env`)
})
it('still installs every agent — claude, gemini, codex, grok and copilot', async () => {
diff --git a/src/main/remote-ssh/remote-hooks.ts b/src/main/remote-ssh/remote-hooks.ts
index bd064d53c..1a61d4daa 100644
--- a/src/main/remote-ssh/remote-hooks.ts
+++ b/src/main/remote-ssh/remote-hooks.ts
@@ -1,3 +1,4 @@
+import { createHash, randomUUID } from 'crypto'
// Connection-time remote hook setup for SSH projects: opens the reverse unix-socket tunnel
// (local loopback hook server → remote socket), writes the owner-only remote endpoint file,
// and installs the managed hook into the remote agent configs (claude + gemini JSON settings,
@@ -165,7 +166,11 @@ export class RemoteHooks {
return null
}
const remoteDir = `${home}/.nodeterm`
- const sock = `${remoteDir}/hook-${projectId}.sock`
+ // A stable public hash of the installation identity namespaces discovery. If identity
+ // initialization failed, the run bearer still isolates this degraded run.
+ // Fresh bind names mean setup cannot unlink a local server or another desktop's tunnel.
+ const owner = createHash('sha256').update(hookServer.nodeAuthSecretOrNull() ?? hook.token).digest('hex').slice(0, 16)
+ let sock = ''
// PER-PROJECT endpoint file. The sock is already per-project, but the endpoint file used to
// be a single shared `hook-endpoint.env`: every connect — a real project AND every transient
// folder-picker browse (projectId `ssh-browse-*`, same connect() path) — overwrote it with
@@ -173,7 +178,7 @@ export class RemoteHooks {
// pointing at a dead socket, so every real project's hook POSTs (`curl --unix-socket`) failed
// 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`
+ const endpoint = `${remoteDir}/hook-endpoint-${projectId}-${owner}.env`
// 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
@@ -188,20 +193,20 @@ export class RemoteHooks {
// 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 ${posixQuote(remoteDir)} && rm -f ${posixQuote(sock)}`)
- )
+ sock = `${remoteDir}/hook-${randomUUID().replace(/-/g, '').slice(0, 20)}.sock`
+ await this.r.run(childArgs(conn, controlPath, `mkdir -p ${posixQuote(remoteDir)}`))
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) {
+ await this.r.run(hookForwardCancelArgs(conn, controlPath, sock, hook.port)).catch(() => {})
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 })
+ const previous = this.specs.get(projectId)
// 2. Remote endpoint file — written only after the tunnel proved live, so sessions are
// never pointed at a socket that answers nothing. The file carries the hook bearer. A
// direct `cat > endpoint` both exposed partial bytes and preserved an old permissive mode;
@@ -215,7 +220,14 @@ export class RemoteHooks {
childArgs(conn, controlPath, endpointWrite.command),
remoteEndpointFileContents(sock, hook.token, hook.version, `${remoteDir}/node-tokens`)
)
- if (endpointResult.code !== 0) return null
+ if (endpointResult.code !== 0) {
+ await this.r.run(hookForwardCancelArgs(conn, controlPath, sock, hook.port)).catch(() => {})
+ return null
+ }
+ this.specs.set(projectId, { sock, port: hook.port })
+ if (previous) {
+ await this.r.run(hookForwardCancelArgs(conn, controlPath, previous.sock, previous.port)).catch(() => {})
+ }
// 3-6. Per-agent hook installs — CONCURRENT, because they are independent of each other.
//
// Each one writes its own script under `<remoteDir>/agent-hooks/` and merges its own agent's
diff --git a/src/main/remote-ssh/ssh-project.test.ts b/src/main/remote-ssh/ssh-project.test.ts
index 4ae20ed19..6e6a10afa 100644
--- a/src/main/remote-ssh/ssh-project.test.ts
+++ b/src/main/remote-ssh/ssh-project.test.ts
@@ -1181,7 +1181,7 @@ describe('SshProjectManager', () => {
expect(spawnMaster).toHaveBeenCalledTimes(1)
expect(seq).toEqual(['agent', 'spawn']) // agent up BEFORE the rebuilt master, on this site too
// The retried setup over the fresh master verified → the remote endpoint file is advertised.
- expect(info.hookEndpointPath).toBe('/home/u/.nodeterm/hook-endpoint-p1.env')
+ expect(info.hookEndpointPath).toMatch(/^\/home\/u\/\.nodeterm\/hook-endpoint-p1-[a-f0-9]{16}\.env$/)
expect(phases(statuses).slice(0, 2)).toEqual(['connecting', 'connected'])
})
@@ -1230,7 +1230,7 @@ describe('SshProjectManager', () => {
expect(spawnMaster).toHaveBeenCalledTimes(1)
expect(checksAfterRespawn).toBeGreaterThanOrEqual(BIND_AT)
// The retried setup over the (slow) fresh master verified, so the endpoint is not dropped.
- expect(info.hookEndpointPath).toBe('/home/u/.nodeterm/hook-endpoint-p1.env')
+ expect(info.hookEndpointPath).toMatch(/^\/home\/u\/\.nodeterm\/hook-endpoint-p1-[a-f0-9]{16}\.env$/)
expect(statuses).toContain('connected')
})
@@ -1438,6 +1438,21 @@ describe('SshProjectManager', () => {
expect(onTunnelVerified).toHaveBeenCalledWith('p1', controlPathFor('p1'), conn)
})
+ it('invalidates a wrong-owner tunnel visibly and clears the warning after repair', async () => {
+ let wrongOwner = false
+ const mgr = makeVerifiedMgr(vi.fn(), () => wrongOwner ? '421' : '204')
+ const onStatus = (mgr as unknown as { r: { onStatus: ReturnType<typeof vi.fn> } }).r.onStatus
+ await mgr.connect('p1', conn, '/remote/cwd')
+ onStatus.mockClear()
+ wrongOwner = true
+ await mgr.connect('p1', conn, '/remote/cwd')
+ await mgr.connect('p1', conn, '/remote/cwd')
+ expect(onStatus.mock.calls.filter(([e]) => e.hookTunnelVerified === false)).toHaveLength(1)
+ wrongOwner = false
+ await mgr.connect('p1', conn, '/remote/cwd')
+ expect(onStatus).toHaveBeenCalledWith({ projectId: 'p1', status: 'connected', hookTunnelVerified: true })
+ })
+
it('rebinds the forward on repair — the endpoint is re-advertised, not merely re-probed', async () => {
// The whole failure is a master with no `-R`, so a repair that did not call `-O forward`
// would leave every hook POST dying exactly as before while reporting success.
@@ -1493,7 +1508,7 @@ describe('SshProjectManager', () => {
const res = await mgr.connect('p1', conn, '/remote/cwd')
expect(res.controlPath).toBe(controlPathFor('p1'))
// Everything AFTER the hook still ran: the connect result is complete, not truncated.
- expect(res.hookEndpointPath).toBe('/home/u/.nodeterm/hook-endpoint-p1.env')
+ expect(res.hookEndpointPath).toMatch(/^\/home\/u\/\.nodeterm\/hook-endpoint-p1-[a-f0-9]{16}\.env$/)
expect(res.remoteHome).toBe('/home/u')
})
})
@@ -2225,7 +2240,7 @@ describe('SshProjectManager', () => {
await new Promise((r) => setImmediate(r))
await mgr.disconnect('p1') // user tears the project down mid-setup
const live = await mgr.connect('p1', conn) // fresh attempt, completes fully
- expect(live.hookEndpointPath).toBe('/home/u/.nodeterm/hook-endpoint-p1.env')
+ expect(live.hookEndpointPath).toMatch(/^\/home\/u\/\.nodeterm\/hook-endpoint-p1-[a-f0-9]{16}\.env$/)
released = true
releaseFirstSetup!()
await stale // settles without owning the entry
@@ -2234,7 +2249,7 @@ describe('SshProjectManager', () => {
// which is the dead-RUNNING-badges failure). Status counts are not asserted: the live
// attempt's claude probe legitimately re-pushes 'connected' on its own schedule.
const reused = await mgr.connect('p1', conn)
- expect(reused.hookEndpointPath).toBe('/home/u/.nodeterm/hook-endpoint-p1.env')
+ expect(reused.hookEndpointPath).toMatch(/^\/home\/u\/\.nodeterm\/hook-endpoint-p1-[a-f0-9]{16}\.env$/)
})
it('a publickey denial with NO passphrase ask gets the agent-only hint, ONE attempt, no retry', async () => {
diff --git a/src/main/remote-ssh/ssh-project.ts b/src/main/remote-ssh/ssh-project.ts
index 952aa10ec..ec2cafffe 100644
--- a/src/main/remote-ssh/ssh-project.ts
+++ b/src/main/remote-ssh/ssh-project.ts
@@ -443,6 +443,17 @@ export class SshProjectManager {
/** Consecutive failed tunnel repairs per project, so a host that can never forward is not
* re-installed on every watchdog tick. See `tunnel-repair.ts` for why the first one is free. */
private tunnelRepair = new Map<string, TunnelRepairState>()
+ private lostHookTunnels = new Set<string>()
+
+ private hookTunnelHealth(projectId: string, verified: boolean): void {
+ if (verified) {
+ if (!this.lostHookTunnels.delete(projectId)) return
+ } else {
+ if (this.lostHookTunnels.has(projectId)) return
+ this.lostHookTunnels.add(projectId)
+ }
+ this.emitStatus({ projectId, status: 'connected', hookTunnelVerified: verified })
+ }
/**
* Re-verify a REUSED master's reverse hook tunnel, and rebuild it if it stopped answering
@@ -470,10 +481,14 @@ export class SshProjectManager {
const hook = this.r.getHook()
// No hook server yet ⇒ nothing to point at, and `setup()` would refuse anyway.
if (!hook?.port || !hook.token) return
- if (await this.remoteHooks.tunnelAlive(projectId, existing.conn, existing.controlPath, hook.token)) {
+ const alive = await this.remoteHooks.tunnelAlive(projectId, existing.conn, existing.controlPath, hook.token)
+ if (this.conns.get(projectId) !== existing) return
+ if (alive) {
this.tunnelRepair.delete(projectId)
+ this.hookTunnelHealth(projectId, true)
return
}
+ this.hookTunnelHealth(projectId, false)
const now = Date.now()
if (!shouldAttemptTunnelRepair(this.tunnelRepair.get(projectId), now)) return
const res = await this.remoteHooks.setup(projectId, existing.conn, existing.controlPath, hook)
@@ -485,6 +500,7 @@ export class SshProjectManager {
// point sessions at a socket belonging to a connection nobody holds.
if (this.conns.get(projectId) !== existing) return
existing.hookEndpointPath = res.endpointPath
+ this.hookTunnelHealth(projectId, true)
// Same contract as the establish path: hook events lost while the tunnel was down are gone
// for good, so the working agents need a resync. Fire-and-forget behind a catch — a repair
// job must never surface to the user as a dead SSH project.
@@ -958,6 +974,7 @@ export class SshProjectManager {
entry.codexRelayRuntimePath = codexRuntime?.runtime
entry.codexCliPath = codexRuntime?.codex
this.emitStatus({ projectId, status: 'connected' })
+ if (hookEndpointPath) this.hookTunnelHealth(projectId, true)
// The tunnel is live again on a master we just established (the reuse branch returned long
// before this line), so this is exactly the moment the hook events lost while it was down
// can be reconstructed from the host.
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index 9cbed6b7a..c85aaa263 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -1289,6 +1289,7 @@ export function Canvas() {
const [cloneDialogOpen, setCloneDialogOpen] = useState(false)
// Live SSH ControlMaster status per project id (drives the thin connection banner).
const [sshStatus, setSshStatus] = useState<Record<string, SshProjectStatus>>({})
+ const [lostHookTunnels, setLostHookTunnels] = useState<Record<string, boolean>>({})
// The cause that came with an `error` status. Kept beside the status because the banner used to
// render a bare "SSH connection error", throwing away the one line ssh gave us (permission
// denied, host unreachable, host key mismatch) that tells the user what to actually fix.
@@ -13312,6 +13313,10 @@ export function Canvas() {
// Track SSH project connection status for the thin connection banner (keyed by project id).
useEffect(() => {
return window.nodeTerminal.sshProject.onStatus((e) => {
+ if (e.hookTunnelVerified !== undefined) {
+ setLostHookTunnels((prev) => ({ ...prev, [e.projectId]: !e.hookTunnelVerified }))
+ return // A health probe must never trigger terminal reconnection.
+ }
setSshStatus((prev) => ({ ...prev, [e.projectId]: e.status }))
// Keep the cause for the banner. Cleared on any non-error status so a stale reason can
// never be shown next to a healthy connection.
@@ -14278,15 +14283,17 @@ export function Canvas() {
)}
{activeSshServer &&
sshStatus[activeProjectId] &&
- sshStatus[activeProjectId] !== 'connected' &&
+ (sshStatus[activeProjectId] !== 'connected' || lostHookTunnels[activeProjectId]) &&
(() => {
const st = sshStatus[activeProjectId]
+ const hooksLost = st === 'connected' && lostHookTunnels[activeProjectId]
const isError = st === 'error' || st === 'disconnected'
// The reason ssh gave, already trimmed to one line by lastSshErrorLine in main. Shown
// inline: a bare "SSH connection error" leaves the user with nothing to act on.
const cause = sshError[activeProjectId]
- const text =
- st === 'connecting'
+ const text = hooksLost
+ ? `${activeSshServer.label}: Agent status and canvas control lost their verified connection. Retrying automatically…`
+ : st === 'connecting'
? `Connecting to ${activeSshServer.label}…`
: st === 'reconnecting'
? `Reconnecting to ${activeSshServer.label}…`
@@ -14310,7 +14317,7 @@ export function Canvas() {
borderRadius: 8
}}
>
- {isError ? (
+ {isError || hooksLost ? (
<span
style={{
width: 8,
diff --git a/src/shared/types.ts b/src/shared/types.ts
index d05cad046..e8115af96 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -2007,6 +2007,8 @@ export type SshProjectStatus = 'connecting' | 'connected' | 'disconnected' | 're
* Absent = not probed / nothing new ⇒ the renderer keeps omitting the `auto` flag (fail-open).
*/
export interface SshProjectStatusEvent {
+ /** Hook-only health update; it does not imply an SSH reconnect or terminal restart. */
+ hookTunnelVerified?: boolean
projectId: string
status: SshProjectStatus
error?: string