@rstreamlabs/webtty 1.10.0 → 1.11.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.
package/dist/node.js CHANGED
@@ -55,8 +55,9 @@ __export(node_exports, {
55
55
  hashWebTTYServerProofTranscript: () => hashWebTTYServerProofTranscript,
56
56
  hashWebTTYSessionKeyGrant: () => hashWebTTYSessionKeyGrant,
57
57
  loadWebTTYKnownServerKeysFile: () => loadWebTTYKnownServerKeysFile,
58
+ nodeWebSocketFactory: () => nodeWebSocketFactory,
58
59
  openWebTTYCommand: () => openWebTTYCommand,
59
- parseWebDAVMultiStatus: () => parseWebDAVMultiStatus,
60
+ parseWebDAVMultiStatus: () => import_filesystem4.parseWebDAVMultiStatus,
60
61
  parseWebTTYKnownServerKey: () => parseWebTTYKnownServerKey,
61
62
  readWebTTYKnownServerKeysFile: () => readWebTTYKnownServerKeysFile,
62
63
  renderWebTTYRecordedTextLog: () => renderWebTTYRecordedTextLog,
@@ -8669,6 +8670,74 @@ function base64URLDecode(value) {
8669
8670
  return out;
8670
8671
  }
8671
8672
 
8673
+ // src/transport-frames.ts
8674
+ var WebTTYFrameDecoder = class {
8675
+ constructor(maxMessageSize) {
8676
+ this.maxMessageSize = maxMessageSize;
8677
+ }
8678
+ maxMessageSize;
8679
+ header = new Uint8Array(4);
8680
+ headerBytes = 0;
8681
+ payload = null;
8682
+ payloadBytes = 0;
8683
+ get incomplete() {
8684
+ return this.headerBytes !== 0 || this.payload !== null;
8685
+ }
8686
+ reset() {
8687
+ this.headerBytes = 0;
8688
+ this.payload = null;
8689
+ this.payloadBytes = 0;
8690
+ }
8691
+ *push(chunk) {
8692
+ const cursor = { offset: 0 };
8693
+ while (cursor.offset < chunk.byteLength) {
8694
+ if (this.payload === null) {
8695
+ const count2 = Math.min(
8696
+ 4 - this.headerBytes,
8697
+ chunk.byteLength - cursor.offset
8698
+ );
8699
+ this.header.set(
8700
+ chunk.subarray(cursor.offset, cursor.offset + count2),
8701
+ this.headerBytes
8702
+ );
8703
+ this.headerBytes += count2;
8704
+ cursor.offset += count2;
8705
+ if (this.headerBytes !== 4) return;
8706
+ const size = new DataView(this.header.buffer).getUint32(0, false);
8707
+ if (size > this.maxMessageSize)
8708
+ throw new Error(
8709
+ `WebTTY message exceeds the ${this.maxMessageSize} byte limit.`
8710
+ );
8711
+ this.headerBytes = 0;
8712
+ if (chunk.byteLength - cursor.offset >= size) {
8713
+ const payload = chunk.subarray(cursor.offset, cursor.offset + size);
8714
+ cursor.offset += size;
8715
+ yield payload;
8716
+ continue;
8717
+ }
8718
+ this.payload = new Uint8Array(size);
8719
+ this.payloadBytes = 0;
8720
+ }
8721
+ const count = Math.min(
8722
+ this.payload.byteLength - this.payloadBytes,
8723
+ chunk.byteLength - cursor.offset
8724
+ );
8725
+ this.payload.set(
8726
+ chunk.subarray(cursor.offset, cursor.offset + count),
8727
+ this.payloadBytes
8728
+ );
8729
+ this.payloadBytes += count;
8730
+ cursor.offset += count;
8731
+ if (this.payloadBytes === this.payload.byteLength) {
8732
+ const payload = this.payload;
8733
+ this.payload = null;
8734
+ this.payloadBytes = 0;
8735
+ yield payload;
8736
+ }
8737
+ }
8738
+ }
8739
+ };
8740
+
8672
8741
  // src/webtty.ts
8673
8742
  function getErrorMessage(error) {
8674
8743
  return error instanceof Error ? error.message : String(error);
@@ -9058,12 +9127,15 @@ function resolveWebTransportConstructor() {
9058
9127
  function webTransportGlobal(value) {
9059
9128
  return "WebTransport" in value;
9060
9129
  }
9130
+ function browserWebSocket(url) {
9131
+ const socket = new WebSocket(url);
9132
+ socket.binaryType = "arraybuffer";
9133
+ return socket;
9134
+ }
9061
9135
  var WebSocketMessageConnection = class {
9062
- ws;
9063
- handlers;
9064
- constructor(url, handlers) {
9065
- this.ws = new WebSocket(url);
9066
- this.ws.binaryType = "arraybuffer";
9136
+ constructor(url, handlers, maxBufferedBytes, factory, maxMessageSize) {
9137
+ this.maxBufferedBytes = maxBufferedBytes;
9138
+ this.ws = factory ? factory(url, { maxMessageSize }) : browserWebSocket(url);
9067
9139
  this.handlers = {
9068
9140
  close: handlers.close,
9069
9141
  error: handlers.error,
@@ -9075,7 +9147,13 @@ var WebSocketMessageConnection = class {
9075
9147
  this.ws.addEventListener("error", this.handlers.error);
9076
9148
  this.ws.addEventListener("close", this.handlers.close);
9077
9149
  }
9150
+ maxBufferedBytes;
9151
+ ws;
9152
+ handlers;
9078
9153
  send(payload) {
9154
+ if (this.ws.bufferedAmount + payload.byteLength > this.maxBufferedBytes) {
9155
+ throw new Error("WebSocket write buffer limit exceeded.");
9156
+ }
9079
9157
  this.ws.send(getWebSocketPayload(payload));
9080
9158
  }
9081
9159
  close() {
@@ -9087,56 +9165,109 @@ var WebSocketMessageConnection = class {
9087
9165
  }
9088
9166
  };
9089
9167
  var WebTransportMessageConnection = class _WebTransportMessageConnection {
9090
- constructor(transport, stream, writer, handlers) {
9168
+ constructor(transport, stream, writer, maxMessageSize, handlers) {
9091
9169
  this.transport = transport;
9092
- this.stream = stream;
9093
9170
  this.writer = writer;
9171
+ this.maxMessageSize = maxMessageSize;
9094
9172
  this.handlers = handlers;
9173
+ this.decoder = new WebTTYFrameDecoder(maxMessageSize);
9174
+ this.reader = stream.readable.getReader();
9095
9175
  }
9096
9176
  transport;
9097
- stream;
9098
9177
  writer;
9178
+ maxMessageSize;
9099
9179
  handlers;
9100
9180
  closed = false;
9101
- readBuffer = new Uint8Array();
9102
- writeQueue = Promise.resolve();
9103
- static async open(url, options, handlers) {
9181
+ decoder;
9182
+ reader;
9183
+ writeQueue = [];
9184
+ writeHead = 0;
9185
+ bufferedBytes = 0;
9186
+ writing = false;
9187
+ static async open(url, options, signal, maxMessageSize, handlers) {
9188
+ signal.throwIfAborted();
9104
9189
  const Transport = resolveWebTransportConstructor();
9105
9190
  const transport = new Transport(url, options);
9106
- await transport.ready;
9107
- const stream = await transport.createBidirectionalStream();
9108
- const writer = stream.writable.getWriter();
9109
- const connection = new _WebTransportMessageConnection(
9110
- transport,
9111
- stream,
9112
- writer,
9113
- handlers
9114
- );
9115
- connection.startReadLoop();
9116
9191
  transport.closed.catch((error) => {
9117
- if (!connection.closed) {
9192
+ if (!signal.aborted) {
9118
9193
  handlers.error(`WebTransport closed: ${getErrorMessage(error)}`);
9119
9194
  }
9120
9195
  });
9121
- return connection;
9196
+ try {
9197
+ await waitForWebTransportOpen(transport.ready, signal);
9198
+ signal.throwIfAborted();
9199
+ const stream = await waitForWebTransportOpen(
9200
+ transport.createBidirectionalStream(),
9201
+ signal
9202
+ );
9203
+ signal.throwIfAborted();
9204
+ const writer = stream.writable.getWriter();
9205
+ const connection = new _WebTransportMessageConnection(
9206
+ transport,
9207
+ stream,
9208
+ writer,
9209
+ maxMessageSize,
9210
+ handlers
9211
+ );
9212
+ connection.startReadLoop();
9213
+ return connection;
9214
+ } catch (error) {
9215
+ transport.close({ closeCode: 0, reason: "open failed" });
9216
+ throw error;
9217
+ }
9122
9218
  }
9123
9219
  send(payload) {
9124
9220
  if (this.closed) return;
9221
+ if (payload.byteLength > this.maxMessageSize) {
9222
+ this.handlers.error(
9223
+ `WebTTY message exceeds the ${this.maxMessageSize} byte limit.`
9224
+ );
9225
+ return;
9226
+ }
9227
+ if (this.bufferedBytes + payload.byteLength + 4 > this.maxMessageSize * 4 || this.writeQueue.length - this.writeHead >= 1024) {
9228
+ this.handlers.error("WebTransport write buffer limit exceeded.");
9229
+ return;
9230
+ }
9125
9231
  const frame = getFramePayload(payload);
9126
- this.writeQueue = this.writeQueue.then(() => this.writer.write(frame)).catch((error) => {
9127
- if (!this.closed) {
9128
- this.handlers.error(
9129
- `WebTransport write failed: ${getErrorMessage(error)}`
9130
- );
9131
- }
9132
- });
9232
+ this.writeQueue.push(frame);
9233
+ this.bufferedBytes += frame.byteLength;
9234
+ if (!this.writing) {
9235
+ this.writing = true;
9236
+ void this.writeLoop();
9237
+ }
9133
9238
  }
9134
9239
  close() {
9135
9240
  if (this.closed) return;
9136
9241
  this.closed = true;
9137
- this.writer.releaseLock();
9242
+ this.writeQueue = [];
9243
+ this.writeHead = 0;
9244
+ this.decoder.reset();
9245
+ void this.reader.cancel().catch(() => void 0).finally(() => this.reader.releaseLock());
9246
+ void this.writer.abort().catch(() => void 0).finally(() => this.writer.releaseLock());
9138
9247
  this.transport.close({ closeCode: 0, reason: "closed" });
9139
9248
  }
9249
+ async writeLoop() {
9250
+ try {
9251
+ while (!this.closed && this.writeHead < this.writeQueue.length) {
9252
+ const frame = this.writeQueue[this.writeHead];
9253
+ this.writeQueue[this.writeHead++] = void 0;
9254
+ if (this.writeHead === this.writeQueue.length || this.writeHead >= 512) {
9255
+ this.writeQueue = this.writeQueue.slice(this.writeHead);
9256
+ this.writeHead = 0;
9257
+ }
9258
+ if (frame === void 0) continue;
9259
+ await this.writer.write(frame);
9260
+ this.bufferedBytes -= frame.byteLength;
9261
+ }
9262
+ } catch (error) {
9263
+ if (!this.closed)
9264
+ this.handlers.error(
9265
+ `WebTransport write failed: ${getErrorMessage(error)}`
9266
+ );
9267
+ } finally {
9268
+ this.writing = false;
9269
+ }
9270
+ }
9140
9271
  startReadLoop() {
9141
9272
  void this.readLoop().catch((error) => {
9142
9273
  if (!this.closed) {
@@ -9147,41 +9278,46 @@ var WebTransportMessageConnection = class _WebTransportMessageConnection {
9147
9278
  });
9148
9279
  }
9149
9280
  async readLoop() {
9150
- const reader = this.stream.readable.getReader();
9151
9281
  try {
9152
9282
  for (; ; ) {
9153
- const result = await reader.read();
9283
+ const result = await this.reader.read();
9284
+ if (this.closed) return;
9154
9285
  if (result.done) {
9155
- if (!this.closed) this.handlers.close();
9286
+ if (this.decoder.incomplete)
9287
+ throw new Error("Incomplete WebTTY frame at end of stream.");
9288
+ this.handlers.close();
9156
9289
  return;
9157
9290
  }
9158
- this.appendReadChunk(result.value);
9291
+ for (const payload of this.decoder.push(result.value)) {
9292
+ if (this.closed) return;
9293
+ await this.handlers.message(payload);
9294
+ if (this.closed) return;
9295
+ }
9159
9296
  }
9160
9297
  } finally {
9161
- reader.releaseLock();
9162
- }
9163
- }
9164
- appendReadChunk(chunk) {
9165
- const next = new Uint8Array(this.readBuffer.byteLength + chunk.byteLength);
9166
- next.set(this.readBuffer);
9167
- next.set(chunk, this.readBuffer.byteLength);
9168
- this.readBuffer = next;
9169
- for (; ; ) {
9170
- if (this.readBuffer.byteLength < 4) return;
9171
- const view = new DataView(
9172
- this.readBuffer.buffer,
9173
- this.readBuffer.byteOffset,
9174
- this.readBuffer.byteLength
9175
- );
9176
- const size = view.getUint32(0, false);
9177
- if (this.readBuffer.byteLength < 4 + size) return;
9178
- const payload = this.readBuffer.slice(4, 4 + size);
9179
- this.readBuffer = this.readBuffer.slice(4 + size);
9180
- this.handlers.message(payload);
9298
+ this.reader.releaseLock();
9181
9299
  }
9182
9300
  }
9183
9301
  };
9302
+ function waitForWebTransportOpen(pending, signal) {
9303
+ return new Promise((resolve, reject) => {
9304
+ const abort = () => reject(new Error("WebTransport connection cancelled."));
9305
+ signal.addEventListener("abort", abort, { once: true });
9306
+ if (signal.aborted) abort();
9307
+ pending.then(
9308
+ (value) => {
9309
+ signal.removeEventListener("abort", abort);
9310
+ resolve(value);
9311
+ },
9312
+ (error) => {
9313
+ signal.removeEventListener("abort", abort);
9314
+ reject(error);
9315
+ }
9316
+ );
9317
+ });
9318
+ }
9184
9319
  var WebTTY = class {
9320
+ connectionAbort = new AbortController();
9185
9321
  connection = null;
9186
9322
  connectionState = "preparing";
9187
9323
  heartbeatTimer = null;
@@ -9189,6 +9325,11 @@ var WebTTY = class {
9189
9325
  execConfig;
9190
9326
  events;
9191
9327
  receiveQueue = null;
9328
+ receivedBytes = 0;
9329
+ receivedMessages = 0;
9330
+ stdinClosed = false;
9331
+ stderrClosed = false;
9332
+ stdoutClosed = false;
9192
9333
  /**
9193
9334
  * Creates a new WebTTY instance.
9194
9335
  *
@@ -9197,6 +9338,12 @@ var WebTTY = class {
9197
9338
  * @param events - Event callbacks for the session.
9198
9339
  */
9199
9340
  constructor(clientConfig2, execConfig, events) {
9341
+ const maxMessageSize = clientConfig2.maxMessageSize ?? 1024 * 1024;
9342
+ if (!Number.isSafeInteger(maxMessageSize) || maxMessageSize < 1 || maxMessageSize > 4294967295) {
9343
+ throw new Error(
9344
+ "WebTTY maxMessageSize must be a positive 32-bit integer."
9345
+ );
9346
+ }
9200
9347
  const transport = resolveWebTTYClientTransport(
9201
9348
  clientConfig2.url,
9202
9349
  clientConfig2.transport
@@ -9220,9 +9367,11 @@ var WebTTY = class {
9220
9367
  endpointIdentity: clientConfig2.endpointIdentity,
9221
9368
  expectedServerIdentity: clientConfig2.expectedServerIdentity,
9222
9369
  heartbeatIntervalMs: clientConfig2.heartbeatIntervalMs ?? 5e3,
9370
+ maxMessageSize,
9223
9371
  sendHeartbeat: clientConfig2.sendHeartbeat ?? true,
9224
9372
  transport,
9225
9373
  url: clientConfig2.url,
9374
+ webSocketFactory: clientConfig2.webSocketFactory,
9226
9375
  webTransportOptions: clientConfig2.webTransportOptions
9227
9376
  };
9228
9377
  this.execConfig = {
@@ -9251,12 +9400,18 @@ var WebTTY = class {
9251
9400
  return;
9252
9401
  }
9253
9402
  const wsUrl = normalizeWebSocketURL(this.clientConfig.url);
9254
- this.connection = new WebSocketMessageConnection(wsUrl, {
9255
- close: this.handleClose,
9256
- error: this.handleError,
9257
- message: this.handleConnectionMessage,
9258
- open: this.handleOpen
9259
- });
9403
+ this.connection = new WebSocketMessageConnection(
9404
+ wsUrl,
9405
+ {
9406
+ close: this.handleClose,
9407
+ error: this.handleError,
9408
+ message: this.handleConnectionMessage,
9409
+ open: this.handleOpen
9410
+ },
9411
+ this.clientConfig.maxMessageSize * 4,
9412
+ this.clientConfig.webSocketFactory,
9413
+ this.clientConfig.maxMessageSize
9414
+ );
9260
9415
  }
9261
9416
  /**
9262
9417
  * Sends data to the remote server's STDIN.
@@ -9294,6 +9449,7 @@ var WebTTY = class {
9294
9449
  return;
9295
9450
  }
9296
9451
  const encrypted = await encrypt(data);
9452
+ this.assertCanWriteStdin();
9297
9453
  this.sendStdinPayload({
9298
9454
  encryptedData: encryptedPayloadToProto(encrypted)
9299
9455
  });
@@ -9305,6 +9461,9 @@ var WebTTY = class {
9305
9461
  if (this.execConfig.interactive === false) {
9306
9462
  throw new Error("STDIN is unavailable in non-interactive mode.");
9307
9463
  }
9464
+ if (this.stdinClosed) {
9465
+ throw new Error("WebTTY STDIN is already closed.");
9466
+ }
9308
9467
  }
9309
9468
  sendStdinPayload(payload) {
9310
9469
  this.send(
@@ -9326,6 +9485,8 @@ var WebTTY = class {
9326
9485
  if (this.execConfig.interactive === false) {
9327
9486
  throw new Error("STDIN is unavailable in non-interactive mode.");
9328
9487
  }
9488
+ if (this.stdinClosed) return;
9489
+ this.stdinClosed = true;
9329
9490
  this.send(
9330
9491
  new rstream.webtty.protobuf.Message({
9331
9492
  data: new rstream.webtty.protobuf.Data({
@@ -9663,6 +9824,8 @@ var WebTTY = class {
9663
9824
  const connection = await WebTransportMessageConnection.open(
9664
9825
  url,
9665
9826
  this.clientConfig.webTransportOptions,
9827
+ this.connectionAbort.signal,
9828
+ this.clientConfig.maxMessageSize,
9666
9829
  {
9667
9830
  close: this.handleClose,
9668
9831
  error: this.handleTransportError,
@@ -9680,16 +9843,46 @@ var WebTTY = class {
9680
9843
  }
9681
9844
  }
9682
9845
  handleConnectionMessage = (data) => {
9683
- const run = () => this.processMessage(data);
9846
+ if (this.connectionState === "closed") return;
9847
+ const payload = this.boundedMessagePayload(data);
9848
+ if (payload === null) return;
9849
+ this.receivedBytes += payload.byteLength;
9850
+ this.receivedMessages += 1;
9851
+ const run = () => this.processMessage(payload);
9852
+ const release = () => {
9853
+ this.receivedBytes -= payload.byteLength;
9854
+ this.receivedMessages -= 1;
9855
+ };
9684
9856
  if (this.receiveQueue) {
9685
- this.trackReceiveQueue(this.receiveQueue.then(run, run));
9686
- return;
9857
+ return this.trackReceiveQueue(
9858
+ this.receiveQueue.then(run, run).finally(release)
9859
+ );
9687
9860
  }
9688
9861
  const result = run();
9689
9862
  if (isPromiseLike(result)) {
9690
- this.trackReceiveQueue(result);
9863
+ return this.trackReceiveQueue(result.finally(release));
9691
9864
  }
9865
+ release();
9692
9866
  };
9867
+ boundedMessagePayload(data) {
9868
+ try {
9869
+ const payload = messagePayloadBytes(data);
9870
+ if (payload.byteLength > this.clientConfig.maxMessageSize) {
9871
+ this.close(
9872
+ `WebTTY message exceeds the ${this.clientConfig.maxMessageSize} byte limit.`
9873
+ );
9874
+ return null;
9875
+ }
9876
+ if (this.receivedBytes + payload.byteLength > this.clientConfig.maxMessageSize * 4 || this.receivedMessages >= 1024) {
9877
+ this.close("WebTTY receive buffer limit exceeded.");
9878
+ return null;
9879
+ }
9880
+ return payload;
9881
+ } catch (error) {
9882
+ this.close(`Failed to decode message: ${getErrorMessage(error)}`);
9883
+ return null;
9884
+ }
9885
+ }
9693
9886
  trackReceiveQueue(promise) {
9694
9887
  const queued = promise.catch((error) => {
9695
9888
  this.close(`Failed to decode message: ${getErrorMessage(error)}`);
@@ -9697,6 +9890,7 @@ var WebTTY = class {
9697
9890
  if (this.receiveQueue === queued) this.receiveQueue = null;
9698
9891
  });
9699
9892
  this.receiveQueue = queued;
9893
+ return queued;
9700
9894
  }
9701
9895
  processMessage(data) {
9702
9896
  if (!data) return;
@@ -9745,41 +9939,47 @@ var WebTTY = class {
9745
9939
  }
9746
9940
  }
9747
9941
  processDataMessage(data) {
9748
- if (data.type === rstream.webtty.protobuf.Data.Type.TYPE_STDOUT) {
9749
- if (data.data) {
9750
- this.events.onStdout?.(data.data);
9751
- }
9752
- if (data.encryptedData) {
9753
- const decrypted = this.decryptData("stdout", data.encryptedData);
9754
- if (isPromiseLike(decrypted)) {
9755
- return decrypted.then((chunk) => {
9756
- if (chunk !== null) this.events.onStdout?.(chunk);
9757
- });
9758
- }
9759
- if (decrypted === null) return;
9760
- this.events.onStdout?.(decrypted);
9761
- }
9762
- if (data.eos) {
9942
+ const stream = data.type === rstream.webtty.protobuf.Data.Type.TYPE_STDOUT ? "stdout" : data.type === rstream.webtty.protobuf.Data.Type.TYPE_STDERR ? "stderr" : null;
9943
+ if (stream === null) {
9944
+ this.close(`Unexpected WebTTY data stream type ${String(data.type)}.`);
9945
+ return;
9946
+ }
9947
+ const hasData = data.data !== void 0 && data.data !== null;
9948
+ const hasEncryptedData = data.encryptedData !== void 0 && data.encryptedData !== null;
9949
+ const hasEos = data.eos !== void 0 && data.eos !== null;
9950
+ if (Number(hasData) + Number(hasEncryptedData) + Number(hasEos) !== 1) {
9951
+ this.close(`Unexpected WebTTY ${stream} payload.`);
9952
+ return;
9953
+ }
9954
+ const streamClosed = stream === "stdout" ? this.stdoutClosed : this.stderrClosed;
9955
+ if (streamClosed) {
9956
+ this.close(
9957
+ hasEos ? `Duplicate WebTTY ${stream} end of stream.` : `WebTTY ${stream} data received after end of stream.`
9958
+ );
9959
+ return;
9960
+ }
9961
+ if (hasEos) {
9962
+ if (stream === "stdout") {
9963
+ this.stdoutClosed = true;
9763
9964
  this.events.onStdoutEos?.();
9764
- }
9765
- } else if (data.type === rstream.webtty.protobuf.Data.Type.TYPE_STDERR) {
9766
- if (data.data) {
9767
- this.events.onStderr?.(data.data);
9768
- }
9769
- if (data.encryptedData) {
9770
- const decrypted = this.decryptData("stderr", data.encryptedData);
9771
- if (isPromiseLike(decrypted)) {
9772
- return decrypted.then((chunk) => {
9773
- if (chunk !== null) this.events.onStderr?.(chunk);
9774
- });
9775
- }
9776
- if (decrypted === null) return;
9777
- this.events.onStderr?.(decrypted);
9778
- }
9779
- if (data.eos) {
9965
+ } else {
9966
+ this.stderrClosed = true;
9780
9967
  this.events.onStderrEos?.();
9781
9968
  }
9969
+ return;
9970
+ }
9971
+ const emit = stream === "stdout" ? this.events.onStdout : this.events.onStderr;
9972
+ if (hasData) {
9973
+ emit?.(data.data);
9974
+ return;
9975
+ }
9976
+ const decrypted = this.decryptData(stream, data.encryptedData);
9977
+ if (isPromiseLike(decrypted)) {
9978
+ return decrypted.then((chunk) => {
9979
+ if (chunk !== null && this.connectionState !== "closed") emit?.(chunk);
9980
+ });
9782
9981
  }
9982
+ if (decrypted !== null) emit?.(decrypted);
9783
9983
  }
9784
9984
  decryptData(stream, payload) {
9785
9985
  const decrypt = stream === "stdout" ? this.execConfig.payloadCrypto?.decryptStdout : this.execConfig.payloadCrypto?.decryptStderr;
@@ -9830,7 +10030,19 @@ var WebTTY = class {
9830
10030
  if (this.connectionState === "preparing" || this.connectionState === "closed")
9831
10031
  return;
9832
10032
  const buffer = rstream.webtty.protobuf.Message.encode(message).finish();
9833
- this.connection.send(buffer);
10033
+ if (buffer.byteLength > this.clientConfig.maxMessageSize) {
10034
+ this.close(
10035
+ `WebTTY message exceeds the ${this.clientConfig.maxMessageSize} byte limit.`
10036
+ );
10037
+ return;
10038
+ }
10039
+ try {
10040
+ this.connection.send(buffer);
10041
+ } catch (error) {
10042
+ this.close(
10043
+ `${this.clientConfig.transport} write failed: ${getErrorMessage(error)}`
10044
+ );
10045
+ }
9834
10046
  }
9835
10047
  /**
9836
10048
  * Closes the WebTTY session and fires exactly one of:
@@ -9843,6 +10055,7 @@ var WebTTY = class {
9843
10055
  return;
9844
10056
  }
9845
10057
  this.connectionState = "closed";
10058
+ this.connectionAbort.abort();
9846
10059
  if (this.heartbeatTimer) {
9847
10060
  clearInterval(this.heartbeatTimer);
9848
10061
  this.heartbeatTimer = null;
@@ -10320,393 +10533,20 @@ var WebTTYRemoteExecutor = class {
10320
10533
  };
10321
10534
 
10322
10535
  // src/filesystem.ts
10323
- var WebTTYFileSystemError = class extends Error {
10324
- operation;
10325
- status;
10536
+ var import_filesystem = require("@rstreamlabs/filesystem");
10537
+ var import_filesystem2 = require("@rstreamlabs/filesystem");
10538
+ var import_filesystem3 = require("@rstreamlabs/filesystem");
10539
+ var import_filesystem4 = require("@rstreamlabs/filesystem");
10540
+ var resolveWebTTYFileSystemURL = import_filesystem3.resolveFileSystemURL;
10541
+ var WebTTYFileSystemError = class extends import_filesystem2.FileSystemError {
10326
10542
  constructor(operation, status, message) {
10327
- super(`${operation} failed with status ${status}: ${message}`);
10543
+ super(operation, status, message);
10328
10544
  this.name = "WebTTYFileSystemError";
10329
- this.operation = operation;
10330
- this.status = status;
10331
10545
  }
10332
10546
  };
10333
- var webDAVPropfindBody = '<?xml version="1.0" encoding="utf-8"?><propfind xmlns="DAV:"><prop><resourcetype/><getcontentlength/><getlastmodified/></prop></propfind>';
10334
- function cleanTrailingSlashes2(value) {
10335
- return value.replace(/\/+$/, "");
10336
- }
10337
- function normalizeRemotePath(remotePath) {
10338
- const trimmed = remotePath.trim();
10339
- const absolute = trimmed === "" || trimmed === "." ? "/" : trimmed;
10340
- return new URL(
10341
- absolute.startsWith("/") ? absolute : `/${absolute}`,
10342
- "http://rstream.local"
10343
- ).pathname;
10344
- }
10345
- function comparableRemotePath(remotePath) {
10346
- const normalized = cleanTrailingSlashes2(normalizeRemotePath(remotePath));
10347
- return normalized === "" ? "/" : normalized;
10348
- }
10349
- function sidecarPath(fsPath) {
10350
- return normalizeRemotePath(fsPath ?? "/fs");
10351
- }
10352
- function filesystemBasePath(pathname, fsPath) {
10353
- const sidecar = sidecarPath(fsPath);
10354
- const basePath = cleanTrailingSlashes2(pathname);
10355
- if (basePath === "") return sidecar;
10356
- if (basePath === "/") return sidecar;
10357
- if (basePath === sidecar || basePath.startsWith(`${sidecar}/`))
10358
- return basePath;
10359
- return `${basePath}${sidecar}`;
10360
- }
10361
- function filesystemPath(pathname, remotePath, fsPath) {
10362
- const basePath = filesystemBasePath(pathname, fsPath);
10363
- const normalized = normalizeRemotePath(remotePath);
10364
- return normalized === "/" ? basePath : `${cleanTrailingSlashes2(basePath)}${normalized}`;
10365
- }
10366
- function resolveWebTTYFileSystemURL(input, remotePath = "/", fsPath) {
10367
- const url = new URL(input.toString());
10368
- if (url.protocol === "rstrm:") {
10369
- throw new Error(
10370
- "rstrm:// WebTTY filesystem URLs require the native rstream dialer."
10371
- );
10372
- }
10373
- if (url.protocol === "ws:") url.protocol = "http:";
10374
- if (url.protocol === "wss:") url.protocol = "https:";
10375
- if (url.protocol !== "http:" && url.protocol !== "https:") {
10376
- throw new Error(
10377
- `Unsupported WebTTY filesystem URL scheme "${url.protocol}".`
10378
- );
10379
- }
10380
- url.pathname = filesystemPath(url.pathname, remotePath, fsPath);
10381
- url.hash = "";
10382
- return url;
10383
- }
10384
- function responseAllowed(response, expectedStatuses) {
10385
- return expectedStatuses.includes(response.status);
10386
- }
10387
- async function responseErrorMessage(response) {
10388
- const text = (await response.text()).trim().slice(0, 4096);
10389
- return text === "" ? response.statusText : text;
10390
- }
10391
- async function requireResponseStatus(response, expectedStatuses, operation) {
10392
- if (responseAllowed(response, expectedStatuses)) return response;
10393
- throw new WebTTYFileSystemError(
10394
- operation,
10395
- response.status,
10396
- await responseErrorMessage(response)
10397
- );
10398
- }
10399
- function requireResponseBody(response, operation) {
10400
- if (response.body) return response.body;
10401
- throw new Error(
10402
- `${operation} failed because the response body is unavailable.`
10403
- );
10404
- }
10405
- function resolveFetch(config) {
10406
- if (config.fetch) return config.fetch;
10407
- if (typeof fetch === "undefined") {
10408
- throw new Error("fetch is unavailable in this runtime.");
10409
- }
10410
- return fetch;
10411
- }
10412
- function applyHeaders(target, source) {
10413
- const sourceHeaders = new Headers(source);
10414
- sourceHeaders.forEach((value, key) => target.set(key, value));
10415
- return target;
10416
- }
10417
- function requestHeaders(config, headers) {
10418
- const result = applyHeaders(new Headers(config.headers), headers);
10419
- if (config.authToken && config.authToken.trim() !== "") {
10420
- result.set("Authorization", `Bearer ${config.authToken.trim()}`);
10421
- }
10422
- return result;
10423
- }
10424
- function contentHeaders(contentType) {
10425
- return contentType === void 0 ? void 0 : { "Content-Type": contentType };
10426
- }
10427
- function deleteStatuses(force) {
10428
- return force ? [200, 204, 404] : [200, 204];
10429
- }
10430
- function isNotFound(error) {
10431
- return error instanceof WebTTYFileSystemError && error.status === 404;
10432
- }
10433
- function pathBaseName(path) {
10434
- const normalized = normalizeRemotePath(path);
10435
- const cleaned = cleanTrailingSlashes2(normalized);
10436
- return cleaned.slice(cleaned.lastIndexOf("/") + 1);
10437
- }
10438
- function parentPath(path) {
10439
- const normalized = cleanTrailingSlashes2(normalizeRemotePath(path));
10440
- const index = normalized.lastIndexOf("/");
10441
- if (index <= 0) return "/";
10442
- return normalized.slice(0, index);
10443
- }
10444
- function readFileEncoding(options) {
10445
- if (typeof options === "string") return options;
10446
- return options?.encoding === void 0 ? null : options.encoding;
10447
- }
10448
- function readFileSignal(options) {
10449
- return typeof options === "string" ? void 0 : options?.signal;
10450
- }
10451
- function textContentHeaders(contentType, data) {
10452
- if (contentType !== void 0) return { "Content-Type": contentType };
10453
- return typeof data === "string" ? { "Content-Type": "text/plain; charset=utf-8" } : void 0;
10454
- }
10455
- function bodyRequiresDuplex(body) {
10456
- return typeof ReadableStream !== "undefined" && body instanceof ReadableStream;
10457
- }
10458
- function requestInit(config, method, options) {
10459
- return {
10460
- body: options.body,
10461
- duplex: bodyRequiresDuplex(options.body) ? "half" : void 0,
10462
- headers: requestHeaders(config, options.headers),
10463
- method,
10464
- signal: options.signal
10465
- };
10466
- }
10467
- async function resolveURL2(url) {
10468
- return typeof url === "function" ? await url() : url;
10469
- }
10470
- function elementBodies(xml, name) {
10471
- return Array.from(
10472
- xml.matchAll(
10473
- new RegExp(
10474
- `<[^>]*:?${name}\\b[^>]*>([\\s\\S]*?)<\\/[^>]*:?${name}>`,
10475
- "gi"
10476
- )
10477
- ),
10478
- (match) => match[1] ?? ""
10479
- );
10480
- }
10481
- function hasElement(xml, name) {
10482
- return new RegExp(`<[^>]*:?${name}(\\s|/|>)`, "i").test(xml);
10483
- }
10484
- function stripTags(xml) {
10485
- return xml.replace(/<[^>]*>/g, "");
10486
- }
10487
- function decodeNumericEntity(value) {
10488
- const parsed = value.startsWith("&#x") ? Number.parseInt(value.slice(3, -1), 16) : Number.parseInt(value.slice(2, -1), 10);
10489
- return Number.isFinite(parsed) ? String.fromCodePoint(parsed) : value;
10490
- }
10491
- function decodeXmlText(value) {
10492
- return value.replace(/&#x[0-9a-f]+;|&#\d+;/gi, decodeNumericEntity).replace(/&apos;/g, "'").replace(/&quot;/g, '"').replace(/&gt;/g, ">").replace(/&lt;/g, "<").replace(/&amp;/g, "&");
10493
- }
10494
- function elementText(xml, name) {
10495
- return decodeXmlText(stripTags(elementBodies(xml, name)[0] ?? "")).trim();
10496
- }
10497
- function okPropstat(response) {
10498
- return elementBodies(response, "propstat").find(
10499
- (propstat) => elementText(propstat, "status").includes(" 200 ")
10500
- ) ?? "";
10501
- }
10502
- function safeDecodePath(path) {
10503
- try {
10504
- return decodeURIComponent(path);
10505
- } catch {
10506
- return path;
10507
- }
10508
- }
10509
- function hrefPath(href) {
10510
- return safeDecodePath(new URL(href, "http://rstream.local").pathname);
10511
- }
10512
- function displayPath(href, fsPath) {
10513
- const value = hrefPath(href);
10514
- const sidecar = cleanTrailingSlashes2(sidecarPath(fsPath));
10515
- const withoutFS = value === sidecar ? "/" : value.startsWith(`${sidecar}/`) ? value.slice(sidecar.length) : value;
10516
- return withoutFS === "" ? "/" : withoutFS;
10517
- }
10518
- function itemSize(value) {
10519
- const parsed = Number.parseInt(value, 10);
10520
- return Number.isFinite(parsed) ? parsed : void 0;
10521
- }
10522
- function itemFromResponse(response, fsPath) {
10523
- const propstat = okPropstat(response);
10524
- const path = displayPath(elementText(response, "href"), fsPath);
10525
- if (propstat === "" || path === "") return null;
10526
- return {
10527
- kind: hasElement(
10528
- elementBodies(propstat, "resourcetype")[0] ?? "",
10529
- "collection"
10530
- ) ? "directory" : "file",
10531
- modified: elementText(propstat, "getlastmodified") || void 0,
10532
- path,
10533
- size: itemSize(elementText(propstat, "getcontentlength"))
10534
- };
10535
- }
10536
- function presentItems(items) {
10537
- return items.filter((item) => item !== null);
10538
- }
10539
- function parseWebDAVMultiStatus(xml, fsPath = "/fs") {
10540
- return presentItems(
10541
- elementBodies(xml, "response").map(
10542
- (response) => itemFromResponse(response, fsPath)
10543
- )
10544
- );
10545
- }
10546
- var WebTTYFileSystem = class {
10547
- config;
10548
- constructor(config) {
10549
- this.config = config;
10550
- }
10551
- async list(path = "/", options = {}) {
10552
- const response = await this.request("PROPFIND", path, {
10553
- body: webDAVPropfindBody,
10554
- expectedStatuses: [207],
10555
- headers: { "Content-Type": "application/xml; charset=utf-8", Depth: "1" },
10556
- operation: "WebTTY filesystem list",
10557
- signal: options.signal
10558
- });
10559
- return parseWebDAVMultiStatus(
10560
- await response.text(),
10561
- sidecarPath(this.config.fsPath)
10562
- );
10563
- }
10564
- async readBytes(path, options = {}) {
10565
- const response = await this.request("GET", path, {
10566
- expectedStatuses: [200],
10567
- operation: "WebTTY filesystem read",
10568
- signal: options.signal
10569
- });
10570
- return new Uint8Array(await response.arrayBuffer());
10571
- }
10572
- async readFile(path, options) {
10573
- const bytes = await this.readBytes(path, {
10574
- signal: readFileSignal(options)
10575
- });
10576
- const encoding = readFileEncoding(options);
10577
- return encoding === null ? bytes : new TextDecoder(encoding).decode(bytes);
10578
- }
10579
- async readText(path, options = {}) {
10580
- return new TextDecoder().decode(await this.readBytes(path, options));
10581
- }
10582
- async readStream(path, options = {}) {
10583
- return requireResponseBody(
10584
- await this.request("GET", path, {
10585
- expectedStatuses: [200],
10586
- operation: "WebTTY filesystem read",
10587
- signal: options.signal
10588
- }),
10589
- "WebTTY filesystem read"
10590
- );
10591
- }
10592
- async writeFile(path, data, options = {}) {
10593
- await this.request("PUT", path, {
10594
- body: data,
10595
- expectedStatuses: [200, 201, 204],
10596
- headers: textContentHeaders(options.contentType, data),
10597
- operation: "WebTTY filesystem write",
10598
- signal: options.signal
10599
- });
10600
- }
10601
- async writeBytes(path, data, options = {}) {
10602
- await this.writeFile(path, data, options);
10603
- }
10604
- async writeStream(path, data, options = {}) {
10605
- await this.request("PUT", path, {
10606
- body: data,
10607
- expectedStatuses: [200, 201, 204],
10608
- headers: contentHeaders(options.contentType),
10609
- operation: "WebTTY filesystem write",
10610
- signal: options.signal
10611
- });
10612
- }
10613
- async writeText(path, data, options = {}) {
10614
- await this.writeFile(path, data, options);
10615
- }
10616
- async copyFile(sourcePath, targetPath, options = {}) {
10617
- await this.request("COPY", sourcePath, {
10618
- expectedStatuses: [200, 201, 204],
10619
- headers: { Destination: (await this.resourceURL(targetPath)).toString() },
10620
- operation: "WebTTY filesystem copy",
10621
- signal: options.signal
10622
- });
10623
- }
10624
- async createDirectory(path, options = {}) {
10625
- await this.request("MKCOL", path, {
10626
- expectedStatuses: [201, 405],
10627
- operation: "WebTTY filesystem mkdir",
10628
- signal: options.signal
10629
- });
10630
- }
10631
- async exists(path, options = {}) {
10632
- return await this.stat(path, options).then(() => true).catch((error) => {
10633
- if (isNotFound(error)) return false;
10634
- throw error;
10635
- });
10636
- }
10637
- async mkdir(path, options = {}) {
10638
- if (options.recursive) {
10639
- await this.createDirectoryRecursive(path, options.signal);
10640
- return normalizeRemotePath(path);
10641
- }
10642
- await this.createDirectory(path, options);
10643
- return void 0;
10644
- }
10645
- async readdir(path = "/", options = {}) {
10646
- const items = (await this.list(path, options)).filter(
10647
- (item) => comparableRemotePath(item.path) !== comparableRemotePath(path)
10648
- );
10649
- return options.withFileTypes ? items : items.map((item) => pathBaseName(item.path));
10650
- }
10651
- async rename(oldPath, newPath, options = {}) {
10652
- await this.request("MOVE", oldPath, {
10653
- expectedStatuses: [200, 201, 204],
10654
- headers: { Destination: (await this.resourceURL(newPath)).toString() },
10655
- operation: "WebTTY filesystem rename",
10656
- signal: options.signal
10657
- });
10658
- }
10659
- async rm(path, options = {}) {
10660
- void options.recursive;
10661
- await this.request("DELETE", path, {
10662
- expectedStatuses: deleteStatuses(options.force),
10663
- operation: "WebTTY filesystem delete",
10664
- signal: options.signal
10665
- });
10666
- }
10667
- async stat(path, options = {}) {
10668
- const response = await this.request("PROPFIND", path, {
10669
- body: webDAVPropfindBody,
10670
- expectedStatuses: [207],
10671
- headers: { "Content-Type": "application/xml; charset=utf-8", Depth: "0" },
10672
- operation: "WebTTY filesystem stat",
10673
- signal: options.signal
10674
- });
10675
- const item = parseWebDAVMultiStatus(
10676
- await response.text(),
10677
- sidecarPath(this.config.fsPath)
10678
- )[0];
10679
- if (item) return item;
10680
- throw new Error(`WebTTY filesystem stat did not return ${path}.`);
10681
- }
10682
- async delete(path, options = {}) {
10683
- await this.rm(path, options);
10684
- }
10685
- async createDirectoryRecursive(path, signal) {
10686
- const normalized = normalizeRemotePath(path);
10687
- if (normalized === "/") return;
10688
- const parent = parentPath(normalized);
10689
- if (parent !== normalized) {
10690
- await this.createDirectoryRecursive(parent, signal);
10691
- }
10692
- await this.createDirectory(normalized, { signal });
10693
- }
10694
- async resourceURL(path) {
10695
- return resolveWebTTYFileSystemURL(
10696
- await resolveURL2(this.config.url),
10697
- path,
10698
- this.config.fsPath
10699
- );
10700
- }
10701
- async request(method, path, options) {
10702
- return await requireResponseStatus(
10703
- await resolveFetch(this.config)(
10704
- await this.resourceURL(path),
10705
- requestInit(this.config, method, options)
10706
- ),
10707
- options.expectedStatuses,
10708
- options.operation
10709
- );
10547
+ var WebTTYFileSystem = class extends import_filesystem.RemoteFileSystem {
10548
+ createError(operation, status, message) {
10549
+ return new WebTTYFileSystemError(operation, status, message);
10710
10550
  }
10711
10551
  };
10712
10552
 
@@ -10969,7 +10809,7 @@ function payloadCryptoMetadataFromRecordedMetadata(metadata) {
10969
10809
  }
10970
10810
  return {
10971
10811
  aadContext: keyContextFromRecordedMetadata(metadata),
10972
- nonce: bytesFromBase64URL(metadata.nonce),
10812
+ nonce: metadata.payload_suite === "aes-256-gcm-random-nonce" && (metadata.nonce === void 0 || metadata.nonce === "") ? new Uint8Array() : bytesFromBase64URL(metadata.nonce),
10973
10813
  payloadKeyId: bytesFromBase64URL(metadata.payload_key_id),
10974
10814
  payloadSuite: metadata.payload_suite
10975
10815
  };
@@ -11276,6 +11116,12 @@ var knownServerKeyEnv = "RSTREAM_WEBTTY_KNOWN_SERVER_KEY";
11276
11116
  var knownServersFileEnv = "RSTREAM_WEBTTY_KNOWN_SERVERS_FILE";
11277
11117
  async function defaultWebTTYKnownServersPath(env) {
11278
11118
  const path = await nodePath();
11119
+ const dataDir = cleanString((env ?? defaultEnv()).RSTREAM_DATA_DIR);
11120
+ if (dataDir !== void 0) {
11121
+ if (!path.isAbsolute(dataDir))
11122
+ throw new Error("RSTREAM_DATA_DIR must be an absolute path.");
11123
+ return path.join(dataDir, "webtty", "known_servers.json");
11124
+ }
11279
11125
  return path.join(
11280
11126
  await homeDir(env ?? defaultEnv()),
11281
11127
  ".rstream",
@@ -11627,7 +11473,7 @@ function objectField(value, key) {
11627
11473
  if (typeof value !== "object" || value === null || Array.isArray(value)) {
11628
11474
  return void 0;
11629
11475
  }
11630
- return Object.fromEntries(Object.entries(value))[key];
11476
+ return Reflect.get(value, key);
11631
11477
  }
11632
11478
  function stringRecord(value) {
11633
11479
  if (typeof value !== "object" || value === null || Array.isArray(value)) {
@@ -11642,6 +11488,21 @@ function stringRecord(value) {
11642
11488
  function errorMessage(error) {
11643
11489
  return error instanceof Error ? error.message : String(error);
11644
11490
  }
11491
+
11492
+ // src/node-websocket.ts
11493
+ var import_ws = __toESM(require("ws"));
11494
+ var nodeWebSocketFactory = (url, options) => {
11495
+ const socketOptions = {
11496
+ closeTimeout: 1e3,
11497
+ handshakeTimeout: 1e4,
11498
+ maxPayload: options.maxMessageSize,
11499
+ perMessageDeflate: false
11500
+ };
11501
+ const socket = new import_ws.default(url, socketOptions);
11502
+ socket.binaryType = "arraybuffer";
11503
+ socket.on("error", () => void 0);
11504
+ return socket;
11505
+ };
11645
11506
  // Annotate the CommonJS export names for ESM import in node:
11646
11507
  0 && (module.exports = {
11647
11508
  WebTTY,
@@ -11669,6 +11530,7 @@ function errorMessage(error) {
11669
11530
  hashWebTTYServerProofTranscript,
11670
11531
  hashWebTTYSessionKeyGrant,
11671
11532
  loadWebTTYKnownServerKeysFile,
11533
+ nodeWebSocketFactory,
11672
11534
  openWebTTYCommand,
11673
11535
  parseWebDAVMultiStatus,
11674
11536
  parseWebTTYKnownServerKey,