Skip to content

Commit 6549b0a

Browse files
authored
fix(desktop): keep concurrent VNC viewers on one connection (#133226)
Retain each node viewer's inspected RFB connection through authentication so concurrent cloud and paired-node viewers do not double TigerVNC's pending connection attempts. Preserve buffered final frames and finish WebSocket closure before retiring desktop or portal control invocations.
1 parent e42bb23 commit 6549b0a

11 files changed

Lines changed: 914 additions & 316 deletions

‎docs/gateway/cloud-workers.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -430,7 +430,7 @@ Crabbox provisions XFCE on display `:99`, an authenticated RFB server on `127.0.
430430

431431
The enrolled node starts CUA inside that same XFCE session. A vision-capable agent whose tool policy permits `computer` controls this desktop through the session's exact placement; it cannot select another node. This works for both OpenClaw workers and Codex remote execution. See [Desktop and computer control](/gateway/cloud-sessions#desktop-and-computer-control) for tool enablement and manual-control guidance.
432432

433-
The desktop never gains public ingress. The node reads `/var/lib/crabbox/vnc.password` locally, probes the authenticated loopback RFB server, and redeems a single-use Gateway broker ticket over the node's already-connected origin. TLS deployments pin the same Gateway certificate used by the node connection. The Gateway revalidates the durable environment, lease, node, owner epoch, desktop descriptor, connection, and pairing both before dispatch and after attach; drain, replacement, or teardown aborts the stream and any pending app launch. The shared desktop session owner performs RFB preauthentication, view-only input filtering, and single-controller arbitration.
433+
The desktop never gains public ingress. The node reads `/var/lib/crabbox/vnc.password` locally, inspects the loopback RFB security offer, and keeps that same connection for the viewer. It redeems a single-use Gateway broker ticket over the node's already-connected origin. Opening viewers therefore creates no extra unauthenticated probe connections. TLS deployments pin the same Gateway certificate used by the node connection. The Gateway revalidates the durable environment, lease, node, owner epoch, desktop descriptor, connection, and pairing both before dispatch and after attach; drain, replacement, or teardown aborts the stream and any pending app launch. The shared desktop session owner performs RFB preauthentication, view-only input filtering, and single-controller arbitration.
434434

435435
The Gateway sends WebSocket keepalives on desktop observer and node desktop or portal streams while idle, so an unchanged screen or quiet preview does not go silent behind a proxy. Backpressure may delay pong replies without revoking the stream; the owning session and control connection still govern teardown.
436436

‎src/gateway/desktop/node-observe.integration.test.ts‎

Lines changed: 227 additions & 172 deletions
Large diffs are not rendered by default.

‎src/gateway/desktop/rfb-preauth.test.ts‎

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -275,15 +275,22 @@ describe("RFB server-side pre-authentication", () => {
275275
}
276276
});
277277

278-
it("matches the VncAuth bit-reversed DES challenge vector", async () => {
278+
it.each([
279+
["RFB 003.003\n", "RFB 003.003\n", true],
280+
["RFB 003.007\n", "RFB 003.007\n", false],
281+
["RFB 003.008\n", "RFB 003.008\n", false],
282+
["RFB 003.889\n", "RFB 003.008\n", false],
283+
])("matches the VncAuth DES vector with server version %j", async (banner, reply, legacy) => {
279284
const challenge = Buffer.from("0123456789abcdef", "ascii");
280285
await runPreauth({
281286
preauth: { auth: "vnc-password", credentials: { password: "password" } },
282287
serverScript: async (server) => {
283-
await server.write(VERSION_3_8);
284-
expect(await server.readExactly(12)).toEqual(VERSION_3_8);
285-
await server.write(Buffer.from([1, 2]));
286-
expect(await server.readExactly(1)).toEqual(Buffer.from([2]));
288+
await server.write(Buffer.from(banner));
289+
expect(await server.readExactly(12)).toEqual(Buffer.from(reply));
290+
await server.write(legacy ? Buffer.from([0, 0, 0, 2]) : Buffer.from([1, 2]));
291+
if (!legacy) {
292+
expect(await server.readExactly(1)).toEqual(Buffer.from([2]));
293+
}
287294
await server.write(challenge);
288295
expect((await server.readExactly(16)).toString("hex")).toBe(
289296
"5645abeb5f1e6475e8feb11beb66ea19",

‎src/gateway/desktop/rfb-preauth.ts‎

Lines changed: 5 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
import { createCipheriv, createHash, randomBytes } from "node:crypto";
22
import type { Duplex } from "node:stream";
3+
import { parseRfbVersionBanner } from "./rfb-probe.js";
34

45
const RFB_VERSION_BYTES = 12;
5-
const RFB_3_3_VERSION = Buffer.from("RFB 003.003\n", "ascii");
66
const RFB_3_8_VERSION = Buffer.from("RFB 003.008\n", "ascii");
77
const RFB_SECURITY_NONE = 1;
88
const RFB_SECURITY_VNC = 2;
@@ -155,18 +155,6 @@ class StreamRfbPreauthPeer implements RfbPreauthPeer {
155155
}
156156
}
157157

158-
function parseServerVersion(banner: Buffer): { minor: number; reply: Buffer } {
159-
const match = /^RFB 003\.(\d{3})\n$/u.exec(banner.toString("ascii"));
160-
if (!match) {
161-
throw new Error(`unsupported RFB protocol version ${JSON.stringify(banner.toString("ascii"))}`);
162-
}
163-
const offeredMinor = Number.parseInt(match[1] ?? "", 10);
164-
if (offeredMinor === 889 || offeredMinor >= 7) {
165-
return { minor: 8, reply: RFB_3_8_VERSION };
166-
}
167-
return { minor: 3, reply: RFB_3_3_VERSION };
168-
}
169-
170158
async function readReason(peer: RfbPreauthPeer, signal: AbortSignal): Promise<string> {
171159
const length = (await peer.readExactly(4, signal)).readUInt32BE(0);
172160
if (length === 0) {
@@ -358,7 +346,10 @@ async function negotiateServer(params: {
358346
throw new Error("ARD account username and password are required");
359347
}
360348
const banner = await params.peer.readExactly(RFB_VERSION_BYTES, params.signal);
361-
const version = parseServerVersion(banner);
349+
const version = parseRfbVersionBanner(banner);
350+
if (version.kind !== "rfb") {
351+
throw new Error(`unsupported RFB protocol version ${JSON.stringify(version.banner)}`);
352+
}
362353
await params.peer.write(version.reply, params.signal);
363354
const requiredType = params.preauth.auth === "ard-account" ? RFB_SECURITY_ARD : RFB_SECURITY_VNC;
364355
await selectSecurityType({

‎src/gateway/desktop/rfb-probe.test.ts‎

Lines changed: 272 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
import net from "node:net";
2-
import { afterEach, describe, expect, it } from "vitest";
3-
import { classifyRfbSecurity, probeRfbServer } from "./rfb-probe.js";
2+
import { finished } from "node:stream/promises";
3+
import { afterEach, describe, expect, it, vi } from "vitest";
4+
import { createDeferred } from "../../../test/helpers/promise.js";
5+
import { classifyRfbSecurity, connectRfbServer, probeRfbServer } from "./rfb-probe.js";
46

57
const cleanups: Array<() => Promise<void>> = [];
68

@@ -159,3 +161,271 @@ describe("RFB security classification", () => {
159161
expect(classifyRfbSecurity([30, 33, 36, 35])).toBe("ard-account");
160162
});
161163
});
164+
165+
describe("retained RFB connection", () => {
166+
it.each([
167+
["3.3", "RFB 003.003\n", "RFB 003.003\n", Buffer.from([0, 0, 0, 2])],
168+
["3.7", "RFB 003.007\n", "RFB 003.007\n", Buffer.from([1, 2])],
169+
["3.8", "RFB 003.008\n", "RFB 003.008\n", Buffer.from([1, 2])],
170+
["macOS", "RFB 003.889\n", "RFB 003.008\n", Buffer.from([2, 30, 2])],
171+
])(
172+
"retains one %s connection across split replies and coalesced server data",
173+
async (_name, banner, reply, offer) => {
174+
const challenge = Buffer.alloc(16, 7);
175+
const clientData = Buffer.from([2, 8, 9]);
176+
const received: Buffer[] = [];
177+
let connections = 0;
178+
const port = await listenScriptedRfb((socket) => {
179+
connections++;
180+
socket.on("data", (data) => received.push(Buffer.from(data)));
181+
socket.write(Buffer.from(banner.slice(0, 5)));
182+
setImmediate(() => socket.write(Buffer.from(banner.slice(5))));
183+
socket.once("data", (version) => {
184+
expect(version).toEqual(Buffer.from(reply));
185+
socket.write(Buffer.concat([offer, challenge]));
186+
});
187+
});
188+
const result = await connectRfbServer({ host: "127.0.0.1", port, timeoutMs: 2_000 });
189+
expect(result.kind).toBe("rfb");
190+
if (result.kind !== "rfb") {
191+
throw new Error("expected retained connection");
192+
}
193+
cleanups.push(async () => {
194+
result.stream.destroy();
195+
});
196+
const output: Buffer[] = [];
197+
result.stream.on("data", (chunk: Buffer) => output.push(chunk));
198+
await vi.waitFor(() =>
199+
expect(Buffer.concat(output)).toEqual(
200+
Buffer.concat([Buffer.from(banner), offer, challenge]),
201+
),
202+
);
203+
result.stream.write(Buffer.from(reply.slice(0, 4)));
204+
result.stream.write(Buffer.from(reply.slice(4, 9)));
205+
result.stream.write(Buffer.concat([Buffer.from(reply.slice(9)), clientData]));
206+
await vi.waitFor(() =>
207+
expect(Buffer.concat(received)).toEqual(Buffer.concat([Buffer.from(reply), clientData])),
208+
);
209+
expect(connections).toBe(1);
210+
},
211+
);
212+
213+
it("rejects a changed downstream version without forwarding authentication bytes", async () => {
214+
const received: Buffer[] = [];
215+
let closed = false;
216+
const port = await listenScriptedRfb((socket) => {
217+
socket.once("close", () => {
218+
closed = true;
219+
});
220+
socket.on("data", (data) => received.push(Buffer.from(data)));
221+
socket.write(Buffer.from("RFB 003.008\n"));
222+
socket.once("data", () => socket.write(Buffer.from([1, 2])));
223+
});
224+
const result = await connectRfbServer({ host: "127.0.0.1", port, timeoutMs: 2_000 });
225+
if (result.kind !== "rfb") {
226+
throw new Error("expected retained connection");
227+
}
228+
const failure = new Promise<Error>((resolve) => {
229+
result.stream.once("error", resolve);
230+
});
231+
result.stream.write(Buffer.from("RFB 003.003\nsecret-response"));
232+
await expect(failure).resolves.toMatchObject({
233+
message: "RFB client changed the inspected protocol version",
234+
});
235+
await vi.waitFor(() => expect(closed).toBe(true));
236+
expect(Buffer.concat(received)).toEqual(Buffer.from("RFB 003.008\n"));
237+
});
238+
239+
it.each(["banner", "security", "handoff"])(
240+
"cancels the owned socket during %s",
241+
async (phase) => {
242+
let connected = false;
243+
let closed = false;
244+
const port = await listenScriptedRfb((socket) => {
245+
connected = true;
246+
socket.once("close", () => {
247+
closed = true;
248+
});
249+
if (phase === "banner") {
250+
return;
251+
}
252+
socket.write(Buffer.from("RFB 003.008\n"));
253+
socket.once("data", () => {
254+
if (phase === "handoff") {
255+
socket.write(Buffer.from([1, 2]));
256+
}
257+
});
258+
});
259+
const controller = new AbortController();
260+
const pending = connectRfbServer({
261+
host: "127.0.0.1",
262+
port,
263+
timeoutMs: 2_000,
264+
signal: controller.signal,
265+
});
266+
if (phase === "handoff") {
267+
const result = await pending;
268+
if (result.kind !== "rfb") {
269+
throw new Error("expected retained connection");
270+
}
271+
controller.abort(new Error("desktop owner stopped"));
272+
await vi.waitFor(() => expect(result.stream.destroyed).toBe(true));
273+
} else {
274+
const rejected = expect(pending).rejects.toThrow("desktop owner stopped");
275+
await vi.waitFor(() => expect(connected).toBe(true));
276+
controller.abort(new Error("desktop owner stopped"));
277+
await rejected;
278+
}
279+
await vi.waitFor(() => expect(closed).toBe(true));
280+
},
281+
);
282+
it("ends writes and preserves terminal response bytes while a consumer remains paused", async () => {
283+
const response = Buffer.alloc(32 * 1024, 7);
284+
const peerClosed = createDeferred();
285+
const port = await listenScriptedRfb((socket) => {
286+
socket.once("close", () => peerClosed.resolve());
287+
socket.write(Buffer.from("RFB 003.008\n"));
288+
socket.once("data", () => {
289+
socket.write(Buffer.from([1, 2]));
290+
socket.once("data", (selection) => {
291+
expect(selection).toEqual(Buffer.from([2]));
292+
socket.end(response);
293+
});
294+
});
295+
});
296+
const result = await connectRfbServer({ host: "127.0.0.1", port, timeoutMs: 2_000 });
297+
if (result.kind !== "rfb") {
298+
throw new Error("expected retained connection");
299+
}
300+
cleanups.push(async () => {
301+
result.stream.destroy();
302+
});
303+
const prefix = await new Promise<Buffer>((resolve) => {
304+
result.stream.once("data", (chunk: Buffer) => {
305+
result.stream.pause();
306+
resolve(chunk);
307+
});
308+
});
309+
expect(prefix).toEqual(Buffer.concat([Buffer.from("RFB 003.008\n"), Buffer.from([1, 2])]));
310+
result.stream.write(Buffer.concat([Buffer.from("RFB 003.008\n"), Buffer.from([2])]));
311+
// The peer has finished and closed while the caller has consumed no response.
312+
await peerClosed.promise;
313+
expect(result.stream.destroyed).toBe(false);
314+
expect(result.stream.writableEnded).toBe(true);
315+
const settled = finished(result.stream);
316+
void settled.catch(() => undefined);
317+
const received: Buffer[] = [];
318+
for await (const chunk of result.stream) {
319+
received.push(Buffer.from(chunk));
320+
}
321+
expect(Buffer.concat(received)).toEqual(response);
322+
await expect(settled).resolves.toBeUndefined();
323+
});
324+
325+
it.each(["peer-fin", "owner-abort"])("settles queued client writes on %s", async (ending) => {
326+
const ready = createDeferred<net.Socket>();
327+
const received: Buffer[] = [];
328+
let receivedBytes = 0;
329+
const response = Buffer.alloc(32 * 1024, 9);
330+
const port = await listenScriptedRfb((peer) => {
331+
peer.on("error", (error: NodeJS.ErrnoException) => {
332+
if (error.code !== "ECONNRESET" && error.code !== "EPIPE") {
333+
throw error;
334+
}
335+
});
336+
peer.write(Buffer.from("RFB 003.008\n"));
337+
peer.once("data", () => {
338+
peer.write(Buffer.from([1, 2]));
339+
peer.once("data", () => {
340+
peer.pause();
341+
peer.on("data", (chunk) => {
342+
const bytes = Buffer.from(chunk);
343+
received.push(bytes);
344+
receivedBytes += bytes.length;
345+
});
346+
ready.resolve(peer);
347+
});
348+
});
349+
});
350+
const controller = new AbortController();
351+
const result = await connectRfbServer({
352+
host: "127.0.0.1",
353+
port,
354+
timeoutMs: 2_000,
355+
signal: controller.signal,
356+
});
357+
if (result.kind !== "rfb") {
358+
throw new Error("expected retained connection");
359+
}
360+
cleanups.push(async () => {
361+
result.stream.destroy();
362+
});
363+
const settled = finished(result.stream);
364+
void settled.catch(() => undefined);
365+
await new Promise<void>((resolve) => {
366+
result.stream.once("data", () => {
367+
result.stream.pause();
368+
resolve();
369+
});
370+
});
371+
result.stream.write(Buffer.concat([Buffer.from("RFB 003.008\n"), Buffer.from([2])]));
372+
const peer = await ready.promise;
373+
const first = Buffer.alloc(8 * 1024 * 1024, 7);
374+
const last = Buffer.from("queued-client-tail");
375+
const callbacks: Array<Error | null> = [];
376+
result.stream.write(first, (error) => callbacks.push(error ?? null));
377+
result.stream.write(last, (error) => callbacks.push(error ?? null));
378+
// Keep the first native write pending and the second queued in the wrapper
379+
// when FIN arrives. The same owner must drain both before ending TCP writes.
380+
expect(result.stream.writableLength).toBe(first.length + last.length);
381+
if (ending === "owner-abort") {
382+
controller.abort(new Error("desktop owner stopped"));
383+
await expect(settled).rejects.toThrow("desktop owner stopped");
384+
await vi.waitFor(() => expect(callbacks).toHaveLength(2));
385+
expect(callbacks.every((error) => error instanceof Error)).toBe(true);
386+
expect(result.stream.destroyed).toBe(true);
387+
return;
388+
}
389+
peer.end(response);
390+
await vi.waitFor(() => expect(result.stream.writableEnded).toBe(true));
391+
peer.resume();
392+
const output: Buffer[] = [];
393+
result.stream.on("data", (chunk: Buffer) => output.push(chunk));
394+
result.stream.resume();
395+
await expect(settled).resolves.toBeUndefined();
396+
expect(Buffer.concat(output)).toEqual(response);
397+
expect(callbacks).toEqual([null, null]);
398+
await vi.waitFor(() => expect(receivedBytes).toBe(first.length + last.length));
399+
expect(Buffer.concat(received).equals(Buffer.concat([first, last]))).toBe(true);
400+
});
401+
402+
it.each(["", "final-pre-attach-response"])(
403+
"retains an offer and FIN before attachment (tail: %j)",
404+
async (tail) => {
405+
const finSent = createDeferred();
406+
const wire = Buffer.concat([
407+
Buffer.from("RFB 003.008\n"),
408+
Buffer.from([1, 2]),
409+
Buffer.from(tail),
410+
]);
411+
const port = await listenScriptedRfb((peer) => {
412+
peer.write(wire.subarray(0, 12));
413+
peer.once("data", () => peer.end(wire.subarray(12), () => finSent.resolve()));
414+
});
415+
const result = await connectRfbServer({ host: "127.0.0.1", port, timeoutMs: 2_000 });
416+
if (result.kind !== "rfb") {
417+
throw new Error("expected retained connection");
418+
}
419+
cleanups.push(async () => {
420+
result.stream.destroy();
421+
});
422+
await finSent.promise;
423+
const settled = finished(result.stream);
424+
const received: Buffer[] = [];
425+
result.stream.on("data", (chunk: Buffer) => received.push(chunk));
426+
await settled;
427+
expect(Buffer.concat(received)).toEqual(wire);
428+
expect(result.stream.writableFinished).toBe(true);
429+
},
430+
);
431+
});

0 commit comments

Comments
 (0)