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(security): backend-only control frames come only from the backend (OH-18) (#352)

0xken151349b6d6e137
diff --git a/backend/src/lib/backendOnlyFrames.test.ts b/backend/src/lib/backendOnlyFrames.test.ts
new file mode 100644
index 000000000..e701844f5
--- /dev/null
+++ b/backend/src/lib/backendOnlyFrames.test.ts
@@ -0,0 +1,16 @@
+import { describe, expect, it } from 'vitest'
+import { isBackendOnlyDownType } from './backendOnlyFrames.js'
+
+describe('isBackendOnlyDownType', () => {
+ it('refuses the backend\'s own control frames from any client socket', () => {
+ for (const type of ['machine_meta', 'machine_revoked', 'desk_changed', 'machines_changed', '__clients', '__billing_suspended']) {
+ expect(isBackendOnlyDownType(type), type).toBe(true)
+ }
+ })
+ it('lets client frames through', () => {
+ for (const type of ['message', 'agents_list', 'e2e_hello', 'terminal_input', 'machine_select']) {
+ expect(isBackendOnlyDownType(type), type).toBe(false)
+ }
+ expect(isBackendOnlyDownType(undefined)).toBe(false)
+ })
+})
diff --git a/backend/src/lib/backendOnlyFrames.ts b/backend/src/lib/backendOnlyFrames.ts
new file mode 100644
index 000000000..446d4c0db
--- /dev/null
+++ b/backend/src/lib/backendOnlyFrames.ts
@@ -0,0 +1,17 @@
+/**
+ * Down-frames the backend mints for an adapter, which a client must never be able to forge.
+ *
+ * The `__` prefix already marks most of these; these predate that convention and are not prefixed, so
+ * each client socket that relays frames down (`webWs`, its legacy apiKey path, `deviceWs`) has to refuse
+ * them by name. The adapter refuses them too unless they arrive on the backend's own `connId: ''`.
+ *
+ * Senders, all backend-side: `lib/adapterWs.ts` (on connect), `services/MachineService.ts`
+ * (rename, revoke) and `lib/adapterAccountPushes.ts` (desk_changed, machines_changed — forged, each
+ * one makes every window on that computer re-read from this backend).
+ */
+export const BACKEND_ONLY_DOWN_TYPES = new Set(['machine_meta', 'machine_revoked', 'desk_changed', 'machines_changed'])
+
+/** A type no client may send down: the backend's own `__` control frames and the named ones above. */
+export function isBackendOnlyDownType(type: unknown): boolean {
+ return typeof type === 'string' && (type.startsWith('__') || BACKEND_ONLY_DOWN_TYPES.has(type))
+}
diff --git a/backend/src/lib/deviceWs.ts b/backend/src/lib/deviceWs.ts
index 4c534a9e3..f2e554eaa 100644
--- a/backend/src/lib/deviceWs.ts
+++ b/backend/src/lib/deviceWs.ts
@@ -43,6 +43,7 @@ import { authenticateAccessToken, SsoAuthError } from './ssoAuth.js'
import { parseAutonomousEnvironment } from './autonomousEnvironment.js'
import { AppError } from '../errors/index.js'
import type { Machine } from '@prisma/client'
+import { isBackendOnlyDownType } from './backendOnlyFrames.js'
import {
VoiceQuotaExceededError,
voiceQuotaService,
@@ -1120,6 +1121,9 @@ function relay(device: WebSocket, opts: RelayOpts): void {
const handleFrame = async (msg: CommanderMsg): Promise<void> => {
const type = msg.type
+ // A device is a client: whatever it sends is relayed down under its own connId, so the backend's own
+ // control frames are refused here as on the web socket (lib/backendOnlyFrames.ts).
+ if (isBackendOnlyDownType(type)) return
if (type === 'machine_select') { await bindMachine(payloadOf(msg).machineId); return }
if (type === 'machine_deselect') {
selectGen++ // cancel any in-flight bindMachine
diff --git a/backend/src/lib/webWs.ts b/backend/src/lib/webWs.ts
index b0b47efec..451b31778 100644
--- a/backend/src/lib/webWs.ts
+++ b/backend/src/lib/webWs.ts
@@ -54,19 +54,10 @@ import {
terminalP2pPolicy,
} from './p2pSignaling.js'
import { recordRemoteUsage } from './dailyTracking.js'
+import { isBackendOnlyDownType } from './backendOnlyFrames.js'
-/**
- * Down-frames the backend mints for an adapter, which a web client must never be able to forge.
- *
- * The `__` prefix already marks most of these; these two predate that convention and are not
- * prefixed, so they fell through this handler's namespace checks into the verbatim forward at the
- * bottom. See the block in `handleFrame` for what each one does when forged.
- *
- * Senders, all backend-side: `lib/adapterWs.ts` (on connect), `services/MachineService.ts`
- * (rename, revoke) and `lib/adapterAccountPushes.ts` (desk_changed, machines_changed — forged, each
- * one makes every window on that computer re-read from this backend).
- */
-export const BACKEND_ONLY_DOWN_TYPES = new Set(['machine_meta', 'machine_revoked', 'desk_changed', 'machines_changed'])
+/** Down-frames only the backend may send — see lib/backendOnlyFrames.ts. Re-exported for existing callers. */
+export { BACKEND_ONLY_DOWN_TYPES } from './backendOnlyFrames.js'
const wss = createWss(WS_LIMITS.web, { echoFirstProtocol: true })
@@ -367,22 +358,10 @@ function attachUserClient(ws: WebSocket, user: AuthUser): void {
const handleFrame = async (frame: Frame): Promise<void> => {
const type = frame.type as string | undefined
- // Double-underscore frames are backend-to-Harness control messages. A web
- // client must never be able to forge its own lifecycle notification.
- if (typeof type === 'string' && type.startsWith('__')) return
- // ⚠️ Same rule, for the two control frames that are NOT `__`-prefixed and so escaped it. Anything
- // reaching this handler holds a valid access token for the account and nothing more, while the
- // frames below are instructions the adapter obeys as the backend's own — everything else here
- // falls through to `client.sendDown(frame)`, which forwards verbatim:
- // - `machine_meta` names the account's private grid, i.e. the inference endpoint every agent on
- // that computer is then pointed at. Forged, it redirects the account's work.
- // - `machine_revoked` makes the adapter clear its stored session and exit.
- // Both are minted here (`adapterWs.ts`, `services/MachineService.ts`); no client in this
- // repository sends either, so refusing them costs nothing. The adapter refuses them from
- // non-backend transports too (`cli/src/backendSocket.ts`, BACKEND_ONLY_DOWN_TYPES) — but it
- // cannot tell a frame the backend decided on from one the backend relayed for a web client, so
- // that check alone does not cover this path. This is where that distinction still exists.
- if (typeof type === 'string' && BACKEND_ONLY_DOWN_TYPES.has(type)) return
+ // The backend's own control frames — `__`-prefixed, plus the named ones in lib/backendOnlyFrames.ts —
+ // are never a web client's to send. Refused here, on the legacy key path and on device-ws alike; the
+ // adapter also takes them only on the backend's own `connId: ''`, so each check stands on its own.
+ if (isBackendOnlyDownType(type)) return
const isTerminal = typeof type === 'string' && TERMINAL_DOWN_TYPES.has(type)
const terminalNamespace = typeof type === 'string' && type.startsWith('terminal_')
if (terminalNamespace && !isTerminal) {
@@ -580,7 +559,8 @@ function attachWebClient(ws: WebSocket, machineId: string): void {
let frame: Frame
try { frame = JSON.parse(raw.toString()) as Frame } catch { return }
const type = frame.type as string | undefined
- if (typeof type === 'string' && type.startsWith('__')) return
+ // The same backend-only refusal as the per-user path: a key holder is a client, not the backend.
+ if (isBackendOnlyDownType(type)) return
if (typeof type === 'string' && type.startsWith('terminal_') && !TERMINAL_DOWN_TYPES.has(type)) return
if (typeof type === 'string' && TERMINAL_DOWN_TYPES.has(type)) {
const bytes = terminalFrameBytes(frame)
diff --git a/cli/src/backendSocket.spec.ts b/cli/src/backendSocket.spec.ts
index e8cbf6465..46076083d 100644
--- a/cli/src/backendSocket.spec.ts
+++ b/cli/src/backendSocket.spec.ts
@@ -2045,7 +2045,7 @@ describe('agent_retarget onto a Local model resolves web tools', () => {
const ws = wsMock.instances[0]
ws.open()
// The grid name is the backend's, pushed on connect; the daemon holds it in memory only.
- ws.message({ t: 'down', connId: 'web-1', frame: { type: 'machine_meta', payload: { name: 'mac', gridName: GRID_NAME } } })
+ ws.message({ t: 'down', connId: '', frame: { type: 'machine_meta', payload: { name: 'mac', gridName: GRID_NAME } } })
ws.message(sealedDown(socket, 'web-1', 'agent_retarget', { requestId: 'r', agentId: 'a1', gridModel: model }))
await vi.waitFor(() => expect(parseSent(ws).some((item) => (item.frame as { type?: string } | undefined)?.type === 'agent_retarget_result')).toBe(true), { timeout: 10_000 })
const reply = parseSent(ws)
@@ -2202,7 +2202,7 @@ describe('grid_models_list says whether this machine has a grid CLI', () => {
socket.connect()
const ws = wsMock.instances[0]
ws.open()
- ws.message({ t: 'down', connId: 'web-1', frame: { type: 'machine_meta', payload: { name: 'mac', gridName: GRID_NAME } } })
+ ws.message({ t: 'down', connId: '', frame: { type: 'machine_meta', payload: { name: 'mac', gridName: GRID_NAME } } })
ws.message(sealedDown(socket, 'web-1', 'grid_models_list', { requestId: 'r' }))
await vi.waitFor(() => expect(parseSent(ws).some((item) => (item.frame as { type?: string } | undefined)?.type === 'grid_models_list_result')).toBe(true), { timeout: 10_000 })
const reply = parseSent(ws)
@@ -2286,18 +2286,18 @@ describe('machine_meta carries the grid name without clobbering it on rename', (
ws.open()
// Connect frame: name and grid together.
- ws.message({ t: 'down', connId: 'web-1', frame: { type: 'machine_meta', payload: { name: 'mac', gridName: 'someone-7f3a91c4' } } })
+ ws.message({ t: 'down', connId: '', frame: { type: 'machine_meta', payload: { name: 'mac', gridName: 'someone-7f3a91c4' } } })
await vi.waitFor(() => expect(socket.gridName()).toBe('someone-7f3a91c4'))
// A rename pushes `{ name }` alone — it must NOT wipe the grid name (the bug that left the picker
// empty the moment a machine was renamed). Wait until the rename is observably processed, then
// confirm the grid name survived it.
- ws.message({ t: 'down', connId: 'web-1', frame: { type: 'machine_meta', payload: { name: 'renamed' } } })
+ ws.message({ t: 'down', connId: '', frame: { type: 'machine_meta', payload: { name: 'renamed' } } })
await vi.waitFor(() => expect(namesSeen).toContain('renamed'))
expect(socket.gridName()).toBe('someone-7f3a91c4')
// An explicit null is the account genuinely having no grid, and does clear it.
- ws.message({ t: 'down', connId: 'web-1', frame: { type: 'machine_meta', payload: { name: 'renamed', gridName: null } } })
+ ws.message({ t: 'down', connId: '', frame: { type: 'machine_meta', payload: { name: 'renamed', gridName: null } } })
await vi.waitFor(() => expect(socket.gridName()).toBeNull())
await socket.stop()
@@ -2311,11 +2311,11 @@ describe('machine_meta carries the grid name without clobbering it on rename', (
const ws = wsMock.instances[0]
ws.open()
expect(socket.machineName()).toBeNull()
- ws.message({ t: 'down', connId: 'web-1', frame: { type: 'machine_meta', payload: { name: ' M2 ', gridName: 'someone-7f3a91c4' } } })
+ ws.message({ t: 'down', connId: '', frame: { type: 'machine_meta', payload: { name: ' M2 ', gridName: 'someone-7f3a91c4' } } })
await vi.waitFor(() => expect(socket.machineName()).toBe('M2'))
- ws.message({ t: 'down', connId: 'web-1', frame: { type: 'machine_meta', payload: { name: 'Studio' } } })
+ ws.message({ t: 'down', connId: '', frame: { type: 'machine_meta', payload: { name: 'Studio' } } })
await vi.waitFor(() => expect(socket.machineName()).toBe('Studio'))
- ws.message({ t: 'down', connId: 'web-1', frame: { type: 'machine_meta', payload: { gridName: 'someone-7f3a91c4' } } })
+ ws.message({ t: 'down', connId: '', frame: { type: 'machine_meta', payload: { gridName: 'someone-7f3a91c4' } } })
await vi.waitFor(() => expect(namesSeen).toHaveLength(3))
expect(socket.machineName()).toBe('Studio')
await socket.stop()
@@ -2330,7 +2330,7 @@ describe('machine_meta carries the grid name without clobbering it on rename', (
ws.open()
// The backend's own frame sets it, as always.
- ws.message({ t: 'down', connId: 'web-1', frame: { type: 'machine_meta', payload: { name: 'mac', gridName: 'someone-7f3a91c4' } } })
+ ws.message({ t: 'down', connId: '', frame: { type: 'machine_meta', payload: { name: 'mac', gridName: 'someone-7f3a91c4' } } })
await vi.waitFor(() => expect(socket.gridName()).toBe('someone-7f3a91c4'))
// Now the same frame from a process on this machine, through the local socket — the shape of the
@@ -2584,6 +2584,27 @@ describe('relay down-frames are default-deny: sealed, or the backend\'s own', ()
expect(onMessage).not.toHaveBeenCalled()
})
+ it('takes backend-only frames only on the backend\'s own address (connId \'\'), never one a client sent', async () => {
+ // The backend writes these with connId ''; a client's frame carries its own connId whichever socket
+ // relayed it, so a client-addressed machine_meta must not repoint this computer's grid.
+ const { socket, dispatch } = harness()
+ const onMachineMeta = vi.fn()
+ socket.onMachineMeta = onMachineMeta
+ const onRevoked = vi.fn()
+ socket.onRevoked = onRevoked
+ for (const connId of ['web-1', 'device-conn-7']) {
+ await dispatch({ type: 'machine_meta', payload: { name: 'x', gridName: 'someone-else' } }, connId)
+ await dispatch({ type: 'machine_revoked', payload: {} }, connId)
+ await dispatch({ type: '__clients', payload: { commander: 9 } }, connId)
+ }
+ expect(onMachineMeta).not.toHaveBeenCalled()
+ expect(onRevoked).not.toHaveBeenCalled()
+ expect(socket.gridName()).toBeNull()
+ await dispatch({ type: 'machine_meta', payload: { name: 'mac', gridName: 'mine-1234' } }, '')
+ expect(onMachineMeta).toHaveBeenCalledWith('mac')
+ expect(socket.gridName()).toBe('mine-1234')
+ })
+
it('never opens a SEALED backend-only frame: a paired client must not speak as the backend', async () => {
// Opening every sealed type is what lets a paired client reach any RPC — and it would also let one seal
// `machine_meta` and repoint this computer's grid. The backend has no key, so its frames are never sealed.
diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.ts
index f28285bc5..b0a31f181 100644
--- a/cli/src/backendSocket.ts
+++ b/cli/src/backendSocket.ts
@@ -1484,7 +1484,11 @@ export class BackendSocket {
const from = `${transport} (${connId ? `conn:${sid(connId)}` : 'backend'})`
const wrapped = isWrapped(frame.payload)
if (type.startsWith('__') || BACKEND_ONLY_DOWN_TYPES.has(type)) {
- if (transport !== 'relay' || wrapped) {
+ // And only on the backend's OWN address: it sends these with `connId: ''`, while every frame a
+ // client sends arrives stamped with that client's connId — so a client-shaped one was relayed, not
+ // written by the backend, whichever socket let it through. `__client_disconnected` is the one the
+ // hub addresses to a client's own connId; it only tears down that connection's state.
+ if (transport !== 'relay' || wrapped || (connId !== '' && type !== '__client_disconnected')) {
console.warn(`[backend] ignoring ${logSafeType(type)} from ${from} — only the backend sends it, and only in the clear`)
return
}