@johnhenry/wsh 0.37.0 → 0.38.1

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.
@@ -9,11 +9,12 @@
9
9
  */
10
10
 
11
11
  import {
12
- MSG, openTcp as openTcpMsg, openUdp as openUdpMsg, openUnix as openUnixMsg, openEndpoint as openEndpointMsg, listenUnix as listenUnixMsg,
12
+ MSG, openTcp as openTcpMsg, openUdp as openUdpMsg, listenRequest as listenRequestMsg, openUnix as openUnixMsg, openEndpoint as openEndpointMsg, listenUnix as listenUnixMsg,
13
13
  listenClose as listenCloseMsg, inboundAccept as inboundAcceptMsg, inboundReject as inboundRejectMsg,
14
14
  gatewayData as gatewayDataMsg, gatewayCredit as gatewayCreditMsg, gatewayClose as gatewayCloseMsg,
15
15
  } from './messages.mjs';
16
16
  import { GatewayChannel, GATEWAY_CREDIT_FEATURE } from './gateway-channel.mjs';
17
+ import { UdpFlow, decodeDatagram } from './gateway-datagram.mjs';
17
18
 
18
19
  const ID_BASE = 0x40000000;
19
20
  const ID_LIMIT = 0xffffffff;
@@ -54,9 +55,20 @@ export class GatewayConnections {
54
55
  * @param {(msg: object) => Promise<void>} o.send
55
56
  * @param {(feature: string) => boolean} o.hasFeature
56
57
  */
57
- constructor({ send, hasFeature }) {
58
+ constructor({ send, hasFeature, datagrams = () => null }) {
58
59
  this.#send = send;
59
60
  this.#hasFeature = hasFeature;
61
+ this.#datagrams = datagrams;
62
+ }
63
+
64
+ #datagrams;
65
+ /** @type {Map<number, UdpFlow>} */
66
+ #udp = new Map();
67
+
68
+ /** A WebTransport datagram arrived: [gateway_id][payload]. A flow we do not have is dropped, as a stray datagram is. */
69
+ handleDatagram(bytes) {
70
+ const d = decodeDatagram(bytes);
71
+ if (d) this.#udp.get(d.id)?.deliverDatagram(d.payload);
60
72
  }
61
73
 
62
74
  #id() {
@@ -68,8 +80,8 @@ export class GatewayConnections {
68
80
  if (!this.#hasFeature(feature)) throw new GatewayError(`this host does not support ${what} (it did not advertise "${feature}")`, 0);
69
81
  }
70
82
 
71
- /** @param {{ datagram?: boolean }} [kind] a datagram flow has no half-close: the peer's close ends it */
72
- #makeChannel(id, { datagram = false } = {}) {
83
+ /** @param {{ datagram?: boolean, onData?: (bytes: Uint8Array) => void }} [kind] a datagram flow has no half-close: the peer's close ends it */
84
+ #makeChannel(id, { datagram = false, onData } = {}) {
73
85
  const channel = new GatewayChannel({
74
86
  id,
75
87
  credit: this.#hasFeature(GATEWAY_CREDIT_FEATURE),
@@ -77,16 +89,19 @@ export class GatewayConnections {
77
89
  // our side closes too, so a connection nobody closes does not stay in the table forever.
78
90
  graceMs: CLIENT_GRACE_MS,
79
91
  onRemoteClose: datagram ? () => channel.destroy() : undefined,
92
+ onData,
80
93
  sendData: (data) => this.#send(gatewayDataMsg({ gatewayId: id, data })),
81
94
  sendCredit: (n) => this.#send(gatewayCreditMsg({ gatewayId: id, bytes: n })),
82
95
  sendClose: (reason) => this.#send(gatewayCloseMsg({ gatewayId: id, reason })),
83
- onClose: () => { this.#channels.delete(id); },
96
+ onClose: () => { this.#channels.delete(id); this.#udp.delete(id); },
84
97
  });
85
98
  this.#channels.set(id, channel);
86
99
  return channel;
87
100
  }
88
101
 
89
102
  #duplex(channel) {
103
+ const flow = this.#udp.get(channel.id);
104
+ if (flow) return flow;
90
105
  const { readable, writable } = channel.streams();
91
106
  return { readable, writable, close: (r) => channel.end(r), destroy: (r) => channel.destroy(r), closed: channel.closedPromise };
92
107
  }
@@ -94,7 +109,9 @@ export class GatewayConnections {
94
109
  async #open(build, { timeoutMs = DEFAULT_TIMEOUT_MS, signal } = {}, kind) {
95
110
  if (signal?.aborted) throw signal.reason ?? new DOMException('aborted', 'AbortError');
96
111
  const id = this.#id();
97
- const channel = this.#makeChannel(id, kind);
112
+ let flow;
113
+ const channel = this.#makeChannel(id, { ...kind, onData: kind?.udp ? (b) => flow.deliverReliable(b) : undefined });
114
+ if (kind?.udp) { flow = new UdpFlow({ id, channel, ...kind.udp }); this.#udp.set(id, flow); }
98
115
  const done = new Promise((resolve, reject) => {
99
116
  const timer = setTimeout(() => { this.#opening.delete(id); channel.abandon(); reject(new GatewayError('the host did not answer the open request in time', 5)); }, timeoutMs);
100
117
  timer.unref?.();
@@ -148,7 +165,45 @@ export class GatewayConnections {
148
165
  async openUdp(host, port, opts) {
149
166
  this.#need('gateway', 'UDP egress');
150
167
  if (typeof host !== 'string' || !host || !Number.isInteger(port)) throw new TypeError('openUdp: host and port are required');
151
- return this.#open((id) => openUdpMsg({ gatewayId: id, host, port }), opts, { datagram: true });
168
+ if (opts?.oversize !== undefined && opts.oversize !== 'reliable' && opts.oversize !== 'drop') throw new TypeError('openUdp: oversize must be "reliable" or "drop"');
169
+ // Whether this flow uses datagrams is fixed at open: both ends negotiated it for the connection.
170
+ const datagrams = this.#datagrams();
171
+ return this.#open((id) => openUdpMsg({ gatewayId: id, host, port }), opts, {
172
+ datagram: true,
173
+ udp: { datagrams, oversize: opts?.oversize },
174
+ });
175
+ }
176
+
177
+ /**
178
+ * Ask the host to listen on a TCP port (a reverse tunnel) and hand each inbound connection to `onConnection(duplex, { peer, peerPort })`.
179
+ * @param {number} port @param {{ bindAddr?: string, onConnection: Function, timeoutMs?: number }} opts
180
+ * @returns {Promise<{ port: number, close: () => Promise<void> }>}
181
+ */
182
+ async listenTcp(port, { bindAddr, onConnection, timeoutMs = DEFAULT_TIMEOUT_MS } = {}) {
183
+ this.#need('gateway', 'reverse tunnels (ListenRequest)');
184
+ if (!Number.isInteger(port) || port < 0 || port > 65535) throw new TypeError('listenTcp: port must be an integer 0-65535');
185
+ if (typeof onConnection !== 'function') throw new TypeError('listenTcp: onConnection is required');
186
+ const id = this.#id();
187
+ const entry = { onConnection, path: '', closed: false, actualPort: 0 };
188
+ const answered = new Promise((resolve, reject) => {
189
+ entry.resolve = resolve; entry.reject = reject;
190
+ entry.timer = setTimeout(() => { this.#listeners.delete(id); reject(new GatewayError('the host did not answer the listen request in time', 5)); }, timeoutMs);
191
+ entry.timer.unref?.();
192
+ });
193
+ this.#listeners.set(id, entry);
194
+ try {
195
+ await this.#send(listenRequestMsg({ listenerId: id, port, ...(bindAddr === undefined ? {} : { bindAddr }) }));
196
+ await answered;
197
+ } catch (e) { this.#listeners.delete(id); throw e; }
198
+ return {
199
+ port: entry.actualPort,
200
+ close: async () => {
201
+ if (entry.closed) return;
202
+ entry.closed = true;
203
+ this.#listeners.delete(id);
204
+ await this.#send(listenCloseMsg({ listenerId: id })).catch(() => {});
205
+ },
206
+ };
152
207
  }
153
208
 
154
209
  /**
@@ -214,7 +269,7 @@ export class GatewayConnections {
214
269
  c.remoteClosed(m.reason);
215
270
  return true;
216
271
  }
217
- case MSG.LISTEN_OK: { const l = this.#listeners.get(m.listener_id); if (!l?.resolve) return false; clearTimeout(l.timer); l.resolve(); l.resolve = undefined; return true; }
272
+ case MSG.LISTEN_OK: { const l = this.#listeners.get(m.listener_id); if (!l?.resolve) return false; clearTimeout(l.timer); l.actualPort = m.actual_port; l.resolve(); l.resolve = undefined; return true; }
218
273
  case MSG.LISTEN_FAIL: {
219
274
  const l = this.#listeners.get(m.listener_id);
220
275
  if (!l?.reject) return false;
@@ -232,7 +287,7 @@ export class GatewayConnections {
232
287
  const channel = this.#makeChannel(id);
233
288
  const duplex = this.#duplex(channel);
234
289
  void this.#send(inboundAcceptMsg({ channelId: m.channel_id, gatewayId: id })).then(() => {
235
- try { l.onConnection(duplex, { peer: m.peer_addr }); } catch { channel.destroy('handler error'); }
290
+ try { l.onConnection(duplex, { peer: m.peer_addr, peerPort: m.peer_port }); } catch { channel.destroy('handler error'); }
236
291
  }, () => channel.abandon());
237
292
  return true;
238
293
  }
@@ -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
 
@@ -1937,6 +1946,8 @@ export interface WshConnectReverseOptions {
1937
1946
  fs?: boolean;
1938
1947
  tools?: boolean;
1939
1948
  };
1949
+ /** List `operator-proof` in the registered capabilities (key logins only; default true): this peer can answer an operator's challenge. */
1950
+ operatorProof?: boolean;
1940
1951
  peerType?: string;
1941
1952
  shellBackend?: string;
1942
1953
  supportsAttach?: boolean;
@@ -2125,6 +2136,19 @@ export interface WshGatewayDuplex {
2125
2136
  closed: Promise<string | undefined>;
2126
2137
  }
2127
2138
 
2139
+ /** A UDP flow (`client.openUdp()`): one chunk = one datagram, and a datagram may be dropped without notice. */
2140
+ export interface WshUdpFlow extends WshGatewayDuplex {
2141
+ /** 'datagram': WebTransport datagrams. 'stream': the reliable control stream (WebSocket, or a host without `gateway-datagram`). */
2142
+ readonly transport: 'datagram' | 'stream';
2143
+ /** The largest payload that travels as one datagram right now (it can change; read it again). */
2144
+ readonly maxDatagramSize: number;
2145
+ /** 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'`). */
2146
+ send(bytes: Uint8Array): Promise<boolean>;
2147
+ stats: { sent: number; received: number; sentReliable: number; receivedReliable: number; sendDropped: number; receiveDropped: number };
2148
+ }
2149
+ /** Feature string for UDP over WebTransport datagrams. */
2150
+ export const GATEWAY_DATAGRAM_FEATURE: 'gateway-datagram';
2151
+
2128
2152
  /** A GatewayFail / ListenFail as an Error: `code` 4 = refused by the host's policy, 7 = too many connections, 1 = refused by the target. */
2129
2153
  export class GatewayError extends Error { code: number }
2130
2154
 
@@ -2232,8 +2256,14 @@ export class WshClient {
2232
2256
  openEndpoint(name: string, opts?: WshGatewayOpenOptions): Promise<WshGatewayDuplex>;
2233
2257
  /** Connect to host:port FROM THE HOST (needs the host feature `gateway`; refused unless its `gateway.allow` lists it). */
2234
2258
  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>;
2259
+ /**
2260
+ * A UDP flow to ONE destination, host:port, FROM THE HOST. Datagram semantics: any payload may be dropped. Over WebTransport, when the
2261
+ * host lists `gateway-datagram`, payloads are WebTransport datagrams (unordered, no retransmission, no head-of-line blocking between
2262
+ * flows); otherwise they ride the reliable control stream. A payload too big for one datagram goes on the control stream unless `oversize: 'drop'`.
2263
+ */
2264
+ openUdp(host: string, port: number, opts?: WshGatewayOpenOptions & { oversize?: 'reliable' | 'drop' }): Promise<WshUdpFlow>;
2265
+ /** 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. */
2266
+ listenTcp(port: number, opts: { bindAddr?: string; timeoutMs?: number; onConnection: (duplex: WshGatewayDuplex, info: { peer: string; peerPort: number }) => void }): Promise<{ port: number; close(): Promise<void> }>;
2237
2267
  /** Ask the host to listen on a unix-domain socket and hand each connection to `onConnection` (OpenSSH `-R`). */
2238
2268
  listenUnix(path: string, opts: { replace?: boolean; timeoutMs?: number; onConnection: (duplex: WshGatewayDuplex, info: { peer: string }) => void }): Promise<{ path: string; close(): Promise<void> }>;
2239
2269
  /**
@@ -2388,8 +2418,10 @@ export class WshClient {
2388
2418
  targetFingerprint: string,
2389
2419
  timeout?: number,
2390
2420
  opts?: {
2391
- /** `'auto'` (default): prove when the relay carries it and the peer asks; `false`: never; `true`: refuse if the relay cannot carry it. */
2421
+ /** `'auto'` (default): offer proof when the relay carries it and the peer's registered record lists `operator-proof`; `false`: never; `true`: offer regardless of the record (the relay still strips it for a peer that did not advertise it) and refuse if the relay cannot carry it. */
2392
2422
  proof?: 'auto' | boolean;
2423
+ /** The peer's capability list, when the caller already holds it (skips the `listPeers()` lookup `'auto'` makes). */
2424
+ peerCapabilities?: string[];
2393
2425
  /** Refuse the bridge unless the peer signed its challenge (so it proved its key to this operator). */
2394
2426
  requirePeerProof?: boolean;
2395
2427
  /**
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');