mirror of
https://github.com/stablyai/orca.git
synced 2026-10-04 08:02:09 +00:00
* fix(runtime): bound the remote-runtime connect against an unreachable host A host that is powered off or firewalled black-holes the TCP SYN, so the remote-runtime WebSocket neither opens nor errors. The Node-side transports set no connect bound, leaving the caller's whole-request timeout as the only one: every `orca <cmd> --environment <unreachable>` sat silent for 60s before failing with a generic `runtime_timeout`. Measured on an unreachable paired host (win-lowspec, SYNs dropped): terminal list / worktree list / repo list / status each took 60.19-60.26s; the same command against a reachable host answered in 0.24s. So this was the shared transport, not one command. Pass `handshakeTimeout` at the three shared remote-runtime WebSocket construction sites, which `ws` applies across TCP connect and the HTTP upgrade. The value matches the bound the browser transport already used. The failure keeps code `remote_runtime_unavailable` so the existing transport-loss classification in terminal-process-inspection still applies, and the message names the endpoint and stops at "unverifiable" — per docs/reference/ssh-execution-boundary.md, loss of contact is never evidence that the host's work stopped. * fix(relay): bound the control socket's connect phase at the transport The relay control socket was constructed with no `handshakeTimeout`, the same gap fixed for the remote-runtime transports. It was not a live defect: the class-level `connectDeadlineMs` (15s) also covers a stalled connect, and that deadline does fire — its `unref()` is safe because the pending TCP connect is itself a ref'd libuv handle that holds the event loop open. Measured in a bare Node process: unref'd timer with an empty loop never fires (exit at 0ms), but the same timer alongside a black-holed connect fired at 2003ms. It was a defect waiting on a refactor. The two bounds cover different phases, and the class deadline covers the connect phase only incidentally. DO NOT REMOVE EITHER BOUND AS REDUNDANT. They are not. Proven by mutation: - Remove the transport bound -> a stalled *connect* falls through to the class deadline, rejecting with `relay_control_connect_timeout` after the full deadline instead of the transport error. - Remove the class deadline -> a stall during the *proving* phase (socket open, host proof never answered) is unbounded; the incumbent test hangs 30s. `handshakeTimeout` cannot see that phase at all. Reuses `remoteRuntimeConnectOptions` rather than forking a second helper, and moves the construction into `relay-control-socket-factory.ts` so a caller that needs a relay control socket gets the bound instead of re-deriving an unbounded one. `handshakeTimeoutMs` is settable apart from `connectDeadlineMs` so a test can stall the connect alone and assert which bound produced the rejection — error identity, not elapsed time. The connect-bound ratchet now covers the relay site and asserts the site still resolves, so an allowlist that silently stopped matching cannot pass vacuously. * fix(lint): carry SAFETY rationales for the connect-bound casts main tightened typescript/consistent-type-assertions to assertionStyle: never, which the rebase brings onto these added lines. Dropping the generic default is not typeable, so each cast keeps its own rationale. * fix(runtime): keep the bounded connect failure inside both message gates The connect bound's new wording dropped out of the two gates that classify remote-transport failures by message text, and those gates are the only ones that run on the path the bound made reachable. `subscribeRemoteRuntimeTransport` reports a connect failure by *rejecting* the subscribe promise, and that rejection crosses `ipcMain.handle`, which keeps only the message. The renderer then classifies it with `RECOVERABLE_MESSAGE_FRAGMENTS`. `Could not reach the remote Orca runtime at …` matched no fragment, so it read as fatal: `recovery.cancel()` and a red banner instead of a retry. Before the bound existed this case reached the 15s subscription-start timer, whose message did match a fragment, so introducing a 12s bound turned an auto-recovering pane into a dead-ended one — the #12650 shape. The same wording also fell outside `REMOTE_RUNTIME_UNREACHABLE_RE`, so the Tailscale remedy was dropped for precisely the unreachable-host failure it exists for. Keep the canonical phrase both gates already recognise rather than teaching each gate a second synonym for one condition, and pin it: the phrase is now a named constant, the corpus in `remote-runtime-transport-error-agreement.test.ts` grows the coded, hinted and code-stripped producers derived from the real helper, and a new subscribe-path test proves the connect bound (not the start timer) is what fires and that its message still classifies as recoverable once the code is gone. Verdict wording is unchanged: `unverifiable`, never a synonym for exited. Also states the bound in seconds, corrects the module comment (`handshakeTimeout` is a socket inactivity timer, so a slow-but-answering host is not cut off), and splits the subscription contract types out to stay under `max-lines`. * fix(relay): drop the duplicate connect bound on the control socket The claim that `connectDeadlineMs` cannot see a black-holed connect is false. `RelayControlClient.connect()` constructs the socket and arms `connectTimer` in the same synchronous call — `new WebSocket()` never blocks — and `expireConnect` fires from `opening` as well as `proving`. The class deadline was already a strict superset of a transport `handshakeTimeout` on that socket. It was also inert. Production passes neither option, so the transport bound was derived from `connectDeadlineMs` and both timers were 15_000, armed in the same tick; the ws timer is an inactivity timer armed on the later `socket` event, so it could not win. Its only reachable effect was changing which string a stalled relay connect rejects with, and it narrowed an existing test's 20ms deadline into a handshake bound it could race. So this removes the factory, the test-only `handshakeTimeoutMs` option and the source-grep test whose premise was wrong, and replaces them with a test that holds the real ground: a connect whose upgrade is never answered expires on the class deadline. Moving the timer arm after `open`, or narrowing `expireConnect` to `proving`, both turn it red — which is what a future reader needs before concluding the phase is uncovered and adding a second bound again. No behaviour change for a reachable relay, and none for the verdict: a stalled connect still rejects and still reaches `unverifiable`, never `exited`. * fix(runtime): stop the endpoint in the failure message from undoing the fix Putting the endpoint into the message created three problems the message itself caused. The Tailscale hint is idempotent by testing whether "tailscale" already appears anywhere in the message. That held while the message was fixed copy. Now a host called `tailscale-box` puts the word there itself, and the hint — the only actionable remedy on an unreachable host — is suppressed for it. Key the guard on the two hints instead of the word. The endpoint comes from a pasted pairing code, which is only length-capped; `normalizePairingUrl` rejects userinfo but nothing re-validates a stored offer. Render scheme, host and port only, so a pasted `wss://user:secret@host` cannot reach a surface the user reads. And drop the elapsed time from the wording. `handshakeTimeout` is a socket inactivity timer, so a `wss://` host that completes TCP and then goes silent re-arms it once and fails at about twice the bound; measured at 2008ms against a 1000ms bound. "within 12s" would have been wrong there, and the endpoint is the actionable part regardless. Also refuse a non-positive or non-finite bound: `ws` and `net` both gate on a truthy timeout, so `0` left the connect completely unbounded while still satisfying the connect-bound ratchet. * fix(runtime): keep the endpoint from smuggling a verdict into the message `isRemoteTerminalGoneMessage` in the pty transport substring-matches `terminal_gone` / `terminal_exited` / `no_connected_pty`, and it runs before the recoverable-connection gate: a match retires the pane's terminal id and cancels recovery. WHATWG URL accepts `_` in a special-scheme host, so once the failure message carried the endpoint, `ws://terminal_gone.example:6768` turned loss of contact into a terminal-gone verdict — the one conclusion `docs/reference/ssh-execution-boundary.md` forbids. Render the host only when it matches a hostname or IP-literal grammar that cannot carry such a token, and fall back to naming no endpoint at all. A well-formed host, including a bracketed IPv6 literal, is still shown. * docs(runtime): say why this connect bound is not the relay's removed duplicate
231 lines
9.7 KiB
TypeScript
231 lines
9.7 KiB
TypeScript
import { readFileSync, readdirSync } from 'node:fs'
|
|
import { createServer, type Server, type Socket } from 'node:net'
|
|
import { basename, join } from 'node:path'
|
|
import { afterEach, describe, expect, it, vi } from 'vitest'
|
|
import { generateKeyPair, publicKeyToBase64 } from './e2ee-crypto'
|
|
import type { RemoteRuntimeClientError } from './remote-runtime-client-error'
|
|
import { isRecoverableRemoteRuntimeConnectionError } from './remote-runtime-client-error-classification'
|
|
import {
|
|
REMOTE_RUNTIME_CONNECT_TIMEOUT_MS,
|
|
WS_HANDSHAKE_TIMEOUT_MESSAGE,
|
|
isRemoteRuntimeConnectTimeout,
|
|
remoteRuntimeConnectFailureMessage,
|
|
remoteRuntimeConnectOptions
|
|
} from './remote-runtime-connect-bound'
|
|
import { openRemoteRuntimeWebSocket } from './remote-runtime-request-websocket'
|
|
import { withRemoteRuntimeTailscaleHint } from './remote-runtime-tailscale-hint'
|
|
|
|
const servers = new Set<Server>()
|
|
const sockets = new Set<Socket>()
|
|
|
|
const handshakeTimeoutError = (): Error => new Error(WS_HANDSHAKE_TIMEOUT_MESSAGE)
|
|
|
|
/**
|
|
* Files whose WebSocket construction must carry the connect bound: the shared
|
|
* remote-runtime transports, swept by prefix. Other WebSocket sites (relay
|
|
* control and data transports, emulator control) carry their own bounds and are
|
|
* deliberately not covered here.
|
|
*/
|
|
function coveredSocketSources(): string[] {
|
|
return readdirSync(__dirname)
|
|
.filter(
|
|
(name) =>
|
|
name.startsWith('remote-runtime-') && name.endsWith('.ts') && !name.includes('.test.')
|
|
)
|
|
.map((name) => join(__dirname, name))
|
|
}
|
|
|
|
afterEach(async () => {
|
|
for (const socket of sockets) {
|
|
socket.destroy()
|
|
}
|
|
sockets.clear()
|
|
await Promise.all(
|
|
[...servers].map(
|
|
(server) =>
|
|
new Promise<void>((resolve) => {
|
|
server.close(() => resolve())
|
|
})
|
|
)
|
|
)
|
|
servers.clear()
|
|
})
|
|
|
|
/**
|
|
* Accepts TCP but never answers the HTTP upgrade, which is the same silent
|
|
* stall a black-holed host produces and is bounded by the same `ws` timer.
|
|
*/
|
|
async function listenSilentUpgradeServer(): Promise<string> {
|
|
const server = createServer((socket) => {
|
|
sockets.add(socket)
|
|
socket.once('close', () => sockets.delete(socket))
|
|
})
|
|
servers.add(server)
|
|
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve))
|
|
const address = server.address()
|
|
if (address === null || typeof address === 'string') {
|
|
throw new Error('expected a TCP address')
|
|
}
|
|
return `ws://127.0.0.1:${address.port}`
|
|
}
|
|
|
|
describe('remote runtime connect bound', () => {
|
|
it('bounds the production connect with a finite handshake timeout', () => {
|
|
const options = remoteRuntimeConnectOptions({ maxPayload: 1024 })
|
|
expect(Number.isFinite(options.handshakeTimeout)).toBe(true)
|
|
expect(options.handshakeTimeout).toBe(REMOTE_RUNTIME_CONNECT_TIMEOUT_MS)
|
|
expect(options.maxPayload).toBe(1024)
|
|
})
|
|
|
|
// Why: the bound only helps if every Node-side remote-runtime socket carries
|
|
// it; a new transport that calls `new WebSocket` directly reintroduces #18191.
|
|
it('routes every covered WebSocket construction through the bounded options', () => {
|
|
const offenders: string[] = []
|
|
let scannedConstructions = 0
|
|
for (const path of coveredSocketSources()) {
|
|
const source = readFileSync(path, 'utf8')
|
|
const constructions = source.split('new WebSocket(').length - 1
|
|
const bounded = source.split('remoteRuntimeConnectOptions(').length - 1
|
|
scannedConstructions += constructions
|
|
if (constructions > bounded) {
|
|
offenders.push(`${basename(path)}: ${constructions} WebSocket(s), ${bounded} bounded`)
|
|
}
|
|
}
|
|
expect(offenders).toEqual([])
|
|
// Guards against the scan silently matching nothing and passing vacuously.
|
|
expect(scannedConstructions).toBeGreaterThan(0)
|
|
})
|
|
|
|
it('reports an unanswered host as unreachable rather than as an empty result', async () => {
|
|
const endpoint = await listenSilentUpgradeServer()
|
|
const keyPair = generateKeyPair()
|
|
const onError = vi.fn()
|
|
const onTextFrame = vi.fn()
|
|
|
|
const opened = openRemoteRuntimeWebSocket(
|
|
{
|
|
v: 2,
|
|
endpoint,
|
|
deviceToken: 'device-token',
|
|
publicKeyB64: publicKeyToBase64(keyPair.publicKey)
|
|
},
|
|
{ onClose: vi.fn(), onError, onTextFrame },
|
|
150
|
|
)
|
|
if (!opened.ok) {
|
|
throw opened.error
|
|
}
|
|
|
|
await vi.waitFor(() => expect(onError).toHaveBeenCalledTimes(1), {
|
|
timeout: 5_000
|
|
})
|
|
|
|
// The bounded path was taken: a connect failure, not a silent empty answer.
|
|
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: vi mock call args are untyped; this subscription's onError is only ever invoked with a RemoteRuntimeClientError.
|
|
const error = onError.mock.calls[0][1] as RemoteRuntimeClientError
|
|
expect(error.code).toBe('remote_runtime_unavailable')
|
|
expect(error.message).toContain(endpoint)
|
|
expect(error.message).toContain('unverifiable')
|
|
expect(onTextFrame).not.toHaveBeenCalled()
|
|
|
|
// Loss of contact is never evidence the host's work stopped.
|
|
expect(error.message).not.toMatch(/\b(exited|gone|stopped|empty|no terminals)\b/i)
|
|
|
|
// The subscribe IPC boundary drops `code`, so the renderer classifies this
|
|
// message alone. Fatal there means `recovery.cancel()` and a dead-ended pane
|
|
// instead of a retry, so the real produced message must still read recoverable.
|
|
expect(isRecoverableRemoteRuntimeConnectionError({ message: error.message })).toBe(true)
|
|
// ...and must still earn the Tailscale remedy, which is gated on the same phrase.
|
|
expect(withRemoteRuntimeTailscaleHint(error.message, endpoint)).not.toBe(error.message)
|
|
|
|
opened.socket.cleanup()
|
|
opened.socket.ws.terminate()
|
|
})
|
|
|
|
it('only calls an elapsed handshake a connect timeout', () => {
|
|
expect(isRemoteRuntimeConnectTimeout(handshakeTimeoutError())).toBe(true)
|
|
expect(isRemoteRuntimeConnectTimeout(new Error('connect ECONNREFUSED'))).toBe(false)
|
|
expect(remoteRuntimeConnectFailureMessage(new Error('connect ECONNREFUSED'), 'ws://h')).toBe(
|
|
'Could not connect to the remote Orca runtime.'
|
|
)
|
|
})
|
|
|
|
// Why: the message is the only carrier on the code-less paths (subscribe IPC,
|
|
// web, mobile). Both gates below match a phrase, so a rewording silently turns
|
|
// a retrying pane into a dead-ended one and drops the only actionable remedy.
|
|
it('keeps the unreachable-host message inside both message gates', () => {
|
|
const message = remoteRuntimeConnectFailureMessage(
|
|
handshakeTimeoutError(),
|
|
'ws://desk.example.com:6768'
|
|
)
|
|
expect(isRecoverableRemoteRuntimeConnectionError({ message })).toBe(true)
|
|
// The shape Electron produces for a rejected ipcMain.handle, which keeps no code.
|
|
expect(
|
|
isRecoverableRemoteRuntimeConnectionError({
|
|
message: `Error invoking remote method 'runtimeEnvironments:subscribe': Error: ${message}`
|
|
})
|
|
).toBe(true)
|
|
expect(withRemoteRuntimeTailscaleHint(message, 'ws://192.168.1.10:6768')).toContain(
|
|
'connect both devices to Tailscale'
|
|
)
|
|
expect(
|
|
withRemoteRuntimeTailscaleHint(
|
|
remoteRuntimeConnectFailureMessage(handshakeTimeoutError(), 'wss://desk.tail1234.ts.net'),
|
|
'wss://desk.tail1234.ts.net'
|
|
)
|
|
).toContain('tailnet')
|
|
})
|
|
|
|
// Why: the hint's idempotency check used to key on the word "tailscale" anywhere in the
|
|
// message. Now that the message carries the endpoint, such a host would suppress the very
|
|
// remedy it needs.
|
|
it('still earns the hint when the endpoint itself contains the vendor name', () => {
|
|
const endpoint = 'wss://tailscale-box.example.com:6768'
|
|
const message = remoteRuntimeConnectFailureMessage(handshakeTimeoutError(), endpoint)
|
|
expect(message).toContain('tailscale-box')
|
|
expect(withRemoteRuntimeTailscaleHint(message, endpoint)).toContain(
|
|
'connect both devices to Tailscale'
|
|
)
|
|
})
|
|
|
|
// Why: the endpoint arrives from a pasted pairing code, which is only length-capped.
|
|
it('shows the endpoint origin only, never pasted credentials', () => {
|
|
const message = remoteRuntimeConnectFailureMessage(
|
|
handshakeTimeoutError(),
|
|
'wss://user:s3cret@desk.example.com:6768/path?token=abc'
|
|
)
|
|
expect(message).toContain('wss://desk.example.com:6768')
|
|
expect(message).not.toContain('s3cret')
|
|
expect(message).not.toContain('token=abc')
|
|
})
|
|
|
|
// Why: `isRemoteTerminalGoneMessage` in the pty transport substring-matches these tokens and
|
|
// runs BEFORE the recoverable gate, and WHATWG URL accepts `_` in a host. An endpoint could
|
|
// otherwise turn loss of contact into a terminal-gone verdict.
|
|
it('never lets the endpoint smuggle a terminal-gone token into the message', () => {
|
|
for (const host of ['terminal_gone.example', 'terminal_exited.example', 'no_connected_pty']) {
|
|
const message = remoteRuntimeConnectFailureMessage(
|
|
handshakeTimeoutError(),
|
|
`ws://${host}:6768`
|
|
)
|
|
expect(message).not.toMatch(/terminal_exited|terminal_gone|no_connected_pty/)
|
|
// Still reads as a recoverable connect failure, so the pane keeps retrying.
|
|
expect(isRecoverableRemoteRuntimeConnectionError({ message })).toBe(true)
|
|
}
|
|
// A well-formed host is still shown, so the redaction is not blanket.
|
|
expect(
|
|
remoteRuntimeConnectFailureMessage(handshakeTimeoutError(), 'ws://[fd7a:115c:a1e0::1]:6768')
|
|
).toContain('[fd7a:115c:a1e0::1]:6768')
|
|
})
|
|
|
|
// Why: `ws` and `net` gate on a truthy timeout, so 0 would leave the connect unbounded.
|
|
it('refuses a non-positive or non-finite bound and keeps the production default', () => {
|
|
for (const value of [0, -1, Number.NaN, Number.POSITIVE_INFINITY]) {
|
|
expect(remoteRuntimeConnectOptions(undefined, value).handshakeTimeout).toBe(
|
|
REMOTE_RUNTIME_CONNECT_TIMEOUT_MS
|
|
)
|
|
}
|
|
expect(remoteRuntimeConnectOptions(undefined, 150).handshakeTimeout).toBe(150)
|
|
})
|
|
})
|