Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

fix: drop peer trust on e2e_denied and close remote relay connections with 4404 status

0xken15831a0c6c2160
diff --git a/cli/debugtest.mjs b/cli/debugtest.mjs
new file mode 100644
index 000000000..f78dffa0f
--- /dev/null
+++ b/cli/debugtest.mjs
@@ -0,0 +1,19 @@
+import { WebSocketServer, WebSocket } from 'ws'
+
+const wss = new WebSocketServer({ port: 0 })
+wss.on('connection', (ws) => {
+ console.log('server: connection established')
+ ws.on('message', (raw) => {
+ console.log('server got:', raw.toString())
+ })
+})
+wss.on('listening', () => console.log('server listening'))
+
+setTimeout(() => {
+ const port = wss.address().port
+ console.log('port', port)
+ const client = new WebSocket(`ws://127.0.0.1:${port}/api/web-ws?autonomousEnv=prod`, ['tok'])
+ client.on('open', () => { console.log('client open'); client.send(JSON.stringify({type:'machine_select'})) })
+ client.on('close', (code, reason) => console.log('client close', code, reason.toString()))
+ client.on('error', (e) => console.log('client error', e))
+}, 100)
diff --git a/cli/src/lib/e2ee/relayLink.spec.ts b/cli/src/lib/e2ee/relayLink.spec.ts
index d682876a7..db4ad9c11 100644
--- a/cli/src/lib/e2ee/relayLink.spec.ts
+++ b/cli/src/lib/e2ee/relayLink.spec.ts
@@ -13,6 +13,7 @@ let E2eeManagerCtor: typeof import('./manager.js')['E2eeManager']
let RelaySessionCrypto: typeof import('./relayClient.js')['RelaySessionCrypto']
let claimSetupToken: typeof import('./relayClient.js')['claimSetupToken']
let MachinePeerStore: typeof import('./machinePeers.js')['MachinePeerStore']
+let RemoteRelayPool: typeof import('../remoteRelay.js')['RemoteRelayPool']
const MACHINE_ID = 'f2e0383771b734e4fc00f0bc8ccf060f'
@@ -24,6 +25,7 @@ beforeAll(async () => {
RelaySessionCrypto = relayClient.RelaySessionCrypto
claimSetupToken = relayClient.claimSetupToken
MachinePeerStore = (await import('./machinePeers.js')).MachinePeerStore
+ RemoteRelayPool = (await import('../remoteRelay.js')).RemoteRelayPool
})
beforeEach(() => {
@@ -156,3 +158,113 @@ describe('link create/import + relay session crypto (interop with the real E2eeM
expect(result).toEqual({ ok: false, error: 'BAD_TOKEN' })
})
})
+
+describe('RemoteRelayPool drops a peer the responder no longer trusts', () => {
+ // A fake AuthSessionManager — RemoteRelayPool only ever calls .accessToken({force}).
+ const fakeAuth = { accessToken: async () => 'unused-in-this-fake' } as unknown as import('../authSession.js').AuthSessionManager
+
+ it('e2e_denied during the handshake unlinks the peer and surfaces NO_PEER_LINK', async () => {
+ const wss = new WebSocketServer({ port: 0 })
+ wss.on('connection', (ws) => {
+ let selected = false
+ ws.on('message', (raw) => {
+ let frame: Frame
+ try { frame = JSON.parse(raw.toString()) as Frame } catch { return }
+ if (!selected && frame.type === 'machine_select') {
+ selected = true
+ ws.send(JSON.stringify({ type: 'connected', payload: { machineId: MACHINE_ID } }))
+ return
+ }
+ if (frame.type === 'e2e_hello') {
+ // Simulate a responder that has since `harness unpair`ed this identity.
+ ws.send(JSON.stringify({ type: 'e2e_denied', payload: { reason: 'revoked' } }))
+ }
+ })
+ })
+
+ try {
+ const port = (wss.address() as AddressInfo).port
+ const peers = new MachinePeerStore()
+ peers.pin(MACHINE_ID, C.b64e(C.newIdentity().pub), 'harness link')
+ const pool = new RemoteRelayPool(fakeAuth, `ws://127.0.0.1:${port}`, C.newIdentity(), peers)
+
+ const sink = { sendFrame: () => true, sendBinary: () => true }
+ await expect(
+ pool.acquire(MACHINE_ID, 'prod', { type: 'machine_select', payload: { machineId: MACHINE_ID } }, sink, () => {}),
+ ).rejects.toThrow('NO_PEER_LINK')
+ expect(peers.get(MACHINE_ID)).toBeNull()
+ } finally {
+ await new Promise<void>((resolve) => wss.close(() => resolve()))
+ }
+ })
+
+ it('a mid-session e2e_denied unlinks the peer and closes the local session with 4404', async () => {
+ const inbox: Frame[] = []
+ const wss = new WebSocketServer({ port: 0 })
+ const manager = new E2eeManagerCtor({
+ machineId: MACHINE_ID,
+ sendTo: (_connId, frame) => {
+ inbox.push(frame)
+ for (const client of wss.clients) client.send(JSON.stringify(frame))
+ },
+ isConnected: () => true,
+ })
+ let serverWs: import('ws').WebSocket | null = null
+ wss.on('connection', (ws) => {
+ serverWs = ws
+ let selected = false
+ ws.on('message', (raw) => {
+ let frame: Frame
+ try { frame = JSON.parse(raw.toString()) as Frame } catch { return }
+ if (!selected) {
+ if (frame.type === 'machine_select') {
+ selected = true
+ ws.send(JSON.stringify({ type: 'connected', payload: { machineId: MACHINE_ID } }))
+ }
+ return
+ }
+ const type = frame.type as string
+ if (type.startsWith('e2e_')) manager.handleFrame('fake-conn', frame)
+ })
+ })
+
+ try {
+ const port = (wss.address() as AddressInfo).port
+ const clientIdentity = C.newIdentity()
+ const token = manager.createSetupToken(MACHINE_ID).token
+ const claim = await claimSetupToken({
+ token,
+ targetMachineId: MACHINE_ID,
+ selfIdentity: clientIdentity,
+ accessToken: 'unused-in-this-fake',
+ backendWsBase: `ws://127.0.0.1:${port}`,
+ autonomousEnv: 'prod',
+ timeoutMs: 2_000,
+ })
+ expect(claim.ok).toBe(true)
+ if (!claim.ok) return
+
+ const peers = new MachinePeerStore()
+ peers.pin(MACHINE_ID, C.b64e(claim.peerPub), 'harness link')
+ const pool = new RemoteRelayPool(fakeAuth, `ws://127.0.0.1:${port}`, clientIdentity, peers)
+
+ const closed = new Promise<{ code: number; reason: string }>((resolve) => {
+ const sink = { sendFrame: () => true, sendBinary: () => true }
+ void pool
+ .acquire(MACHINE_ID, 'prod', { type: 'machine_select', payload: { machineId: MACHINE_ID } }, sink, (code, reason) => resolve({ code, reason }))
+ .then(() => {
+ // Session is live — now simulate the responder revoking mid-session, exactly as
+ // E2eeManager.denyAndDropSessionsFor does on `harness unpair`: send e2e_denied without
+ // closing the socket itself.
+ serverWs?.send(JSON.stringify({ type: 'e2e_denied', payload: { reason: 'revoked' } }))
+ })
+ })
+
+ const result = await closed
+ expect(result.code).toBe(4404)
+ expect(peers.get(MACHINE_ID)).toBeNull()
+ } finally {
+ await new Promise<void>((resolve) => wss.close(() => resolve()))
+ }
+ })
+})
diff --git a/cli/src/lib/remoteRelay.ts b/cli/src/lib/remoteRelay.ts
index 929b8554a..b4b06012f 100644
--- a/cli/src/lib/remoteRelay.ts
+++ b/cli/src/lib/remoteRelay.ts
@@ -164,8 +164,15 @@ export class RemoteRelayPool {
if (frame.type === 'e2e_denied') {
if (!settled) {
settled = true; clearTimeout(timeout)
- const reason = (frame.payload as { reason?: unknown } | undefined)?.reason
- reject(new RelayConnectError(typeof reason === 'string' ? `E2EE_DENIED:${reason}` : 'E2EE_DENIED'))
+ // The peer no longer trusts our identity — most commonly `harness unpair` run on ITS
+ // side. Our own pinned trust is now stale too; drop it so the next attempt fails fast
+ // with NO_PEER_LINK (same close-code-4404 mapping in localWsServer.ts) instead of
+ // repeating a handshake that will only be denied again. The handshake never got as far
+ // as being usable, so there is nothing more to read from this socket — close it rather
+ // than leaving it dangling open.
+ this.peers.unlink(machineId)
+ try { ws.close(1000, 'peer denied') } catch { ws.terminate() }
+ reject(new RelayConnectError('NO_PEER_LINK'))
}
return
}
@@ -182,6 +189,16 @@ export class RemoteRelayPool {
let frame: Frame
try { frame = JSON.parse(raw.toString()) as Frame } catch { return }
if (frame.type === 'e2e_rekey') { crypto.handleRekey((frame.payload ?? {}) as Record<string, unknown>); return }
+ if (frame.type === 'e2e_denied') {
+ // Mid-session revoke (e.g. `harness unpair` run on the peer while this relay was already
+ // live) — the peer proactively sends this instead of just going silent. Drop our now-stale
+ // trust and close with the same 4404 the app already knows how to turn into "needs to be
+ // linked": the `ws.on('close', ...)` handler below forwards this code verbatim to
+ // `entry.onClosed`, which `localWsServer.ts` wires straight to the local client's own close.
+ this.peers.unlink(machineId)
+ try { ws.close(4404, 'peer revoked trust') } catch { ws.terminate() }
+ return
+ }
const plain = crypto.unwrapIncoming(frame)
if (plain) entry.sink?.sendFrame(plain)
})