Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(device): serve HTTP tunnel requests from the device (#19855)

Arvin Xu50571e6a0f3b
diff --git a/apps/cli/src/commands/status.ts b/apps/cli/src/commands/status.ts
index 9f33f959691..ae6b5022b10 100644
--- a/apps/cli/src/commands/status.ts
+++ b/apps/cli/src/commands/status.ts
@@ -59,6 +59,8 @@ export function registerStatusCommand(program: Command) {
gatewayUrl: gatewayUrl || OFFICIAL_GATEWAY_URL,
logger: log,
serverUrl: auth.serverUrl,
+ // Status is a one-shot probe, not a serving connection.
+ tunnel: false,
token: auth.token,
tokenType: auth.tokenType,
userId: auth.userId,
diff --git a/apps/cli/src/doctor/checks/device.ts b/apps/cli/src/doctor/checks/device.ts
index 9bc17086a06..45e088579aa 100644
--- a/apps/cli/src/doctor/checks/device.ts
+++ b/apps/cli/src/doctor/checks/device.ts
@@ -125,6 +125,9 @@ const gatewayHandshake: DoctorCheck = {
autoReconnect: false,
gatewayUrl,
serverUrl: credential.serverUrl,
+ // A probe connection proves reachability and exits; it must never
+ // advertise itself as able to serve tunnels.
+ tunnel: false,
token: credential.token!,
tokenType: credential.tokenType,
userId: credential.userId!,
diff --git a/packages/device-gateway-client/src/client.test.ts b/packages/device-gateway-client/src/client.test.ts
index 429f6a712fb..386b7783de0 100644
--- a/packages/device-gateway-client/src/client.test.ts
+++ b/packages/device-gateway-client/src/client.test.ts
@@ -553,6 +553,66 @@ describe('GatewayClient', () => {
});
});
+ describe('tunnel serving', () => {
+ it('forwards tunnel frames to the tunnel host', async () => {
+ client.connect();
+ await vi.advanceTimersByTimeAsync(1);
+ (client as any).handleMessage(JSON.stringify({ type: 'auth_success' }));
+
+ const handleFrame = vi.spyOn((client as any).tunnelHost, 'handleFrame');
+ const frame = { bytes: 64, connId: 'c1', type: 'tunnel_ack' };
+ (client as any).handleMessage(JSON.stringify(frame));
+
+ expect(handleFrame).toHaveBeenCalledWith(frame);
+ });
+
+ it('releases tunnels on a forced reconnect, not just on a clean close', async () => {
+ client.connect();
+ await vi.advanceTimersByTimeAsync(1);
+ (client as any).handleMessage(JSON.stringify({ type: 'auth_success' }));
+
+ const closeAll = vi.spyOn((client as any).tunnelHost, 'closeAll');
+ // Miss enough heartbeat acks to trip forceReconnect, which detaches
+ // handleClose and so never reaches the normal close cleanup.
+ await vi.advanceTimersByTimeAsync(30_000 * 5);
+
+ expect(closeAll).toHaveBeenCalledWith('DEVICE_DISCONNECTED');
+ });
+
+ it('answers tunnel_open with TUNNEL_DISABLED when serving is off', async () => {
+ const offClient = new GatewayClient({
+ autoReconnect: false,
+ gatewayUrl: 'https://gateway.test.com',
+ token: 'tok',
+ tunnel: false,
+ });
+ offClient.connect();
+ await vi.advanceTimersByTimeAsync(1);
+ (offClient as any).handleMessage(JSON.stringify({ type: 'auth_success' }));
+ const ws = (offClient as any).ws;
+ ws.send.mockClear();
+
+ (offClient as any).handleMessage(
+ JSON.stringify({
+ connId: 'c1',
+ head: { headers: [], method: 'GET', path: '/' },
+ target: { host: '127.0.0.1', port: 3000 },
+ type: 'tunnel_open',
+ }),
+ );
+
+ expect(ws.send).toHaveBeenCalledWith(
+ JSON.stringify({
+ connId: 'c1',
+ error: 'TUNNEL_DISABLED',
+ ok: false,
+ type: 'tunnel_open_ack',
+ }),
+ );
+ offClient.disconnect();
+ });
+ });
+
describe('reconnection', () => {
it('should reconnect on close when autoReconnect is true', async () => {
const reconnectClient = new GatewayClient({
diff --git a/packages/device-gateway-client/src/client.ts b/packages/device-gateway-client/src/client.ts
index 0f980d7883c..ff586afa01a 100644
--- a/packages/device-gateway-client/src/client.ts
+++ b/packages/device-gateway-client/src/client.ts
@@ -4,6 +4,7 @@ import os from 'node:os';
import WebSocket from 'ws';
+import { DeviceTunnelHost } from './tunnel';
import type {
AgentRunAckMessage,
AgentRunRequestMessage,
@@ -80,6 +81,14 @@ export interface GatewayClientOptions {
serverUrl?: string;
token: string;
tokenType?: 'apiKey' | 'jwt' | 'serviceToken';
+ /**
+ * Serve HTTP tunnel requests: the gateway relays a browser request to a
+ * loopback port on this machine (`http://127.0.0.1:<port>/…`) so a dev server
+ * running here can be opened from the cloud UI. Default: enabled. Callers
+ * that must never expose local ports can turn it off; the gateway then gets a
+ * `TUNNEL_DISABLED` ack instead of silence.
+ */
+ tunnel?: boolean;
userAgent?: string;
userId?: string;
/**
@@ -93,6 +102,7 @@ export interface GatewayClientOptions {
export class GatewayClient extends EventEmitter {
private ws: WebSocket | null = null;
+ private tunnelHost: DeviceTunnelHost | null = null;
private heartbeatTimer: ReturnType<typeof setInterval> | null = null;
private reconnectTimer: ReturnType<typeof setTimeout> | null = null;
private connectWatchdogTimer: ReturnType<typeof setTimeout> | null = null;
@@ -129,6 +139,12 @@ export class GatewayClient extends EventEmitter {
this.logger = options.logger || noopLogger;
this.autoReconnect = options.autoReconnect ?? true;
this.connectTimeoutMs = options.connectTimeoutMs ?? CONNECT_TIMEOUT;
+ if (options.tunnel !== false) {
+ this.tunnelHost = new DeviceTunnelHost({
+ logger: this.logger,
+ send: (frame) => this.sendMessage(frame),
+ });
+ }
}
// ─── Public API ───
@@ -389,6 +405,21 @@ export class GatewayClient extends EventEmitter {
break;
}
+ case 'tunnel_open':
+ case 'tunnel_data':
+ case 'tunnel_ack':
+ case 'tunnel_close': {
+ if (this.tunnelHost) this.tunnelHost.handleFrame(message);
+ else if (message.type === 'tunnel_open')
+ this.sendMessage({
+ connId: message.connId,
+ error: 'TUNNEL_DISABLED',
+ ok: false,
+ type: 'tunnel_open_ack',
+ });
+ break;
+ }
+
default: {
this.logger.warn('Unknown message type:', (message as any).type);
}
@@ -401,6 +432,9 @@ export class GatewayClient extends EventEmitter {
private handleClose = (code: number, reason: Buffer) => {
this.logger.info(`WebSocket closed: code=${code} reason=${reason.toString()}`);
this.stopHeartbeat();
+ // In-flight tunnels can't survive the socket: their frames have nowhere to
+ // go and the browser side is already being failed by the gateway.
+ this.tunnelHost?.closeAll('DEVICE_DISCONNECTED');
// `handshakeTimeout` closes the socket on its own, so the watchdog must be
// disarmed here or it would fire later and force a SECOND reconnect on top
// of the one this close already scheduled.
@@ -526,6 +560,10 @@ export class GatewayClient extends EventEmitter {
}
private closeWebSocket() {
+ // Every teardown funnels through here β€” including `forceReconnect`, which
+ // detaches `handleClose` β€” so tunnels must be released here or a forced
+ // reconnect would leave loopback fetches running and slots consumed.
+ this.tunnelHost?.closeAll('DEVICE_DISCONNECTED');
if (!this.ws) {
return;
}
diff --git a/packages/device-gateway-client/src/index.ts b/packages/device-gateway-client/src/index.ts
index a07885a5343..65442d05ec5 100644
--- a/packages/device-gateway-client/src/index.ts
+++ b/packages/device-gateway-client/src/index.ts
@@ -18,4 +18,6 @@ export type {
GatewayHttpClientOptions,
} from './http';
export { GatewayHttpClient } from './http';
+export type { DeviceTunnelHostOptions } from './tunnel';
+export { DeviceTunnelHost } from './tunnel';
export * from './types';
diff --git a/packages/device-gateway-client/src/tunnel.test.ts b/packages/device-gateway-client/src/tunnel.test.ts
new file mode 100644
index 00000000000..e97408d1b55
--- /dev/null
+++ b/packages/device-gateway-client/src/tunnel.test.ts
@@ -0,0 +1,369 @@
+import { Buffer } from 'node:buffer';
+import http from 'node:http';
+import type { Socket } from 'node:net';
+import { gzipSync } from 'node:zlib';
+
+import { afterAll, beforeAll, describe, expect, it } from 'vitest';
+
+import type { TunnelFetch } from './tunnel';
+import { DeviceTunnelHost } from './tunnel';
+import type { TunnelClientFrame, TunnelOpenMessage } from './types';
+import { TUNNEL_CHUNK_SIZE, TUNNEL_FLOW_WINDOW } from './types';
+
+let server: http.Server;
+let port: number;
+/** Requests the origin saw torn down early, so aborts are observable. */
+const aborted: string[] = [];
+/** Requests the origin actually received, so tests don't abort before dispatch. */
+const received: string[] = [];
+const sockets = new Set<Socket>();
+
+beforeAll(async () => {
+ server = http.createServer((req, res) => {
+ const url = new URL(req.url!, 'http://127.0.0.1');
+ if (url.pathname === '/') {
+ res.writeHead(200, { 'content-type': 'text/html' });
+ res.end('<h1>origin</h1>');
+ return;
+ }
+ if (url.pathname === '/echo') {
+ const chunks: Buffer[] = [];
+ req.on('data', (c) => chunks.push(c));
+ req.on('end', () => {
+ res.writeHead(200, { 'content-type': 'application/octet-stream' });
+ res.end(Buffer.concat(chunks));
+ });
+ return;
+ }
+ if (url.pathname === '/cookies') {
+ res.writeHead(200, {
+ 'content-type': 'text/plain',
+ 'set-cookie': ['a=1; Path=/', 'b=2; Path=/'],
+ });
+ res.end('ok');
+ return;
+ }
+ if (url.pathname === '/gzip') {
+ const payload = gzipSync(Buffer.from('compressed-payload'));
+ res.writeHead(200, { 'content-encoding': 'gzip', 'content-type': 'text/plain' });
+ res.end(payload);
+ return;
+ }
+ if (url.pathname === '/redirect') {
+ res.writeHead(302, { location: '/elsewhere' });
+ res.end();
+ return;
+ }
+ if (url.pathname === '/big') {
+ res.writeHead(200, { 'content-type': 'application/octet-stream' });
+ res.end(Buffer.alloc(2 * 1024 * 1024, 0x61));
+ return;
+ }
+ if (url.pathname === '/hang') {
+ received.push('/hang');
+ // Fires when the connection goes away before a response was written.
+ res.on('close', () => aborted.push('/hang'));
+ return; // never responds
+ }
+ res.writeHead(404, { 'content-type': 'text/plain' });
+ res.end('not here');
+ });
+ server.on('connection', (socket) => {
+ sockets.add(socket);
+ socket.on('close', () => sockets.delete(socket));
+ });
+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
+ port = (server.address() as { port: number }).port;
+});
+
+afterAll(async () => {
+ // `/hang` deliberately leaves requests open; close() would wait on them.
+ for (const socket of sockets) socket.destroy();
+ await new Promise<void>((resolve) => server.close(() => resolve()));
+});
+
+const openFrame = (
+ connId: string,
+ path: string,
+ overrides: Partial<TunnelOpenMessage> = {},
+): TunnelOpenMessage => ({
+ connId,
+ head: { headers: [], method: 'GET', path },
+ target: { host: '127.0.0.1', port },
+ type: 'tunnel_open',
+ ...overrides,
+});
+
+const nextTick = () => new Promise<void>((resolve) => setTimeout(resolve, 0));
+
+const waitFor = async (predicate: () => boolean, timeoutMs = 5000) => {
+ const deadline = Date.now() + timeoutMs;
+ while (!predicate()) {
+ if (Date.now() > deadline) throw new Error('timed out waiting for condition');
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ }
+};
+
+/** Collects everything the device sends up, and replays the gateway's acks. */
+const createHost = (options: { autoAck?: boolean } = {}) => {
+ const frames: TunnelClientFrame[] = [];
+ const host = new DeviceTunnelHost({
+ send: (frame) => {
+ frames.push(frame);
+ // The real gateway acks response bytes as the browser pulls them.
+ if (options.autoAck !== false && frame.type === 'tunnel_data' && frame.data) {
+ const bytes = Buffer.from(frame.data, 'base64').byteLength;
+ queueMicrotask(() => host.handleFrame({ bytes, connId: frame.connId, type: 'tunnel_ack' }));
+ }
+ },
+ });
+ const bodyOf = (connId: string) =>
+ Buffer.concat(
+ frames
+ .filter((f) => f.type === 'tunnel_data' && f.connId === connId && f.data)
+ .map((f) => Buffer.from((f as { data: string }).data, 'base64')),
+ );
+ const finished = (connId: string) =>
+ frames.some((f) => f.type === 'tunnel_data' && f.connId === connId && f.fin);
+ return { bodyOf, finished, frames, host };
+};
+
+describe('DeviceTunnelHost', () => {
+ it('serves a GET and streams the response back', async () => {
+ const { bodyOf, finished, frames, host } = createHost();
+ host.handleFrame(openFrame('c1', '/'));
+ // The gateway always closes the upload side, even with no body.
+ host.handleFrame({ connId: 'c1', data: '', fin: true, seq: 1, type: 'tunnel_data' });
+
+ await waitFor(() => finished('c1'));
+
+ const ack = frames.find((f) => f.type === 'tunnel_open_ack');
+ expect(ack).toMatchObject({ ok: true });
+ expect((ack as { head: { status: number } }).head.status).toBe(200);
+ expect(bodyOf('c1').toString()).toBe('<h1>origin</h1>');
+ expect(host.activeCount).toBe(0);
+ });
+
+ it('passes an upstream 404 through instead of erroring', async () => {
+ const { bodyOf, finished, frames, host } = createHost();
+ host.handleFrame(openFrame('c1', '/missing'));
+ host.handleFrame({ connId: 'c1', data: '', fin: true, seq: 1, type: 'tunnel_data' });
+
+ await waitFor(() => finished('c1'));
+
+ expect(frames.find((f) => f.type === 'tunnel_open_ack')).toMatchObject({
+ head: { status: 404 },
+ ok: true,
+ });
+ expect(bodyOf('c1').toString()).toBe('not here');
+ });
+
+ it('streams a POST body up and acks the bytes it consumed', async () => {
+ const { bodyOf, finished, frames, host } = createHost();
+ host.handleFrame(
+ openFrame('c1', '/echo', { head: { headers: [], method: 'POST', path: '/echo' } }),
+ );
+ const payload = Buffer.from('request-body-over-the-tunnel');
+ host.handleFrame({
+ connId: 'c1',
+ data: payload.toString('base64'),
+ seq: 1,
+ type: 'tunnel_data',
+ });
+ host.handleFrame({ connId: 'c1', data: '', fin: true, seq: 2, type: 'tunnel_data' });
+
+ await waitFor(() => finished('c1'));
+
+ expect(bodyOf('c1').toString()).toBe('request-body-over-the-tunnel');
+ // Flow control: the gateway's send window must be refilled.
+ expect(frames.filter((f) => f.type === 'tunnel_ack')).toEqual([
+ { bytes: payload.byteLength, connId: 'c1', type: 'tunnel_ack' },
+ ]);
+ });
+
+ it('keeps each set-cookie header separate', async () => {
+ const { finished, frames, host } = createHost();
+ host.handleFrame(openFrame('c1', '/cookies'));
+ host.handleFrame({ connId: 'c1', data: '', fin: true, seq: 1, type: 'tunnel_data' });
+
+ await waitFor(() => finished('c1'));
+
+ const ack = frames.find((f) => f.type === 'tunnel_open_ack') as {
+ head: { headers: [string, string][] };
+ };
+ const cookies = ack.head.headers.filter(([name]) => name.toLowerCase() === 'set-cookie');
+ expect(cookies.map(([, value]) => value)).toEqual(['a=1; Path=/', 'b=2; Path=/']);
+ });
+
+ it('drops content-encoding because the body is forwarded decoded', async () => {
+ const { bodyOf, finished, frames, host } = createHost();
+ host.handleFrame(openFrame('c1', '/gzip'));
+ host.handleFrame({ connId: 'c1', data: '', fin: true, seq: 1, type: 'tunnel_data' });
+
+ await waitFor(() => finished('c1'));
+
+ const ack = frames.find((f) => f.type === 'tunnel_open_ack') as {
+ head: { headers: [string, string][] };
+ };
+ expect(ack.head.headers.map(([name]) => name.toLowerCase())).not.toContain('content-encoding');
+ expect(bodyOf('c1').toString()).toBe('compressed-payload');
+ });
+
+ it('hands a redirect to the browser instead of following it', async () => {
+ const { finished, frames, host } = createHost();
+ host.handleFrame(openFrame('c1', '/redirect'));
+ host.handleFrame({ connId: 'c1', data: '', fin: true, seq: 1, type: 'tunnel_data' });
+
+ await waitFor(() => finished('c1'));
+
+ const ack = frames.find((f) => f.type === 'tunnel_open_ack') as {
+ head: { headers: [string, string][]; status: number };
+ };
+ expect(ack.head.status).toBe(302);
+ expect(ack.head.headers).toContainEqual(['location', '/elsewhere']);
+ });
+
+ it('pauses the response once the flow window is full and resumes on ack', async () => {
+ const { frames, host } = createHost({ autoAck: false });
+ host.handleFrame(openFrame('c1', '/big'));
+ host.handleFrame({ connId: 'c1', data: '', fin: true, seq: 1, type: 'tunnel_data' });
+
+ // Frame sizes follow whatever the upstream reader yields, so the window is
+ // measured in bytes, not frames.
+ const bytesSent = () =>
+ frames
+ .filter((f) => f.type === 'tunnel_data' && f.data)
+ .reduce(
+ (total, f) => total + Buffer.from((f as { data: string }).data, 'base64').byteLength,
+ 0,
+ );
+
+ await waitFor(() => bytesSent() >= TUNNEL_FLOW_WINDOW);
+ await nextTick();
+ await nextTick();
+ const stalledAt = bytesSent();
+ // At most one frame may overshoot: the window is checked before each send.
+ expect(stalledAt).toBeLessThan(TUNNEL_FLOW_WINDOW + TUNNEL_CHUNK_SIZE);
+
+ host.handleFrame({ bytes: TUNNEL_FLOW_WINDOW, connId: 'c1', type: 'tunnel_ack' });
+ await waitFor(() => bytesSent() > stalledAt);
+ expect(bytesSent()).toBeLessThan(stalledAt + TUNNEL_FLOW_WINDOW + TUNNEL_CHUNK_SIZE);
+ });
+
+ it('acks request-body bytes only once the origin consumes them', async () => {
+ const frames: TunnelClientFrame[] = [];
+ let uploaded: ReadableStream<Uint8Array> | undefined;
+ const host = new DeviceTunnelHost({
+ // Stands in for an origin that accepts the connection but reads the body
+ // lazily; the response head never arrives.
+ fetchImpl: ((_url, init) => {
+ uploaded = init.body as ReadableStream<Uint8Array>;
+ return new Promise<Response>(() => {});
+ }) as TunnelFetch,
+ send: (frame) => frames.push(frame),
+ });
+ host.handleFrame(
+ openFrame('c1', '/echo', { head: { headers: [], method: 'POST', path: '/echo' } }),
+ );
+ const chunk = Buffer.alloc(1024, 0x64);
+ host.handleFrame({ connId: 'c1', data: chunk.toString('base64'), seq: 1, type: 'tunnel_data' });
+ await nextTick();
+ await nextTick();
+
+ // Buffered but not consumed: acking here would refill the gateway's window
+ // and let an upload pile up in this process without bound.
+ expect(frames.filter((f) => f.type === 'tunnel_ack')).toHaveLength(0);
+
+ const { value } = await uploaded!.getReader().read();
+ expect(value?.byteLength).toBe(1024);
+ await nextTick();
+ expect(frames.filter((f) => f.type === 'tunnel_ack')).toEqual([
+ { bytes: 1024, connId: 'c1', type: 'tunnel_ack' },
+ ]);
+ host.closeAll('TEST_CLEANUP');
+ });
+
+ it('acks immediately for a bodyless method, whose data frames are dropped', async () => {
+ const { frames, host } = createHost();
+ host.handleFrame(openFrame('c1', '/'));
+ const stray = Buffer.from('body-on-a-get');
+ host.handleFrame({ connId: 'c1', data: stray.toString('base64'), seq: 1, type: 'tunnel_data' });
+
+ expect(frames).toContainEqual({ bytes: stray.byteLength, connId: 'c1', type: 'tunnel_ack' });
+ host.closeAll('TEST_CLEANUP');
+ });
+
+ it('brackets an IPv6 loopback target when building the URL', async () => {
+ const urls: string[] = [];
+ const host = new DeviceTunnelHost({
+ fetchImpl: (async (url) => {
+ urls.push(url);
+ return new Response('ok', { status: 200 });
+ }) as TunnelFetch,
+ send: () => {},
+ });
+ host.handleFrame(openFrame('c1', '/thing', { target: { host: '::1', port: 5173 } }));
+
+ await waitFor(() => urls.length === 1);
+ expect(urls[0]).toBe('http://[::1]:5173/thing');
+ });
+
+ it('rejects a non-loopback target', async () => {
+ const { frames, host } = createHost();
+ host.handleFrame(openFrame('c1', '/', { target: { host: '10.0.0.5', port } }));
+ expect(frames).toEqual([
+ { connId: 'c1', error: 'TUNNEL_TARGET_NOT_LOOPBACK', ok: false, type: 'tunnel_open_ack' },
+ ]);
+ expect(host.activeCount).toBe(0);
+ });
+
+ it('reports a refused connection as a failed open instead of hanging', async () => {
+ const { frames, host } = createHost();
+ // Port 1 is reserved and never listening in CI or locally.
+ host.handleFrame(openFrame('c1', '/', { target: { host: '127.0.0.1', port: 1 } }));
+ host.handleFrame({ connId: 'c1', data: '', fin: true, seq: 1, type: 'tunnel_data' });
+
+ await waitFor(() => frames.some((f) => f.type === 'tunnel_open_ack'));
+ expect(frames.find((f) => f.type === 'tunnel_open_ack')).toMatchObject({ ok: false });
+ expect(host.activeCount).toBe(0);
+ });
+
+ it('rejects an open past the concurrency limit', async () => {
+ const frames: TunnelClientFrame[] = [];
+ const host = new DeviceTunnelHost({ maxConcurrent: 1, send: (f) => frames.push(f) });
+ host.handleFrame(openFrame('c1', '/hang'));
+ host.handleFrame(openFrame('c2', '/'));
+
+ expect(frames).toContainEqual({
+ connId: 'c2',
+ error: 'TUNNEL_LIMIT_REACHED',
+ ok: false,
+ type: 'tunnel_open_ack',
+ });
+ host.closeAll('TEST_CLEANUP');
+ });
+
+ it('aborts the upstream request when the gateway closes the tunnel', async () => {
+ const { host } = createHost();
+ host.handleFrame(openFrame('c1', '/hang'));
+ host.handleFrame({ connId: 'c1', data: '', fin: true, seq: 1, type: 'tunnel_data' });
+ // Abort only once the origin is genuinely holding the request open.
+ await waitFor(() => received.includes('/hang'));
+
+ host.handleFrame({ connId: 'c1', reason: 'BROWSER_GONE', type: 'tunnel_close' });
+
+ expect(host.activeCount).toBe(0);
+ await waitFor(() => aborted.includes('/hang'));
+ });
+
+ it('closes every tunnel when the device socket drops', async () => {
+ const { host } = createHost();
+ host.handleFrame(openFrame('c1', '/hang'));
+ host.handleFrame(openFrame('c2', '/hang'));
+ await waitFor(() => host.activeCount === 2);
+
+ host.closeAll('DEVICE_DISCONNECTED');
+
+ expect(host.activeCount).toBe(0);
+ });
+});
diff --git a/packages/device-gateway-client/src/tunnel.ts b/packages/device-gateway-client/src/tunnel.ts
new file mode 100644
index 00000000000..94dafc4cbc5
--- /dev/null
+++ b/packages/device-gateway-client/src/tunnel.ts
@@ -0,0 +1,369 @@
+import { Buffer } from 'node:buffer';
+
+import type { GatewayClientLogger } from './client';
+import type {
+ TunnelClientFrame,
+ TunnelOpenMessage,
+ TunnelRequestHead,
+ TunnelServerFrame,
+} from './types';
+import { TUNNEL_CHUNK_SIZE, TUNNEL_FLOW_WINDOW } from './types';
+
+/**
+ * Device half of the HTTP tunnel: turns the gateway's tunnel frames into a real
+ * HTTP request against a loopback port on this machine and streams the response
+ * back frame by frame.
+ *
+ * The gateway owns the browser-facing HTTP semantics (auth, ingress URLs,
+ * header sanitising) and pins the target host, so this side only has to be a
+ * faithful, well-paced HTTP client.
+ */
+
+/** Only loopback targets are servable β€” defence in depth behind the gateway's pin. */
+const LOOPBACK_HOSTS = new Set(['127.0.0.1', '::1', 'localhost']);
+
+/**
+ * Response headers that describe the *upstream* transfer and no longer hold
+ * once the body has been decoded and re-framed. `content-encoding` matters
+ * most: `fetch` transparently gunzips, so forwarding it would hand the browser
+ * decoded bytes labelled as compressed.
+ */
+const RESPONSE_HEADER_DENYLIST = new Set([
+ 'connection',
+ 'content-encoding',
+ 'content-length',
+ 'keep-alive',
+ 'trailer',
+ 'transfer-encoding',
+ 'upgrade',
+]);
+
+const noopLogger: GatewayClientLogger = {
+ debug: () => {},
+ error: () => {},
+ info: () => {},
+ warn: () => {},
+};
+
+/**
+ * The one shape of `fetch` this host uses. Narrower than `typeof fetch` on
+ * purpose: the global is overloaded, and forwarding those overloads through a
+ * wrapper or `bind` doesn't type-check under every tsconfig in the monorepo.
+ */
+export type TunnelFetch = (url: string, init: RequestInit) => Promise<Response>;
+
+export interface DeviceTunnelHostOptions {
+ /** Injectable for tests; defaults to global `fetch`. */
+ fetchImpl?: TunnelFetch;
+ logger?: GatewayClientLogger;
+ /** Tunnels served at once. Extra opens are rejected rather than queued. */
+ maxConcurrent?: number;
+ /** Sends a frame up the device WebSocket. */
+ send: (frame: TunnelClientFrame) => void;
+}
+
+interface TunnelConnection {
+ abort: AbortController;
+ /** Upload finished: the gateway sent its fin frame. */
+ bodyFin: boolean;
+ /** True for methods that carry no body, whose data frames are dropped. */
+ bodyless: boolean;
+ /** Request-body chunks received but not yet handed to `fetch`. */
+ bodyQueue: Uint8Array[];
+ /** Parked `pull` waiting for the next request-body chunk. */
+ bodyWaiters: (() => void)[];
+ closed: boolean;
+ connId: string;
+ /** Set once `tunnel_open_ack` has gone out, so failures switch to `tunnel_close`. */
+ headSent: boolean;
+ seq: number;
+ /** Response bytes sent but not yet acked by the gateway. */
+ unacked: number;
+ /** Parked senders waiting for the flow window to refill. */
+ waiters: (() => void)[];
+}
+
+const describeError = (error: unknown): string => {
+ if (error && typeof error === 'object') {
+ const { cause, code, message } = error as { cause?: unknown; code?: string; message?: string };
+ const causeCode =
+ cause && typeof cause === 'object' ? (cause as { code?: string }).code : undefined;
+ return code ?? causeCode ?? message ?? 'TUNNEL_ERROR';
+ }
+ return String(error ?? 'TUNNEL_ERROR');
+};
+
+export class DeviceTunnelHost {
+ private connections = new Map<string, TunnelConnection>();
+ private fetchImpl: TunnelFetch;
+ private logger: GatewayClientLogger;
+ private maxConcurrent: number;
+ private send: (frame: TunnelClientFrame) => void;
+
+ constructor(options: DeviceTunnelHostOptions) {
+ this.fetchImpl = options.fetchImpl ?? ((url, init) => globalThis.fetch(url, init));
+ this.logger = options.logger ?? noopLogger;
+ this.maxConcurrent = options.maxConcurrent ?? 32;
+ this.send = options.send;
+ }
+
+ get activeCount(): number {
+ return this.connections.size;
+ }
+
+ handleFrame(frame: TunnelServerFrame): void {
+ switch (frame.type) {
+ case 'tunnel_open': {
+ this.handleOpen(frame);
+ return;
+ }
+ case 'tunnel_data': {
+ const conn = this.connections.get(frame.connId);
+ if (!conn || conn.closed) return;
+ if (frame.data) {
+ const bytes = Buffer.from(frame.data, 'base64');
+ if (conn.bodyless) {
+ // Nothing will ever consume these, so ack now: an unrefilled window
+ // would stall the gateway's pump for the rest of the request.
+ this.send({ bytes: bytes.byteLength, connId: frame.connId, type: 'tunnel_ack' });
+ } else {
+ // Queued, not acked. The ack is the gateway's permission to send
+ // more, so it has to mean "consumed by the origin", not "buffered
+ // here" β€” otherwise a slow local handler lets an upload accumulate
+ // in this process without bound.
+ conn.bodyQueue.push(new Uint8Array(bytes));
+ }
+ }
+ if (frame.fin) conn.bodyFin = true;
+ this.wakeBody(conn);
+ return;
+ }
+ case 'tunnel_ack': {
+ this.ack(frame.connId, frame.bytes);
+ return;
+ }
+ case 'tunnel_close': {
+ this.closeConnection(frame.connId, frame.reason ?? 'PEER_CLOSED', false);
+ return;
+ }
+ default: {
+ return;
+ }
+ }
+ }
+
+ /** Abort every in-flight tunnel, e.g. when the device socket drops. */
+ closeAll(reason: string): void {
+ for (const connId of this.connections.keys()) {
+ this.closeConnection(connId, reason, false);
+ }
+ }
+
+ // ─── internals ───
+
+ private handleOpen(frame: TunnelOpenMessage): void {
+ const { connId, head, target } = frame;
+ if (this.connections.has(connId)) return;
+
+ if (!LOOPBACK_HOSTS.has(target.host)) {
+ this.send({
+ connId,
+ error: 'TUNNEL_TARGET_NOT_LOOPBACK',
+ ok: false,
+ type: 'tunnel_open_ack',
+ });
+ return;
+ }
+ if (this.connections.size >= this.maxConcurrent) {
+ this.send({ connId, error: 'TUNNEL_LIMIT_REACHED', ok: false, type: 'tunnel_open_ack' });
+ return;
+ }
+
+ const method = head.method.toUpperCase();
+ const conn: TunnelConnection = {
+ abort: new AbortController(),
+ bodyFin: false,
+ bodyless: method === 'GET' || method === 'HEAD',
+ bodyQueue: [],
+ bodyWaiters: [],
+ closed: false,
+ connId,
+ headSent: false,
+ seq: 0,
+ unacked: 0,
+ waiters: [],
+ };
+ this.connections.set(connId, conn);
+
+ // Started eagerly: the gateway streams the request body *after* the open
+ // frame, so the body pump must already be attached when it arrives.
+ void this.serve(conn, head, target).catch((error) => {
+ this.logger.warn(`[tunnel] ${connId} failed: ${describeError(error)}`);
+ });
+ }
+
+ private async serve(
+ conn: TunnelConnection,
+ head: TunnelRequestHead,
+ target: { host: string; port: number },
+ ): Promise<void> {
+ const body = conn.bodyless
+ ? undefined
+ : new ReadableStream<Uint8Array>(
+ {
+ cancel: () => {
+ conn.bodyQueue.length = 0;
+ this.wakeBody(conn);
+ },
+ // `pull` only runs when the HTTP client actually wants more bytes,
+ // which is what makes the ack below mean "consumed".
+ pull: async (controller) => {
+ while (conn.bodyQueue.length === 0 && !conn.bodyFin && !conn.closed) {
+ await new Promise<void>((resolve) => conn.bodyWaiters.push(resolve));
+ }
+ if (conn.closed) throw new Error('TUNNEL_CLOSED');
+ const chunk = conn.bodyQueue.shift();
+ if (!chunk) {
+ controller.close();
+ return;
+ }
+ controller.enqueue(chunk);
+ this.send({ bytes: chunk.byteLength, connId: conn.connId, type: 'tunnel_ack' });
+ },
+ },
+ // Nothing is buffered ahead of a read, so backpressure reaches the
+ // gateway instead of stopping at this process.
+ { highWaterMark: 0 },
+ );
+
+ // An IPv6 literal needs brackets or the URL is invalid.
+ const authority = target.host.includes(':') ? `[${target.host}]` : target.host;
+
+ try {
+ const response = await this.fetchImpl(`http://${authority}:${target.port}${head.path}`, {
+ body,
+ // Required by undici whenever the body is a stream.
+ ...(body ? { duplex: 'half' } : {}),
+ headers: head.headers,
+ method: head.method.toUpperCase(),
+ // A dev server's redirect belongs to the browser, not to this hop.
+ redirect: 'manual',
+ signal: conn.abort.signal,
+ } as RequestInit);
+
+ if (conn.closed) return;
+
+ this.send({
+ connId: conn.connId,
+ head: { headers: collectResponseHeaders(response.headers), status: response.status },
+ ok: true,
+ type: 'tunnel_open_ack',
+ });
+ conn.headSent = true;
+
+ if (response.body) {
+ const reader = response.body.getReader();
+ try {
+ for (;;) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ if (conn.closed) return;
+ await this.sendBodyChunk(conn, value);
+ }
+ } finally {
+ reader.releaseLock();
+ }
+ }
+
+ if (conn.closed) return;
+ conn.seq += 1;
+ this.send({ connId: conn.connId, data: '', fin: true, seq: conn.seq, type: 'tunnel_data' });
+ this.dropConnection(conn.connId);
+ } catch (error) {
+ if (conn.closed) return;
+ const reason = describeError(error);
+ if (conn.headSent) {
+ this.send({ connId: conn.connId, reason, type: 'tunnel_close' });
+ } else {
+ this.send({ connId: conn.connId, error: reason, ok: false, type: 'tunnel_open_ack' });
+ }
+ this.dropConnection(conn.connId);
+ }
+ }
+
+ /** Split into protocol-sized frames and pace them against the flow window. */
+ private async sendBodyChunk(conn: TunnelConnection, chunk: Uint8Array): Promise<void> {
+ for (let offset = 0; offset < chunk.byteLength; offset += TUNNEL_CHUNK_SIZE) {
+ const slice = chunk.subarray(offset, offset + TUNNEL_CHUNK_SIZE);
+ while (conn.unacked >= TUNNEL_FLOW_WINDOW && !conn.closed) {
+ await new Promise<void>((resolve) => conn.waiters.push(resolve));
+ }
+ if (conn.closed) return;
+ conn.seq += 1;
+ conn.unacked += slice.byteLength;
+ this.send({
+ connId: conn.connId,
+ data: Buffer.from(slice.buffer, slice.byteOffset, slice.byteLength).toString('base64'),
+ seq: conn.seq,
+ type: 'tunnel_data',
+ });
+ }
+ }
+
+ /** Gateway acked delivered bytes β€” refill the window and wake parked senders. */
+ private ack(connId: string, bytes: number): void {
+ const conn = this.connections.get(connId);
+ if (!conn) return;
+ conn.unacked = Math.max(0, conn.unacked - bytes);
+ this.wake(conn);
+ }
+
+ private closeConnection(connId: string, reason: string, notify: boolean): void {
+ const conn = this.connections.get(connId);
+ if (!conn) return;
+ conn.closed = true;
+ conn.abort.abort();
+ conn.bodyQueue.length = 0;
+ this.wakeBody(conn);
+ this.wake(conn);
+ this.connections.delete(connId);
+ if (notify) this.send({ connId, reason, type: 'tunnel_close' });
+ }
+
+ private dropConnection(connId: string): void {
+ const conn = this.connections.get(connId);
+ if (!conn) return;
+ conn.closed = true;
+ this.wake(conn);
+ this.wakeBody(conn);
+ this.connections.delete(connId);
+ }
+
+ private wake(conn: TunnelConnection): void {
+ const waiters = conn.waiters;
+ conn.waiters = [];
+ for (const waiter of waiters) waiter();
+ }
+
+ private wakeBody(conn: TunnelConnection): void {
+ const waiters = conn.bodyWaiters;
+ conn.bodyWaiters = [];
+ for (const waiter of waiters) waiter();
+ }
+}
+
+/**
+ * Flatten response headers, keeping every `set-cookie` separate (the Headers
+ * API folds them into one comma-joined value, which breaks cookie parsing).
+ */
+const collectResponseHeaders = (headers: Headers): [string, string][] => {
+ const out: [string, string][] = [];
+ headers.forEach((value, name) => {
+ const lower = name.toLowerCase();
+ if (RESPONSE_HEADER_DENYLIST.has(lower) || lower === 'set-cookie') return;
+ out.push([name, value]);
+ });
+ const setCookies = headers.getSetCookie?.() ?? [];
+ for (const cookie of setCookies) out.push(['set-cookie', cookie]);
+ return out;
+};
diff --git a/packages/device-gateway-client/src/types.ts b/packages/device-gateway-client/src/types.ts
index 55cab48be48..3ed5879610a 100644
--- a/packages/device-gateway-client/src/types.ts
+++ b/packages/device-gateway-client/src/types.ts
@@ -283,6 +283,89 @@ export interface AgentRunRequestMessage {
workspaceId?: string;
}
+// ─── HTTP Tunnel Frames ───
+//
+// A tunnel relays one browser HTTP request to a TCP port on this device as a
+// sequence of JSON frames over the device WebSocket, multiplexed by `connId`.
+// The browser-facing HTTP semantics live on the gateway; the device only sees
+// a target (`127.0.0.1:<port>`) plus a request head and a byte stream.
+//
+// Flow control is credit-based per direction: each side sends at most
+// `TUNNEL_FLOW_WINDOW` unacked bytes and the receiver refills that window with
+// `tunnel_ack`. Exceeding the gateway's hard cap tears the tunnel down, so the
+// device must pace its response body rather than firing it all at once.
+//
+// Frame shapes mirror `device-gateway/src/types.ts`; keep both in step.
+
+/** Bytes per `tunnel_data` frame. */
+export const TUNNEL_CHUNK_SIZE = 64 * 1024;
+/** Unacked bytes one side may have in flight before it must wait. */
+export const TUNNEL_FLOW_WINDOW = 512 * 1024;
+
+export interface TunnelRequestHead {
+ headers: [string, string][];
+ method: string;
+ /** Path + query of the target request, e.g. `/api/items?a=1`. */
+ path: string;
+}
+
+export interface TunnelResponseHead {
+ headers: [string, string][];
+ status: number;
+}
+
+/** Server β†’ Client: open a tunnel to `127.0.0.1:<port>` for one HTTP request. */
+export interface TunnelOpenMessage {
+ connId: string;
+ head: TunnelRequestHead;
+ target: {
+ host: string;
+ port: number;
+ };
+ type: 'tunnel_open';
+}
+
+/** Client β†’ Server: result of a tunnel_open. On success `head` is the response head. */
+export interface TunnelOpenAckMessage {
+ connId: string;
+ error?: string;
+ head?: TunnelResponseHead;
+ ok: boolean;
+ type: 'tunnel_open_ack';
+}
+
+/** Both directions: a body chunk. `fin` marks the last chunk of that direction. */
+export interface TunnelDataMessage {
+ connId: string;
+ /** base64-encoded bytes. */
+ data: string;
+ fin?: boolean;
+ seq: number;
+ type: 'tunnel_data';
+}
+
+/** Both directions: acknowledge `bytes` consumed, refilling the sender's window. */
+export interface TunnelAckMessage {
+ bytes: number;
+ connId: string;
+ type: 'tunnel_ack';
+}
+
+/** Both directions: tear the tunnel down (abort, error, or peer gone). */
+export interface TunnelCloseMessage {
+ connId: string;
+ reason?: string;
+ type: 'tunnel_close';
+}
+
+/** Tunnel frames the gateway sends down to this device. */
+export type TunnelServerFrame =
+ TunnelAckMessage | TunnelCloseMessage | TunnelDataMessage | TunnelOpenMessage;
+
+/** Tunnel frames this device sends up to the gateway. */
+export type TunnelClientFrame =
+ TunnelAckMessage | TunnelCloseMessage | TunnelDataMessage | TunnelOpenAckMessage;
+
/** Client β†’ Server: acknowledgement for an agent_run_request. */
export interface AgentRunAckMessage {
operationId: string;
@@ -298,7 +381,8 @@ export type ClientMessage =
| MessageApiResponseMessage
| RpcResponseMessage
| SystemInfoResponseMessage
- | ToolCallResponseMessage;
+ | ToolCallResponseMessage
+ | TunnelClientFrame;
export type ServerMessage =
| AgentRunRequestMessage
| AuthExpiredMessage
@@ -308,7 +392,8 @@ export type ServerMessage =
| MessageApiRequestMessage
| RpcRequestMessage
| SystemInfoRequestMessage
- | ToolCallRequestMessage;
+ | ToolCallRequestMessage
+ | TunnelServerFrame;
// ─── Client Types ───