@radheim/plugin-browser 0.0.0-stage → 2.4.3

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,1129 @@
1
+ export * as StreamMux from "./stream-mux.js";
2
+ import { randomBytes } from "node:crypto";
3
+ import { Duplex } from "node:stream";
4
+ import { EgressPolicy } from "./egress-policy.js";
5
+ import { StreamWire } from "./stream-wire.js";
6
+ import { BrowserTunnelHost } from "./tunnel-host.js";
7
+ const WS_OPEN = 1;
8
+ const MAX_INFLIGHT_WS_SENDS = 16;
9
+ const DRAIN_RETRY_MS = 4;
10
+ function resolveConfig(options) {
11
+ const streamWindowBytes = clamp(options.streamWindowBytes ?? StreamWire.DEFAULT_STREAM_WINDOW_BYTES, 4096, StreamWire.MAX_STREAM_WINDOW_BYTES);
12
+ const creditBatchBytes = Math.max(1, Math.min(options.creditBatchBytes ?? Math.min(256 * 1024, Math.floor(streamWindowBytes / 4)), streamWindowBytes));
13
+ const frameChunkBytes = clamp(options.frameChunkBytes ?? StreamWire.FRAME_DATA_CHUNK_BYTES, 1024, StreamWire.MAX_FRAME_PAYLOAD_BYTES);
14
+ const maxWsBufferedBytes = Math.max(frameChunkBytes, options.maxWsBufferedBytes ?? StreamWire.MAX_WS_BUFFERED_BYTES);
15
+ const maxStreams = Math.max(1, options.maxStreams ?? StreamWire.MAX_STREAMS_PER_ATTACHMENT);
16
+ const maxPendingConnects = Math.max(1, options.maxPendingConnects ?? StreamWire.MAX_PENDING_CONNECTS_PER_ATTACHMENT);
17
+ const maxAttachmentBufferedBytes = Math.max(streamWindowBytes, options.maxAttachmentBufferedBytes ?? StreamWire.MAX_ATTACHMENT_BUFFERED_BYTES);
18
+ const streamOutboundHighWaterBytes = Math.max(frameChunkBytes, options.streamOutboundHighWaterBytes ?? Math.min(256 * 1024, streamWindowBytes));
19
+ const streamOutboundLowWaterBytes = Math.max(frameChunkBytes, Math.floor(streamOutboundHighWaterBytes / 2));
20
+ const heartbeatIntervalMs = options.heartbeatIntervalMs ?? 25_000;
21
+ const heartbeatTimeoutMs = options.heartbeatTimeoutMs ?? 60_000;
22
+ const globalLimits = options.globalLimits ?? BrowserTunnelHost.defaultGlobalLimits;
23
+ return {
24
+ streamWindowBytes,
25
+ creditBatchBytes,
26
+ frameChunkBytes,
27
+ maxWsBufferedBytes,
28
+ maxStreams,
29
+ maxPendingConnects,
30
+ maxAttachmentBufferedBytes,
31
+ streamOutboundHighWaterBytes,
32
+ streamOutboundLowWaterBytes,
33
+ heartbeatIntervalMs,
34
+ heartbeatTimeoutMs,
35
+ globalLimits,
36
+ };
37
+ }
38
+ /**
39
+ * Single-writer frame scheduler:
40
+ * - Always drains priority control frames first (OPEN, OPENED, WINDOW_UPDATE, RESET, PING, PONG, GOAWAY).
41
+ * - Serves writable streams strictly round-robin, one bounded DATA frame per turn.
42
+ * - Never pushes DATA frames once `socket.bufferedAmount >= maxWsBufferedBytes`, preventing a bulk
43
+ * download from burying interactive HMR/control traffic inside the WebSocket library or TCP send buffer.
44
+ */
45
+ function createFrameWriter(socket, maxWsBufferedBytes, onWriteError) {
46
+ const controlQueue = [];
47
+ const roundRobin = [];
48
+ let closed = false;
49
+ let inFlightSends = 0;
50
+ let pumping = false;
51
+ let drainTimer;
52
+ const scheduleDrainCheck = () => {
53
+ if (closed || drainTimer)
54
+ return;
55
+ drainTimer = setTimeout(() => {
56
+ drainTimer = undefined;
57
+ pump();
58
+ }, DRAIN_RETRY_MS);
59
+ drainTimer.unref?.();
60
+ };
61
+ const pump = () => {
62
+ if (closed || pumping || socket.readyState !== WS_OPEN)
63
+ return;
64
+ pumping = true;
65
+ try {
66
+ while (!closed && socket.readyState === WS_OPEN && inFlightSends < MAX_INFLIGHT_WS_SENDS) {
67
+ const buffered = socket.bufferedAmount;
68
+ // Priority control frames (WINDOW_UPDATE, RESET, PING/PONG) may still transmit up to 2x cap
69
+ // so neither side can deadlock waiting for credits while DATA is paused.
70
+ if (controlQueue.length > 0 && (inFlightSends === 0 || buffered < maxWsBufferedBytes * 2)) {
71
+ const frame = controlQueue.shift();
72
+ sendOne(frame);
73
+ continue;
74
+ }
75
+ if (buffered >= maxWsBufferedBytes) {
76
+ scheduleDrainCheck();
77
+ break;
78
+ }
79
+ if (roundRobin.length === 0)
80
+ break;
81
+ const stream = roundRobin.shift();
82
+ stream.inRoundRobin = false;
83
+ const frame = stream.nextOutboundFrame();
84
+ if (stream.hasWritableOutput() && !stream.inRoundRobin) {
85
+ stream.inRoundRobin = true;
86
+ roundRobin.push(stream);
87
+ }
88
+ if (frame)
89
+ sendOne(frame);
90
+ }
91
+ }
92
+ finally {
93
+ pumping = false;
94
+ }
95
+ };
96
+ const sendOne = (frame) => {
97
+ inFlightSends += 1;
98
+ try {
99
+ socket.send(frame, (error) => {
100
+ inFlightSends = Math.max(0, inFlightSends - 1);
101
+ if (error && !closed) {
102
+ onWriteError(error);
103
+ return;
104
+ }
105
+ pump();
106
+ });
107
+ }
108
+ catch (error) {
109
+ inFlightSends = Math.max(0, inFlightSends - 1);
110
+ onWriteError(asError(error));
111
+ }
112
+ };
113
+ return {
114
+ enqueueControl(frame) {
115
+ if (closed)
116
+ return;
117
+ controlQueue.push(StreamWire.encodeFrame(frame));
118
+ pump();
119
+ },
120
+ markWritable(stream) {
121
+ if (closed || stream.inRoundRobin || !stream.hasWritableOutput())
122
+ return;
123
+ stream.inRoundRobin = true;
124
+ roundRobin.push(stream);
125
+ pump();
126
+ },
127
+ kick() {
128
+ pump();
129
+ },
130
+ close() {
131
+ closed = true;
132
+ controlQueue.length = 0;
133
+ roundRobin.length = 0;
134
+ if (drainTimer) {
135
+ clearTimeout(drainTimer);
136
+ drainTimer = undefined;
137
+ }
138
+ },
139
+ };
140
+ }
141
+ function startHeartbeat(socket, writer, intervalMs, timeoutMs, onTimeout) {
142
+ let lastHeard = Date.now();
143
+ const heard = () => {
144
+ lastHeard = Date.now();
145
+ };
146
+ const offPong = socket.onPong?.(heard);
147
+ let timer;
148
+ if (intervalMs > 0) {
149
+ timer = setInterval(() => {
150
+ if (Date.now() - lastHeard > timeoutMs) {
151
+ onTimeout();
152
+ return;
153
+ }
154
+ if (socket.readyState !== WS_OPEN)
155
+ return;
156
+ socket.ping?.();
157
+ writer.enqueueControl({ type: StreamWire.FrameType.PING, token: randomBytes(8) });
158
+ }, intervalMs);
159
+ timer.unref?.();
160
+ }
161
+ return {
162
+ heard,
163
+ stop() {
164
+ if (timer) {
165
+ clearInterval(timer);
166
+ timer = undefined;
167
+ }
168
+ offPong?.();
169
+ },
170
+ };
171
+ }
172
+ /**
173
+ * Server-side multiplexed stream owner bound to one live desktop browser attachment.
174
+ * Enforces egress policy, per-attachment and cross-attachment caps, credit-based flow control,
175
+ * half-close, RESET cancellation, and clean teardown of every owned target TCP socket on close.
176
+ */
177
+ export function createServerMux(socket, options) {
178
+ const cfg = resolveConfig(options);
179
+ const connectTarget = options.connect ?? EgressPolicy.resolveAndConnect;
180
+ const closedDeferred = Promise.withResolvers();
181
+ let closed = false;
182
+ let attachmentBytes = 0;
183
+ let pendingConnects = 0;
184
+ const streams = new Map();
185
+ const reserveBytes = (bytes) => {
186
+ if (bytes <= 0)
187
+ return true;
188
+ if (attachmentBytes + bytes > cfg.maxAttachmentBufferedBytes)
189
+ return false;
190
+ if (!cfg.globalLimits.tryReserveBytes(bytes))
191
+ return false;
192
+ attachmentBytes += bytes;
193
+ return true;
194
+ };
195
+ const releaseBytes = (bytes) => {
196
+ if (bytes <= 0)
197
+ return;
198
+ attachmentBytes = Math.max(0, attachmentBytes - bytes);
199
+ cfg.globalLimits.releaseBytes(bytes);
200
+ };
201
+ const writer = createFrameWriter(socket, cfg.maxWsBufferedBytes, () => {
202
+ shutdown(1006, "write failed", false);
203
+ });
204
+ const heartbeat = startHeartbeat(socket, writer, cfg.heartbeatIntervalMs, cfg.heartbeatTimeoutMs, () => {
205
+ shutdown(1001, "heartbeat timeout", true);
206
+ });
207
+ const cleanupStream = (stream, sendReset) => {
208
+ if (stream.status === "closed")
209
+ return;
210
+ const wasConnecting = stream.status === "connecting";
211
+ stream.status = "closed";
212
+ streams.delete(stream.id);
213
+ cfg.globalLimits.releaseStream();
214
+ if (wasConnecting) {
215
+ pendingConnects = Math.max(0, pendingConnects - 1);
216
+ cfg.globalLimits.releasePendingConnect();
217
+ stream.connectAbort.abort();
218
+ }
219
+ if (stream.inboundPendingBytes > 0) {
220
+ releaseBytes(stream.inboundPendingBytes);
221
+ stream.inboundPendingBytes = 0;
222
+ }
223
+ if (stream.outboundBytes > 0) {
224
+ releaseBytes(stream.outboundBytes);
225
+ stream.outboundBytes = 0;
226
+ }
227
+ stream.outboundChunks.length = 0;
228
+ stream.outboundOffset = 0;
229
+ stream.target?.destroy();
230
+ stream.target = undefined;
231
+ if (sendReset && !closed) {
232
+ writer.enqueueControl({
233
+ type: StreamWire.FrameType.RESET,
234
+ streamID: stream.id,
235
+ code: sendReset.code,
236
+ reason: sendReset.reason,
237
+ });
238
+ }
239
+ };
240
+ const maybeFinishStream = (stream) => {
241
+ if (stream.status === "open" && stream.inboundFinReceived && stream.outboundFinSent) {
242
+ cleanupStream(stream);
243
+ }
244
+ };
245
+ const protocolFail = (reason) => {
246
+ if (closed)
247
+ return;
248
+ writer.enqueueControl({ type: StreamWire.FrameType.GOAWAY, code: StreamWire.ResetCode.PROTOCOL_ERROR, reason });
249
+ shutdown(1002, reason, false);
250
+ };
251
+ const handleOpen = (frame) => {
252
+ if (streams.has(frame.streamID)) {
253
+ protocolFail(`Duplicate streamID ${frame.streamID}.`);
254
+ return;
255
+ }
256
+ if (streams.size >= cfg.maxStreams || pendingConnects >= cfg.maxPendingConnects) {
257
+ writer.enqueueControl({
258
+ type: StreamWire.FrameType.RESET,
259
+ streamID: frame.streamID,
260
+ code: StreamWire.ResetCode.LIMIT_EXCEEDED,
261
+ reason: "Browser attachment stream limit exceeded.",
262
+ });
263
+ return;
264
+ }
265
+ if (!cfg.globalLimits.tryAcquireStream()) {
266
+ writer.enqueueControl({
267
+ type: StreamWire.FrameType.RESET,
268
+ streamID: frame.streamID,
269
+ code: StreamWire.ResetCode.LIMIT_EXCEEDED,
270
+ reason: "Server browser stream capacity reached.",
271
+ });
272
+ return;
273
+ }
274
+ if (!cfg.globalLimits.tryAcquirePendingConnect()) {
275
+ cfg.globalLimits.releaseStream();
276
+ writer.enqueueControl({
277
+ type: StreamWire.FrameType.RESET,
278
+ streamID: frame.streamID,
279
+ code: StreamWire.ResetCode.LIMIT_EXCEEDED,
280
+ reason: "Server pending connect capacity reached.",
281
+ });
282
+ return;
283
+ }
284
+ pendingConnects += 1;
285
+ const stream = {
286
+ id: frame.streamID,
287
+ status: "connecting",
288
+ connectAbort: new AbortController(),
289
+ sendWindow: frame.initialWindow,
290
+ recvWindow: cfg.streamWindowBytes,
291
+ consumedSinceCredit: 0,
292
+ inboundPendingBytes: 0,
293
+ outboundChunks: [],
294
+ outboundOffset: 0,
295
+ outboundBytes: 0,
296
+ outboundFinPending: false,
297
+ outboundFinSent: false,
298
+ inboundFinReceived: false,
299
+ paused: false,
300
+ inRoundRobin: false,
301
+ hasWritableOutput() {
302
+ if (stream.status !== "open")
303
+ return false;
304
+ if (stream.outboundBytes > 0 && stream.sendWindow > 0)
305
+ return true;
306
+ return stream.outboundBytes === 0 && stream.outboundFinPending && !stream.outboundFinSent;
307
+ },
308
+ nextOutboundFrame() {
309
+ if (stream.status !== "open")
310
+ return undefined;
311
+ if (stream.outboundBytes > 0 && stream.sendWindow > 0) {
312
+ const maxTake = Math.min(cfg.frameChunkBytes, stream.sendWindow);
313
+ const slice = takeChunk(stream.outboundChunks, stream.outboundOffset, maxTake);
314
+ stream.outboundOffset = slice.nextOffset;
315
+ stream.outboundBytes -= slice.bytes.byteLength;
316
+ stream.sendWindow -= slice.bytes.byteLength;
317
+ releaseBytes(slice.bytes.byteLength);
318
+ if (stream.paused && stream.outboundBytes <= cfg.streamOutboundLowWaterBytes && stream.sendWindow > 0) {
319
+ stream.paused = false;
320
+ stream.target?.resume();
321
+ }
322
+ return StreamWire.encodeFrame({
323
+ type: StreamWire.FrameType.DATA,
324
+ streamID: stream.id,
325
+ data: slice.bytes,
326
+ });
327
+ }
328
+ if (stream.outboundBytes === 0 && stream.outboundFinPending && !stream.outboundFinSent) {
329
+ stream.outboundFinSent = true;
330
+ const encoded = StreamWire.encodeFrame({ type: StreamWire.FrameType.FIN, streamID: stream.id });
331
+ maybeFinishStream(stream);
332
+ return encoded;
333
+ }
334
+ return undefined;
335
+ },
336
+ };
337
+ streams.set(stream.id, stream);
338
+ void connectTarget({ host: frame.host, port: frame.port }, options.policy, { signal: stream.connectAbort.signal, timeoutMs: options.connectTimeoutMs ?? 10_000 }).then((targetSocket) => {
339
+ if (closed || stream.status !== "connecting") {
340
+ targetSocket.destroy();
341
+ return;
342
+ }
343
+ pendingConnects = Math.max(0, pendingConnects - 1);
344
+ cfg.globalLimits.releasePendingConnect();
345
+ stream.status = "open";
346
+ stream.target = targetSocket;
347
+ writer.enqueueControl({
348
+ type: StreamWire.FrameType.OPENED,
349
+ streamID: stream.id,
350
+ initialWindow: stream.recvWindow,
351
+ });
352
+ targetSocket.on("data", (chunk) => {
353
+ if (closed || stream.status !== "open")
354
+ return;
355
+ const copy = new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength).slice();
356
+ if (!reserveBytes(copy.byteLength)) {
357
+ cleanupStream(stream, {
358
+ code: StreamWire.ResetCode.LIMIT_EXCEEDED,
359
+ reason: "Attachment buffer limit exceeded.",
360
+ });
361
+ return;
362
+ }
363
+ stream.outboundChunks.push(copy);
364
+ stream.outboundBytes += copy.byteLength;
365
+ if (stream.outboundBytes >= cfg.streamOutboundHighWaterBytes || stream.sendWindow === 0) {
366
+ stream.paused = true;
367
+ targetSocket.pause();
368
+ }
369
+ writer.markWritable(stream);
370
+ });
371
+ targetSocket.once("end", () => {
372
+ if (closed || stream.status !== "open")
373
+ return;
374
+ stream.outboundFinPending = true;
375
+ writer.markWritable(stream);
376
+ });
377
+ targetSocket.on("error", (error) => {
378
+ if (closed || stream.status !== "open")
379
+ return;
380
+ cleanupStream(stream, { code: StreamWire.ResetCode.INTERNAL_ERROR, reason: error.message.slice(0, 200) });
381
+ });
382
+ targetSocket.once("close", (hadError) => {
383
+ if (closed || stream.status !== "open")
384
+ return;
385
+ if (hadError) {
386
+ cleanupStream(stream, { code: StreamWire.ResetCode.INTERNAL_ERROR, reason: "Target socket closed with error." });
387
+ return;
388
+ }
389
+ if (!stream.outboundFinPending && !stream.outboundFinSent) {
390
+ stream.outboundFinPending = true;
391
+ writer.markWritable(stream);
392
+ }
393
+ });
394
+ }, (cause) => {
395
+ if (closed || stream.status !== "connecting")
396
+ return;
397
+ const error = asError(cause);
398
+ const code = error instanceof EgressPolicy.EgressDeniedError
399
+ ? StreamWire.ResetCode.POLICY_DENIED
400
+ : StreamWire.ResetCode.CONNECT_FAILED;
401
+ cleanupStream(stream, { code, reason: error.message.slice(0, 200) });
402
+ });
403
+ };
404
+ const handleData = (frame) => {
405
+ const stream = streams.get(frame.streamID);
406
+ if (!stream)
407
+ return;
408
+ if (stream.status !== "open" || !stream.target || stream.inboundFinReceived) {
409
+ cleanupStream(stream, { code: StreamWire.ResetCode.PROTOCOL_ERROR, reason: "DATA on non-writable stream." });
410
+ return;
411
+ }
412
+ const len = frame.data.byteLength;
413
+ if (len > stream.recvWindow) {
414
+ cleanupStream(stream, { code: StreamWire.ResetCode.PROTOCOL_ERROR, reason: "Stream receive window exceeded." });
415
+ return;
416
+ }
417
+ if (!reserveBytes(len)) {
418
+ cleanupStream(stream, { code: StreamWire.ResetCode.LIMIT_EXCEEDED, reason: "Attachment inbound buffer limit exceeded." });
419
+ return;
420
+ }
421
+ stream.recvWindow -= len;
422
+ stream.inboundPendingBytes += len;
423
+ let drained = false;
424
+ // Never block the shared WS reader: hand bytes to target TCP socket and replenish credits
425
+ // in batches once the target socket drains them.
426
+ stream.target.write(frame.data, (error) => {
427
+ if (drained)
428
+ return;
429
+ drained = true;
430
+ if (stream.inboundPendingBytes >= len) {
431
+ stream.inboundPendingBytes -= len;
432
+ releaseBytes(len);
433
+ }
434
+ if (closed || stream.status !== "open")
435
+ return;
436
+ if (error) {
437
+ cleanupStream(stream, { code: StreamWire.ResetCode.INTERNAL_ERROR, reason: error.message.slice(0, 200) });
438
+ return;
439
+ }
440
+ stream.consumedSinceCredit += len;
441
+ if (!stream.inboundFinReceived && stream.consumedSinceCredit >= cfg.creditBatchBytes) {
442
+ const delta = stream.consumedSinceCredit;
443
+ stream.consumedSinceCredit = 0;
444
+ stream.recvWindow += delta;
445
+ writer.enqueueControl({ type: StreamWire.FrameType.WINDOW_UPDATE, streamID: stream.id, delta });
446
+ }
447
+ });
448
+ };
449
+ const handleWindowUpdate = (frame) => {
450
+ const stream = streams.get(frame.streamID);
451
+ if (!stream || stream.status === "closed")
452
+ return;
453
+ if (stream.sendWindow + frame.delta > StreamWire.MAX_STREAM_WINDOW_BYTES) {
454
+ cleanupStream(stream, { code: StreamWire.ResetCode.PROTOCOL_ERROR, reason: "Send window overflow." });
455
+ return;
456
+ }
457
+ stream.sendWindow += frame.delta;
458
+ if (stream.status === "open") {
459
+ writer.markWritable(stream);
460
+ if (stream.paused && stream.outboundBytes <= cfg.streamOutboundLowWaterBytes && stream.sendWindow > 0) {
461
+ stream.paused = false;
462
+ stream.target?.resume();
463
+ }
464
+ }
465
+ };
466
+ const handleFin = (frame) => {
467
+ const stream = streams.get(frame.streamID);
468
+ if (!stream || stream.status !== "open" || !stream.target)
469
+ return;
470
+ if (stream.inboundFinReceived)
471
+ return;
472
+ stream.inboundFinReceived = true;
473
+ stream.target.end();
474
+ maybeFinishStream(stream);
475
+ };
476
+ const handleReset = (frame) => {
477
+ const stream = streams.get(frame.streamID);
478
+ if (!stream)
479
+ return;
480
+ cleanupStream(stream);
481
+ };
482
+ const offMessage = socket.onMessage((raw) => {
483
+ if (closed)
484
+ return;
485
+ heartbeat.heard();
486
+ if (typeof raw === "string") {
487
+ protocolFail("Text WebSocket frames are not permitted on browser stream tunnel.");
488
+ return;
489
+ }
490
+ let frame;
491
+ try {
492
+ frame = StreamWire.decodeFrame(raw);
493
+ }
494
+ catch (error) {
495
+ protocolFail(asError(error).message);
496
+ return;
497
+ }
498
+ switch (frame.type) {
499
+ case StreamWire.FrameType.OPEN:
500
+ handleOpen(frame);
501
+ return;
502
+ case StreamWire.FrameType.DATA:
503
+ handleData(frame);
504
+ return;
505
+ case StreamWire.FrameType.WINDOW_UPDATE:
506
+ handleWindowUpdate(frame);
507
+ return;
508
+ case StreamWire.FrameType.FIN:
509
+ handleFin(frame);
510
+ return;
511
+ case StreamWire.FrameType.RESET:
512
+ handleReset(frame);
513
+ return;
514
+ case StreamWire.FrameType.PING:
515
+ writer.enqueueControl({ type: StreamWire.FrameType.PONG, token: frame.token });
516
+ return;
517
+ case StreamWire.FrameType.PONG:
518
+ return;
519
+ case StreamWire.FrameType.GOAWAY:
520
+ shutdown(1000, frame.reason || "peer goaway", false);
521
+ return;
522
+ case StreamWire.FrameType.OPENED:
523
+ protocolFail("Client may not send OPENED frames.");
524
+ return;
525
+ }
526
+ });
527
+ const offClose = socket.onClose((code, reason) => {
528
+ shutdown(code, reason, false);
529
+ });
530
+ const offError = socket.onError((error) => {
531
+ shutdown(1006, error.message, true);
532
+ });
533
+ function shutdown(code, reason, terminate) {
534
+ if (closed)
535
+ return;
536
+ closed = true;
537
+ heartbeat.stop();
538
+ offMessage();
539
+ offClose();
540
+ offError();
541
+ for (const stream of Array.from(streams.values())) {
542
+ cleanupStream(stream);
543
+ }
544
+ writer.close();
545
+ try {
546
+ if (terminate)
547
+ socket.terminate();
548
+ else if (socket.readyState === WS_OPEN)
549
+ socket.close(code, reason.slice(0, 120));
550
+ }
551
+ catch {
552
+ // Socket may already be closing or destroyed.
553
+ }
554
+ closedDeferred.resolve({
555
+ code,
556
+ reason,
557
+ replaced: code === BrowserTunnelHost.CLOSE_ATTACHMENT_REPLACED,
558
+ });
559
+ }
560
+ return {
561
+ closed: closedDeferred.promise,
562
+ activeStreams: () => streams.size,
563
+ bufferedBytes: () => attachmentBytes,
564
+ close(code = BrowserTunnelHost.CLOSE_ATTACHMENT_CLOSED, reason = "attachment closed") {
565
+ if (closed)
566
+ return;
567
+ if (socket.readyState === WS_OPEN) {
568
+ try {
569
+ socket.send(StreamWire.encodeFrame({
570
+ type: StreamWire.FrameType.GOAWAY,
571
+ code: StreamWire.ResetCode.ATTACHMENT_CLOSED,
572
+ reason,
573
+ }));
574
+ }
575
+ catch {
576
+ // Best-effort GOAWAY before closing.
577
+ }
578
+ }
579
+ shutdown(code, reason, false);
580
+ },
581
+ };
582
+ }
583
+ /**
584
+ * Desktop-side multiplexed stream client bound to one prewarmed binary WebSocket.
585
+ * Returns standard Node `Duplex` sockets per target TCP connection with end-to-end
586
+ * credit backpressure, half-close, RESET cancellation, and zero automatic replay of writes.
587
+ */
588
+ export function createClientMux(socket, options = {}) {
589
+ const cfg = resolveConfig({
590
+ streamWindowBytes: StreamWire.DEFAULT_CLIENT_STREAM_WINDOW_BYTES,
591
+ ...options,
592
+ });
593
+ const closedDeferred = Promise.withResolvers();
594
+ let closed = false;
595
+ let closeReason = "Browser tunnel disconnected.";
596
+ let nextStreamID = 1;
597
+ let attachmentBytes = 0;
598
+ let pendingConnects = 0;
599
+ const streams = new Map();
600
+ const reserveBytes = (bytes) => {
601
+ if (bytes <= 0)
602
+ return true;
603
+ if (attachmentBytes + bytes > cfg.maxAttachmentBufferedBytes)
604
+ return false;
605
+ attachmentBytes += bytes;
606
+ return true;
607
+ };
608
+ const releaseBytes = (bytes) => {
609
+ if (bytes <= 0)
610
+ return;
611
+ attachmentBytes = Math.max(0, attachmentBytes - bytes);
612
+ };
613
+ const writer = createFrameWriter(socket, cfg.maxWsBufferedBytes, (error) => {
614
+ shutdown(1006, error.message, true);
615
+ });
616
+ const heartbeat = startHeartbeat(socket, writer, cfg.heartbeatIntervalMs, cfg.heartbeatTimeoutMs, () => {
617
+ shutdown(1001, "Browser tunnel heartbeat timed out.", true);
618
+ });
619
+ const cleanupStream = (stream, input = {}) => {
620
+ if (stream.status === "closed")
621
+ return;
622
+ const wasOpening = stream.status === "opening";
623
+ stream.status = "closed";
624
+ streams.delete(stream.id);
625
+ if (wasOpening)
626
+ pendingConnects = Math.max(0, pendingConnects - 1);
627
+ if (stream.outboundBytes > 0) {
628
+ releaseBytes(stream.outboundBytes);
629
+ stream.outboundBytes = 0;
630
+ }
631
+ if (stream.inboundBytes > 0) {
632
+ releaseBytes(stream.inboundBytes);
633
+ stream.inboundBytes = 0;
634
+ }
635
+ stream.outboundChunks.length = 0;
636
+ stream.outboundOffset = 0;
637
+ stream.inboundChunks.length = 0;
638
+ const writeResume = stream.writeResume;
639
+ stream.writeResume = undefined;
640
+ const finalCallback = stream.finalCallback;
641
+ stream.finalCallback = undefined;
642
+ if (input.sendReset !== undefined && !closed) {
643
+ writer.enqueueControl({
644
+ type: StreamWire.FrameType.RESET,
645
+ streamID: stream.id,
646
+ code: input.sendReset,
647
+ reason: input.resetReason ?? "",
648
+ });
649
+ }
650
+ if (wasOpening) {
651
+ stream.opened.reject(input.error ?? new Error("Browser tunnel stream closed while opening."));
652
+ }
653
+ const duplex = stream.duplex;
654
+ stream.duplex = undefined;
655
+ const streamError = input.error ?? new Error("Browser tunnel stream closed.");
656
+ if (input.normalClose) {
657
+ // Destroy first so Node/Bun never emit an uncaught async 'error' event on idle or unpiped sockets,
658
+ // then settle any outstanding write/FIN callbacks with the cancellation error so discarded bytes
659
+ // are never reported as delivered.
660
+ if (duplex && !duplex.destroyed)
661
+ duplex.destroy();
662
+ if (writeResume)
663
+ writeResume(streamError);
664
+ if (finalCallback)
665
+ finalCallback(streamError);
666
+ return;
667
+ }
668
+ if (duplex && !duplex.destroyed) {
669
+ // Settle pending write/final callbacks with the genuine error before destroying, or destroy with error.
670
+ if (writeResume)
671
+ writeResume(streamError);
672
+ if (finalCallback)
673
+ finalCallback(streamError);
674
+ if (!duplex.destroyed) {
675
+ if (input.error && duplex.listenerCount("error") > 0)
676
+ duplex.destroy(input.error);
677
+ else
678
+ duplex.destroy();
679
+ }
680
+ return;
681
+ }
682
+ if (writeResume)
683
+ writeResume(streamError);
684
+ if (finalCallback)
685
+ finalCallback(streamError);
686
+ };
687
+ const maybeFinishStream = (stream) => {
688
+ if (stream.status === "open" && stream.inboundFinReceived && stream.inboundBytes === 0 && stream.outboundFinSent) {
689
+ stream.status = "closed";
690
+ streams.delete(stream.id);
691
+ }
692
+ };
693
+ class StreamDuplex extends Duplex {
694
+ stream;
695
+ connecting = false;
696
+ reading = false;
697
+ idleTimer;
698
+ constructor(stream) {
699
+ super({ highWaterMark: cfg.frameChunkBytes * 4, allowHalfOpen: true });
700
+ this.stream = stream;
701
+ }
702
+ drainInbound() {
703
+ if (!this.reading || this.destroyed)
704
+ return;
705
+ while (this.stream.inboundChunks.length > 0) {
706
+ const chunk = this.stream.inboundChunks.shift();
707
+ this.stream.inboundBytes -= chunk.byteLength;
708
+ releaseBytes(chunk.byteLength);
709
+ this.stream.consumedSinceCredit += chunk.byteLength;
710
+ if (!this.stream.inboundFinReceived && this.stream.consumedSinceCredit >= cfg.creditBatchBytes) {
711
+ const delta = this.stream.consumedSinceCredit;
712
+ this.stream.consumedSinceCredit = 0;
713
+ this.stream.recvWindow += delta;
714
+ writer.enqueueControl({
715
+ type: StreamWire.FrameType.WINDOW_UPDATE,
716
+ streamID: this.stream.id,
717
+ delta,
718
+ });
719
+ }
720
+ const more = this.push(chunk);
721
+ if (!more) {
722
+ this.reading = false;
723
+ return;
724
+ }
725
+ }
726
+ if (this.stream.inboundFinReceived) {
727
+ this.reading = false;
728
+ this.push(null);
729
+ maybeFinishStream(this.stream);
730
+ }
731
+ }
732
+ _read() {
733
+ this.reading = true;
734
+ this.drainInbound();
735
+ }
736
+ _write(chunk, encoding, callback) {
737
+ if (closed || this.stream.status !== "open") {
738
+ callback(new Error(closeReason));
739
+ return;
740
+ }
741
+ const data = typeof chunk === "string" ? Buffer.from(chunk, encoding) : chunk;
742
+ if (data.byteLength === 0) {
743
+ callback();
744
+ return;
745
+ }
746
+ if (!reserveBytes(data.byteLength)) {
747
+ const error = new Error("Browser tunnel attachment buffer limit exceeded.");
748
+ cleanupStream(this.stream, { error, sendReset: StreamWire.ResetCode.LIMIT_EXCEEDED });
749
+ callback(error);
750
+ return;
751
+ }
752
+ const copy = new Uint8Array(data.buffer, data.byteOffset, data.byteLength).slice();
753
+ this.stream.outboundChunks.push(copy);
754
+ this.stream.outboundBytes += copy.byteLength;
755
+ writer.markWritable(this.stream);
756
+ if (this.stream.outboundBytes >= cfg.streamOutboundHighWaterBytes) {
757
+ this.stream.writeResume = callback;
758
+ return;
759
+ }
760
+ callback();
761
+ }
762
+ _final(callback) {
763
+ if (closed || this.stream.status !== "open") {
764
+ callback(new Error(closeReason));
765
+ return;
766
+ }
767
+ this.stream.outboundFinPending = true;
768
+ this.stream.finalCallback = callback;
769
+ writer.markWritable(this.stream);
770
+ }
771
+ _destroy(error, callback) {
772
+ if (this.idleTimer) {
773
+ clearTimeout(this.idleTimer);
774
+ this.idleTimer = undefined;
775
+ }
776
+ if (this.stream.status !== "closed") {
777
+ const clean = this.stream.inboundFinReceived && this.stream.inboundBytes === 0 && this.stream.outboundFinSent;
778
+ cleanupStream(this.stream, {
779
+ error: error ?? undefined,
780
+ sendReset: clean ? undefined : StreamWire.ResetCode.CANCELLED,
781
+ });
782
+ }
783
+ callback(error);
784
+ }
785
+ setKeepAlive() {
786
+ return this;
787
+ }
788
+ setNoDelay() {
789
+ return this;
790
+ }
791
+ setTimeout(timeout, callback) {
792
+ if (this.idleTimer) {
793
+ clearTimeout(this.idleTimer);
794
+ this.idleTimer = undefined;
795
+ }
796
+ if (timeout === 0) {
797
+ if (callback)
798
+ this.off("timeout", callback);
799
+ return this;
800
+ }
801
+ if (callback)
802
+ this.once("timeout", callback);
803
+ this.idleTimer = setTimeout(() => {
804
+ this.idleTimer = undefined;
805
+ this.emit("timeout");
806
+ }, timeout);
807
+ this.idleTimer.unref?.();
808
+ return this;
809
+ }
810
+ ref() {
811
+ return this;
812
+ }
813
+ unref() {
814
+ return this;
815
+ }
816
+ }
817
+ const protocolFail = (reason) => {
818
+ if (closed)
819
+ return;
820
+ writer.enqueueControl({ type: StreamWire.FrameType.GOAWAY, code: StreamWire.ResetCode.PROTOCOL_ERROR, reason });
821
+ shutdown(1002, reason, true);
822
+ };
823
+ const offMessage = socket.onMessage((raw) => {
824
+ if (closed)
825
+ return;
826
+ heartbeat.heard();
827
+ if (typeof raw === "string") {
828
+ protocolFail("Server sent text frame on binary browser stream tunnel.");
829
+ return;
830
+ }
831
+ let frame;
832
+ try {
833
+ frame = StreamWire.decodeFrame(raw);
834
+ }
835
+ catch (error) {
836
+ protocolFail(asError(error).message);
837
+ return;
838
+ }
839
+ switch (frame.type) {
840
+ case StreamWire.FrameType.OPENED: {
841
+ const stream = streams.get(frame.streamID);
842
+ if (!stream || stream.status !== "opening")
843
+ return;
844
+ pendingConnects = Math.max(0, pendingConnects - 1);
845
+ stream.status = "open";
846
+ stream.sendWindow = frame.initialWindow;
847
+ const duplex = new StreamDuplex(stream);
848
+ stream.duplex = duplex;
849
+ stream.opened.resolve(duplex);
850
+ return;
851
+ }
852
+ case StreamWire.FrameType.DATA: {
853
+ const stream = streams.get(frame.streamID);
854
+ if (!stream || stream.status !== "open" || !stream.duplex)
855
+ return;
856
+ if (stream.inboundFinReceived) {
857
+ cleanupStream(stream, {
858
+ error: new Error("Server sent DATA after FIN."),
859
+ sendReset: StreamWire.ResetCode.PROTOCOL_ERROR,
860
+ });
861
+ return;
862
+ }
863
+ const len = frame.data.byteLength;
864
+ if (len > stream.recvWindow) {
865
+ cleanupStream(stream, {
866
+ error: new Error("Server exceeded stream receive window."),
867
+ sendReset: StreamWire.ResetCode.PROTOCOL_ERROR,
868
+ });
869
+ return;
870
+ }
871
+ if (!reserveBytes(len)) {
872
+ cleanupStream(stream, {
873
+ error: new Error("Attachment receive buffer exceeded."),
874
+ sendReset: StreamWire.ResetCode.LIMIT_EXCEEDED,
875
+ });
876
+ return;
877
+ }
878
+ stream.recvWindow -= len;
879
+ stream.inboundChunks.push(frame.data);
880
+ stream.inboundBytes += len;
881
+ stream.duplex.drainInbound();
882
+ return;
883
+ }
884
+ case StreamWire.FrameType.WINDOW_UPDATE: {
885
+ const stream = streams.get(frame.streamID);
886
+ if (!stream || stream.status !== "open")
887
+ return;
888
+ if (stream.sendWindow + frame.delta > StreamWire.MAX_STREAM_WINDOW_BYTES) {
889
+ cleanupStream(stream, {
890
+ error: new Error("Server sent overflowing WINDOW_UPDATE."),
891
+ sendReset: StreamWire.ResetCode.PROTOCOL_ERROR,
892
+ });
893
+ return;
894
+ }
895
+ stream.sendWindow += frame.delta;
896
+ writer.markWritable(stream);
897
+ return;
898
+ }
899
+ case StreamWire.FrameType.FIN: {
900
+ const stream = streams.get(frame.streamID);
901
+ if (!stream || stream.status !== "open" || !stream.duplex)
902
+ return;
903
+ stream.inboundFinReceived = true;
904
+ stream.duplex.drainInbound();
905
+ return;
906
+ }
907
+ case StreamWire.FrameType.RESET: {
908
+ const stream = streams.get(frame.streamID);
909
+ if (!stream)
910
+ return;
911
+ const message = frame.reason || resetCodeMessage(frame.code);
912
+ cleanupStream(stream, { error: new Error(message) });
913
+ return;
914
+ }
915
+ case StreamWire.FrameType.PING:
916
+ writer.enqueueControl({ type: StreamWire.FrameType.PONG, token: frame.token });
917
+ return;
918
+ case StreamWire.FrameType.PONG:
919
+ return;
920
+ case StreamWire.FrameType.GOAWAY: {
921
+ const code = frame.reason === "replaced"
922
+ ? BrowserTunnelHost.CLOSE_ATTACHMENT_REPLACED
923
+ : BrowserTunnelHost.CLOSE_ATTACHMENT_CLOSED;
924
+ shutdown(code, frame.reason || "Browser tunnel closed by server.", false);
925
+ return;
926
+ }
927
+ case StreamWire.FrameType.OPEN:
928
+ protocolFail("Server may not send OPEN frames.");
929
+ return;
930
+ }
931
+ });
932
+ const offClose = socket.onClose((code, reason) => {
933
+ shutdown(code, reason || "Browser tunnel closed.", false);
934
+ });
935
+ const offError = socket.onError((error) => {
936
+ shutdown(1006, error.message || "Browser tunnel socket error.", true);
937
+ });
938
+ function shutdown(code, reason, terminate, normalClose = false) {
939
+ if (closed)
940
+ return;
941
+ closed = true;
942
+ closeReason = reason || "Browser tunnel disconnected.";
943
+ heartbeat.stop();
944
+ offMessage();
945
+ offClose();
946
+ offError();
947
+ const err = new Error(closeReason);
948
+ for (const stream of Array.from(streams.values())) {
949
+ cleanupStream(stream, { error: err, normalClose });
950
+ }
951
+ writer.close();
952
+ try {
953
+ if (terminate)
954
+ socket.terminate();
955
+ else if (socket.readyState === WS_OPEN)
956
+ socket.close(code, reason.slice(0, 120));
957
+ }
958
+ catch {
959
+ // Socket may already be closed.
960
+ }
961
+ closedDeferred.resolve({
962
+ code,
963
+ reason: closeReason,
964
+ replaced: code === BrowserTunnelHost.CLOSE_ATTACHMENT_REPLACED || reason === "replaced",
965
+ });
966
+ }
967
+ return {
968
+ closed: closedDeferred.promise,
969
+ activeStreams: () => streams.size,
970
+ bufferedBytes: () => attachmentBytes,
971
+ isClosed: () => closed,
972
+ ping() {
973
+ if (closed)
974
+ return;
975
+ writer.enqueueControl({ type: StreamWire.FrameType.PING, token: randomBytes(8) });
976
+ },
977
+ async openStream(target, signal) {
978
+ if (closed)
979
+ throw new Error(closeReason);
980
+ if (signal?.aborted)
981
+ throw new Error("Browser tunnel open was cancelled.");
982
+ if (streams.size >= cfg.maxStreams || pendingConnects >= cfg.maxPendingConnects) {
983
+ throw new Error(`Browser attachment has reached its ${cfg.maxStreams}-stream limit.`);
984
+ }
985
+ const id = nextStreamID;
986
+ nextStreamID = nextStreamID >= 0xfffffffe ? 1 : nextStreamID + 1;
987
+ if (streams.has(id))
988
+ throw new Error("Browser stream ID space exhausted.");
989
+ const opened = Promise.withResolvers();
990
+ pendingConnects += 1;
991
+ const stream = {
992
+ id,
993
+ status: "opening",
994
+ opened,
995
+ sendWindow: 0,
996
+ recvWindow: cfg.streamWindowBytes,
997
+ consumedSinceCredit: 0,
998
+ inboundChunks: [],
999
+ inboundBytes: 0,
1000
+ inboundFinReceived: false,
1001
+ outboundChunks: [],
1002
+ outboundOffset: 0,
1003
+ outboundBytes: 0,
1004
+ outboundFinPending: false,
1005
+ outboundFinSent: false,
1006
+ inRoundRobin: false,
1007
+ hasWritableOutput() {
1008
+ if (stream.status !== "open")
1009
+ return false;
1010
+ if (stream.outboundBytes > 0 && stream.sendWindow > 0)
1011
+ return true;
1012
+ return stream.outboundBytes === 0 && stream.outboundFinPending && !stream.outboundFinSent;
1013
+ },
1014
+ nextOutboundFrame() {
1015
+ if (stream.status !== "open")
1016
+ return undefined;
1017
+ if (stream.outboundBytes > 0 && stream.sendWindow > 0) {
1018
+ const maxTake = Math.min(cfg.frameChunkBytes, stream.sendWindow);
1019
+ const slice = takeChunk(stream.outboundChunks, stream.outboundOffset, maxTake);
1020
+ stream.outboundOffset = slice.nextOffset;
1021
+ stream.outboundBytes -= slice.bytes.byteLength;
1022
+ stream.sendWindow -= slice.bytes.byteLength;
1023
+ releaseBytes(slice.bytes.byteLength);
1024
+ if (stream.writeResume && stream.outboundBytes <= cfg.streamOutboundLowWaterBytes) {
1025
+ const resume = stream.writeResume;
1026
+ stream.writeResume = undefined;
1027
+ resume();
1028
+ }
1029
+ return StreamWire.encodeFrame({
1030
+ type: StreamWire.FrameType.DATA,
1031
+ streamID: stream.id,
1032
+ data: slice.bytes,
1033
+ });
1034
+ }
1035
+ if (stream.outboundBytes === 0 && stream.outboundFinPending && !stream.outboundFinSent) {
1036
+ stream.outboundFinSent = true;
1037
+ const cb = stream.finalCallback;
1038
+ stream.finalCallback = undefined;
1039
+ const encoded = StreamWire.encodeFrame({ type: StreamWire.FrameType.FIN, streamID: stream.id });
1040
+ if (cb)
1041
+ cb();
1042
+ maybeFinishStream(stream);
1043
+ return encoded;
1044
+ }
1045
+ return undefined;
1046
+ },
1047
+ };
1048
+ streams.set(id, stream);
1049
+ const onAbort = () => {
1050
+ if (stream.status !== "opening")
1051
+ return;
1052
+ cleanupStream(stream, {
1053
+ error: new Error("Browser tunnel open was cancelled."),
1054
+ sendReset: StreamWire.ResetCode.CANCELLED,
1055
+ });
1056
+ };
1057
+ signal?.addEventListener("abort", onAbort, { once: true });
1058
+ writer.enqueueControl({
1059
+ type: StreamWire.FrameType.OPEN,
1060
+ streamID: id,
1061
+ host: target.host,
1062
+ port: target.port,
1063
+ initialWindow: cfg.streamWindowBytes,
1064
+ });
1065
+ try {
1066
+ return await opened.promise;
1067
+ }
1068
+ finally {
1069
+ signal?.removeEventListener("abort", onAbort);
1070
+ }
1071
+ },
1072
+ close(code = 1000, reason = "client closed") {
1073
+ if (closed)
1074
+ return;
1075
+ if (socket.readyState === WS_OPEN) {
1076
+ try {
1077
+ socket.send(StreamWire.encodeFrame({
1078
+ type: StreamWire.FrameType.GOAWAY,
1079
+ code: StreamWire.ResetCode.CANCELLED,
1080
+ reason,
1081
+ }));
1082
+ }
1083
+ catch {
1084
+ // Best-effort GOAWAY.
1085
+ }
1086
+ }
1087
+ shutdown(code, reason, false, true);
1088
+ },
1089
+ };
1090
+ }
1091
+ function takeChunk(chunks, offset, maxBytes) {
1092
+ const head = chunks[0];
1093
+ const available = head.byteLength - offset;
1094
+ if (available <= maxBytes) {
1095
+ chunks.shift();
1096
+ return {
1097
+ bytes: offset === 0 ? head : head.subarray(offset),
1098
+ nextOffset: 0,
1099
+ };
1100
+ }
1101
+ return {
1102
+ bytes: head.subarray(offset, offset + maxBytes),
1103
+ nextOffset: offset + maxBytes,
1104
+ };
1105
+ }
1106
+ function clamp(value, min, max) {
1107
+ return Math.max(min, Math.min(max, value));
1108
+ }
1109
+ function asError(error) {
1110
+ return error instanceof Error ? error : new Error(String(error));
1111
+ }
1112
+ function resetCodeMessage(code) {
1113
+ switch (code) {
1114
+ case StreamWire.ResetCode.CANCELLED:
1115
+ return "Browser tunnel stream was cancelled.";
1116
+ case StreamWire.ResetCode.CONNECT_FAILED:
1117
+ return "Browser tunnel could not connect to the target.";
1118
+ case StreamWire.ResetCode.POLICY_DENIED:
1119
+ return "Target address is blocked by browser egress policy.";
1120
+ case StreamWire.ResetCode.LIMIT_EXCEEDED:
1121
+ return "Browser tunnel resource limit exceeded.";
1122
+ case StreamWire.ResetCode.PROTOCOL_ERROR:
1123
+ return "Browser tunnel protocol error.";
1124
+ case StreamWire.ResetCode.ATTACHMENT_CLOSED:
1125
+ return "Browser attachment was closed.";
1126
+ case StreamWire.ResetCode.INTERNAL_ERROR:
1127
+ return "Browser tunnel target socket error.";
1128
+ }
1129
+ }