Files
archived-orca/src/shared/remote-runtime/remote-runtime-passthrough-socket.ts
T
Neil 4e1d42ef7b perf(ssh): desktop and CLI read compressed frames from remote hosts (#39659)
* refactor(remote-runtime): share compressed frame inflate across client platforms

Move the length checks and decode of paired E2EE compressed frames into
the shared module behind a small gzip/UTF-8 codec, so the desktop can
read them with node zlib while mobile keeps its native/fflate path.

* perf(remote-runtime): read compressed frames from paired hosts on desktop and CLI

Desktop and CLI sockets to orcad/orca serve now advertise
transport.compressed-frames.v1, so a v2 host gzips large text replies and
terminal output before sealing them, as it already does for phones.

- Every Node client transport (one-shot requests, request connection,
  shared control, subscriptions) opens frames through one sealed-frame
  reader that inflates compressed frames on v2 channels, synchronously so
  frame order and v2 counters stay in arrival order.
- A compressed binary frame may claim up to the 8 MB binary outbound cap
  (terminal frames can exceed the 4 MB JSON cap), for phones too.
- ORCA_DISABLE_MOBILE_COMPRESSED_FRAMES=1 now also stops a desktop or CLI
  from asking for compressed frames.
- Relayed phones and the browser client are unchanged.

* refactor(remote-runtime): simplify the mobile inflate codec and clarify capability comment

* fix(remote-runtime): name why a sealed frame could not be read

Text-only sockets report an authentic binary payload as an unexpected
binary frame again, and tell a decrypt failure apart from a corrupt
compressed frame, instead of calling every failure undecryptable.
2026-11-07 18:27:58 -08:00

177 lines
6.2 KiB
TypeScript

import WebSocket from 'ws'
import type { PairedRuntimeConnection } from './pairing/paired-runtime-connection'
import type { RuntimeCapability } from '../protocol-version'
import {
formatRemoteRuntimeCloseMessage,
sendRemoteRuntimeTokenAuth
} from './remote-runtime-client-handshake'
import { RemoteRuntimeClientError } from './remote-runtime-client-error'
import { openRemoteRuntimeWebSocket } from './requests/remote-runtime-request-websocket'
import { closeRemoteRuntimeSocket } from './remote-runtime-socket-close'
import {
startRemoteRuntimeSocketLiveness,
type RemoteRuntimeSocketLivenessOptions
} from './remote-runtime-socket-liveness'
import { RemoteRuntimeSubscriptionOutbound } from './requests/remote-runtime-subscription-outbound'
export type RemoteRuntimePassthroughSocket = {
/** Queues one plaintext RPC frame; false when the socket can no longer carry it. */
send: (plaintext: string) => boolean
close: () => void
}
export type RemoteRuntimePassthroughCallbacks = {
onText: (plaintext: string) => void
onBinary: (bytes: Uint8Array<ArrayBufferLike>) => void
/** Called once when an open socket ends for any reason other than `close()`. */
onClose: (error: RemoteRuntimeClientError) => void
}
/** Relay E2EE frames for arbitrary multiplexed request IDs; subscription sockets own one ID and reject others. */
export function openRemoteRuntimePassthroughSocket(
connection: PairedRuntimeConnection,
clientCapabilities: readonly RuntimeCapability[],
callbacks: RemoteRuntimePassthroughCallbacks,
options: RemoteRuntimeSocketLivenessOptions & { timeoutMs: number }
): Promise<RemoteRuntimePassthroughSocket> {
return new Promise((resolve, reject) => {
let state: 'awaiting_ready' | 'awaiting_authenticated' | 'ready' | 'ended' = 'awaiting_ready'
const opened = openRemoteRuntimeWebSocket(connection, {
onFrame: (_ws, frame) =>
typeof frame === 'string' ? onTextFrame(frame) : onBinaryFrame(frame),
onError: (_ws, error) => end(error),
onClose: (_ws, code, reason) =>
end(
new RemoteRuntimeClientError(
'remote_runtime_unavailable',
formatRemoteRuntimeCloseMessage(code, reason)
)
),
onPong: () => liveness.noteActivity(),
onPing: () => liveness.noteActivity()
})
if (!opened.ok) {
reject(opened.error)
return
}
const { ws, handshake, cleanup } = opened.socket
const outbound = new RemoteRuntimeSubscriptionOutbound({ fail: (error) => end(error) })
const timeout = setTimeout(
() =>
end(
new RemoteRuntimeClientError(
'runtime_timeout',
'Timed out connecting to the remote Orca runtime.'
)
),
options.timeoutMs
)
const liveness = startRemoteRuntimeSocketLiveness({
ping: () => {
if (ws.readyState !== WebSocket.OPEN) {
return false
}
ws.ping()
return true
},
onDead: () =>
end(
new RemoteRuntimeClientError(
'remote_runtime_unavailable',
'Remote Orca runtime stopped responding; the connection was reset.'
)
),
options
})
function end(error: RemoteRuntimeClientError | null): void {
if (state === 'ended') {
return
}
const wasReady = state === 'ready'
state = 'ended'
clearTimeout(timeout)
liveness.stop()
outbound.releaseQueues()
outbound.retainSocketMemoryUntilClose(ws)
cleanup()
closeRemoteRuntimeSocket(ws)
if (!wasReady) {
reject(error ?? new RemoteRuntimeClientError('remote_runtime_unavailable', 'Closed.'))
} else if (error) {
callbacks.onClose(error)
}
}
function protocolError(message: string): RemoteRuntimeClientError {
return new RemoteRuntimeClientError('invalid_runtime_response', message)
}
// No inflate: relayed phones' capabilities omit compressed frames, so the host sends none here.
function onBinaryFrame(frame: Uint8Array<ArrayBufferLike>): void {
liveness.noteActivity()
const bytes = state === 'ready' ? handshake.channel.openBinary(frame) : null
if (!bytes) {
end(protocolError('Remote Orca runtime returned an unreadable binary frame.'))
return
}
callbacks.onBinary(bytes)
}
function onTextFrame(frame: string): void {
liveness.noteActivity()
if (state === 'awaiting_ready') {
if (handshake.acceptReadyText(frame) !== 'accepted') {
end(protocolError('Remote Orca runtime returned an invalid E2EE handshake frame.'))
return
}
state = 'awaiting_authenticated'
void sendRemoteRuntimeTokenAuth({
handshake,
deviceToken: connection.credential.deviceToken,
clientCapabilities,
stillAwaiting: () => state === 'awaiting_authenticated',
send: (authFrame) => ws.send(authFrame),
fail: (error) =>
end(
error instanceof RemoteRuntimeClientError
? error
: new RemoteRuntimeClientError('invalid_argument', String(error))
)
})
return
}
const plaintext = handshake.channel.openText(frame)
if (plaintext === null) {
end(protocolError('Remote Orca runtime returned an undecryptable frame.'))
return
}
if (state === 'ready') {
callbacks.onText(plaintext)
return
}
const authenticated = handshake.classifyAuthReply(plaintext)
if (authenticated.kind !== 'authenticated') {
end(
authenticated.kind === 'rejected' && authenticated.errorCode === 'unauthorized'
? new RemoteRuntimeClientError(
'unauthorized',
'Remote Orca runtime rejected the pairing token.'
)
: protocolError('Remote Orca runtime returned an invalid E2EE auth frame.')
)
return
}
state = 'ready'
clearTimeout(timeout)
resolve({
send: (plaintext) =>
state === 'ready' && ws.readyState === WebSocket.OPEN
? outbound.enqueueRequest(ws, handshake.channel.sealText(plaintext))
: false,
close: () => end(null)
})
}
})
}