@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/index.js CHANGED
@@ -53,7 +53,7 @@ __export(index_exports, {
53
53
  hashWebTTYServerProofTranscript: () => hashWebTTYServerProofTranscript,
54
54
  hashWebTTYSessionKeyGrant: () => hashWebTTYSessionKeyGrant,
55
55
  openWebTTYCommand: () => openWebTTYCommand,
56
- parseWebDAVMultiStatus: () => parseWebDAVMultiStatus,
56
+ parseWebDAVMultiStatus: () => import_filesystem4.parseWebDAVMultiStatus,
57
57
  renderWebTTYRecordedTextLog: () => renderWebTTYRecordedTextLog,
58
58
  resolveWebTTYExecutionURL: () => resolveWebTTYExecutionURL,
59
59
  resolveWebTTYFileSystemURL: () => resolveWebTTYFileSystemURL,
@@ -8664,6 +8664,74 @@ function base64URLDecode(value) {
8664
8664
  return out;
8665
8665
  }
8666
8666
 
8667
+ // src/transport-frames.ts
8668
+ var WebTTYFrameDecoder = class {
8669
+ constructor(maxMessageSize) {
8670
+ this.maxMessageSize = maxMessageSize;
8671
+ }
8672
+ maxMessageSize;
8673
+ header = new Uint8Array(4);
8674
+ headerBytes = 0;
8675
+ payload = null;
8676
+ payloadBytes = 0;
8677
+ get incomplete() {
8678
+ return this.headerBytes !== 0 || this.payload !== null;
8679
+ }
8680
+ reset() {
8681
+ this.headerBytes = 0;
8682
+ this.payload = null;
8683
+ this.payloadBytes = 0;
8684
+ }
8685
+ *push(chunk) {
8686
+ const cursor = { offset: 0 };
8687
+ while (cursor.offset < chunk.byteLength) {
8688
+ if (this.payload === null) {
8689
+ const count2 = Math.min(
8690
+ 4 - this.headerBytes,
8691
+ chunk.byteLength - cursor.offset
8692
+ );
8693
+ this.header.set(
8694
+ chunk.subarray(cursor.offset, cursor.offset + count2),
8695
+ this.headerBytes
8696
+ );
8697
+ this.headerBytes += count2;
8698
+ cursor.offset += count2;
8699
+ if (this.headerBytes !== 4) return;
8700
+ const size = new DataView(this.header.buffer).getUint32(0, false);
8701
+ if (size > this.maxMessageSize)
8702
+ throw new Error(
8703
+ `WebTTY message exceeds the ${this.maxMessageSize} byte limit.`
8704
+ );
8705
+ this.headerBytes = 0;
8706
+ if (chunk.byteLength - cursor.offset >= size) {
8707
+ const payload = chunk.subarray(cursor.offset, cursor.offset + size);
8708
+ cursor.offset += size;
8709
+ yield payload;
8710
+ continue;
8711
+ }
8712
+ this.payload = new Uint8Array(size);
8713
+ this.payloadBytes = 0;
8714
+ }
8715
+ const count = Math.min(
8716
+ this.payload.byteLength - this.payloadBytes,
8717
+ chunk.byteLength - cursor.offset
8718
+ );
8719
+ this.payload.set(
8720
+ chunk.subarray(cursor.offset, cursor.offset + count),
8721
+ this.payloadBytes
8722
+ );
8723
+ this.payloadBytes += count;
8724
+ cursor.offset += count;
8725
+ if (this.payloadBytes === this.payload.byteLength) {
8726
+ const payload = this.payload;
8727
+ this.payload = null;
8728
+ this.payloadBytes = 0;
8729
+ yield payload;
8730
+ }
8731
+ }
8732
+ }
8733
+ };
8734
+
8667
8735
  // src/webtty.ts
8668
8736
  function getErrorMessage(error) {
8669
8737
  return error instanceof Error ? error.message : String(error);
@@ -9053,12 +9121,15 @@ function resolveWebTransportConstructor() {
9053
9121
  function webTransportGlobal(value) {
9054
9122
  return "WebTransport" in value;
9055
9123
  }
9124
+ function browserWebSocket(url) {
9125
+ const socket = new WebSocket(url);
9126
+ socket.binaryType = "arraybuffer";
9127
+ return socket;
9128
+ }
9056
9129
  var WebSocketMessageConnection = class {
9057
- ws;
9058
- handlers;
9059
- constructor(url, handlers) {
9060
- this.ws = new WebSocket(url);
9061
- this.ws.binaryType = "arraybuffer";
9130
+ constructor(url, handlers, maxBufferedBytes, factory, maxMessageSize) {
9131
+ this.maxBufferedBytes = maxBufferedBytes;
9132
+ this.ws = factory ? factory(url, { maxMessageSize }) : browserWebSocket(url);
9062
9133
  this.handlers = {
9063
9134
  close: handlers.close,
9064
9135
  error: handlers.error,
@@ -9070,7 +9141,13 @@ var WebSocketMessageConnection = class {
9070
9141
  this.ws.addEventListener("error", this.handlers.error);
9071
9142
  this.ws.addEventListener("close", this.handlers.close);
9072
9143
  }
9144
+ maxBufferedBytes;
9145
+ ws;
9146
+ handlers;
9073
9147
  send(payload) {
9148
+ if (this.ws.bufferedAmount + payload.byteLength > this.maxBufferedBytes) {
9149
+ throw new Error("WebSocket write buffer limit exceeded.");
9150
+ }
9074
9151
  this.ws.send(getWebSocketPayload(payload));
9075
9152
  }
9076
9153
  close() {
@@ -9082,56 +9159,109 @@ var WebSocketMessageConnection = class {
9082
9159
  }
9083
9160
  };
9084
9161
  var WebTransportMessageConnection = class _WebTransportMessageConnection {
9085
- constructor(transport, stream, writer, handlers) {
9162
+ constructor(transport, stream, writer, maxMessageSize, handlers) {
9086
9163
  this.transport = transport;
9087
- this.stream = stream;
9088
9164
  this.writer = writer;
9165
+ this.maxMessageSize = maxMessageSize;
9089
9166
  this.handlers = handlers;
9167
+ this.decoder = new WebTTYFrameDecoder(maxMessageSize);
9168
+ this.reader = stream.readable.getReader();
9090
9169
  }
9091
9170
  transport;
9092
- stream;
9093
9171
  writer;
9172
+ maxMessageSize;
9094
9173
  handlers;
9095
9174
  closed = false;
9096
- readBuffer = new Uint8Array();
9097
- writeQueue = Promise.resolve();
9098
- static async open(url, options, handlers) {
9175
+ decoder;
9176
+ reader;
9177
+ writeQueue = [];
9178
+ writeHead = 0;
9179
+ bufferedBytes = 0;
9180
+ writing = false;
9181
+ static async open(url, options, signal, maxMessageSize, handlers) {
9182
+ signal.throwIfAborted();
9099
9183
  const Transport = resolveWebTransportConstructor();
9100
9184
  const transport = new Transport(url, options);
9101
- await transport.ready;
9102
- const stream = await transport.createBidirectionalStream();
9103
- const writer = stream.writable.getWriter();
9104
- const connection = new _WebTransportMessageConnection(
9105
- transport,
9106
- stream,
9107
- writer,
9108
- handlers
9109
- );
9110
- connection.startReadLoop();
9111
9185
  transport.closed.catch((error) => {
9112
- if (!connection.closed) {
9186
+ if (!signal.aborted) {
9113
9187
  handlers.error(`WebTransport closed: ${getErrorMessage(error)}`);
9114
9188
  }
9115
9189
  });
9116
- return connection;
9190
+ try {
9191
+ await waitForWebTransportOpen(transport.ready, signal);
9192
+ signal.throwIfAborted();
9193
+ const stream = await waitForWebTransportOpen(
9194
+ transport.createBidirectionalStream(),
9195
+ signal
9196
+ );
9197
+ signal.throwIfAborted();
9198
+ const writer = stream.writable.getWriter();
9199
+ const connection = new _WebTransportMessageConnection(
9200
+ transport,
9201
+ stream,
9202
+ writer,
9203
+ maxMessageSize,
9204
+ handlers
9205
+ );
9206
+ connection.startReadLoop();
9207
+ return connection;
9208
+ } catch (error) {
9209
+ transport.close({ closeCode: 0, reason: "open failed" });
9210
+ throw error;
9211
+ }
9117
9212
  }
9118
9213
  send(payload) {
9119
9214
  if (this.closed) return;
9215
+ if (payload.byteLength > this.maxMessageSize) {
9216
+ this.handlers.error(
9217
+ `WebTTY message exceeds the ${this.maxMessageSize} byte limit.`
9218
+ );
9219
+ return;
9220
+ }
9221
+ if (this.bufferedBytes + payload.byteLength + 4 > this.maxMessageSize * 4 || this.writeQueue.length - this.writeHead >= 1024) {
9222
+ this.handlers.error("WebTransport write buffer limit exceeded.");
9223
+ return;
9224
+ }
9120
9225
  const frame = getFramePayload(payload);
9121
- this.writeQueue = this.writeQueue.then(() => this.writer.write(frame)).catch((error) => {
9122
- if (!this.closed) {
9123
- this.handlers.error(
9124
- `WebTransport write failed: ${getErrorMessage(error)}`
9125
- );
9126
- }
9127
- });
9226
+ this.writeQueue.push(frame);
9227
+ this.bufferedBytes += frame.byteLength;
9228
+ if (!this.writing) {
9229
+ this.writing = true;
9230
+ void this.writeLoop();
9231
+ }
9128
9232
  }
9129
9233
  close() {
9130
9234
  if (this.closed) return;
9131
9235
  this.closed = true;
9132
- this.writer.releaseLock();
9236
+ this.writeQueue = [];
9237
+ this.writeHead = 0;
9238
+ this.decoder.reset();
9239
+ void this.reader.cancel().catch(() => void 0).finally(() => this.reader.releaseLock());
9240
+ void this.writer.abort().catch(() => void 0).finally(() => this.writer.releaseLock());
9133
9241
  this.transport.close({ closeCode: 0, reason: "closed" });
9134
9242
  }
9243
+ async writeLoop() {
9244
+ try {
9245
+ while (!this.closed && this.writeHead < this.writeQueue.length) {
9246
+ const frame = this.writeQueue[this.writeHead];
9247
+ this.writeQueue[this.writeHead++] = void 0;
9248
+ if (this.writeHead === this.writeQueue.length || this.writeHead >= 512) {
9249
+ this.writeQueue = this.writeQueue.slice(this.writeHead);
9250
+ this.writeHead = 0;
9251
+ }
9252
+ if (frame === void 0) continue;
9253
+ await this.writer.write(frame);
9254
+ this.bufferedBytes -= frame.byteLength;
9255
+ }
9256
+ } catch (error) {
9257
+ if (!this.closed)
9258
+ this.handlers.error(
9259
+ `WebTransport write failed: ${getErrorMessage(error)}`
9260
+ );
9261
+ } finally {
9262
+ this.writing = false;
9263
+ }
9264
+ }
9135
9265
  startReadLoop() {
9136
9266
  void this.readLoop().catch((error) => {
9137
9267
  if (!this.closed) {
@@ -9142,41 +9272,46 @@ var WebTransportMessageConnection = class _WebTransportMessageConnection {
9142
9272
  });
9143
9273
  }
9144
9274
  async readLoop() {
9145
- const reader = this.stream.readable.getReader();
9146
9275
  try {
9147
9276
  for (; ; ) {
9148
- const result = await reader.read();
9277
+ const result = await this.reader.read();
9278
+ if (this.closed) return;
9149
9279
  if (result.done) {
9150
- if (!this.closed) this.handlers.close();
9280
+ if (this.decoder.incomplete)
9281
+ throw new Error("Incomplete WebTTY frame at end of stream.");
9282
+ this.handlers.close();
9151
9283
  return;
9152
9284
  }
9153
- this.appendReadChunk(result.value);
9285
+ for (const payload of this.decoder.push(result.value)) {
9286
+ if (this.closed) return;
9287
+ await this.handlers.message(payload);
9288
+ if (this.closed) return;
9289
+ }
9154
9290
  }
9155
9291
  } finally {
9156
- reader.releaseLock();
9157
- }
9158
- }
9159
- appendReadChunk(chunk) {
9160
- const next = new Uint8Array(this.readBuffer.byteLength + chunk.byteLength);
9161
- next.set(this.readBuffer);
9162
- next.set(chunk, this.readBuffer.byteLength);
9163
- this.readBuffer = next;
9164
- for (; ; ) {
9165
- if (this.readBuffer.byteLength < 4) return;
9166
- const view = new DataView(
9167
- this.readBuffer.buffer,
9168
- this.readBuffer.byteOffset,
9169
- this.readBuffer.byteLength
9170
- );
9171
- const size = view.getUint32(0, false);
9172
- if (this.readBuffer.byteLength < 4 + size) return;
9173
- const payload = this.readBuffer.slice(4, 4 + size);
9174
- this.readBuffer = this.readBuffer.slice(4 + size);
9175
- this.handlers.message(payload);
9292
+ this.reader.releaseLock();
9176
9293
  }
9177
9294
  }
9178
9295
  };
9296
+ function waitForWebTransportOpen(pending, signal) {
9297
+ return new Promise((resolve, reject) => {
9298
+ const abort = () => reject(new Error("WebTransport connection cancelled."));
9299
+ signal.addEventListener("abort", abort, { once: true });
9300
+ if (signal.aborted) abort();
9301
+ pending.then(
9302
+ (value) => {
9303
+ signal.removeEventListener("abort", abort);
9304
+ resolve(value);
9305
+ },
9306
+ (error) => {
9307
+ signal.removeEventListener("abort", abort);
9308
+ reject(error);
9309
+ }
9310
+ );
9311
+ });
9312
+ }
9179
9313
  var WebTTY = class {
9314
+ connectionAbort = new AbortController();
9180
9315
  connection = null;
9181
9316
  connectionState = "preparing";
9182
9317
  heartbeatTimer = null;
@@ -9184,6 +9319,11 @@ var WebTTY = class {
9184
9319
  execConfig;
9185
9320
  events;
9186
9321
  receiveQueue = null;
9322
+ receivedBytes = 0;
9323
+ receivedMessages = 0;
9324
+ stdinClosed = false;
9325
+ stderrClosed = false;
9326
+ stdoutClosed = false;
9187
9327
  /**
9188
9328
  * Creates a new WebTTY instance.
9189
9329
  *
@@ -9192,6 +9332,12 @@ var WebTTY = class {
9192
9332
  * @param events - Event callbacks for the session.
9193
9333
  */
9194
9334
  constructor(clientConfig2, execConfig, events) {
9335
+ const maxMessageSize = clientConfig2.maxMessageSize ?? 1024 * 1024;
9336
+ if (!Number.isSafeInteger(maxMessageSize) || maxMessageSize < 1 || maxMessageSize > 4294967295) {
9337
+ throw new Error(
9338
+ "WebTTY maxMessageSize must be a positive 32-bit integer."
9339
+ );
9340
+ }
9195
9341
  const transport = resolveWebTTYClientTransport(
9196
9342
  clientConfig2.url,
9197
9343
  clientConfig2.transport
@@ -9215,9 +9361,11 @@ var WebTTY = class {
9215
9361
  endpointIdentity: clientConfig2.endpointIdentity,
9216
9362
  expectedServerIdentity: clientConfig2.expectedServerIdentity,
9217
9363
  heartbeatIntervalMs: clientConfig2.heartbeatIntervalMs ?? 5e3,
9364
+ maxMessageSize,
9218
9365
  sendHeartbeat: clientConfig2.sendHeartbeat ?? true,
9219
9366
  transport,
9220
9367
  url: clientConfig2.url,
9368
+ webSocketFactory: clientConfig2.webSocketFactory,
9221
9369
  webTransportOptions: clientConfig2.webTransportOptions
9222
9370
  };
9223
9371
  this.execConfig = {
@@ -9246,12 +9394,18 @@ var WebTTY = class {
9246
9394
  return;
9247
9395
  }
9248
9396
  const wsUrl = normalizeWebSocketURL(this.clientConfig.url);
9249
- this.connection = new WebSocketMessageConnection(wsUrl, {
9250
- close: this.handleClose,
9251
- error: this.handleError,
9252
- message: this.handleConnectionMessage,
9253
- open: this.handleOpen
9254
- });
9397
+ this.connection = new WebSocketMessageConnection(
9398
+ wsUrl,
9399
+ {
9400
+ close: this.handleClose,
9401
+ error: this.handleError,
9402
+ message: this.handleConnectionMessage,
9403
+ open: this.handleOpen
9404
+ },
9405
+ this.clientConfig.maxMessageSize * 4,
9406
+ this.clientConfig.webSocketFactory,
9407
+ this.clientConfig.maxMessageSize
9408
+ );
9255
9409
  }
9256
9410
  /**
9257
9411
  * Sends data to the remote server's STDIN.
@@ -9289,6 +9443,7 @@ var WebTTY = class {
9289
9443
  return;
9290
9444
  }
9291
9445
  const encrypted = await encrypt(data);
9446
+ this.assertCanWriteStdin();
9292
9447
  this.sendStdinPayload({
9293
9448
  encryptedData: encryptedPayloadToProto(encrypted)
9294
9449
  });
@@ -9300,6 +9455,9 @@ var WebTTY = class {
9300
9455
  if (this.execConfig.interactive === false) {
9301
9456
  throw new Error("STDIN is unavailable in non-interactive mode.");
9302
9457
  }
9458
+ if (this.stdinClosed) {
9459
+ throw new Error("WebTTY STDIN is already closed.");
9460
+ }
9303
9461
  }
9304
9462
  sendStdinPayload(payload) {
9305
9463
  this.send(
@@ -9321,6 +9479,8 @@ var WebTTY = class {
9321
9479
  if (this.execConfig.interactive === false) {
9322
9480
  throw new Error("STDIN is unavailable in non-interactive mode.");
9323
9481
  }
9482
+ if (this.stdinClosed) return;
9483
+ this.stdinClosed = true;
9324
9484
  this.send(
9325
9485
  new rstream.webtty.protobuf.Message({
9326
9486
  data: new rstream.webtty.protobuf.Data({
@@ -9658,6 +9818,8 @@ var WebTTY = class {
9658
9818
  const connection = await WebTransportMessageConnection.open(
9659
9819
  url,
9660
9820
  this.clientConfig.webTransportOptions,
9821
+ this.connectionAbort.signal,
9822
+ this.clientConfig.maxMessageSize,
9661
9823
  {
9662
9824
  close: this.handleClose,
9663
9825
  error: this.handleTransportError,
@@ -9675,16 +9837,46 @@ var WebTTY = class {
9675
9837
  }
9676
9838
  }
9677
9839
  handleConnectionMessage = (data) => {
9678
- const run = () => this.processMessage(data);
9840
+ if (this.connectionState === "closed") return;
9841
+ const payload = this.boundedMessagePayload(data);
9842
+ if (payload === null) return;
9843
+ this.receivedBytes += payload.byteLength;
9844
+ this.receivedMessages += 1;
9845
+ const run = () => this.processMessage(payload);
9846
+ const release = () => {
9847
+ this.receivedBytes -= payload.byteLength;
9848
+ this.receivedMessages -= 1;
9849
+ };
9679
9850
  if (this.receiveQueue) {
9680
- this.trackReceiveQueue(this.receiveQueue.then(run, run));
9681
- return;
9851
+ return this.trackReceiveQueue(
9852
+ this.receiveQueue.then(run, run).finally(release)
9853
+ );
9682
9854
  }
9683
9855
  const result = run();
9684
9856
  if (isPromiseLike(result)) {
9685
- this.trackReceiveQueue(result);
9857
+ return this.trackReceiveQueue(result.finally(release));
9686
9858
  }
9859
+ release();
9687
9860
  };
9861
+ boundedMessagePayload(data) {
9862
+ try {
9863
+ const payload = messagePayloadBytes(data);
9864
+ if (payload.byteLength > this.clientConfig.maxMessageSize) {
9865
+ this.close(
9866
+ `WebTTY message exceeds the ${this.clientConfig.maxMessageSize} byte limit.`
9867
+ );
9868
+ return null;
9869
+ }
9870
+ if (this.receivedBytes + payload.byteLength > this.clientConfig.maxMessageSize * 4 || this.receivedMessages >= 1024) {
9871
+ this.close("WebTTY receive buffer limit exceeded.");
9872
+ return null;
9873
+ }
9874
+ return payload;
9875
+ } catch (error) {
9876
+ this.close(`Failed to decode message: ${getErrorMessage(error)}`);
9877
+ return null;
9878
+ }
9879
+ }
9688
9880
  trackReceiveQueue(promise) {
9689
9881
  const queued = promise.catch((error) => {
9690
9882
  this.close(`Failed to decode message: ${getErrorMessage(error)}`);
@@ -9692,6 +9884,7 @@ var WebTTY = class {
9692
9884
  if (this.receiveQueue === queued) this.receiveQueue = null;
9693
9885
  });
9694
9886
  this.receiveQueue = queued;
9887
+ return queued;
9695
9888
  }
9696
9889
  processMessage(data) {
9697
9890
  if (!data) return;
@@ -9740,41 +9933,47 @@ var WebTTY = class {
9740
9933
  }
9741
9934
  }
9742
9935
  processDataMessage(data) {
9743
- if (data.type === rstream.webtty.protobuf.Data.Type.TYPE_STDOUT) {
9744
- if (data.data) {
9745
- this.events.onStdout?.(data.data);
9746
- }
9747
- if (data.encryptedData) {
9748
- const decrypted = this.decryptData("stdout", data.encryptedData);
9749
- if (isPromiseLike(decrypted)) {
9750
- return decrypted.then((chunk) => {
9751
- if (chunk !== null) this.events.onStdout?.(chunk);
9752
- });
9753
- }
9754
- if (decrypted === null) return;
9755
- this.events.onStdout?.(decrypted);
9756
- }
9757
- if (data.eos) {
9936
+ const stream = data.type === rstream.webtty.protobuf.Data.Type.TYPE_STDOUT ? "stdout" : data.type === rstream.webtty.protobuf.Data.Type.TYPE_STDERR ? "stderr" : null;
9937
+ if (stream === null) {
9938
+ this.close(`Unexpected WebTTY data stream type ${String(data.type)}.`);
9939
+ return;
9940
+ }
9941
+ const hasData = data.data !== void 0 && data.data !== null;
9942
+ const hasEncryptedData = data.encryptedData !== void 0 && data.encryptedData !== null;
9943
+ const hasEos = data.eos !== void 0 && data.eos !== null;
9944
+ if (Number(hasData) + Number(hasEncryptedData) + Number(hasEos) !== 1) {
9945
+ this.close(`Unexpected WebTTY ${stream} payload.`);
9946
+ return;
9947
+ }
9948
+ const streamClosed = stream === "stdout" ? this.stdoutClosed : this.stderrClosed;
9949
+ if (streamClosed) {
9950
+ this.close(
9951
+ hasEos ? `Duplicate WebTTY ${stream} end of stream.` : `WebTTY ${stream} data received after end of stream.`
9952
+ );
9953
+ return;
9954
+ }
9955
+ if (hasEos) {
9956
+ if (stream === "stdout") {
9957
+ this.stdoutClosed = true;
9758
9958
  this.events.onStdoutEos?.();
9759
- }
9760
- } else if (data.type === rstream.webtty.protobuf.Data.Type.TYPE_STDERR) {
9761
- if (data.data) {
9762
- this.events.onStderr?.(data.data);
9763
- }
9764
- if (data.encryptedData) {
9765
- const decrypted = this.decryptData("stderr", data.encryptedData);
9766
- if (isPromiseLike(decrypted)) {
9767
- return decrypted.then((chunk) => {
9768
- if (chunk !== null) this.events.onStderr?.(chunk);
9769
- });
9770
- }
9771
- if (decrypted === null) return;
9772
- this.events.onStderr?.(decrypted);
9773
- }
9774
- if (data.eos) {
9959
+ } else {
9960
+ this.stderrClosed = true;
9775
9961
  this.events.onStderrEos?.();
9776
9962
  }
9963
+ return;
9777
9964
  }
9965
+ const emit = stream === "stdout" ? this.events.onStdout : this.events.onStderr;
9966
+ if (hasData) {
9967
+ emit?.(data.data);
9968
+ return;
9969
+ }
9970
+ const decrypted = this.decryptData(stream, data.encryptedData);
9971
+ if (isPromiseLike(decrypted)) {
9972
+ return decrypted.then((chunk) => {
9973
+ if (chunk !== null && this.connectionState !== "closed") emit?.(chunk);
9974
+ });
9975
+ }
9976
+ if (decrypted !== null) emit?.(decrypted);
9778
9977
  }
9779
9978
  decryptData(stream, payload) {
9780
9979
  const decrypt = stream === "stdout" ? this.execConfig.payloadCrypto?.decryptStdout : this.execConfig.payloadCrypto?.decryptStderr;
@@ -9825,7 +10024,19 @@ var WebTTY = class {
9825
10024
  if (this.connectionState === "preparing" || this.connectionState === "closed")
9826
10025
  return;
9827
10026
  const buffer = rstream.webtty.protobuf.Message.encode(message).finish();
9828
- this.connection.send(buffer);
10027
+ if (buffer.byteLength > this.clientConfig.maxMessageSize) {
10028
+ this.close(
10029
+ `WebTTY message exceeds the ${this.clientConfig.maxMessageSize} byte limit.`
10030
+ );
10031
+ return;
10032
+ }
10033
+ try {
10034
+ this.connection.send(buffer);
10035
+ } catch (error) {
10036
+ this.close(
10037
+ `${this.clientConfig.transport} write failed: ${getErrorMessage(error)}`
10038
+ );
10039
+ }
9829
10040
  }
9830
10041
  /**
9831
10042
  * Closes the WebTTY session and fires exactly one of:
@@ -9838,6 +10049,7 @@ var WebTTY = class {
9838
10049
  return;
9839
10050
  }
9840
10051
  this.connectionState = "closed";
10052
+ this.connectionAbort.abort();
9841
10053
  if (this.heartbeatTimer) {
9842
10054
  clearInterval(this.heartbeatTimer);
9843
10055
  this.heartbeatTimer = null;
@@ -10315,393 +10527,20 @@ var WebTTYRemoteExecutor = class {
10315
10527
  };
10316
10528
 
10317
10529
  // src/filesystem.ts
10318
- var WebTTYFileSystemError = class extends Error {
10319
- operation;
10320
- status;
10530
+ var import_filesystem = require("@rstreamlabs/filesystem");
10531
+ var import_filesystem2 = require("@rstreamlabs/filesystem");
10532
+ var import_filesystem3 = require("@rstreamlabs/filesystem");
10533
+ var import_filesystem4 = require("@rstreamlabs/filesystem");
10534
+ var resolveWebTTYFileSystemURL = import_filesystem3.resolveFileSystemURL;
10535
+ var WebTTYFileSystemError = class extends import_filesystem2.FileSystemError {
10321
10536
  constructor(operation, status, message) {
10322
- super(`${operation} failed with status ${status}: ${message}`);
10537
+ super(operation, status, message);
10323
10538
  this.name = "WebTTYFileSystemError";
10324
- this.operation = operation;
10325
- this.status = status;
10326
10539
  }
10327
10540
  };
10328
- var webDAVPropfindBody = '<?xml version="1.0" encoding="utf-8"?><propfind xmlns="DAV:"><prop><resourcetype/><getcontentlength/><getlastmodified/></prop></propfind>';
10329
- function cleanTrailingSlashes2(value) {
10330
- return value.replace(/\/+$/, "");
10331
- }
10332
- function normalizeRemotePath(remotePath) {
10333
- const trimmed = remotePath.trim();
10334
- const absolute = trimmed === "" || trimmed === "." ? "/" : trimmed;
10335
- return new URL(
10336
- absolute.startsWith("/") ? absolute : `/${absolute}`,
10337
- "http://rstream.local"
10338
- ).pathname;
10339
- }
10340
- function comparableRemotePath(remotePath) {
10341
- const normalized = cleanTrailingSlashes2(normalizeRemotePath(remotePath));
10342
- return normalized === "" ? "/" : normalized;
10343
- }
10344
- function sidecarPath(fsPath) {
10345
- return normalizeRemotePath(fsPath ?? "/fs");
10346
- }
10347
- function filesystemBasePath(pathname, fsPath) {
10348
- const sidecar = sidecarPath(fsPath);
10349
- const basePath = cleanTrailingSlashes2(pathname);
10350
- if (basePath === "") return sidecar;
10351
- if (basePath === "/") return sidecar;
10352
- if (basePath === sidecar || basePath.startsWith(`${sidecar}/`))
10353
- return basePath;
10354
- return `${basePath}${sidecar}`;
10355
- }
10356
- function filesystemPath(pathname, remotePath, fsPath) {
10357
- const basePath = filesystemBasePath(pathname, fsPath);
10358
- const normalized = normalizeRemotePath(remotePath);
10359
- return normalized === "/" ? basePath : `${cleanTrailingSlashes2(basePath)}${normalized}`;
10360
- }
10361
- function resolveWebTTYFileSystemURL(input, remotePath = "/", fsPath) {
10362
- const url = new URL(input.toString());
10363
- if (url.protocol === "rstrm:") {
10364
- throw new Error(
10365
- "rstrm:// WebTTY filesystem URLs require the native rstream dialer."
10366
- );
10367
- }
10368
- if (url.protocol === "ws:") url.protocol = "http:";
10369
- if (url.protocol === "wss:") url.protocol = "https:";
10370
- if (url.protocol !== "http:" && url.protocol !== "https:") {
10371
- throw new Error(
10372
- `Unsupported WebTTY filesystem URL scheme "${url.protocol}".`
10373
- );
10374
- }
10375
- url.pathname = filesystemPath(url.pathname, remotePath, fsPath);
10376
- url.hash = "";
10377
- return url;
10378
- }
10379
- function responseAllowed(response, expectedStatuses) {
10380
- return expectedStatuses.includes(response.status);
10381
- }
10382
- async function responseErrorMessage(response) {
10383
- const text = (await response.text()).trim().slice(0, 4096);
10384
- return text === "" ? response.statusText : text;
10385
- }
10386
- async function requireResponseStatus(response, expectedStatuses, operation) {
10387
- if (responseAllowed(response, expectedStatuses)) return response;
10388
- throw new WebTTYFileSystemError(
10389
- operation,
10390
- response.status,
10391
- await responseErrorMessage(response)
10392
- );
10393
- }
10394
- function requireResponseBody(response, operation) {
10395
- if (response.body) return response.body;
10396
- throw new Error(
10397
- `${operation} failed because the response body is unavailable.`
10398
- );
10399
- }
10400
- function resolveFetch(config) {
10401
- if (config.fetch) return config.fetch;
10402
- if (typeof fetch === "undefined") {
10403
- throw new Error("fetch is unavailable in this runtime.");
10404
- }
10405
- return fetch;
10406
- }
10407
- function applyHeaders(target, source) {
10408
- const sourceHeaders = new Headers(source);
10409
- sourceHeaders.forEach((value, key) => target.set(key, value));
10410
- return target;
10411
- }
10412
- function requestHeaders(config, headers) {
10413
- const result = applyHeaders(new Headers(config.headers), headers);
10414
- if (config.authToken && config.authToken.trim() !== "") {
10415
- result.set("Authorization", `Bearer ${config.authToken.trim()}`);
10416
- }
10417
- return result;
10418
- }
10419
- function contentHeaders(contentType) {
10420
- return contentType === void 0 ? void 0 : { "Content-Type": contentType };
10421
- }
10422
- function deleteStatuses(force) {
10423
- return force ? [200, 204, 404] : [200, 204];
10424
- }
10425
- function isNotFound(error) {
10426
- return error instanceof WebTTYFileSystemError && error.status === 404;
10427
- }
10428
- function pathBaseName(path) {
10429
- const normalized = normalizeRemotePath(path);
10430
- const cleaned = cleanTrailingSlashes2(normalized);
10431
- return cleaned.slice(cleaned.lastIndexOf("/") + 1);
10432
- }
10433
- function parentPath(path) {
10434
- const normalized = cleanTrailingSlashes2(normalizeRemotePath(path));
10435
- const index = normalized.lastIndexOf("/");
10436
- if (index <= 0) return "/";
10437
- return normalized.slice(0, index);
10438
- }
10439
- function readFileEncoding(options) {
10440
- if (typeof options === "string") return options;
10441
- return options?.encoding === void 0 ? null : options.encoding;
10442
- }
10443
- function readFileSignal(options) {
10444
- return typeof options === "string" ? void 0 : options?.signal;
10445
- }
10446
- function textContentHeaders(contentType, data) {
10447
- if (contentType !== void 0) return { "Content-Type": contentType };
10448
- return typeof data === "string" ? { "Content-Type": "text/plain; charset=utf-8" } : void 0;
10449
- }
10450
- function bodyRequiresDuplex(body) {
10451
- return typeof ReadableStream !== "undefined" && body instanceof ReadableStream;
10452
- }
10453
- function requestInit(config, method, options) {
10454
- return {
10455
- body: options.body,
10456
- duplex: bodyRequiresDuplex(options.body) ? "half" : void 0,
10457
- headers: requestHeaders(config, options.headers),
10458
- method,
10459
- signal: options.signal
10460
- };
10461
- }
10462
- async function resolveURL2(url) {
10463
- return typeof url === "function" ? await url() : url;
10464
- }
10465
- function elementBodies(xml, name) {
10466
- return Array.from(
10467
- xml.matchAll(
10468
- new RegExp(
10469
- `<[^>]*:?${name}\\b[^>]*>([\\s\\S]*?)<\\/[^>]*:?${name}>`,
10470
- "gi"
10471
- )
10472
- ),
10473
- (match) => match[1] ?? ""
10474
- );
10475
- }
10476
- function hasElement(xml, name) {
10477
- return new RegExp(`<[^>]*:?${name}(\\s|/|>)`, "i").test(xml);
10478
- }
10479
- function stripTags(xml) {
10480
- return xml.replace(/<[^>]*>/g, "");
10481
- }
10482
- function decodeNumericEntity(value) {
10483
- const parsed = value.startsWith("&#x") ? Number.parseInt(value.slice(3, -1), 16) : Number.parseInt(value.slice(2, -1), 10);
10484
- return Number.isFinite(parsed) ? String.fromCodePoint(parsed) : value;
10485
- }
10486
- function decodeXmlText(value) {
10487
- 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, "&");
10488
- }
10489
- function elementText(xml, name) {
10490
- return decodeXmlText(stripTags(elementBodies(xml, name)[0] ?? "")).trim();
10491
- }
10492
- function okPropstat(response) {
10493
- return elementBodies(response, "propstat").find(
10494
- (propstat) => elementText(propstat, "status").includes(" 200 ")
10495
- ) ?? "";
10496
- }
10497
- function safeDecodePath(path) {
10498
- try {
10499
- return decodeURIComponent(path);
10500
- } catch {
10501
- return path;
10502
- }
10503
- }
10504
- function hrefPath(href) {
10505
- return safeDecodePath(new URL(href, "http://rstream.local").pathname);
10506
- }
10507
- function displayPath(href, fsPath) {
10508
- const value = hrefPath(href);
10509
- const sidecar = cleanTrailingSlashes2(sidecarPath(fsPath));
10510
- const withoutFS = value === sidecar ? "/" : value.startsWith(`${sidecar}/`) ? value.slice(sidecar.length) : value;
10511
- return withoutFS === "" ? "/" : withoutFS;
10512
- }
10513
- function itemSize(value) {
10514
- const parsed = Number.parseInt(value, 10);
10515
- return Number.isFinite(parsed) ? parsed : void 0;
10516
- }
10517
- function itemFromResponse(response, fsPath) {
10518
- const propstat = okPropstat(response);
10519
- const path = displayPath(elementText(response, "href"), fsPath);
10520
- if (propstat === "" || path === "") return null;
10521
- return {
10522
- kind: hasElement(
10523
- elementBodies(propstat, "resourcetype")[0] ?? "",
10524
- "collection"
10525
- ) ? "directory" : "file",
10526
- modified: elementText(propstat, "getlastmodified") || void 0,
10527
- path,
10528
- size: itemSize(elementText(propstat, "getcontentlength"))
10529
- };
10530
- }
10531
- function presentItems(items) {
10532
- return items.filter((item) => item !== null);
10533
- }
10534
- function parseWebDAVMultiStatus(xml, fsPath = "/fs") {
10535
- return presentItems(
10536
- elementBodies(xml, "response").map(
10537
- (response) => itemFromResponse(response, fsPath)
10538
- )
10539
- );
10540
- }
10541
- var WebTTYFileSystem = class {
10542
- config;
10543
- constructor(config) {
10544
- this.config = config;
10545
- }
10546
- async list(path = "/", options = {}) {
10547
- const response = await this.request("PROPFIND", path, {
10548
- body: webDAVPropfindBody,
10549
- expectedStatuses: [207],
10550
- headers: { "Content-Type": "application/xml; charset=utf-8", Depth: "1" },
10551
- operation: "WebTTY filesystem list",
10552
- signal: options.signal
10553
- });
10554
- return parseWebDAVMultiStatus(
10555
- await response.text(),
10556
- sidecarPath(this.config.fsPath)
10557
- );
10558
- }
10559
- async readBytes(path, options = {}) {
10560
- const response = await this.request("GET", path, {
10561
- expectedStatuses: [200],
10562
- operation: "WebTTY filesystem read",
10563
- signal: options.signal
10564
- });
10565
- return new Uint8Array(await response.arrayBuffer());
10566
- }
10567
- async readFile(path, options) {
10568
- const bytes = await this.readBytes(path, {
10569
- signal: readFileSignal(options)
10570
- });
10571
- const encoding = readFileEncoding(options);
10572
- return encoding === null ? bytes : new TextDecoder(encoding).decode(bytes);
10573
- }
10574
- async readText(path, options = {}) {
10575
- return new TextDecoder().decode(await this.readBytes(path, options));
10576
- }
10577
- async readStream(path, options = {}) {
10578
- return requireResponseBody(
10579
- await this.request("GET", path, {
10580
- expectedStatuses: [200],
10581
- operation: "WebTTY filesystem read",
10582
- signal: options.signal
10583
- }),
10584
- "WebTTY filesystem read"
10585
- );
10586
- }
10587
- async writeFile(path, data, options = {}) {
10588
- await this.request("PUT", path, {
10589
- body: data,
10590
- expectedStatuses: [200, 201, 204],
10591
- headers: textContentHeaders(options.contentType, data),
10592
- operation: "WebTTY filesystem write",
10593
- signal: options.signal
10594
- });
10595
- }
10596
- async writeBytes(path, data, options = {}) {
10597
- await this.writeFile(path, data, options);
10598
- }
10599
- async writeStream(path, data, options = {}) {
10600
- await this.request("PUT", path, {
10601
- body: data,
10602
- expectedStatuses: [200, 201, 204],
10603
- headers: contentHeaders(options.contentType),
10604
- operation: "WebTTY filesystem write",
10605
- signal: options.signal
10606
- });
10607
- }
10608
- async writeText(path, data, options = {}) {
10609
- await this.writeFile(path, data, options);
10610
- }
10611
- async copyFile(sourcePath, targetPath, options = {}) {
10612
- await this.request("COPY", sourcePath, {
10613
- expectedStatuses: [200, 201, 204],
10614
- headers: { Destination: (await this.resourceURL(targetPath)).toString() },
10615
- operation: "WebTTY filesystem copy",
10616
- signal: options.signal
10617
- });
10618
- }
10619
- async createDirectory(path, options = {}) {
10620
- await this.request("MKCOL", path, {
10621
- expectedStatuses: [201, 405],
10622
- operation: "WebTTY filesystem mkdir",
10623
- signal: options.signal
10624
- });
10625
- }
10626
- async exists(path, options = {}) {
10627
- return await this.stat(path, options).then(() => true).catch((error) => {
10628
- if (isNotFound(error)) return false;
10629
- throw error;
10630
- });
10631
- }
10632
- async mkdir(path, options = {}) {
10633
- if (options.recursive) {
10634
- await this.createDirectoryRecursive(path, options.signal);
10635
- return normalizeRemotePath(path);
10636
- }
10637
- await this.createDirectory(path, options);
10638
- return void 0;
10639
- }
10640
- async readdir(path = "/", options = {}) {
10641
- const items = (await this.list(path, options)).filter(
10642
- (item) => comparableRemotePath(item.path) !== comparableRemotePath(path)
10643
- );
10644
- return options.withFileTypes ? items : items.map((item) => pathBaseName(item.path));
10645
- }
10646
- async rename(oldPath, newPath, options = {}) {
10647
- await this.request("MOVE", oldPath, {
10648
- expectedStatuses: [200, 201, 204],
10649
- headers: { Destination: (await this.resourceURL(newPath)).toString() },
10650
- operation: "WebTTY filesystem rename",
10651
- signal: options.signal
10652
- });
10653
- }
10654
- async rm(path, options = {}) {
10655
- void options.recursive;
10656
- await this.request("DELETE", path, {
10657
- expectedStatuses: deleteStatuses(options.force),
10658
- operation: "WebTTY filesystem delete",
10659
- signal: options.signal
10660
- });
10661
- }
10662
- async stat(path, options = {}) {
10663
- const response = await this.request("PROPFIND", path, {
10664
- body: webDAVPropfindBody,
10665
- expectedStatuses: [207],
10666
- headers: { "Content-Type": "application/xml; charset=utf-8", Depth: "0" },
10667
- operation: "WebTTY filesystem stat",
10668
- signal: options.signal
10669
- });
10670
- const item = parseWebDAVMultiStatus(
10671
- await response.text(),
10672
- sidecarPath(this.config.fsPath)
10673
- )[0];
10674
- if (item) return item;
10675
- throw new Error(`WebTTY filesystem stat did not return ${path}.`);
10676
- }
10677
- async delete(path, options = {}) {
10678
- await this.rm(path, options);
10679
- }
10680
- async createDirectoryRecursive(path, signal) {
10681
- const normalized = normalizeRemotePath(path);
10682
- if (normalized === "/") return;
10683
- const parent = parentPath(normalized);
10684
- if (parent !== normalized) {
10685
- await this.createDirectoryRecursive(parent, signal);
10686
- }
10687
- await this.createDirectory(normalized, { signal });
10688
- }
10689
- async resourceURL(path) {
10690
- return resolveWebTTYFileSystemURL(
10691
- await resolveURL2(this.config.url),
10692
- path,
10693
- this.config.fsPath
10694
- );
10695
- }
10696
- async request(method, path, options) {
10697
- return await requireResponseStatus(
10698
- await resolveFetch(this.config)(
10699
- await this.resourceURL(path),
10700
- requestInit(this.config, method, options)
10701
- ),
10702
- options.expectedStatuses,
10703
- options.operation
10704
- );
10541
+ var WebTTYFileSystem = class extends import_filesystem.RemoteFileSystem {
10542
+ createError(operation, status, message) {
10543
+ return new WebTTYFileSystemError(operation, status, message);
10705
10544
  }
10706
10545
  };
10707
10546
 
@@ -10964,7 +10803,7 @@ function payloadCryptoMetadataFromRecordedMetadata(metadata) {
10964
10803
  }
10965
10804
  return {
10966
10805
  aadContext: keyContextFromRecordedMetadata(metadata),
10967
- nonce: bytesFromBase64URL(metadata.nonce),
10806
+ nonce: metadata.payload_suite === "aes-256-gcm-random-nonce" && (metadata.nonce === void 0 || metadata.nonce === "") ? new Uint8Array() : bytesFromBase64URL(metadata.nonce),
10968
10807
  payloadKeyId: bytesFromBase64URL(metadata.payload_key_id),
10969
10808
  payloadSuite: metadata.payload_suite
10970
10809
  };