@johnhenry/wsh 0.37.0 → 0.38.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,191 @@
1
+ /**
2
+ * UDP flows as WebTransport datagrams (#124): the wire format, the rate limiter both ends use, and the client's flow
3
+ * object. Browser-safe: no `node:*` import.
4
+ *
5
+ * Negotiation: the client lists `gateway-datagram` in `Hello.features` when its transport has datagrams (WebTransport
6
+ * only), the host lists it in `ServerHello.features` when its transport has them AND its gateway serves UDP. Both =
7
+ * every `OpenUdp` flow of that connection carries its payloads as datagrams instead of `GatewayData` on the control
8
+ * stream. Open, close and errors (`OpenUdp`, `GatewayOk`/`GatewayFail`, `GatewayClose`) always stay on the control stream.
9
+ *
10
+ * Datagram layout (the whole QUIC datagram payload, one UDP payload per datagram):
11
+ *
12
+ * 0 1 2 3 4 ...
13
+ * +-------+-------+-------+-------+----------------------------+
14
+ * | gateway_id (u32, big endian) | UDP payload (0..n bytes) |
15
+ * +-------+-------+-------+-------+----------------------------+
16
+ *
17
+ * `gateway_id` is the id the client chose in `OpenUdp`. A datagram naming a flow the receiver does not have is dropped.
18
+ * Nothing is metered by `GatewayCredit` on a datagram flow (datagrams are never queued without bound: they are dropped).
19
+ * A payload that does not fit `maxDatagramSize - 4` travels as `GatewayData` on the control stream instead, unless the
20
+ * receiver is configured to drop it (see the host's `udp.oversize` and `openUdp`'s `oversize` option).
21
+ */
22
+
23
+ /** Feature string: "UDP flows may use WebTransport datagrams". */
24
+ export const GATEWAY_DATAGRAM_FEATURE = 'gateway-datagram';
25
+ /** Bytes of the flow-id header in front of each UDP payload. */
26
+ export const DATAGRAM_HEADER_BYTES = 4;
27
+ /** The largest UDP payload a flow carries (an IPv4 datagram's limit). */
28
+ export const MAX_UDP_PAYLOAD = 65507;
29
+
30
+ /** @param {number} id @param {Uint8Array} payload */
31
+ export function encodeDatagram(id, payload) {
32
+ const out = new Uint8Array(DATAGRAM_HEADER_BYTES + payload.byteLength);
33
+ new DataView(out.buffer).setUint32(0, id, false);
34
+ out.set(payload, DATAGRAM_HEADER_BYTES);
35
+ return out;
36
+ }
37
+
38
+ /** @param {Uint8Array} bytes @returns {{ id: number, payload: Uint8Array } | null} null when it is too short to be one */
39
+ export function decodeDatagram(bytes) {
40
+ if (!(bytes instanceof Uint8Array) || bytes.byteLength < DATAGRAM_HEADER_BYTES) return null;
41
+ const id = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength).getUint32(0, false);
42
+ return { id, payload: bytes.subarray(DATAGRAM_HEADER_BYTES) };
43
+ }
44
+
45
+ /**
46
+ * A token bucket: `take(cost)` is true (and spends) when `cost` tokens are available. Refills continuously at
47
+ * `ratePerSecond` up to `burst`. `ratePerSecond` of `Infinity` never refuses.
48
+ */
49
+ export class TokenBucket {
50
+ #rate;
51
+ #burst;
52
+ #tokens;
53
+ #last;
54
+ #now;
55
+ /** @param {number} ratePerSecond @param {number} [burst] @param {() => number} [now] milliseconds */
56
+ constructor(ratePerSecond, burst = ratePerSecond, now = () => Date.now()) {
57
+ this.#rate = ratePerSecond;
58
+ this.#burst = Math.max(burst, 1);
59
+ this.#tokens = this.#burst;
60
+ this.#now = now;
61
+ this.#last = now();
62
+ }
63
+
64
+ take(cost = 1) {
65
+ if (this.#rate === Infinity) return true;
66
+ const t = this.#now();
67
+ this.#tokens = Math.min(this.#burst, this.#tokens + ((t - this.#last) / 1000) * this.#rate);
68
+ this.#last = t;
69
+ if (this.#tokens < cost) return false;
70
+ this.#tokens -= cost;
71
+ return true;
72
+ }
73
+ }
74
+
75
+ const DEFAULT_QUEUE_DATAGRAMS = 128;
76
+
77
+ /**
78
+ * The client's end of a UDP flow: what `client.openUdp()` resolves with. Datagram semantics, explicitly: a datagram may
79
+ * be dropped (by a rate limit, by transport back-pressure, by a full receive queue) and nothing tells you which.
80
+ *
81
+ * - `send(bytes)`: resolves `true` when handed to the transport, `false` when dropped locally (transport busy). Rejects
82
+ * with a `RangeError` for a payload over 65507 bytes, and (with `oversize: 'drop'` on a datagram flow) for one that does
83
+ * not fit `maxDatagramSize`; otherwise a payload too big for one datagram goes on the reliable control stream.
84
+ * - `readable`: one chunk per datagram. When the reader is slower than the arrivals the NEWEST are dropped past a queue
85
+ * of `queueDatagrams` (counted in `stats.receiveDropped`).
86
+ * - `writable`: the same as `send()` as a stream; it never fills up and never errors on a drop.
87
+ * - `transport`: `'datagram'` or `'stream'` (the reliable fallback: WebSocket, no datagram support on either end).
88
+ * - `maxDatagramSize`: the largest payload that travels as a datagram now (it can change; read it again).
89
+ */
90
+ export class UdpFlow {
91
+ #o;
92
+ #queue = [];
93
+ #waiter = null;
94
+ #ended = false;
95
+ #streams = null;
96
+ stats = { sent: 0, received: 0, sentReliable: 0, receivedReliable: 0, sendDropped: 0, receiveDropped: 0 };
97
+
98
+ /**
99
+ * @param {object} o
100
+ * @param {number} o.id
101
+ * @param {import('./gateway-channel.mjs').GatewayChannel} o.channel
102
+ * @param {{ send(bytes: Uint8Array): boolean, maxSize(): number } | null} o.datagrams null = reliable path only
103
+ * @param {'reliable' | 'drop'} [o.oversize]
104
+ * @param {number} [o.queueDatagrams]
105
+ */
106
+ constructor(o) {
107
+ this.#o = { oversize: 'reliable', queueDatagrams: DEFAULT_QUEUE_DATAGRAMS, ...o };
108
+ this.channel = o.channel;
109
+ this.closed = o.channel.closedPromise;
110
+ this.closed.then(() => { this.#ended = true; this.#waiter?.(); });
111
+ }
112
+
113
+ get transport() { return this.#o.datagrams ? 'datagram' : 'stream'; }
114
+
115
+ get maxDatagramSize() {
116
+ if (!this.#o.datagrams) return MAX_UDP_PAYLOAD;
117
+ return Math.max(0, this.#o.datagrams.maxSize() - DATAGRAM_HEADER_BYTES);
118
+ }
119
+
120
+ /** @param {Uint8Array} bytes @returns {Promise<boolean>} */
121
+ async send(bytes) {
122
+ if (!(bytes instanceof Uint8Array)) throw new TypeError('send: bytes must be a Uint8Array');
123
+ if (bytes.byteLength > MAX_UDP_PAYLOAD) throw new RangeError(`a UDP payload is at most ${MAX_UDP_PAYLOAD} bytes (got ${bytes.byteLength})`);
124
+ if (this.channel.closed) throw new Error('the UDP flow is closed');
125
+ const dg = this.#o.datagrams;
126
+ if (dg && bytes.byteLength <= this.maxDatagramSize) {
127
+ const ok = dg.send(encodeDatagram(this.channel.id, bytes));
128
+ if (ok) this.stats.sent++; else this.stats.sendDropped++;
129
+ return ok;
130
+ }
131
+ if (dg && this.#o.oversize === 'drop') {
132
+ this.stats.sendDropped++;
133
+ throw new RangeError(`this payload (${bytes.byteLength} bytes) does not fit one datagram (${this.maxDatagramSize} bytes) and this flow drops oversize payloads`);
134
+ }
135
+ await this.channel.write(bytes); // the reliable control stream: ordered, retransmitted, metered by credit
136
+ this.stats.sentReliable++;
137
+ return true;
138
+ }
139
+
140
+ /** A datagram for this flow arrived (the payload, header removed). */
141
+ deliverDatagram(payload) { this.#push(payload, false); }
142
+
143
+ /** A GatewayData for this flow arrived on the control stream (the reliable path, or an oversize payload). */
144
+ deliverReliable(bytes) { this.#push(bytes, true); }
145
+
146
+ #push(bytes, reliable) {
147
+ if (this.#ended) return;
148
+ if (this.#queue.length >= this.#o.queueDatagrams) {
149
+ this.stats.receiveDropped++;
150
+ if (reliable) this.channel.consumed(bytes.byteLength);
151
+ return;
152
+ }
153
+ if (reliable) this.stats.receivedReliable++; else this.stats.received++;
154
+ // Copy: a datagram is a view into a buffer the transport may reuse.
155
+ this.#queue.push({ bytes: reliable ? bytes : bytes.slice(), reliable });
156
+ this.#waiter?.();
157
+ }
158
+
159
+ get streams() {
160
+ if (this.#streams) return this.#streams;
161
+ const self = this;
162
+ const readable = new ReadableStream({
163
+ async pull(controller) {
164
+ while (self.#queue.length === 0 && !self.#ended) await new Promise((r) => { self.#waiter = r; });
165
+ self.#waiter = null;
166
+ const next = self.#queue.shift();
167
+ if (next) {
168
+ controller.enqueue(next.bytes);
169
+ if (next.reliable) self.channel.consumed(next.bytes.byteLength);
170
+ return;
171
+ }
172
+ controller.close();
173
+ },
174
+ cancel() { self.destroy(); },
175
+ }, { highWaterMark: 0 });
176
+ const writable = new WritableStream({
177
+ async write(chunk) { try { await self.send(chunk instanceof Uint8Array ? chunk : new Uint8Array(chunk)); } catch (e) { if (!(e instanceof RangeError)) throw e; } },
178
+ close() { self.close(); },
179
+ abort() { self.destroy(); },
180
+ });
181
+ this.#streams = { readable, writable };
182
+ return this.#streams;
183
+ }
184
+
185
+ get readable() { return this.streams.readable; }
186
+ get writable() { return this.streams.writable; }
187
+
188
+ /** A flow has no half-close: closing ends it (the host closes the socket). */
189
+ close(reason) { this.channel.destroy(reason); }
190
+ destroy(reason) { this.channel.destroy(reason); }
191
+ }
package/src/index.d.ts CHANGED
@@ -1284,6 +1284,15 @@ export class WshTransport {
1284
1284
  /** Callback on transport error. */
1285
1285
  onError: ((err: Error) => void) | null;
1286
1286
 
1287
+ /** Callback for an unreliable datagram (WebTransport only). */
1288
+ onDatagram: ((bytes: Uint8Array) => void) | null;
1289
+ /** True where the transport can carry unreliable datagrams (WebTransport). */
1290
+ readonly supportsDatagrams: boolean;
1291
+ /** The largest datagram the connection can carry now, in bytes (0 = none). Read it again before sending. */
1292
+ readonly maxDatagramSize: number;
1293
+ /** Send one datagram without waiting or queueing; false = dropped. */
1294
+ sendDatagram(bytes: Uint8Array): boolean;
1295
+
1287
1296
  /** Current transport state. */
1288
1297
  readonly state: 'disconnected' | 'connecting' | 'connected' | 'closed';
1289
1298
 
@@ -2125,6 +2134,19 @@ export interface WshGatewayDuplex {
2125
2134
  closed: Promise<string | undefined>;
2126
2135
  }
2127
2136
 
2137
+ /** A UDP flow (`client.openUdp()`): one chunk = one datagram, and a datagram may be dropped without notice. */
2138
+ export interface WshUdpFlow extends WshGatewayDuplex {
2139
+ /** 'datagram': WebTransport datagrams. 'stream': the reliable control stream (WebSocket, or a host without `gateway-datagram`). */
2140
+ readonly transport: 'datagram' | 'stream';
2141
+ /** The largest payload that travels as one datagram right now (it can change; read it again). */
2142
+ readonly maxDatagramSize: number;
2143
+ /** Resolves true when handed to the transport, false when dropped locally. Rejects with RangeError for a payload over 65507 bytes (or over the datagram size with `oversize: 'drop'`). */
2144
+ send(bytes: Uint8Array): Promise<boolean>;
2145
+ stats: { sent: number; received: number; sentReliable: number; receivedReliable: number; sendDropped: number; receiveDropped: number };
2146
+ }
2147
+ /** Feature string for UDP over WebTransport datagrams. */
2148
+ export const GATEWAY_DATAGRAM_FEATURE: 'gateway-datagram';
2149
+
2128
2150
  /** A GatewayFail / ListenFail as an Error: `code` 4 = refused by the host's policy, 7 = too many connections, 1 = refused by the target. */
2129
2151
  export class GatewayError extends Error { code: number }
2130
2152
 
@@ -2232,8 +2254,14 @@ export class WshClient {
2232
2254
  openEndpoint(name: string, opts?: WshGatewayOpenOptions): Promise<WshGatewayDuplex>;
2233
2255
  /** Connect to host:port FROM THE HOST (needs the host feature `gateway`; refused unless its `gateway.allow` lists it). */
2234
2256
  openTcp(host: string, port: number, opts?: WshGatewayOpenOptions): Promise<WshGatewayDuplex>;
2235
- /** A UDP flow to host:port FROM THE HOST over the reliable control stream: each chunk is one datagram (at most 65507 bytes); the host drops what the receiver cannot keep up with. */
2236
- openUdp(host: string, port: number, opts?: WshGatewayOpenOptions): Promise<WshGatewayDuplex>;
2257
+ /**
2258
+ * A UDP flow to ONE destination, host:port, FROM THE HOST. Datagram semantics: any payload may be dropped. Over WebTransport, when the
2259
+ * host lists `gateway-datagram`, payloads are WebTransport datagrams (unordered, no retransmission, no head-of-line blocking between
2260
+ * flows); otherwise they ride the reliable control stream. A payload too big for one datagram goes on the control stream unless `oversize: 'drop'`.
2261
+ */
2262
+ openUdp(host: string, port: number, opts?: WshGatewayOpenOptions & { oversize?: 'reliable' | 'drop' }): Promise<WshUdpFlow>;
2263
+ /** Ask the host to listen on a TCP port (a reverse tunnel); needs `gateway` and the host's `gateway.reverse`. `bindAddr` is a request the host may ignore. */
2264
+ listenTcp(port: number, opts: { bindAddr?: string; timeoutMs?: number; onConnection: (duplex: WshGatewayDuplex, info: { peer: string; peerPort: number }) => void }): Promise<{ port: number; close(): Promise<void> }>;
2237
2265
  /** Ask the host to listen on a unix-domain socket and hand each connection to `onConnection` (OpenSSH `-R`). */
2238
2266
  listenUnix(path: string, opts: { replace?: boolean; timeoutMs?: number; onConnection: (duplex: WshGatewayDuplex, info: { peer: string }) => void }): Promise<{ path: string; close(): Promise<void> }>;
2239
2267
  /**
package/src/index.mjs CHANGED
@@ -79,6 +79,7 @@ export { WshClient, MCP_CALL_ID_FEATURE, MCP_CANCEL_FEATURE, STREAM_ANNOUNCE_FEA
79
79
  // Gateway forwarding (unix sockets, named endpoints, flow control) -- wsh #120, #123
80
80
  export { GatewayError } from './gateway-client.mjs';
81
81
  export { GATEWAY_CREDIT_FEATURE, GATEWAY_CREDIT_WINDOW } from './gateway-channel.mjs';
82
+ export { GATEWAY_DATAGRAM_FEATURE } from './gateway-datagram.mjs';
82
83
 
83
84
  // End-to-end key exchange (responder side, feature names, signed transcript) -- wsh #90
84
85
  export { E2E_FEATURE, E2E_SIGN_FEATURE, keyExchangeTranscript, verifyKeyExchangeSignature } from './e2e-exchange.mjs';
@@ -30,6 +30,7 @@ import { sealFrame, openFrame, ROLE_TAGS } from '../e2e-frame.mjs';
30
30
  import { E2EResponder, E2E_FEATURE, E2E_SIGN_FEATURE } from '../e2e-exchange.mjs';
31
31
  import { MULTI_OPERATOR_FEATURE } from './relay.mjs';
32
32
  import { gatewayFeatures } from './gateway-core.mjs';
33
+ import { GATEWAY_DATAGRAM_FEATURE } from '../gateway-datagram.mjs';
33
34
  import { OPERATOR_PROOF_FEATURE } from '../operator-proof.mjs';
34
35
  import { clientEnvFilter } from './client-env.mjs';
35
36
  import { acceptableBindings, bindingFeatures } from '../channel-binding.mjs';
@@ -128,7 +129,7 @@ export function createConnectionFactory(cfg) {
128
129
  * `dataStreams: false` means there are no client-opened streams to bind, so exec output rides SessionData.
129
130
  * `e2e` overrides `cfg.e2e` for this connection.
130
131
  */
131
- return function attach({ send: sendBytes, sendMessage = null, remote = {}, authenticated = null, dataStreams = true, closeTransport = null, e2e: e2eOverride, channelBinding = null }) {
132
+ return function attach({ send: sendBytes, sendMessage = null, remote = {}, authenticated = null, dataStreams = true, closeTransport = null, e2e: e2eOverride, channelBinding = null, datagrams = null }) {
132
133
  const cid = ++counter;
133
134
  const log = (m) => cfg.log(`[conn ${cid}] ${m}`);
134
135
  const state = {
@@ -159,7 +160,7 @@ export function createConnectionFactory(cfg) {
159
160
  // host in a page passes the endpoints-only session of `gateway-core.mjs` (`createMemoryHost({ endpoints })`).
160
161
  if (cfg.gateway && typeof cfg.createGatewaySession !== 'function') throw new TypeError('createConnectionFactory: gateway needs createGatewaySession (only @johnhenry/wsh/server provides one)');
161
162
  const gateway = cfg.gateway
162
- ? cfg.createGatewaySession(cfg.gateway, (m) => send(m), log, { who: () => ({ username: state.username, fingerprint: state.fingerprint }) })
163
+ ? cfg.createGatewaySession(cfg.gateway, (m) => send(m), log, { who: () => ({ username: state.username, fingerprint: state.fingerprint }), datagrams })
163
164
  : null;
164
165
 
165
166
  const qmux = sendMessage ? null : new QMuxConnection({ isClient: false, send: (b) => { if (!state.closed) sendBytes(b); } });
@@ -366,6 +367,8 @@ export function createConnectionFactory(cfg) {
366
367
  state.method = method;
367
368
  gateway?.setPeerFeatures(m.features);
368
369
  const features = hostFeatures(cfg, { dataStreams });
370
+ // UDP over datagrams only where this transport has them and the gateway serves (and allows) UDP.
371
+ if (datagrams && cfg.gateway?.tcp && cfg.gateway.udp?.datagrams) features.push(GATEWAY_DATAGRAM_FEATURE);
369
372
  let hostFingerprint;
370
373
  if (cfg.hostKey) {
371
374
  hostFingerprint = cfg.hostKey.fingerprint;
@@ -1072,6 +1075,8 @@ export function createConnectionFactory(cfg) {
1072
1075
 
1073
1076
  return {
1074
1077
  receive(bytes) { if (!state.closed) qmux?.receiveBytes(bytes); },
1078
+ /** A transport datagram (WebTransport) arrived: only the gateway's UDP flows use them. */
1079
+ receiveDatagram(bytes) { if (!state.closed && state.authed) gateway?.handleDatagram?.(bytes); },
1075
1080
  receiveMessage(msg) { if (!state.closed) chain = chain.then(() => handle(msg)).catch((e) => log(`handler error: ${e.message}`)); },
1076
1081
  bindStream: bindDataStream,
1077
1082
  close() { shutdownAfterQueue('transport closed'); },
@@ -58,7 +58,8 @@ export function normalizeEndpointGateway(opts = {}) {
58
58
  /** Which gateway-related features a host with this config advertises (besides what the connection adds). */
59
59
  export function gatewayFeatures(cfg) {
60
60
  const f = [];
61
- if (cfg.tcp) f.push('gateway');
61
+ // "gateway" also covers reverse tunnels (the Rust server lists nothing more specific for ListenRequest).
62
+ if (cfg.tcp || cfg.reverse) f.push('gateway');
62
63
  f.push(GATEWAY_CREDIT_FEATURE);
63
64
  if (cfg.unix) f.push('gateway-unix');
64
65
  if (cfg.endpoints) f.push('gateway-endpoints');
@@ -21,10 +21,15 @@
21
21
  * `src/gateway-channel.mjs`); with an older peer the host bounds its buffering by `maxBufferedBytes` per connection
22
22
  * and `maxClientBufferedBytes` per client and closes a connection that exceeds them.
23
23
  *
24
- * `OpenUdp` is served over the same reliable control stream (one GatewayData = one datagram; same destination policy;
25
- * a datagram the client cannot take fast enough is dropped; idle flows are closed after `udpIdleMs`). WebTransport
26
- * datagrams are not used yet (#124). Not implemented, and answered with a clean ListenFail rather than silence: TCP
27
- * reverse tunnels (`ListenRequest`).
24
+ * `OpenUdp` flows go to ONE destination chosen at open (same destination policy as TCP, resolved-address check
25
+ * included; replies are accepted only from that address and port, the socket is `connect()`ed to it). Over a
26
+ * WebSocket (or any peer without "gateway-datagram") one GatewayData is one datagram on the reliable control stream; over
27
+ * WebTransport, when both ends list "gateway-datagram", the payloads are WebTransport datagrams with a 4-byte flow-id
28
+ * header (`src/gateway-datagram.mjs`), so loss on one flow delays no other and nothing is retransmitted. Bounds
29
+ * (`udp: {...}`): flows per client, packets per second per flow and per client, bytes per second per client, idle flows
30
+ * closed after `udpIdleMs`; a payload bigger than the datagram limit goes on the reliable stream (or is dropped, by `udp.oversize`).
31
+ *
32
+ * `reverse: {...}` (off unless given): TCP reverse tunnels (`ListenRequest`), see `reverse-policy.mjs`.
28
33
  *
29
34
  * `socks`: dial through a SOCKS5 proxy (`'host:port'`, `socks5://host:port` or `{ host, port }`), e.g. a local Tor
30
35
  * client (`127.0.0.1:9050`). Commands carry the destination as a domain name (ATYP 3), so name resolution happens at
@@ -39,6 +44,12 @@ import {
39
44
  GATEWAY_FAIL, HALF_CLOSE_GRACE_MS, gatewayFeatures, createGatewayCore, normalizeGatewayLimits, normalizeEndpoints,
40
45
  } from './gateway-core.mjs';
41
46
  import { isPublicAddress, parseCidr, addressInCidr, parseIp, sameAddress } from './address-guard.mjs';
47
+ import { normalizeReverse, reversePortAllowed, reversePortRefusal, reverseBindAddress } from './reverse-policy.mjs';
48
+ import { normalizeUdp, newGatewayStats } from './udp-policy.mjs';
49
+ import { TokenBucket, encodeDatagram, decodeDatagram, MAX_UDP_PAYLOAD, GATEWAY_DATAGRAM_FEATURE } from '../gateway-datagram.mjs';
50
+
51
+ export { normalizeReverse, reversePortAllowed } from './reverse-policy.mjs';
52
+ export { normalizeUdp } from './udp-policy.mjs';
42
53
 
43
54
  // Loaded on first use so that importing the connection handler (which serves the gateway opcodes)
44
55
  // does not pull `node:net` into a browser bundle (see `src/memory-host.mjs`).
@@ -55,7 +66,7 @@ const DEFAULT_CONNECT_TIMEOUT_MS = 15_000;
55
66
  const MAX_PENDING_INBOUND = 16;
56
67
  const INBOUND_ACCEPT_TIMEOUT_MS = 30_000;
57
68
  const DEFAULT_UDP_IDLE_MS = 60_000;
58
- const MAX_DATAGRAM = 65507;
69
+ const MAX_DATAGRAM = MAX_UDP_PAYLOAD;
59
70
  const UDP_OUTBOX_BYTES = 256 * 1024;
60
71
 
61
72
  /** @param {string|{host:string,port:number}} socks */
@@ -232,6 +243,8 @@ export async function dialChecked(cfg, host, port, explicitLiteral, timeoutMs =
232
243
  * @param {number} [opts.maxClientBufferedBytes=33554432] the same, summed over one client's connections
233
244
  * @param {string|{host:string,port:number}} [opts.socks] dial through this SOCKS5 proxy (Tor)
234
245
  * @param {{ connect?: string[], listen?: string[], replaceStale?: boolean, maxListeners?: number }} [opts.unix] unix-domain sockets (see unix-policy.mjs)
246
+ * @param {boolean | object} [opts.reverse] TCP reverse tunnels, off unless given (see reverse-policy.mjs)
247
+ * @param {object} [opts.udp] UDP bounds (see udp-policy.mjs)
235
248
  * @param {Record<string, Function | { open: Function, authorize?: Function }>} [opts.endpoints] named virtual endpoints
236
249
  * @param {boolean} [opts.tcp=true] false: no TCP or DNS at all (an endpoints-only host such as the memory host)
237
250
  * @param {(line: string) => void} [opts.log]
@@ -264,6 +277,9 @@ export function normalizeGateway(opts) {
264
277
  maxClientBufferedBytes,
265
278
  connectTimeoutMs: opts.connectTimeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS,
266
279
  udpIdleMs: opts.udpIdleMs ?? DEFAULT_UDP_IDLE_MS,
280
+ udp: normalizeUdp(opts.udp),
281
+ reverse: normalizeReverse(opts.reverse),
282
+ stats: newGatewayStats(),
267
283
  socks: parseSocks(opts.socks),
268
284
  tcp: opts.tcp !== false,
269
285
  unix,
@@ -398,11 +414,23 @@ export function createGatewaySession(cfg, send, log = () => {}, ctx = {}) {
398
414
  }
399
415
  }
400
416
 
401
- // ── UDP over the reliable path ───────────────────────────────────
402
- // One GatewayData is one datagram. This rides the ordered, reliable control stream, so it has the head-of-line
403
- // blocking and retransmission a UDP user does not expect (WebTransport datagrams are #124's second half); what it
404
- // does keep is UDP's loss model toward the origin side: a datagram the client cannot take fast enough is DROPPED
405
- // here rather than buffered, and one the client sends beyond what fits in a datagram is dropped.
417
+ // ── UDP ──────────────────────────────────────────────────────────
418
+ // A flow is one connect()ed UDP socket: one destination, fixed at OpenUdp, whose address passed the resolved-address
419
+ // policy; the kernel delivers nothing to it from any other address or port, so the host is no relay to arbitrary peers.
420
+ // Payloads travel as WebTransport datagrams when both ends negotiated "gateway-datagram" (no retransmission, no
421
+ // head-of-line blocking between flows), else one GatewayData per datagram on the reliable control stream. Both
422
+ // directions are rate-limited (token buckets: per flow, per client, and bytes per client) and a datagram over a limit
423
+ // is dropped and counted, as a congested network would. What a client cannot take fast enough is dropped, never buffered.
424
+
425
+ const udpCfg = cfg.udp;
426
+ const stats = cfg.stats.udp;
427
+ const clientPackets = new TokenBucket(udpCfg.packetsPerSecondPerClient, Math.max(udpCfg.packetsPerSecondPerClient / 4, 32));
428
+ const clientBytes = new TokenBucket(udpCfg.bytesPerSecondPerClient, Math.max(udpCfg.bytesPerSecondPerClient / 4, 65536));
429
+ /** gateway_id -> handler for a datagram that arrived for the flow. */
430
+ const udpFlows = new Map();
431
+ const udpPending = new Set();
432
+ let peerDatagrams = false;
433
+ const datagramsOn = () => peerDatagrams && udpCfg.datagrams && !!ctx.datagrams;
406
434
 
407
435
  async function openUdp(m) {
408
436
  const id = m.gateway_id;
@@ -417,7 +445,9 @@ export function createGatewaySession(cfg, send, log = () => {}, ctx = {}) {
417
445
  log(`gateway: refused udp ${m.host}:${m.port} (not on the allow list)`);
418
446
  return fail(id, GATEWAY_FAIL.POLICY_DENIED, 'destination not allowed by the gateway policy');
419
447
  }
448
+ if (udpFlows.size + udpPending.size >= udpCfg.maxFlows) return fail(id, GATEWAY_FAIL.QUEUE_FULL, `too many UDP flows (limit ${udpCfg.maxFlows})`);
420
449
  if (active() >= cfg.maxConnections) return fail(id, GATEWAY_FAIL.QUEUE_FULL, 'too many gateway connections');
450
+ udpPending.add(id);
421
451
  pending.add(id);
422
452
  let sock;
423
453
  let address;
@@ -427,34 +457,50 @@ export function createGatewaySession(cfg, send, log = () => {}, ctx = {}) {
427
457
  sock = dgram.createSocket(address.includes(':') ? 'udp6' : 'udp4');
428
458
  await new Promise((resolve, reject) => { sock.once('error', reject); sock.connect(m.port, address, () => { sock.off('error', reject); resolve(); }); });
429
459
  } catch (e) {
430
- pending.delete(id);
460
+ pending.delete(id); udpPending.delete(id);
431
461
  try { sock?.close(); } catch { /* not open */ }
432
462
  if (e.code === GATEWAY_FAIL.POLICY_DENIED) log(`gateway: refused udp ${m.host}:${m.port} (${e.message})`);
433
463
  return fail(id, typeof e.code === 'number' ? e.code : GATEWAY_FAIL.HOST_UNREACHABLE, String(e.message).slice(0, 200));
434
464
  }
435
- pending.delete(id);
465
+ pending.delete(id); udpPending.delete(id);
436
466
  if (closed) { sock.close(); return undefined; }
437
467
  attachDatagrams(id, sock);
438
- log(`gateway: ${id} -> udp ${m.host}:${m.port}${address !== m.host ? ` (${address})` : ''}`);
468
+ stats.flowsOpened++;
469
+ log(`gateway: ${id} -> udp ${m.host}:${m.port}${address !== m.host ? ` (${address})` : ''}${datagramsOn() ? ' (datagrams)' : ''} (local port ${sock.address().port})`);
439
470
  return reply(gatewayOk({ gatewayId: id, resolvedAddr: address }));
440
471
  }
441
472
 
442
473
  function attachDatagrams(id, sock) {
443
474
  let idle = null;
444
475
  const touch = () => { clearTimeout(idle); idle = setTimeout(() => channel.destroy('idle timeout'), cfg.udpIdleMs); idle.unref?.(); };
476
+ const flowPackets = new TokenBucket(udpCfg.packetsPerSecondPerFlow, Math.max(udpCfg.packetsPerSecondPerFlow / 4, 16));
477
+ const useDatagrams = datagramsOn();
478
+ /** All three buckets must have room; a datagram over any limit is dropped. */
479
+ const admit = (n) => {
480
+ if (flowPackets.take(1) && clientPackets.take(1) && clientBytes.take(n)) return true;
481
+ stats.rateDropped++;
482
+ return false;
483
+ };
445
484
  const outbox = [];
446
485
  let outboxBytes = 0;
447
486
  let pumping = false;
448
487
  const channel = makeChannel(id, {
449
- onData: (bytes) => {
488
+ onData: (bytes) => { // a payload on the reliable stream (the only path without datagrams; the oversize path with them)
450
489
  touch();
451
- if (bytes.byteLength > MAX_DATAGRAM) { channel.consumed(bytes.byteLength); return; }
490
+ if (bytes.byteLength > MAX_DATAGRAM || !admit(bytes.byteLength)) { channel.consumed(bytes.byteLength); return; }
491
+ stats.reliableFromClient++;
452
492
  sock.send(bytes, () => channel.consumed(bytes.byteLength));
453
493
  },
454
494
  onRemoteClose: () => channel.destroy(), // UDP has no half-close
455
- onClose: () => { clearTimeout(idle); try { sock.close(); } catch { /* closed */ } },
495
+ onClose: () => { clearTimeout(idle); udpFlows.delete(id); try { sock.close(); } catch { /* closed */ } },
456
496
  });
457
497
  conns.set(id, { channel, sock: null });
498
+ udpFlows.set(id, (payload) => { // a datagram from the client
499
+ touch();
500
+ if (payload.byteLength > MAX_DATAGRAM || !admit(payload.byteLength)) return;
501
+ stats.datagramsFromClient++;
502
+ sock.send(payload);
503
+ });
458
504
  async function pump() {
459
505
  if (pumping) return;
460
506
  pumping = true;
@@ -468,7 +514,18 @@ export function createGatewaySession(cfg, send, log = () => {}, ctx = {}) {
468
514
  }
469
515
  sock.on('message', (d) => {
470
516
  touch();
517
+ if (!admit(d.length)) return;
518
+ if (useDatagrams) {
519
+ const frame = encodeDatagram(id, d);
520
+ if (frame.length <= ctx.datagrams.maxSize()) {
521
+ if (ctx.datagrams.send(frame)) stats.datagramsToClient++; else stats.backpressureDropped++;
522
+ return;
523
+ }
524
+ if (udpCfg.oversize === 'drop') { stats.oversizeDropped++; log(`gateway ${id}: dropped a ${d.length}-byte reply that does not fit a datagram (${ctx.datagrams.maxSize() - 4} bytes)`); return; }
525
+ stats.oversizeReliable++;
526
+ }
471
527
  if (outboxBytes + d.length > UDP_OUTBOX_BYTES) return; // the client is not keeping up: drop, as a network would
528
+ stats.reliableToClient++;
472
529
  outbox.push(d); outboxBytes += d.length;
473
530
  void pump();
474
531
  });
@@ -561,7 +618,7 @@ export function createGatewaySession(cfg, send, log = () => {}, ctx = {}) {
561
618
  stat = await unix.statSocket(chk.path);
562
619
  }
563
620
  if (closed) { server.close(); if (stat) await unix.unlinkIfSocket(chk.path, stat); return undefined; }
564
- const entry = { server, path: chk.path, abstract: chk.abstract, stat, pendingChannels: new Set() };
621
+ const entry = { server, kind: 'unix', path: chk.path, abstract: chk.abstract, stat, pendingChannels: new Set(), open: 0 };
565
622
  listeners.set(id, entry);
566
623
  server.on('connection', (sock) => onInbound(id, entry, sock));
567
624
  server.on('error', (e) => log(`gateway listener ${id}: ${e.message}`));
@@ -575,17 +632,58 @@ export function createGatewaySession(cfg, send, log = () => {}, ctx = {}) {
575
632
  }
576
633
  }
577
634
 
635
+ // ── TCP reverse tunnels ──────────────────────────────────────────
636
+
637
+ async function listenTcp(m) {
638
+ const id = m.listener_id;
639
+ if (!Number.isInteger(id) || !Number.isInteger(m.port) || m.port < 0 || m.port > 65535) return failListen(id, 'malformed ListenRequest');
640
+ if (!cfg.reverse) return failListen(id, 'reverse tunnels are not enabled on this gateway');
641
+ if (listeners.has(id) || pendingListeners.has(id)) return failListen(id, 'listener_id already in use');
642
+ const rev = cfg.reverse;
643
+ if (!reversePortAllowed(rev, m.port)) { log(`gateway: refused reverse listen on port ${m.port} (port policy)`); return failListen(id, reversePortRefusal(rev, m.port)); }
644
+ let tcpCount = pendingListeners.size;
645
+ for (const l of listeners.values()) if (l.kind === 'tcp') tcpCount++;
646
+ if (tcpCount >= rev.maxListeners) return failListen(id, `too many reverse listeners (limit ${rev.maxListeners})`);
647
+ pendingListeners.add(id);
648
+ let server;
649
+ try {
650
+ const net = await loadNet();
651
+ const host = reverseBindAddress(rev, m.bind_addr);
652
+ if (host !== m.bind_addr) log(`gateway: reverse listen: ignoring the client's bind address ${JSON.stringify(String(m.bind_addr).slice(0, 64))}, binding ${host}`);
653
+ server = net.createServer();
654
+ await new Promise((resolve, reject) => { server.once('error', reject); server.listen({ port: m.port, host, backlog: rev.backlog }, () => { server.off('error', reject); resolve(); }); });
655
+ if (closed) { server.close(); return undefined; }
656
+ const addr = server.address();
657
+ const entry = { server, kind: 'tcp', path: '', abstract: false, stat: null, pendingChannels: new Set(), open: 0 };
658
+ listeners.set(id, entry);
659
+ server.on('connection', (sock) => onInbound(id, entry, sock));
660
+ server.on('error', (e) => log(`gateway listener ${id}: ${e.message}`));
661
+ cfg.stats.reverse.listeners++;
662
+ log(`gateway: listening on ${host}:${addr.port} (reverse listener ${id})`);
663
+ return await reply(listenOk({ listenerId: id, actualPort: addr.port }));
664
+ } catch (e) {
665
+ try { server?.close(); } catch { /* not listening */ }
666
+ return failListen(id, e.code === 'EADDRINUSE' ? 'address in use' : e.code === 'EACCES' ? 'permission denied binding that port' : String(e.message).slice(0, 200));
667
+ } finally {
668
+ pendingListeners.delete(id);
669
+ }
670
+ }
671
+
578
672
  function onInbound(listenerId, entry, sock) {
579
- if (closed || inbound.size >= MAX_PENDING_INBOUND || active() + inbound.size >= cfg.maxConnections) { sock.destroy(); return; }
673
+ const tcp = entry.kind === 'tcp';
674
+ const refuse = (why) => { if (tcp) cfg.stats.reverse.refusedConnections++; log(`gateway: reverse listener ${listenerId}: dropped a connection (${why})`); sock.destroy(); };
675
+ if (closed || inbound.size >= MAX_PENDING_INBOUND || active() + inbound.size >= cfg.maxConnections) return refuse('too many gateway connections');
676
+ if (tcp && entry.open >= cfg.reverse.maxConnectionsPerListener) return refuse(`listener is at its limit of ${cfg.reverse.maxConnectionsPerListener} connections`);
580
677
  sock.pause();
581
678
  sock.on('error', () => {});
582
679
  const channelId = ++nextInbound;
583
680
  const timer = setTimeout(() => { inbound.delete(channelId); entry.pendingChannels.delete(channelId); sock.destroy(); }, INBOUND_ACCEPT_TIMEOUT_MS);
584
681
  timer.unref?.();
682
+ if (tcp) { entry.open++; cfg.stats.reverse.accepted++; sock.once('close', () => { entry.open--; }); }
585
683
  sock.once('close', () => { if (inbound.get(channelId)?.sock === sock) { clearTimeout(timer); inbound.delete(channelId); entry.pendingChannels.delete(channelId); } });
586
684
  inbound.set(channelId, { sock, listenerId, timer });
587
685
  entry.pendingChannels.add(channelId);
588
- void reply(inboundOpen({ listenerId, channelId, peerAddr: 'unix', peerPort: 0 }));
686
+ void reply(inboundOpen({ listenerId, channelId, peerAddr: tcp ? (sock.remoteAddress ?? '') : 'unix', peerPort: tcp ? (sock.remotePort ?? 0) : 0 }));
589
687
  }
590
688
 
591
689
  function inboundAccept(m) {
@@ -597,6 +695,11 @@ export function createGatewaySession(cfg, send, log = () => {}, ctx = {}) {
597
695
  const id = m.gateway_id;
598
696
  if (!Number.isInteger(id) || idInUse(id) || p.sock.destroyed || active() >= cfg.maxConnections) { p.sock.destroy(); return; }
599
697
  attachSocket(id, p.sock);
698
+ const rev = listeners.get(p.listenerId)?.kind === 'tcp' ? cfg.reverse : null;
699
+ if (rev && rev.idleMs > 0) {
700
+ // Inactivity in either direction ends the connection (the socket's own timeout counts reads and writes).
701
+ p.sock.setTimeout(rev.idleMs, () => { cfg.stats.reverse.idleClosed++; log(`gateway: reverse connection ${id} idle for ${rev.idleMs} ms, closing`); p.sock.destroy(); });
702
+ }
600
703
  p.sock.resume();
601
704
  }
602
705
 
@@ -618,7 +721,16 @@ export function createGatewaySession(cfg, send, log = () => {}, ctx = {}) {
618
721
  }
619
722
 
620
723
  return {
621
- setPeerFeatures: (features) => core.setPeerFeatures(features),
724
+ setPeerFeatures: (features) => { core.setPeerFeatures(features); peerDatagrams = Array.isArray(features) && features.includes(GATEWAY_DATAGRAM_FEATURE); },
725
+ /** A WebTransport datagram arrived from the client: [flow id][payload]. */
726
+ handleDatagram(bytes) {
727
+ if (closed) return;
728
+ const d = decodeDatagram(bytes);
729
+ if (!d) { stats.malformed++; return; }
730
+ const flow = datagramsOn() ? udpFlows.get(d.id) : undefined;
731
+ if (!flow) { stats.unknownFlow++; return; }
732
+ flow(d.payload);
733
+ },
622
734
  /** @returns {Promise<boolean>} true when the message was a gateway message this session consumed */
623
735
  async handle(m) {
624
736
  if (closed) return true;
@@ -627,7 +739,7 @@ export function createGatewaySession(cfg, send, log = () => {}, ctx = {}) {
627
739
  case MSG.OPEN_UDP: await openUdp(m); return true;
628
740
  case MSG.OPEN_UNIX: await openUnix(m); return true;
629
741
  case MSG.RESOLVE_DNS: await resolveDns(m); return true;
630
- case MSG.LISTEN_REQUEST: reply(listenFail({ listenerId: m.listener_id, reason: 'reverse tunnels are not supported by this gateway' })); return true;
742
+ case MSG.LISTEN_REQUEST: await listenTcp(m); return true;
631
743
  case MSG.LISTEN_UNIX: await listenUnix(m); return true;
632
744
  case MSG.LISTEN_CLOSE: await closeListener(m.listener_id); return true;
633
745
  case MSG.INBOUND_ACCEPT: inboundAccept(m); return true;
@@ -158,6 +158,39 @@ export interface WshServerGatewayOptions {
158
158
  endpoints?: Record<string, WshGatewayEndpointHandler | { open: WshGatewayEndpointHandler; authorize?: (who: WshGatewayWho) => boolean | Promise<boolean> }>;
159
159
  /** `false`: no TCP or DNS at all (an endpoints-only gateway). Default true. */
160
160
  tcp?: boolean;
161
+ /**
162
+ * TCP reverse tunnels (`ListenRequest`). OFF unless given (`true` = the defaults). The host binds `bindAddr` (default
163
+ * 127.0.0.1) and ignores the client's `bind_addr` unless it is listed in `allowBindAddrs`; `ports` (default `[0, "1024-65535"]`)
164
+ * is what a client may ask for, privileged ports only if listed.
165
+ */
166
+ reverse?: boolean | {
167
+ enabled?: boolean;
168
+ bindAddr?: string;
169
+ allowBindAddrs?: string[];
170
+ ports?: Array<number | string>;
171
+ /** Reverse listeners per client (default 4). */
172
+ maxListeners?: number;
173
+ /** Open connections per listener (default 16); the next one is closed unannounced. */
174
+ maxConnectionsPerListener?: number;
175
+ /** `listen()` backlog (default 8). */
176
+ backlog?: number;
177
+ /** An accepted connection with no traffic either way for this long is closed (default 300000; 0 = never). */
178
+ idleMs?: number;
179
+ };
180
+ /** Bounds of UDP flows (`OpenUdp`); all rates drop, not queue. */
181
+ udp?: {
182
+ /** Use WebTransport datagrams for a flow when the transport and the client have them (default true). */
183
+ datagrams?: boolean;
184
+ /** Concurrent UDP flows per client (default 16). */
185
+ maxFlows?: number;
186
+ /** Datagrams per second per flow (500), per client (2000), both directions. `Infinity` = unlimited. */
187
+ packetsPerSecondPerFlow?: number;
188
+ packetsPerSecondPerClient?: number;
189
+ /** Payload bytes per second per client, both directions (default 4 MiB): bounds amplification. */
190
+ bytesPerSecondPerClient?: number;
191
+ /** A reply that does not fit one datagram: 'reliable' sends it on the control stream (default), 'drop' drops it and counts it. */
192
+ oversize?: 'reliable' | 'drop';
193
+ };
161
194
  }
162
195
 
163
196
  export interface WshServerPtyOptions {
@@ -530,6 +563,8 @@ export interface WshServer {
530
563
  rotateCertificate(options?: { activate?: boolean }): Promise<{ current: WshServerCertificateInfo; next: WshServerCertificateInfo | null }>;
531
564
  /** Fingerprints of the peers currently registered with this relay (`[]` when it is not one). */
532
565
  peerFingerprints(): string[];
566
+ /** Counters of the gateway's UDP flows (datagrams in/out, drops by cause, oversize handling) and reverse listeners; null without a gateway. */
567
+ gatewayStats(): { udp: Record<string, number>; reverse: Record<string, number> } | null;
533
568
  /** The advertised host identity; `null` before `listen()` resolves or without a `hostKey`. */
534
569
  hostKey(): WshServerHostKey | null;
535
570
  }