Skip to content

Commit 983b4bc

Browse files
authored
feat: add createWebSocketProxy util (#184)
1 parent 6291e7c commit 983b4bc

5 files changed

Lines changed: 948 additions & 1 deletion

File tree

docs/1.guide/7.proxy.md

Lines changed: 157 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,157 @@
1+
---
2+
icon: tabler:arrows-exchange
3+
---
4+
5+
# WebSocket Proxy
6+
7+
> Forward incoming WebSocket connections to an upstream `ws://` or `wss://` target.
8+
9+
crossws ships a small helper that returns a set of ready-made hooks which proxy every peer to an upstream WebSocket server. Use it to put crossws in front of an existing backend, split traffic across services, or bridge protocols between runtimes.
10+
11+
> [!NOTE]
12+
> The proxy uses the global [`WebSocket`](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket) constructor to dial the upstream, which is available on Node.js ≥ 22, Bun, Deno, Cloudflare Workers, and browsers. On older Node versions, pass a custom constructor via the [`WebSocket` option](#custom-websocket-constructor) or install a polyfill on `globalThis`.
13+
14+
## Usage
15+
16+
`createWebSocketProxy()` returns a `Partial<Hooks>` object that you can pass straight to any crossws adapter.
17+
18+
```ts
19+
// https://crossws.h3.dev/adapters
20+
import crossws from "crossws/adapters/<adapter>";
21+
import { createWebSocketProxy } from "crossws";
22+
23+
const websocket = crossws({
24+
hooks: createWebSocketProxy("wss://echo.websocket.org"),
25+
});
26+
```
27+
28+
Every incoming peer opens a matching upstream connection. Text and binary messages are forwarded in both directions, and close/error events are propagated to the client.
29+
30+
> [!TIP]
31+
> Messages sent by the client before the upstream connection is ready are buffered and flushed as soon as the upstream is open.
32+
33+
> [!CAUTION]
34+
> **The default proxy is an open relay.** It accepts every incoming connection and forwards it to the configured upstream without any authorization check. Always combine it with an [`upgrade` hook](#authentication) when the upstream is not itself publicly accessible — otherwise anyone who can reach the proxy can reach the upstream.
35+
36+
## Authentication
37+
38+
`createWebSocketProxy()` returns a plain hooks object, so you can spread it and override individual hooks. Authenticate the upgrade request before proxying by wrapping the proxy's `upgrade` hook:
39+
40+
```ts
41+
import { createWebSocketProxy } from "crossws";
42+
43+
const proxyHooks = createWebSocketProxy("wss://backend.example.com");
44+
45+
const hooks = {
46+
...proxyHooks,
47+
async upgrade(req) {
48+
const token = req.headers.get("authorization");
49+
if (!(await isValidToken(token))) {
50+
return new Response("Unauthorized", { status: 401 });
51+
}
52+
// Delegate to the proxy's own `upgrade` so subprotocol echoing still works.
53+
return proxyHooks.upgrade?.(req);
54+
},
55+
};
56+
```
57+
58+
> [!NOTE]
59+
> The WHATWG `WebSocket` constructor cannot forward cookies, `Authorization`, or `Origin` to the upstream, so upstream identity checks relying on those headers will silently fail. Authenticate at the proxy, or pass a custom `WebSocket` client and use the [`headers` option](#forwarding-headers) to propagate identity.
60+
61+
## Dynamic target
62+
63+
Pass a function to resolve the upstream URL from the incoming [`Peer`](/guide/peer) — useful for routing based on request URL, headers, or authenticated context.
64+
65+
```ts
66+
import { createWebSocketProxy } from "crossws";
67+
68+
const hooks = createWebSocketProxy({
69+
target: (peer) => {
70+
const { pathname } = new URL(peer.request.url);
71+
return pathname.startsWith("/admin")
72+
? "wss://admin.internal/ws"
73+
: "wss://public.internal/ws";
74+
},
75+
});
76+
```
77+
78+
> [!WARNING]
79+
> **SSRF risk.** A dynamic `target` resolver is a trust boundary. Never interpolate untrusted input (query strings, headers, path segments a client controls) directly into the returned URL — a naive resolver turns the proxy into an SSRF primitive that can dial `ws://127.0.0.1`, `ws://169.254.169.254`, or any reachable internal service. Always resolve against a hard-coded allowlist of hosts you control.
80+
81+
## Subprotocol negotiation
82+
83+
By default, the proxy forwards the client's `sec-websocket-protocol` header to the upstream and echoes the first requested subprotocol back in the upgrade response so the client handshake succeeds. Disable this if you want to negotiate subprotocols yourself:
84+
85+
```ts
86+
createWebSocketProxy({
87+
target: "wss://backend.example.com",
88+
forwardProtocol: false,
89+
});
90+
```
91+
92+
> [!WARNING]
93+
> The proxy commits to a subprotocol in the upgrade response before the upstream connection is established. If the upstream ultimately picks a different subprotocol (or rejects), the client will still see the one the proxy promised. Only keep `forwardProtocol` enabled when the upstream is known to accept the same subprotocols the client negotiates.
94+
95+
## Custom WebSocket constructor
96+
97+
Pass a `WebSocket` constructor via options to override the global — useful on Node.js < 22, to plug in a different client implementation, or to stub the upstream in tests.
98+
99+
```ts
100+
import { WebSocket } from "ws";
101+
import { createWebSocketProxy } from "crossws";
102+
103+
const hooks = createWebSocketProxy({
104+
target: "wss://backend.example.com",
105+
WebSocket: WebSocket as unknown as typeof globalThis.WebSocket,
106+
});
107+
```
108+
109+
### Unix domain sockets
110+
111+
The proxy does not enforce any scheme allowlist — whatever the configured `WebSocket` constructor accepts is accepted. For example, the [`ws`](https://github.com/websockets/ws) package supports Unix domain sockets via its `ws+unix:` scheme:
112+
113+
```ts
114+
import { WebSocket } from "ws";
115+
import { createWebSocketProxy } from "crossws";
116+
117+
const hooks = createWebSocketProxy({
118+
target: "ws+unix:/var/run/backend.sock:/chat",
119+
WebSocket: WebSocket as unknown as typeof globalThis.WebSocket,
120+
});
121+
```
122+
123+
## Forwarding headers
124+
125+
Passing a `headers` option attaches extra headers to the upstream handshake. This is the usual way to forward identity (`cookie`, `authorization`, `origin`) or inject a shared secret to the upstream.
126+
127+
```ts
128+
import { WebSocket } from "ws";
129+
import { createWebSocketProxy } from "crossws";
130+
131+
const hooks = createWebSocketProxy({
132+
target: "wss://backend.example.com",
133+
WebSocket: WebSocket as unknown as typeof globalThis.WebSocket,
134+
headers: (peer) => ({
135+
cookie: peer.request.headers.get("cookie") ?? "",
136+
"x-forwarded-for": peer.remoteAddress ?? "",
137+
}),
138+
});
139+
```
140+
141+
> [!IMPORTANT]
142+
> The WHATWG global `WebSocket` constructor does **not** accept custom headers. `headers` is only honored when a `WebSocket` constructor that takes a third options argument is passed via the [`WebSocket` option](#custom-websocket-constructor) — e.g. [`ws`](https://github.com/websockets/ws) or [`undici`](https://undici.nodejs.org). With the global constructor the option is silently ignored.
143+
144+
## API
145+
146+
### `createWebSocketProxy(target)`
147+
148+
Accepts either a target URL (`string` or `URL`), a resolver function, or an options object:
149+
150+
- **`target`**`string | URL | (peer: Peer) => string | URL`. The upstream WebSocket URL, or a function that resolves it per peer. The proxy does not enforce a scheme allowlist; any URL the configured `WebSocket` constructor accepts (including `ws+unix:` with `ws`) works. See the [SSRF warning](#dynamic-target) before using a dynamic resolver.
151+
- **`forwardProtocol`**`boolean` (default `true`). When enabled, the client's `sec-websocket-protocol` header is forwarded to the upstream and echoed back in the upgrade response. Values that are not valid RFC 7230 tokens are dropped.
152+
- **`headers`**`HeadersInit | (peer: Peer) => HeadersInit`. Extra headers to send on the upstream handshake. Only honored when a custom `WebSocket` constructor that accepts a third options argument is supplied — the WHATWG global ignores it.
153+
- **`maxBufferSize`**`number` (default `1048576`, i.e. 1 MiB). Maximum number of bytes buffered per peer while the upstream is still connecting. String frames are accounted at their UTF-8 worst case (3 bytes per UTF-16 code unit) to avoid undercounting multi-byte content. When exceeded, the peer is closed with code `1009` (Message Too Big). Set to `0` to disable.
154+
- **`connectTimeout`**`number` (default `10000`). Milliseconds to wait for the upstream WebSocket handshake to complete. If exceeded, the peer is closed with code `1011`. Set to `0` to disable.
155+
- **`WebSocket`**`typeof WebSocket` (default `globalThis.WebSocket`). Custom `WebSocket` constructor used to dial the upstream. Falls back to the global when omitted; throws at setup time if neither is available.
156+
157+
Returns a `Partial<Hooks>` object containing `upgrade`, `open`, `message`, `close`, and `error` hooks.

src/adapters/node.ts

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -74,10 +74,13 @@ const nodeAdapter: Adapter<NodeAdapter, NodeOptions> = (options = {}) => {
7474
});
7575
peers.add(peer);
7676
hooks.callHook("open", peer); // ws is already open
77-
ws.on("message", (data: unknown) => {
77+
ws.on("message", (data: unknown, isBinary: boolean) => {
7878
if (Array.isArray(data)) {
7979
data = Buffer.concat(data);
8080
}
81+
if (!isBinary && Buffer.isBuffer(data)) {
82+
data = data.toString("utf8");
83+
}
8184
hooks.callHook("message", peer, new Message(data, peer));
8285
});
8386
ws.on("error", (error: Error) => {

src/index.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,4 +18,8 @@ export type { WSError } from "./error.ts";
1818
// Server
1919
export type { ServerWithWSOptions, WSOptions } from "./server/_types.ts";
2020

21+
// Proxy
22+
export { createWebSocketProxy } from "./proxy.ts";
23+
export type { WebSocketProxyOptions } from "./proxy.ts";
24+
2125
// Removed from 0.2.x: createCrossWS, Caller, WSRequest, CrossWS

0 commit comments

Comments
 (0)