@johnhenry/wsh 0.36.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,307 @@
1
+ /**
2
+ * The client half of gateway forwarding: `openUnix`, `openEndpoint`, `openTcp` and `listenUnix` on `WshClient`.
3
+ * Browser-safe (no `node:*`): the connections are web streams with backpressure (see `gateway-channel.mjs`);
4
+ * `forward-node.mjs` builds the Node helper `client.forwardUnix()` on top.
5
+ *
6
+ * gateway_ids and listener_ids this client allocates start at 0x40000000, so they cannot collide with the small
7
+ * ids an application that drives the raw gateway messages itself (netway's `GatewayBackend`) hands out; messages for
8
+ * ids this class does not own go on to `client.onGatewayMessage`.
9
+ */
10
+
11
+ import {
12
+ MSG, openTcp as openTcpMsg, openUdp as openUdpMsg, listenRequest as listenRequestMsg, openUnix as openUnixMsg, openEndpoint as openEndpointMsg, listenUnix as listenUnixMsg,
13
+ listenClose as listenCloseMsg, inboundAccept as inboundAcceptMsg, inboundReject as inboundRejectMsg,
14
+ gatewayData as gatewayDataMsg, gatewayCredit as gatewayCreditMsg, gatewayClose as gatewayCloseMsg,
15
+ } from './messages.mjs';
16
+ import { GatewayChannel, GATEWAY_CREDIT_FEATURE } from './gateway-channel.mjs';
17
+ import { UdpFlow, decodeDatagram } from './gateway-datagram.mjs';
18
+
19
+ const ID_BASE = 0x40000000;
20
+ const ID_LIMIT = 0xffffffff;
21
+ const DEFAULT_TIMEOUT_MS = 30_000;
22
+ const CLIENT_GRACE_MS = 5_000;
23
+
24
+ /** An Error from a GatewayFail / ListenFail: `.code` is the GatewayFail code (4 = refused by policy), `.reason` the host's text. */
25
+ export class GatewayError extends Error {
26
+ constructor(message, code) {
27
+ super(message);
28
+ this.name = 'GatewayError';
29
+ this.code = code;
30
+ }
31
+ }
32
+
33
+ /**
34
+ * @typedef {object} GatewayDuplex
35
+ * @property {ReadableStream<Uint8Array>} readable what the peer sends; read it to keep the peer's credit coming
36
+ * @property {WritableStream<Uint8Array>} writable what you send; each write waits for credit
37
+ * @property {(reason?: string) => void} close half-close: nothing more will be written
38
+ * @property {(reason?: string) => void} destroy tear the connection down now
39
+ * @property {Promise<string | undefined>} closed settles when the connection is over
40
+ */
41
+
42
+ export class GatewayConnections {
43
+ #send;
44
+ #hasFeature;
45
+ #nextId = ID_BASE;
46
+ /** @type {Map<number, GatewayChannel>} */
47
+ #channels = new Map();
48
+ /** @type {Map<number, { channel: GatewayChannel, resolve: Function, reject: Function, timer: any }>} */
49
+ #opening = new Map();
50
+ /** @type {Map<number, { onConnection: Function, resolve?: Function, reject?: Function, timer?: any, path: string, closed: boolean }>} */
51
+ #listeners = new Map();
52
+
53
+ /**
54
+ * @param {object} o
55
+ * @param {(msg: object) => Promise<void>} o.send
56
+ * @param {(feature: string) => boolean} o.hasFeature
57
+ */
58
+ constructor({ send, hasFeature, datagrams = () => null }) {
59
+ this.#send = send;
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);
72
+ }
73
+
74
+ #id() {
75
+ if (this.#nextId >= ID_LIMIT) throw new Error('gateway ids exhausted on this connection');
76
+ return this.#nextId++;
77
+ }
78
+
79
+ #need(feature, what) {
80
+ if (!this.#hasFeature(feature)) throw new GatewayError(`this host does not support ${what} (it did not advertise "${feature}")`, 0);
81
+ }
82
+
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 } = {}) {
85
+ const channel = new GatewayChannel({
86
+ id,
87
+ credit: this.#hasFeature(GATEWAY_CREDIT_FEATURE),
88
+ // After the peer's GatewayClose the application has this long to finish writing (a half-open connection) before
89
+ // our side closes too, so a connection nobody closes does not stay in the table forever.
90
+ graceMs: CLIENT_GRACE_MS,
91
+ onRemoteClose: datagram ? () => channel.destroy() : undefined,
92
+ onData,
93
+ sendData: (data) => this.#send(gatewayDataMsg({ gatewayId: id, data })),
94
+ sendCredit: (n) => this.#send(gatewayCreditMsg({ gatewayId: id, bytes: n })),
95
+ sendClose: (reason) => this.#send(gatewayCloseMsg({ gatewayId: id, reason })),
96
+ onClose: () => { this.#channels.delete(id); this.#udp.delete(id); },
97
+ });
98
+ this.#channels.set(id, channel);
99
+ return channel;
100
+ }
101
+
102
+ #duplex(channel) {
103
+ const flow = this.#udp.get(channel.id);
104
+ if (flow) return flow;
105
+ const { readable, writable } = channel.streams();
106
+ return { readable, writable, close: (r) => channel.end(r), destroy: (r) => channel.destroy(r), closed: channel.closedPromise };
107
+ }
108
+
109
+ async #open(build, { timeoutMs = DEFAULT_TIMEOUT_MS, signal } = {}, kind) {
110
+ if (signal?.aborted) throw signal.reason ?? new DOMException('aborted', 'AbortError');
111
+ const id = this.#id();
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); }
115
+ const done = new Promise((resolve, reject) => {
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);
117
+ timer.unref?.();
118
+ this.#opening.set(id, { channel, resolve, reject, timer });
119
+ });
120
+ const onAbort = () => {
121
+ const o = this.#opening.get(id);
122
+ if (!o) return;
123
+ this.#opening.delete(id); clearTimeout(o.timer);
124
+ channel.destroy(); // the host's Ok, if it comes, finds nothing; its connection is closed by this GatewayClose
125
+ o.reject(signal.reason ?? new DOMException('aborted', 'AbortError'));
126
+ };
127
+ signal?.addEventListener('abort', onAbort, { once: true });
128
+ try {
129
+ await this.#send(build(id));
130
+ } catch (e) {
131
+ const o = this.#opening.get(id);
132
+ if (o) { clearTimeout(o.timer); this.#opening.delete(id); }
133
+ channel.abandon();
134
+ throw e;
135
+ }
136
+ try { return await done; } finally { signal?.removeEventListener('abort', onAbort); }
137
+ }
138
+
139
+ /** Connect to a unix-domain socket on the HOST. */
140
+ async openUnix(path, opts) {
141
+ this.#need('gateway-unix', 'unix-domain socket forwarding');
142
+ if (typeof path !== 'string' || !path) throw new TypeError('openUnix: path must be a non-empty string');
143
+ return this.#open((id) => openUnixMsg({ gatewayId: id, path }), opts);
144
+ }
145
+
146
+ /** Open a named virtual endpoint of the host. */
147
+ async openEndpoint(name, opts) {
148
+ this.#need('gateway-endpoints', 'named endpoints');
149
+ if (typeof name !== 'string' || !name) throw new TypeError('openEndpoint: name must be a non-empty string');
150
+ return this.#open((id) => openEndpointMsg({ gatewayId: id, name }), opts);
151
+ }
152
+
153
+ /** Connect to host:port FROM THE HOST (the gateway's TCP egress, subject to the host's allow list). */
154
+ async openTcp(host, port, opts) {
155
+ this.#need('gateway', 'TCP egress');
156
+ if (typeof host !== 'string' || !host || !Number.isInteger(port)) throw new TypeError('openTcp: host and port are required');
157
+ return this.#open((id) => openTcpMsg({ gatewayId: id, host, port }), opts);
158
+ }
159
+
160
+ /**
161
+ * A UDP "connection" to host:port FROM THE HOST: each chunk written is one datagram, each chunk read is one datagram
162
+ * (at most 65507 bytes). It rides the reliable control stream, so it is ordered and retransmitted; datagrams the
163
+ * receiving side cannot keep up with are dropped by the host. Same destination policy as TCP.
164
+ */
165
+ async openUdp(host, port, opts) {
166
+ this.#need('gateway', 'UDP egress');
167
+ if (typeof host !== 'string' || !host || !Number.isInteger(port)) throw new TypeError('openUdp: host and port are required');
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
+ };
207
+ }
208
+
209
+ /**
210
+ * Ask the host to listen on a unix-domain socket and hand each connection to `onConnection(duplex)`.
211
+ * @param {string} path
212
+ * @param {{ replace?: boolean, onConnection: (duplex: GatewayDuplex) => void, timeoutMs?: number }} opts
213
+ * @returns {Promise<{ path: string, close: () => Promise<void> }>}
214
+ */
215
+ async listenUnix(path, { replace, onConnection, timeoutMs = DEFAULT_TIMEOUT_MS } = {}) {
216
+ this.#need('gateway-unix', 'unix-domain socket forwarding');
217
+ if (typeof path !== 'string' || !path) throw new TypeError('listenUnix: path must be a non-empty string');
218
+ if (typeof onConnection !== 'function') throw new TypeError('listenUnix: onConnection is required');
219
+ const id = this.#id();
220
+ const entry = { onConnection, path, closed: false };
221
+ const answered = new Promise((resolve, reject) => {
222
+ entry.resolve = resolve; entry.reject = reject;
223
+ entry.timer = setTimeout(() => { this.#listeners.delete(id); reject(new GatewayError('the host did not answer the listen request in time', 5)); }, timeoutMs);
224
+ entry.timer.unref?.();
225
+ });
226
+ this.#listeners.set(id, entry);
227
+ try {
228
+ await this.#send(listenUnixMsg({ listenerId: id, path, replace: replace === true ? true : undefined }));
229
+ await answered;
230
+ } catch (e) { this.#listeners.delete(id); throw e; }
231
+ return {
232
+ path,
233
+ close: async () => {
234
+ if (entry.closed) return;
235
+ entry.closed = true;
236
+ this.#listeners.delete(id);
237
+ await this.#send(listenCloseMsg({ listenerId: id })).catch(() => {});
238
+ },
239
+ };
240
+ }
241
+
242
+ /** Feed a control message in. Returns true when it belonged to a connection or listener this object owns. */
243
+ handle(m) {
244
+ switch (m.type) {
245
+ case MSG.GATEWAY_OK: {
246
+ const o = this.#opening.get(m.gateway_id);
247
+ if (!o) return this.#channels.has(m.gateway_id);
248
+ this.#opening.delete(m.gateway_id);
249
+ clearTimeout(o.timer);
250
+ o.resolve(this.#duplex(o.channel));
251
+ return true;
252
+ }
253
+ case MSG.GATEWAY_FAIL: {
254
+ const o = this.#opening.get(m.gateway_id);
255
+ if (!o) return false;
256
+ this.#opening.delete(m.gateway_id);
257
+ clearTimeout(o.timer);
258
+ o.channel.abandon();
259
+ o.reject(new GatewayError(m.message || 'refused by the host', m.code));
260
+ return true;
261
+ }
262
+ case MSG.GATEWAY_DATA: { const c = this.#channels.get(m.gateway_id); if (!c) return false; c.receive(m.data); return true; }
263
+ case MSG.GATEWAY_CREDIT: { const c = this.#channels.get(m.gateway_id); if (!c) return false; c.grant(m.bytes); return true; }
264
+ case MSG.GATEWAY_CLOSE: {
265
+ const c = this.#channels.get(m.gateway_id);
266
+ if (!c) return false;
267
+ const o = this.#opening.get(m.gateway_id);
268
+ if (o) { this.#opening.delete(m.gateway_id); clearTimeout(o.timer); c.abandon(); o.reject(new GatewayError('closed by the host', 6)); return true; }
269
+ c.remoteClosed(m.reason);
270
+ return true;
271
+ }
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; }
273
+ case MSG.LISTEN_FAIL: {
274
+ const l = this.#listeners.get(m.listener_id);
275
+ if (!l?.reject) return false;
276
+ clearTimeout(l.timer);
277
+ this.#listeners.delete(m.listener_id);
278
+ l.reject(new GatewayError(m.reason || 'refused by the host', 4));
279
+ return true;
280
+ }
281
+ case MSG.INBOUND_OPEN: {
282
+ const l = this.#listeners.get(m.listener_id);
283
+ if (!l) return false;
284
+ if (l.closed) { void this.#send(inboundRejectMsg({ channelId: m.channel_id, reason: 'listener closed' })).catch(() => {}); return true; }
285
+ let id;
286
+ try { id = this.#id(); } catch { void this.#send(inboundRejectMsg({ channelId: m.channel_id, reason: 'out of ids' })).catch(() => {}); return true; }
287
+ const channel = this.#makeChannel(id);
288
+ const duplex = this.#duplex(channel);
289
+ void this.#send(inboundAcceptMsg({ channelId: m.channel_id, gatewayId: id })).then(() => {
290
+ try { l.onConnection(duplex, { peer: m.peer_addr, peerPort: m.peer_port }); } catch { channel.destroy('handler error'); }
291
+ }, () => channel.abandon());
292
+ return true;
293
+ }
294
+ default: return false;
295
+ }
296
+ }
297
+
298
+ /** The connection is gone: every open connection ends, every pending open fails. */
299
+ abandonAll(reason = 'connection closed') {
300
+ for (const o of this.#opening.values()) { clearTimeout(o.timer); o.reject(new GatewayError(reason, 6)); }
301
+ this.#opening.clear();
302
+ for (const l of this.#listeners.values()) { clearTimeout(l.timer); l.reject?.(new GatewayError(reason, 6)); }
303
+ this.#listeners.clear();
304
+ for (const c of [...this.#channels.values()]) c.abandon(reason);
305
+ this.#channels.clear();
306
+ }
307
+ }
@@ -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/host.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import type { WshSigner } from './index.js';
2
2
  import type {
3
- WshExecRunner, WshServerPtyOptions, WshServerMcpOptions, WshServerAuthOptions, WshServerPrincipal, WshAcceptableSocket, WshAcceptOptions,
3
+ WshExecRunner, WshServerPtyOptions, WshServerMcpOptions, WshServerAuthOptions, WshServerPrincipal, WshAcceptableSocket, WshAcceptOptions, WshClientEnv,
4
4
  } from './server/index.js';
5
5
 
6
6
  /**
@@ -41,7 +41,7 @@ export interface WshResolvedHostKey {
41
41
 
42
42
  export interface WshResolvedBackends {
43
43
  execRunner: WshExecRunner | null;
44
- execOptions: { timeoutMs?: number; clientEnv?: boolean };
44
+ execOptions: { timeoutMs?: number; clientEnv?: WshClientEnv };
45
45
  pty: { spawn: WshServerPtyOptions['spawn']; shell: string; cwd?: string; env?: Record<string, string | undefined>; term: string } | null;
46
46
  files: Required<Pick<WshFileBackend, 'operate' | 'readWhole' | 'writeWhole' | 'writeAt' | 'maxFileBytes'>> & Pick<WshFileBackend, 'openRange'> | null;
47
47
  mcp: object | null;
@@ -49,7 +49,7 @@ export interface WshResolvedBackends {
49
49
 
50
50
  /** Validate injected backends (no shell, no directory: `exec` is a function or `{ run }`, `fs` an object of operations). */
51
51
  export function resolveBackends(options?: {
52
- exec?: WshExecRunner | { run: WshExecRunner; timeoutMs?: number; clientEnv?: boolean };
52
+ exec?: WshExecRunner | { run: WshExecRunner; timeoutMs?: number; clientEnv?: WshClientEnv };
53
53
  pty?: WshServerPtyOptions;
54
54
  fs?: WshFileBackend;
55
55
  mcp?: WshServerMcpOptions;