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): relay WebSockets through tunnels and mint links with a dedicated param (#19892)

Arvin Xue5f43fde5144
diff --git a/apps/server/src/routers/lambda/device.ts b/apps/server/src/routers/lambda/device.ts
index 06f8c634781..24326c7affa 100644
--- a/apps/server/src/routers/lambda/device.ts
+++ b/apps/server/src/routers/lambda/device.ts
@@ -1,3 +1,4 @@
+import { TUNNEL_TOKEN_PARAM } from '@lobechat/device-gateway-client';
import {
type HeterogeneousAgentScanMap,
REMOTE_HETEROGENEOUS_AGENT_CONFIGS,
@@ -96,7 +97,9 @@ const buildTunnelOpenUrl = async (
userId: ctx.userId,
workspaceId: ctx.workspaceId,
});
- return `${url}?token=${encodeURIComponent(token)}`;
+ // A dedicated param, not `?token=`: apps behind a tunnel own that name
+ // (Vite's HMR socket authenticates with it).
+ return `${url}?${TUNNEL_TOKEN_PARAM}=${encodeURIComponent(token)}`;
};
const canEditWorkspaceDevice = (
diff --git a/packages/device-gateway-client/src/client.ts b/packages/device-gateway-client/src/client.ts
index ff586afa01a..49a920583a4 100644
--- a/packages/device-gateway-client/src/client.ts
+++ b/packages/device-gateway-client/src/client.ts
@@ -141,6 +141,7 @@ export class GatewayClient extends EventEmitter {
this.connectTimeoutMs = options.connectTimeoutMs ?? CONNECT_TIMEOUT;
if (options.tunnel !== false) {
this.tunnelHost = new DeviceTunnelHost({
+ backlog: () => this.ws?.bufferedAmount ?? 0,
logger: this.logger,
send: (frame) => this.sendMessage(frame),
});
@@ -408,14 +409,17 @@ export class GatewayClient extends EventEmitter {
case 'tunnel_open':
case 'tunnel_data':
case 'tunnel_ack':
- case 'tunnel_close': {
+ case 'tunnel_close':
+ case 'tunnel_ws_open':
+ case 'tunnel_ws_message':
+ case 'tunnel_ws_close': {
if (this.tunnelHost) this.tunnelHost.handleFrame(message);
- else if (message.type === 'tunnel_open')
+ else if (message.type === 'tunnel_open' || message.type === 'tunnel_ws_open')
this.sendMessage({
connId: message.connId,
error: 'TUNNEL_DISABLED',
ok: false,
- type: 'tunnel_open_ack',
+ type: message.type === 'tunnel_open' ? 'tunnel_open_ack' : 'tunnel_ws_open_ack',
});
break;
}
diff --git a/packages/device-gateway-client/src/index.ts b/packages/device-gateway-client/src/index.ts
index 65442d05ec5..4259a56d35e 100644
--- a/packages/device-gateway-client/src/index.ts
+++ b/packages/device-gateway-client/src/index.ts
@@ -21,3 +21,4 @@ export { GatewayHttpClient } from './http';
export type { DeviceTunnelHostOptions } from './tunnel';
export { DeviceTunnelHost } from './tunnel';
export * from './types';
+export type { TunnelUpstreamFactory, TunnelUpstreamSocket } from './wsTunnel';
diff --git a/packages/device-gateway-client/src/tunnel.ts b/packages/device-gateway-client/src/tunnel.ts
index 94dafc4cbc5..70fe3c1e37e 100644
--- a/packages/device-gateway-client/src/tunnel.ts
+++ b/packages/device-gateway-client/src/tunnel.ts
@@ -8,6 +8,7 @@ import type {
TunnelServerFrame,
} from './types';
import { TUNNEL_CHUNK_SIZE, TUNNEL_FLOW_WINDOW } from './types';
+import { DeviceWsTunnelHost, type TunnelUpstreamFactory } from './wsTunnel';
/**
* Device half of the HTTP tunnel: turns the gateway's tunnel frames into a real
@@ -53,6 +54,13 @@ const noopLogger: GatewayClientLogger = {
export type TunnelFetch = (url: string, init: RequestInit) => Promise<Response>;
export interface DeviceTunnelHostOptions {
+ /**
+ * Bytes queued on the gateway socket but not yet written β€” lets WebSocket
+ * tunnels pause a fast local producer instead of buffering without bound.
+ */
+ backlog?: () => number;
+ /** Injectable for tests; defaults to a `ws` client socket. */
+ createUpstreamSocket?: TunnelUpstreamFactory;
/** Injectable for tests; defaults to global `fetch`. */
fetchImpl?: TunnelFetch;
logger?: GatewayClientLogger;
@@ -99,16 +107,24 @@ export class DeviceTunnelHost {
private logger: GatewayClientLogger;
private maxConcurrent: number;
private send: (frame: TunnelClientFrame) => void;
+ private sockets: DeviceWsTunnelHost;
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;
+ this.sockets = new DeviceWsTunnelHost({
+ backlog: options.backlog,
+ createSocket: options.createUpstreamSocket,
+ logger: this.logger,
+ send: options.send,
+ });
}
+ /** HTTP requests and WebSockets in flight; both count against the limit. */
get activeCount(): number {
- return this.connections.size;
+ return this.connections.size + this.sockets.activeCount;
}
handleFrame(frame: TunnelServerFrame): void {
@@ -146,6 +162,28 @@ export class DeviceTunnelHost {
this.closeConnection(frame.connId, frame.reason ?? 'PEER_CLOSED', false);
return;
}
+ case 'tunnel_ws_open': {
+ const refusal = this.refuse(frame.target.host);
+ if (refusal) {
+ this.send({
+ connId: frame.connId,
+ error: refusal,
+ ok: false,
+ type: 'tunnel_ws_open_ack',
+ });
+ return;
+ }
+ this.sockets.open(frame);
+ return;
+ }
+ case 'tunnel_ws_message': {
+ this.sockets.message(frame);
+ return;
+ }
+ case 'tunnel_ws_close': {
+ this.sockets.close(frame);
+ return;
+ }
default: {
return;
}
@@ -157,6 +195,14 @@ export class DeviceTunnelHost {
for (const connId of this.connections.keys()) {
this.closeConnection(connId, reason, false);
}
+ this.sockets.closeAll();
+ }
+
+ /** Why an open must be refused, or undefined when it may proceed. */
+ private refuse(host: string): string | undefined {
+ if (!LOOPBACK_HOSTS.has(host)) return 'TUNNEL_TARGET_NOT_LOOPBACK';
+ if (this.activeCount >= this.maxConcurrent) return 'TUNNEL_LIMIT_REACHED';
+ return undefined;
}
// ─── internals ───
@@ -165,17 +211,9 @@ export class DeviceTunnelHost {
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' });
+ const refusal = this.refuse(target.host);
+ if (refusal) {
+ this.send({ connId, error: refusal, ok: false, type: 'tunnel_open_ack' });
return;
}
diff --git a/packages/device-gateway-client/src/types.ts b/packages/device-gateway-client/src/types.ts
index aa026c71421..52bbd85036b 100644
--- a/packages/device-gateway-client/src/types.ts
+++ b/packages/device-gateway-client/src/types.ts
@@ -385,13 +385,73 @@ export interface TunnelCloseMessage {
type: 'tunnel_close';
}
+/**
+ * Query parameter that carries the entry-ticket JWT on a tunnel link. Not
+ * `token`: apps behind a tunnel use `?token=` themselves (Vite's HMR socket).
+ * Mirrors `device-gateway/src/types.ts`.
+ */
+export const TUNNEL_TOKEN_PARAM = '__lobe_tunnel_token';
+
+/** Largest WebSocket message relayed either way; bigger closes with 1009. */
+export const TUNNEL_WS_MAX_MESSAGE = 1024 * 1024;
+
+/** Server β†’ Client: open a WebSocket to `127.0.0.1:<port>` (e.g. dev-server HMR). */
+export interface TunnelWsOpenMessage {
+ connId: string;
+ head: {
+ /** Offered subprotocols, in the browser's order. */
+ protocols: string[];
+ /** Path + query, e.g. `/?token=abc`. */
+ path: string;
+ };
+ target: { host: string; port: number };
+ type: 'tunnel_ws_open';
+}
+
+/** Client β†’ Server: the upstream socket opened (with its subprotocol) or failed. */
+export interface TunnelWsOpenAckMessage {
+ connId: string;
+ error?: string;
+ ok: boolean;
+ protocol?: string;
+ type: 'tunnel_ws_open_ack';
+}
+
+/** Both directions: one WebSocket message. `data` is base64 when `binary`. */
+export interface TunnelWsDataMessage {
+ binary?: boolean;
+ connId: string;
+ data: string;
+ type: 'tunnel_ws_message';
+}
+
+/** Both directions: one side closed. */
+export interface TunnelWsCloseMessage {
+ code?: number;
+ connId: string;
+ reason?: string;
+ type: 'tunnel_ws_close';
+}
+
/** Tunnel frames the gateway sends down to this device. */
export type TunnelServerFrame =
- TunnelAckMessage | TunnelCloseMessage | TunnelDataMessage | TunnelOpenMessage;
+ | TunnelAckMessage
+ | TunnelCloseMessage
+ | TunnelDataMessage
+ | TunnelOpenMessage
+ | TunnelWsCloseMessage
+ | TunnelWsDataMessage
+ | TunnelWsOpenMessage;
/** Tunnel frames this device sends up to the gateway. */
export type TunnelClientFrame =
- TunnelAckMessage | TunnelCloseMessage | TunnelDataMessage | TunnelOpenAckMessage;
+ | TunnelAckMessage
+ | TunnelCloseMessage
+ | TunnelDataMessage
+ | TunnelOpenAckMessage
+ | TunnelWsCloseMessage
+ | TunnelWsDataMessage
+ | TunnelWsOpenAckMessage;
/** Client β†’ Server: acknowledgement for an agent_run_request. */
export interface AgentRunAckMessage {
diff --git a/packages/device-gateway-client/src/wsTunnel.test.ts b/packages/device-gateway-client/src/wsTunnel.test.ts
new file mode 100644
index 00000000000..6f98bdb26dd
--- /dev/null
+++ b/packages/device-gateway-client/src/wsTunnel.test.ts
@@ -0,0 +1,278 @@
+import { Buffer } from 'node:buffer';
+import type { AddressInfo } from 'node:net';
+
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
+import { type WebSocket as ServerSocket, WebSocketServer } from 'ws';
+
+import { DeviceTunnelHost } from './tunnel';
+import type { TunnelClientFrame } from './types';
+import { WS_RELAY_HARD_LIMIT, WS_RELAY_HIGH_WATER, WS_RELAY_LOW_WATER } from './wsTunnel';
+
+// A real upstream WebSocket server, standing in for a dev server's HMR socket.
+let server: WebSocketServer;
+let port: number;
+const connections: { protocol: string; socket: ServerSocket; url: string }[] = [];
+
+beforeAll(async () => {
+ server = new WebSocketServer({
+ handleProtocols: (protocols) => (protocols.has('vite-hmr') ? 'vite-hmr' : false),
+ host: '127.0.0.1',
+ port: 0,
+ });
+ server.on('connection', (socket, request) => {
+ connections.push({ protocol: socket.protocol, socket, url: request.url ?? '' });
+ socket.on('message', (data, isBinary) => {
+ // Echo, so relays in both directions are observable.
+ socket.send(isBinary ? data : `echo:${data.toString()}`, { binary: isBinary });
+ });
+ });
+ await new Promise<void>((resolve) => server.once('listening', () => resolve()));
+ port = (server.address() as AddressInfo).port;
+});
+
+afterAll(async () => {
+ for (const client of server.clients) client.terminate();
+ await new Promise<void>((resolve) => server.close(() => resolve()));
+});
+
+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));
+ }
+};
+
+const setup = () => {
+ const frames: TunnelClientFrame[] = [];
+ const host = new DeviceTunnelHost({ send: (frame) => frames.push(frame) });
+ const of = <T extends TunnelClientFrame['type']>(type: T) =>
+ frames.filter((f) => f.type === type) as Extract<TunnelClientFrame, { type: T }>[];
+ return { frames, host, of };
+};
+
+const open = (host: DeviceTunnelHost, connId: string, overrides: Record<string, unknown> = {}) =>
+ host.handleFrame({
+ connId,
+ head: { path: '/?token=vite-token', protocols: ['vite-hmr'] },
+ target: { host: '127.0.0.1', port },
+ type: 'tunnel_ws_open',
+ ...overrides,
+ } as never);
+
+describe('WebSocket tunnels', () => {
+ it('opens upstream with the path and subprotocol, and acks with the chosen protocol', async () => {
+ const { host, of } = setup();
+ open(host, 'w1');
+
+ await waitFor(() => of('tunnel_ws_open_ack').length === 1);
+ expect(of('tunnel_ws_open_ack')[0]).toEqual({
+ connId: 'w1',
+ ok: true,
+ protocol: 'vite-hmr',
+ type: 'tunnel_ws_open_ack',
+ });
+ // The app's own `?token=` reaches it untouched.
+ expect(connections.at(-1)).toMatchObject({ protocol: 'vite-hmr', url: '/?token=vite-token' });
+ host.closeAll('TEST');
+ });
+
+ it('relays text and binary messages both ways', async () => {
+ const { host, of } = setup();
+ open(host, 'w2');
+ await waitFor(() => of('tunnel_ws_open_ack').length === 1);
+
+ host.handleFrame({ connId: 'w2', data: '{"type":"ping"}', type: 'tunnel_ws_message' });
+ await waitFor(() => of('tunnel_ws_message').length === 1);
+ expect(of('tunnel_ws_message')[0]).toEqual({
+ connId: 'w2',
+ data: 'echo:{"type":"ping"}',
+ type: 'tunnel_ws_message',
+ });
+
+ host.handleFrame({
+ binary: true,
+ connId: 'w2',
+ data: Buffer.from([1, 2, 3]).toString('base64'),
+ type: 'tunnel_ws_message',
+ });
+ await waitFor(() => of('tunnel_ws_message').length === 2);
+ const echoed = of('tunnel_ws_message')[1];
+ expect(echoed.binary).toBe(true);
+ expect([...Buffer.from(echoed.data, 'base64')]).toEqual([1, 2, 3]);
+ host.closeAll('TEST');
+ });
+
+ it('closes upstream when the browser closes', async () => {
+ const { host, of } = setup();
+ open(host, 'w3');
+ await waitFor(() => of('tunnel_ws_open_ack').length === 1);
+ const upstream = connections.at(-1)!.socket;
+
+ const closed = new Promise<number>((resolve) =>
+ upstream.once('close', (code) => resolve(code)),
+ );
+ host.handleFrame({ code: 1001, connId: 'w3', reason: 'tab closed', type: 'tunnel_ws_close' });
+
+ expect(await closed).toBe(1001);
+ expect(host.activeCount).toBe(0);
+ });
+
+ it('tells the gateway when the upstream closes', async () => {
+ const { host, of } = setup();
+ open(host, 'w4');
+ await waitFor(() => of('tunnel_ws_open_ack').length === 1);
+
+ connections.at(-1)!.socket.close(4000, 'server restart');
+
+ await waitFor(() => of('tunnel_ws_close').length === 1);
+ expect(of('tunnel_ws_close')[0]).toEqual({
+ code: 4000,
+ connId: 'w4',
+ reason: 'server restart',
+ type: 'tunnel_ws_close',
+ });
+ });
+
+ it('fails the open when nothing listens, instead of hanging the handshake', async () => {
+ const { host, of } = setup();
+ open(host, 'w5', { target: { host: '127.0.0.1', port: 1 } });
+
+ await waitFor(() => of('tunnel_ws_open_ack').length === 1);
+ expect(of('tunnel_ws_open_ack')[0]).toMatchObject({ connId: 'w5', ok: false });
+ expect(host.activeCount).toBe(0);
+ });
+
+ it('refuses a non-loopback target without dialing out', () => {
+ const { host, of } = setup();
+ open(host, 'w6', { target: { host: '10.0.0.5', port } });
+
+ expect(of('tunnel_ws_open_ack')).toEqual([
+ { connId: 'w6', error: 'TUNNEL_TARGET_NOT_LOOPBACK', ok: false, type: 'tunnel_ws_open_ack' },
+ ]);
+ });
+
+ it('counts sockets against the shared concurrency limit', async () => {
+ const frames: TunnelClientFrame[] = [];
+ const host = new DeviceTunnelHost({ maxConcurrent: 1, send: (frame) => frames.push(frame) });
+ open(host, 'w7');
+ open(host, 'w8');
+
+ expect(frames).toContainEqual({
+ connId: 'w8',
+ error: 'TUNNEL_LIMIT_REACHED',
+ ok: false,
+ type: 'tunnel_ws_open_ack',
+ });
+ host.closeAll('TEST');
+ });
+
+ it('drops every upstream socket when the device disconnects', async () => {
+ const { host, of } = setup();
+ open(host, 'w9');
+ await waitFor(() => of('tunnel_ws_open_ack').length === 1);
+ const upstream = connections.at(-1)!.socket;
+ const closed = new Promise<void>((resolve) => upstream.once('close', () => resolve()));
+
+ host.closeAll('DEVICE_DISCONNECTED');
+
+ await closed;
+ expect(host.activeCount).toBe(0);
+ });
+});
+
+describe('WebSocket relay backpressure', () => {
+ /** A fake upstream whose events the test fires by hand. */
+ const fakeUpstream = () => {
+ const handlers: Record<string, (...args: any[]) => void> = {};
+ const socket = {
+ close: vi.fn(),
+ on: (event: string, listener: (...args: any[]) => void) => {
+ handlers[event] = listener;
+ },
+ pause: vi.fn(),
+ protocol: '',
+ resume: vi.fn(),
+ send: vi.fn(),
+ terminate: vi.fn(),
+ };
+ return { emit: (event: string, ...args: any[]) => handlers[event]?.(...args), socket };
+ };
+
+ const setupFake = () => {
+ const upstream = fakeUpstream();
+ const backlog = { value: 0 };
+ const frames: TunnelClientFrame[] = [];
+ const host = new DeviceTunnelHost({
+ backlog: () => backlog.value,
+ createUpstreamSocket: () => upstream.socket as never,
+ send: (frame) => frames.push(frame),
+ });
+ open(host, 'b1');
+ upstream.emit('open');
+ return { backlog, frames, host, upstream };
+ };
+
+ beforeEach(() => vi.useFakeTimers());
+ afterEach(() => vi.useRealTimers());
+
+ it('pauses a fast producer above the high mark and resumes once drained', () => {
+ const { backlog, host, upstream } = setupFake();
+
+ backlog.value = WS_RELAY_HIGH_WATER + 1;
+ upstream.emit('message', Buffer.from('hmr update'), false);
+ expect(upstream.socket.pause).toHaveBeenCalledTimes(1);
+
+ // Still above the low mark: stays paused.
+ backlog.value = WS_RELAY_LOW_WATER + 1;
+ vi.advanceTimersByTime(200);
+ expect(upstream.socket.resume).not.toHaveBeenCalled();
+
+ backlog.value = 0;
+ vi.advanceTimersByTime(100);
+ expect(upstream.socket.resume).toHaveBeenCalledTimes(1);
+ host.closeAll('TEST');
+ });
+
+ it('keeps relaying without pausing while the uplink keeps up', () => {
+ const { backlog, frames, host, upstream } = setupFake();
+
+ backlog.value = 1024;
+ upstream.emit('message', Buffer.from('a'), false);
+ upstream.emit('message', Buffer.from('b'), false);
+
+ expect(upstream.socket.pause).not.toHaveBeenCalled();
+ expect(frames.filter((f) => f.type === 'tunnel_ws_message')).toHaveLength(2);
+ host.closeAll('TEST');
+ });
+
+ it('closes with 1013 when the backlog blows past the hard cap', () => {
+ const { backlog, frames, host, upstream } = setupFake();
+
+ backlog.value = WS_RELAY_HARD_LIMIT + 1;
+ upstream.emit('message', Buffer.from('x'), false);
+
+ expect(upstream.socket.close).toHaveBeenCalledWith(1013, 'RELAY_BACKLOG');
+ expect(frames).toContainEqual({
+ code: 1013,
+ connId: 'b1',
+ reason: 'RELAY_BACKLOG',
+ type: 'tunnel_ws_close',
+ });
+ expect(host.activeCount).toBe(0);
+ });
+
+ it('stops polling the backlog once the tunnel is gone', () => {
+ const { backlog, host, upstream } = setupFake();
+
+ backlog.value = WS_RELAY_HIGH_WATER + 1;
+ upstream.emit('message', Buffer.from('x'), false);
+ host.closeAll('DEVICE_DISCONNECTED');
+
+ backlog.value = 0;
+ vi.advanceTimersByTime(500);
+ // A closed tunnel must not be resumed by a leftover timer.
+ expect(upstream.socket.resume).not.toHaveBeenCalled();
+ expect(vi.getTimerCount()).toBe(0);
+ });
+});
diff --git a/packages/device-gateway-client/src/wsTunnel.ts b/packages/device-gateway-client/src/wsTunnel.ts
new file mode 100644
index 00000000000..dc7b2461db8
--- /dev/null
+++ b/packages/device-gateway-client/src/wsTunnel.ts
@@ -0,0 +1,242 @@
+import { Buffer } from 'node:buffer';
+
+import WebSocket from 'ws';
+
+import type { GatewayClientLogger } from './client';
+import type {
+ TunnelClientFrame,
+ TunnelWsCloseMessage,
+ TunnelWsDataMessage,
+ TunnelWsOpenMessage,
+} from './types';
+import { TUNNEL_WS_MAX_MESSAGE } from './types';
+
+/**
+ * Device half of a WebSocket tunnel: opens `ws://127.0.0.1:<port>` for a
+ * browser socket the gateway is holding, and relays messages whole in both
+ * directions. This is what a dev server's live reload (Vite/webpack HMR)
+ * needs; plain HTTP is handled by `DeviceTunnelHost`.
+ */
+
+/** The slice of a `ws` socket this host touches β€” injectable for tests. */
+export interface TunnelUpstreamSocket {
+ close: (code?: number, reason?: string) => void;
+ on: {
+ (event: 'close', listener: (code: number, reason: Buffer) => void): unknown;
+ (event: 'error', listener: (error: Error) => void): unknown;
+ (event: 'message', listener: (data: Buffer, isBinary: boolean) => void): unknown;
+ (event: 'open', listener: () => void): unknown;
+ };
+ /** Stop reading from the upstream socket (TCP backpressure reaches the app). */
+ pause: () => void;
+ readonly protocol: string;
+ resume: () => void;
+ send: (data: Buffer | string) => void;
+ terminate: () => void;
+}
+
+export type TunnelUpstreamFactory = (url: string, protocols: string[]) => TunnelUpstreamSocket;
+
+const defaultFactory: TunnelUpstreamFactory = (url, protocols) =>
+ new WebSocket(url, protocols, {
+ handshakeTimeout: 10_000,
+ maxPayload: TUNNEL_WS_MAX_MESSAGE,
+ }) as unknown as TunnelUpstreamSocket;
+
+/** Close codes a socket may legally send; anything else becomes 1000/1011. */
+const sendableCode = (code?: number, fallback = 1000) =>
+ code &&
+ ((code >= 1000 && code <= 1003) ||
+ (code >= 1007 && code <= 1014) ||
+ (code >= 3000 && code <= 4999))
+ ? code
+ : fallback;
+
+/**
+ * Relay backpressure. Frames to the gateway go through a socket whose `send`
+ * never blocks, so a local app emitting faster than the uplink drains would
+ * grow this process's memory without bound. Above the high mark the upstream
+ * is paused (its TCP window then pushes back on the app) until the queue
+ * drains below the low mark. The hard cap is a backstop for a queue that
+ * keeps growing anyway β€” it closes the tunnel with 1013 "try again later".
+ */
+export const WS_RELAY_HIGH_WATER = 4 * 1024 * 1024;
+export const WS_RELAY_LOW_WATER = 1024 * 1024;
+export const WS_RELAY_HARD_LIMIT = 32 * 1024 * 1024;
+const WS_RELAY_DRAIN_POLL_MS = 50;
+
+interface WsTunnel {
+ closed: boolean;
+ connId: string;
+ /** Polls the backlog while the upstream is paused. */
+ drainTimer?: ReturnType<typeof setInterval>;
+ opened: boolean;
+ socket: TunnelUpstreamSocket;
+}
+
+export class DeviceWsTunnelHost {
+ private tunnels = new Map<string, WsTunnel>();
+
+ constructor(
+ private options: {
+ /** Bytes queued on the gateway socket but not yet written out. */
+ backlog?: () => number;
+ createSocket?: TunnelUpstreamFactory;
+ logger: GatewayClientLogger;
+ send: (frame: TunnelClientFrame) => void;
+ },
+ ) {}
+
+ get activeCount(): number {
+ return this.tunnels.size;
+ }
+
+ open(frame: TunnelWsOpenMessage): void {
+ const { connId, head, target } = frame;
+ if (this.tunnels.has(connId)) return;
+
+ // An IPv6 literal needs brackets or the URL is invalid.
+ const authority = target.host.includes(':') ? `[${target.host}]` : target.host;
+ let socket: TunnelUpstreamSocket;
+ try {
+ socket = (this.options.createSocket ?? defaultFactory)(
+ `ws://${authority}:${target.port}${head.path}`,
+ head.protocols,
+ );
+ } catch (error) {
+ this.fail(connId, error);
+ return;
+ }
+
+ const tunnel: WsTunnel = { closed: false, connId, opened: false, socket };
+ this.tunnels.set(connId, tunnel);
+
+ socket.on('open', () => {
+ tunnel.opened = true;
+ this.options.send({
+ connId,
+ ok: true,
+ ...(socket.protocol ? { protocol: socket.protocol } : {}),
+ type: 'tunnel_ws_open_ack',
+ });
+ });
+
+ socket.on('message', (data, isBinary) => {
+ if (tunnel.closed) return;
+ this.options.send({
+ ...(isBinary ? { binary: true } : {}),
+ connId,
+ data: isBinary ? data.toString('base64') : data.toString('utf8'),
+ type: 'tunnel_ws_message',
+ });
+ this.applyBackpressure(tunnel);
+ });
+
+ socket.on('close', (code, reason) => {
+ if (tunnel.closed) return;
+ this.release(tunnel);
+ if (!tunnel.opened) {
+ this.options.send({
+ connId,
+ error: 'UPSTREAM_CLOSED',
+ ok: false,
+ type: 'tunnel_ws_open_ack',
+ });
+ return;
+ }
+ this.options.send({ code, connId, reason: reason.toString('utf8'), type: 'tunnel_ws_close' });
+ });
+
+ socket.on('error', (error) => {
+ if (tunnel.closed) return;
+ // Before the handshake completes the gateway is still waiting on an ack;
+ // after it, the browser needs a close.
+ if (!tunnel.opened) {
+ this.release(tunnel);
+ this.fail(connId, error);
+ return;
+ }
+ this.options.logger.warn(`[tunnel] ws ${connId} upstream error: ${error.message}`);
+ });
+ }
+
+ /** A browser message for the upstream socket. */
+ message(frame: TunnelWsDataMessage): void {
+ const tunnel = this.tunnels.get(frame.connId);
+ if (!tunnel || tunnel.closed || !tunnel.opened) return;
+ tunnel.socket.send(frame.binary ? Buffer.from(frame.data, 'base64') : frame.data);
+ }
+
+ /** The browser side closed; close upstream to match. */
+ close(frame: TunnelWsCloseMessage): void {
+ const tunnel = this.tunnels.get(frame.connId);
+ if (!tunnel || tunnel.closed) return;
+ this.release(tunnel);
+ try {
+ tunnel.socket.close(sendableCode(frame.code), (frame.reason ?? '').slice(0, 100));
+ } catch {
+ tunnel.socket.terminate();
+ }
+ }
+
+ /** Drop every upstream socket, e.g. when the device socket goes away. */
+ closeAll(): void {
+ for (const tunnel of this.tunnels.values()) {
+ this.release(tunnel);
+ tunnel.socket.terminate();
+ }
+ }
+
+ // ─── internals ───
+
+ private applyBackpressure(tunnel: WsTunnel): void {
+ const backlog = this.options.backlog?.() ?? 0;
+
+ if (backlog > WS_RELAY_HARD_LIMIT) {
+ this.options.logger.warn(`[tunnel] ws ${tunnel.connId} relay backlog ${backlog}B, closing`);
+ this.release(tunnel);
+ tunnel.socket.close(1013, 'RELAY_BACKLOG');
+ this.options.send({
+ code: 1013,
+ connId: tunnel.connId,
+ reason: 'RELAY_BACKLOG',
+ type: 'tunnel_ws_close',
+ });
+ return;
+ }
+
+ if (backlog <= WS_RELAY_HIGH_WATER || tunnel.drainTimer) return;
+
+ tunnel.socket.pause();
+ tunnel.drainTimer = setInterval(() => {
+ if (tunnel.closed) return;
+ if ((this.options.backlog?.() ?? 0) > WS_RELAY_LOW_WATER) return;
+ clearInterval(tunnel.drainTimer);
+ tunnel.drainTimer = undefined;
+ tunnel.socket.resume();
+ }, WS_RELAY_DRAIN_POLL_MS);
+ }
+
+ /** Mark closed, forget it, and stop any drain polling. */
+ private release(tunnel: WsTunnel): void {
+ tunnel.closed = true;
+ this.tunnels.delete(tunnel.connId);
+ if (tunnel.drainTimer) {
+ clearInterval(tunnel.drainTimer);
+ tunnel.drainTimer = undefined;
+ }
+ }
+
+ private fail(connId: string, error: unknown) {
+ const code =
+ error && typeof error === 'object' && 'code' in error
+ ? String((error as { code: unknown }).code)
+ : undefined;
+ this.options.send({
+ connId,
+ error: code ?? (error instanceof Error ? error.message : 'TUNNEL_WS_OPEN_FAILED'),
+ ok: false,
+ type: 'tunnel_ws_open_ack',
+ });
+ }
+}