Skip to content

The agent that grows with you

fix(desktop): SSH orphan reaper fails CLOSED on remote lockfile schema/ownership skew

Hermes Agent3ee0c62224a2
diff --git a/apps/desktop/electron/remote-lifecycle.test.ts b/apps/desktop/electron/remote-lifecycle.test.ts
index 832be8836a7..56897775c51 100644
--- a/apps/desktop/electron/remote-lifecycle.test.ts
+++ b/apps/desktop/electron/remote-lifecycle.test.ts
@@ -17,6 +17,7 @@ import {
expandRemotePath,
fingerprintToken,
isForwardBindCollision,
+ isLockfileSkew,
listRemoteHermesProfiles,
locateHermes,
LOCKFILE_SCHEMA_VERSION,
@@ -272,14 +273,102 @@ test('ownership paths are isolated by ownership ID and spawn nonce', () => {
assert.equal(spawnLogPath(OWNERSHIP_ID, SPAWN_NONCE), `~/.hermes/desktop-ssh/${OWNERSHIP_ID}/${SPAWN_NONCE}.log`)
})
-test('readLockfile returns null for missing, empty, malformed, or wrong-schema', async () => {
+test('readLockfile returns null ONLY for a missing/empty lockfile', async () => {
assert.equal(await readLockfile(fakeSsh([[/cat/, '']]), OWNERSHIP_ID), null)
- assert.equal(await readLockfile(fakeSsh([[/cat/, 'not json']]), OWNERSHIP_ID), null)
- assert.equal(await readLockfile(fakeSsh([[/cat/, JSON.stringify({ schemaVersion: 999 })]]), OWNERSHIP_ID), null)
const good = ownedLock({ pid: 1, port: 2 })
assert.deepEqual(await readLockfile(fakeSsh([[/cat/, JSON.stringify(good)]]), OWNERSHIP_ID), good)
})
+// #95532 fail-closed guard: a lockfile that EXISTS but doesn't match what this
+// build writes is SKEW (foreign fork build, corruption, or a future schema) —
+// it must be distinguishable from "no lockfile" so no reap/overwrite path can
+// treat foreign live state as reapable.
+test('readLockfile classifies existing-but-foreign lockfiles as skew, never null', async () => {
+ // (a) foreign-schema lockfile (fork build wrote a different shape)
+ const foreign = await readLockfile(fakeSsh([[/cat/, 'not json at all']]), OWNERSHIP_ID)
+ assert.equal(isLockfileSkew(foreign), true)
+ // (b) truncated lockfile (partial write / corruption)
+ const truncated = await readLockfile(
+ fakeSsh([[/cat/, JSON.stringify(ownedLock()).slice(0, 40)]]),
+ OWNERSHIP_ID
+ )
+ assert.equal(isLockfileSkew(truncated), true)
+ // (c) future schemaVersion (newer build owns this remote)
+ const future = await readLockfile(
+ fakeSsh([[/cat/, JSON.stringify(ownedLock({ schemaVersion: LOCKFILE_SCHEMA_VERSION + 1 }))]]),
+ OWNERSHIP_ID
+ )
+ assert.equal(isLockfileSkew(future), true)
+ // unknown schema number entirely
+ const unknown = await readLockfile(fakeSsh([[/cat/, JSON.stringify({ schemaVersion: 999 })]]), OWNERSHIP_ID)
+ assert.equal(isLockfileSkew(unknown), true)
+ // missing ownershipId / foreign ownership
+ const foreignOwner = await readLockfile(
+ fakeSsh([[/cat/, JSON.stringify(ownedLock({ ownershipId: undefined }))]]),
+ OWNERSHIP_ID
+ )
+ assert.equal(isLockfileSkew(foreignOwner), true)
+ // every skew carries a diagnosable reason and is never a valid lock
+ for (const skew of [foreign, truncated, future, unknown, foreignOwner]) {
+ assert.equal(typeof (skew as any).reason, 'string')
+ assert.notEqual(skew, null)
+ }
+ // a valid lock and a missing lockfile are NOT skew
+ assert.equal(isLockfileSkew(await readLockfile(fakeSsh([[/cat/, '']]), OWNERSHIP_ID)), false)
+ assert.equal(
+ isLockfileSkew(await readLockfile(fakeSsh([[/cat/, JSON.stringify(ownedLock())]]), OWNERSHIP_ID)),
+ false
+ )
+})
+
+// #95532: on skew the reap pass must FAIL CLOSED — no kill, no lockfile
+// removal/overwrite, no fresh spawn on top of foreign live state.
+test('connect() fails closed on lockfile schema/ownership skew: skips reap, touches nothing', async () => {
+ const skewShapes: Array<[string, string]> = [
+ ['foreign-schema lockfile', '{"pid":333,"owner":"some-fork-desktop","version":"9.9.9"}'],
+ ['truncated lockfile', JSON.stringify(ownedLock()).slice(0, 40)],
+ ['future schemaVersion', JSON.stringify(ownedLock({ schemaVersion: LOCKFILE_SCHEMA_VERSION + 1 }))]
+ ]
+
+ for (const [label, raw] of skewShapes) {
+ const ssh = fakeSsh([
+ [/uname/, 'Linux\nx86_64'],
+ [/\[ -x/, 'OK'],
+ [/cat .*lock\.json/, raw],
+ [/kill -0/, 'ALIVE'],
+ [/print\("OWNED"/, 'OWNED\n']
+ ])
+
+ await assert.rejects(
+ () => connect(connectDeps(ssh, { reuseToken: 'stored-token' })),
+ (error: any) => error.kind === 'remote-lockfile-skew',
+ `${label}: connect must refuse with remote-lockfile-skew`
+ )
+ assert.ok(!ssh.calls.some(c => /(^|[^-\d])kill -?9? ?\d/.test(c) && !/kill -0/.test(c)), `${label}: must not kill any pid`)
+ assert.ok(!ssh.calls.some(c => /rm -f/.test(c)), `${label}: must not remove any remote file`)
+ assert.ok(!ssh.calls.some(c => /setsid|nohup/.test(c)), `${label}: must not spawn on top of foreign state`)
+ assert.ok(!ssh.calls.some(c => /printf '%s' '.*schemaVersion/.test(c)), `${label}: must not overwrite the lockfile`)
+ }
+})
+
+test('disconnect() fails closed on lockfile skew: never reaps, never drops the foreign lockfile', async () => {
+ const ssh = fakeSsh([
+ [/cat .*lock\.json/, JSON.stringify(ownedLock({ schemaVersion: LOCKFILE_SCHEMA_VERSION + 1 }))],
+ [/kill -0/, 'ALIVE'],
+ [/print\("OWNED"/, 'OWNED\n']
+ ])
+
+ await disconnect(ssh, OWNERSHIP_ID)
+ assert.ok(!ssh.calls.some(c => /(^|[^-\d])kill -?9? ?\d/.test(c) && !/kill -0/.test(c)), 'must not kill any pid')
+ assert.ok(!ssh.calls.some(c => /rm -f/.test(c)), 'must not remove the foreign lockfile or logs')
+})
+
+test('cleanupStale is inert when handed a skew sentinel (defense in depth)', async () => {
+ const ssh = fakeSsh([[/print\("OWNED"/, 'OWNED\n']])
+ await cleanupStale(ssh, OWNERSHIP_ID, { skew: true, reason: 'schema-version' } as any)
+ assert.equal(ssh.calls.length, 0, 'skew must short-circuit before any remote command')
+})
+
test('writeLockfile mkdir -ps and stamps the schema version', async () => {
const ssh = fakeSsh([])
await writeLockfile(ssh, OWNERSHIP_ID, ownedLock({ pid: 7, port: 9 }))
@@ -815,13 +904,10 @@ test('connect() respawns when the lockfile hermesPath differs from the resolved
test('connect() respawns when the lockfile protocolVersion is incompatible', async () => {
const reuseToken = 'stored-token'
- const lock = {
- schemaVersion: LOCKFILE_SCHEMA_VERSION,
+ const lock = ownedLock({
protocolVersion: PROTOCOL_VERSION + 99,
- pid: 333,
- port: 40000,
tokenFingerprint: fingerprintToken(reuseToken)
- }
+ })
const ssh = fakeSsh([
[/uname/, 'Linux\nx86_64'],
@@ -899,14 +985,7 @@ test('connect() respawns when the lockfile pid is dead (killed dashboard)', asyn
test('connect() respawns when the dashboard is wedged (alive pid, probe fails)', async () => {
const reuseToken = 'stored'
-
- const lock = {
- schemaVersion: LOCKFILE_SCHEMA_VERSION,
- protocolVersion: PROTOCOL_VERSION,
- pid: 333,
- port: 40000,
- tokenFingerprint: fingerprintToken(reuseToken)
- }
+ const lock = ownedLock({ tokenFingerprint: fingerprintToken(reuseToken) })
const ssh = fakeSsh([
[/uname/, 'Linux\nx86_64'],
@@ -1194,21 +1273,21 @@ test('spawnRemoteDashboard upload uses exclusive-create and O_NOFOLLOW', async (
assert.ok(!uploadCmd.includes('tk'), 'token must not appear in the upload command')
})
-test('readLockfile rejects lock with non-integer pid', async () => {
+test('readLockfile treats a lock with non-integer pid as skew', async () => {
const lock = { schemaVersion: LOCKFILE_SCHEMA_VERSION, pid: 'not-a-number', port: 8080 }
- assert.equal(await readLockfile(fakeSsh([[/cat/, JSON.stringify(lock)]]), OWNERSHIP_ID), null)
+ assert.equal(isLockfileSkew(await readLockfile(fakeSsh([[/cat/, JSON.stringify(lock)]]), OWNERSHIP_ID)), true)
})
-test('readLockfile rejects lock with pid <= 0', async () => {
+test('readLockfile treats a lock with pid <= 0 as skew', async () => {
const lock = { schemaVersion: LOCKFILE_SCHEMA_VERSION, pid: -1, port: 8080 }
- assert.equal(await readLockfile(fakeSsh([[/cat/, JSON.stringify(lock)]]), OWNERSHIP_ID), null)
+ assert.equal(isLockfileSkew(await readLockfile(fakeSsh([[/cat/, JSON.stringify(lock)]]), OWNERSHIP_ID)), true)
})
-test('readLockfile rejects lock with port out of range', async () => {
+test('readLockfile treats a lock with port out of range as skew', async () => {
const lock = { schemaVersion: LOCKFILE_SCHEMA_VERSION, pid: 100, port: 99999 }
- assert.equal(await readLockfile(fakeSsh([[/cat/, JSON.stringify(lock)]]), OWNERSHIP_ID), null)
+ assert.equal(isLockfileSkew(await readLockfile(fakeSsh([[/cat/, JSON.stringify(lock)]]), OWNERSHIP_ID)), true)
const lock2 = { schemaVersion: LOCKFILE_SCHEMA_VERSION, pid: 100, port: 0 }
- assert.equal(await readLockfile(fakeSsh([[/cat/, JSON.stringify(lock2)]]), OWNERSHIP_ID), null)
+ assert.equal(isLockfileSkew(await readLockfile(fakeSsh([[/cat/, JSON.stringify(lock2)]]), OWNERSHIP_ID)), true)
})
test('readLockfile accepts a complete owned lock', async () => {
@@ -1248,10 +1327,10 @@ test('spawnRemoteDashboard fails with update-required when remote lacks --ssh-se
)
})
-test('readLockfile rejects a log path outside the exact ownership and spawn path', async () => {
+test('readLockfile treats a log path outside the exact ownership and spawn path as skew', async () => {
const lock = ownedLock({ logPath: '~/.hermes/desktop-ssh/other.log' })
const ssh = fakeSsh([[/cat .*lock\.json/, JSON.stringify(lock)]])
- assert.equal(await readLockfile(ssh, OWNERSHIP_ID), null)
+ assert.equal(isLockfileSkew(await readLockfile(ssh, OWNERSHIP_ID)), true)
})
test('cleanupStale never deletes a lock-supplied unexpected log path', async () => {
diff --git a/apps/desktop/electron/remote-lifecycle.ts b/apps/desktop/electron/remote-lifecycle.ts
index b671de2b3d4..1df60c7a668 100644
--- a/apps/desktop/electron/remote-lifecycle.ts
+++ b/apps/desktop/electron/remote-lifecycle.ts
@@ -97,6 +97,22 @@ function lockfilePath(ownershipId) {
return `${ownershipDirectory(ownershipId)}/backend.lock.json`
}
+// #95532 fail-closed skew sentinel. A backend.lock.json that EXISTS but does
+// not match what this build writes (unknown schemaVersion, missing/foreign
+// ownershipId, truncated JSON, malformed shape) is "skew" — most likely a
+// different desktop build (fork) owns this remote, or the file is corrupt.
+// Skew must never be conflated with "no lockfile": every reap/cleanup path
+// (#78872 ownership guard) must SKIP on skew, because killing or overwriting
+// on unparseable/foreign state is exactly the wrong-way failure — it murders
+// a live tunnel some other build is depending on.
+function lockfileSkew(reason) {
+ return { skew: true, reason: String(reason) }
+}
+
+function isLockfileSkew(lock) {
+ return Boolean(lock) && (lock as any).skew === true
+}
+
function spawnLogPath(ownershipId, spawnNonce) {
return `${ownershipDirectory(ownershipId)}/${validateSpawnNonce(spawnNonce)}.log`
}
@@ -323,45 +339,55 @@ async function readLockfile(ssh, ownershipId) {
try {
parsed = JSON.parse(text)
} catch {
- return null
+ // Exists but doesn't parse: truncated write or a foreign format. NOT the
+ // same as "no lockfile" — see lockfileSkew().
+ return lockfileSkew('unparseable-json')
}
- if (!parsed || parsed.schemaVersion !== LOCKFILE_SCHEMA_VERSION) {
- return null
+ if (!parsed || typeof parsed !== 'object') {
+ return lockfileSkew('non-object')
+ }
+
+ if (parsed.schemaVersion !== LOCKFILE_SCHEMA_VERSION) {
+ return lockfileSkew(`schema-version ${JSON.stringify(parsed.schemaVersion ?? null)}`)
}
const pid = parsed.pid
const port = parsed.port
if (!Number.isInteger(pid) || pid <= 0 || pid > 4194304) {
- return null
+ return lockfileSkew('malformed-pid')
}
// port 0 = spawn-in-progress record (written before readiness); valid
// ownership proof for cleanup, but never reusable.
if (!Number.isInteger(port) || port < 0 || port > 65535) {
- return null
+ return lockfileSkew('malformed-port')
}
if (parsed.ownershipId !== ownershipId || !/^[0-9a-f]{16}$/.test(parsed.spawnNonce || '')) {
- return null
+ return lockfileSkew('ownership-mismatch')
}
if (!/^[0-9a-f]{32}$/.test(parsed.tokenFingerprint || '')) {
- return null
+ return lockfileSkew('malformed-token-fingerprint')
}
if (parsed.protocolVersion !== PROTOCOL_VERSION) {
+ // Fully validated ownership (our schema, our ownershipId, our shape) from
+ // a protocol-incompatible build of OUR OWN lineage: the record is not
+ // reusable and readLockfile keeps its historical contract of hiding it,
+ // which routes connect() to a fresh spawn.
return null
}
if (parsed.logPath !== spawnLogPath(ownershipId, parsed.spawnNonce)) {
- return null
+ return lockfileSkew('log-path-mismatch')
}
for (const field of ['profile', 'hermesPath', 'hermesHome', 'logPath', 'startedAt']) {
if (typeof parsed[field] !== 'string' || parsed[field].length > 1024) {
- return null
+ return lockfileSkew(`malformed-field ${field}`)
}
}
@@ -483,6 +509,12 @@ async function pidIsOurDashboard(
// Kill the stale dashboard ONLY if provably ours, then drop the lockfile.
async function cleanupStale(ssh, ownershipId, lock, pidAlive = true) {
+ // Defense in depth (#95532): a skew sentinel is foreign/corrupt state, not
+ // an ownership record — never reap or remove anything based on it.
+ if (isLockfileSkew(lock)) {
+ return
+ }
+
if (
pidAlive &&
lock &&
@@ -555,7 +587,9 @@ async function disconnect(ssh, ownershipId) {
const lock = await readLockfile(ssh, ownershipId)
- if (!lock) {
+ if (!lock || isLockfileSkew(lock)) {
+ // Skew (#95532): fail closed — this is not our record, so there is
+ // nothing we may safely reap or remove here.
return
}
@@ -822,6 +856,22 @@ async function connect(deps) {
const hermesHome = await probeRemoteHermesHome(ssh)
const lock = await readLockfile(ssh, ownershipId)
+ if (isLockfileSkew(lock)) {
+ // #95532: the lockfile exists but was written by a different (fork) build
+ // or is corrupt. FAIL CLOSED: no reap, no removal, no overwrite, no spawn
+ // on top of foreign live state — reaping here is how live tunnels die.
+ const lpath = lockfilePath(ownershipId)
+ log(`lockfile schema/ownership skew (${lock.reason}) at ${lpath} — failing closed: skipping reap, leaving remote state untouched`)
+ const error: any = new Error(
+ `The remote ownership record ${lpath} does not match this Hermes Desktop build (${lock.reason}). ` +
+ 'It was probably written by a different or modified desktop build sharing this remote, or the file is corrupt. ' +
+ 'Refusing to reap or overwrite it — that could kill a live SSH backend owned by another build. ' +
+ 'If nothing else uses this remote, delete that file on the remote host and reconnect.'
+ )
+ error.kind = 'remote-lockfile-skew'
+ throw error
+ }
+
if (lock) {
const pidAlive = await remotePidAlive(ssh, lock.pid)
@@ -1010,6 +1060,7 @@ export {
expandRemotePath,
fingerprintToken,
isForwardBindCollision,
+ isLockfileSkew,
listRemoteHermesProfiles,
locateHermes,
LOCKFILE_SCHEMA_VERSION,