@rstreamlabs/webtty 1.10.0 → 1.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -8590,6 +8590,74 @@ function base64URLDecode(value) {
8590
8590
  return out;
8591
8591
  }
8592
8592
 
8593
+ // src/transport-frames.ts
8594
+ var WebTTYFrameDecoder = class {
8595
+ constructor(maxMessageSize) {
8596
+ this.maxMessageSize = maxMessageSize;
8597
+ }
8598
+ maxMessageSize;
8599
+ header = new Uint8Array(4);
8600
+ headerBytes = 0;
8601
+ payload = null;
8602
+ payloadBytes = 0;
8603
+ get incomplete() {
8604
+ return this.headerBytes !== 0 || this.payload !== null;
8605
+ }
8606
+ reset() {
8607
+ this.headerBytes = 0;
8608
+ this.payload = null;
8609
+ this.payloadBytes = 0;
8610
+ }
8611
+ *push(chunk) {
8612
+ const cursor = { offset: 0 };
8613
+ while (cursor.offset < chunk.byteLength) {
8614
+ if (this.payload === null) {
8615
+ const count2 = Math.min(
8616
+ 4 - this.headerBytes,
8617
+ chunk.byteLength - cursor.offset
8618
+ );
8619
+ this.header.set(
8620
+ chunk.subarray(cursor.offset, cursor.offset + count2),
8621
+ this.headerBytes
8622
+ );
8623
+ this.headerBytes += count2;
8624
+ cursor.offset += count2;
8625
+ if (this.headerBytes !== 4) return;
8626
+ const size = new DataView(this.header.buffer).getUint32(0, false);
8627
+ if (size > this.maxMessageSize)
8628
+ throw new Error(
8629
+ `WebTTY message exceeds the ${this.maxMessageSize} byte limit.`
8630
+ );
8631
+ this.headerBytes = 0;
8632
+ if (chunk.byteLength - cursor.offset >= size) {
8633
+ const payload = chunk.subarray(cursor.offset, cursor.offset + size);
8634
+ cursor.offset += size;
8635
+ yield payload;
8636
+ continue;
8637
+ }
8638
+ this.payload = new Uint8Array(size);
8639
+ this.payloadBytes = 0;
8640
+ }
8641
+ const count = Math.min(
8642
+ this.payload.byteLength - this.payloadBytes,
8643
+ chunk.byteLength - cursor.offset
8644
+ );
8645
+ this.payload.set(
8646
+ chunk.subarray(cursor.offset, cursor.offset + count),
8647
+ this.payloadBytes
8648
+ );
8649
+ this.payloadBytes += count;
8650
+ cursor.offset += count;
8651
+ if (this.payloadBytes === this.payload.byteLength) {
8652
+ const payload = this.payload;
8653
+ this.payload = null;
8654
+ this.payloadBytes = 0;
8655
+ yield payload;
8656
+ }
8657
+ }
8658
+ }
8659
+ };
8660
+
8593
8661
  // src/webtty.ts
8594
8662
  function getErrorMessage(error) {
8595
8663
  return error instanceof Error ? error.message : String(error);
@@ -8979,12 +9047,15 @@ function resolveWebTransportConstructor() {
8979
9047
  function webTransportGlobal(value) {
8980
9048
  return "WebTransport" in value;
8981
9049
  }
9050
+ function browserWebSocket(url) {
9051
+ const socket = new WebSocket(url);
9052
+ socket.binaryType = "arraybuffer";
9053
+ return socket;
9054
+ }
8982
9055
  var WebSocketMessageConnection = class {
8983
- ws;
8984
- handlers;
8985
- constructor(url, handlers) {
8986
- this.ws = new WebSocket(url);
8987
- this.ws.binaryType = "arraybuffer";
9056
+ constructor(url, handlers, maxBufferedBytes, factory, maxMessageSize) {
9057
+ this.maxBufferedBytes = maxBufferedBytes;
9058
+ this.ws = factory ? factory(url, { maxMessageSize }) : browserWebSocket(url);
8988
9059
  this.handlers = {
8989
9060
  close: handlers.close,
8990
9061
  error: handlers.error,
@@ -8996,7 +9067,13 @@ var WebSocketMessageConnection = class {
8996
9067
  this.ws.addEventListener("error", this.handlers.error);
8997
9068
  this.ws.addEventListener("close", this.handlers.close);
8998
9069
  }
9070
+ maxBufferedBytes;
9071
+ ws;
9072
+ handlers;
8999
9073
  send(payload) {
9074
+ if (this.ws.bufferedAmount + payload.byteLength > this.maxBufferedBytes) {
9075
+ throw new Error("WebSocket write buffer limit exceeded.");
9076
+ }
9000
9077
  this.ws.send(getWebSocketPayload(payload));
9001
9078
  }
9002
9079
  close() {
@@ -9008,56 +9085,109 @@ var WebSocketMessageConnection = class {
9008
9085
  }
9009
9086
  };
9010
9087
  var WebTransportMessageConnection = class _WebTransportMessageConnection {
9011
- constructor(transport, stream, writer, handlers) {
9088
+ constructor(transport, stream, writer, maxMessageSize, handlers) {
9012
9089
  this.transport = transport;
9013
- this.stream = stream;
9014
9090
  this.writer = writer;
9091
+ this.maxMessageSize = maxMessageSize;
9015
9092
  this.handlers = handlers;
9093
+ this.decoder = new WebTTYFrameDecoder(maxMessageSize);
9094
+ this.reader = stream.readable.getReader();
9016
9095
  }
9017
9096
  transport;
9018
- stream;
9019
9097
  writer;
9098
+ maxMessageSize;
9020
9099
  handlers;
9021
9100
  closed = false;
9022
- readBuffer = new Uint8Array();
9023
- writeQueue = Promise.resolve();
9024
- static async open(url, options, handlers) {
9101
+ decoder;
9102
+ reader;
9103
+ writeQueue = [];
9104
+ writeHead = 0;
9105
+ bufferedBytes = 0;
9106
+ writing = false;
9107
+ static async open(url, options, signal, maxMessageSize, handlers) {
9108
+ signal.throwIfAborted();
9025
9109
  const Transport = resolveWebTransportConstructor();
9026
9110
  const transport = new Transport(url, options);
9027
- await transport.ready;
9028
- const stream = await transport.createBidirectionalStream();
9029
- const writer = stream.writable.getWriter();
9030
- const connection = new _WebTransportMessageConnection(
9031
- transport,
9032
- stream,
9033
- writer,
9034
- handlers
9035
- );
9036
- connection.startReadLoop();
9037
9111
  transport.closed.catch((error) => {
9038
- if (!connection.closed) {
9112
+ if (!signal.aborted) {
9039
9113
  handlers.error(`WebTransport closed: ${getErrorMessage(error)}`);
9040
9114
  }
9041
9115
  });
9042
- return connection;
9116
+ try {
9117
+ await waitForWebTransportOpen(transport.ready, signal);
9118
+ signal.throwIfAborted();
9119
+ const stream = await waitForWebTransportOpen(
9120
+ transport.createBidirectionalStream(),
9121
+ signal
9122
+ );
9123
+ signal.throwIfAborted();
9124
+ const writer = stream.writable.getWriter();
9125
+ const connection = new _WebTransportMessageConnection(
9126
+ transport,
9127
+ stream,
9128
+ writer,
9129
+ maxMessageSize,
9130
+ handlers
9131
+ );
9132
+ connection.startReadLoop();
9133
+ return connection;
9134
+ } catch (error) {
9135
+ transport.close({ closeCode: 0, reason: "open failed" });
9136
+ throw error;
9137
+ }
9043
9138
  }
9044
9139
  send(payload) {
9045
9140
  if (this.closed) return;
9141
+ if (payload.byteLength > this.maxMessageSize) {
9142
+ this.handlers.error(
9143
+ `WebTTY message exceeds the ${this.maxMessageSize} byte limit.`
9144
+ );
9145
+ return;
9146
+ }
9147
+ if (this.bufferedBytes + payload.byteLength + 4 > this.maxMessageSize * 4 || this.writeQueue.length - this.writeHead >= 1024) {
9148
+ this.handlers.error("WebTransport write buffer limit exceeded.");
9149
+ return;
9150
+ }
9046
9151
  const frame = getFramePayload(payload);
9047
- this.writeQueue = this.writeQueue.then(() => this.writer.write(frame)).catch((error) => {
9048
- if (!this.closed) {
9049
- this.handlers.error(
9050
- `WebTransport write failed: ${getErrorMessage(error)}`
9051
- );
9052
- }
9053
- });
9152
+ this.writeQueue.push(frame);
9153
+ this.bufferedBytes += frame.byteLength;
9154
+ if (!this.writing) {
9155
+ this.writing = true;
9156
+ void this.writeLoop();
9157
+ }
9054
9158
  }
9055
9159
  close() {
9056
9160
  if (this.closed) return;
9057
9161
  this.closed = true;
9058
- this.writer.releaseLock();
9162
+ this.writeQueue = [];
9163
+ this.writeHead = 0;
9164
+ this.decoder.reset();
9165
+ void this.reader.cancel().catch(() => void 0).finally(() => this.reader.releaseLock());
9166
+ void this.writer.abort().catch(() => void 0).finally(() => this.writer.releaseLock());
9059
9167
  this.transport.close({ closeCode: 0, reason: "closed" });
9060
9168
  }
9169
+ async writeLoop() {
9170
+ try {
9171
+ while (!this.closed && this.writeHead < this.writeQueue.length) {
9172
+ const frame = this.writeQueue[this.writeHead];
9173
+ this.writeQueue[this.writeHead++] = void 0;
9174
+ if (this.writeHead === this.writeQueue.length || this.writeHead >= 512) {
9175
+ this.writeQueue = this.writeQueue.slice(this.writeHead);
9176
+ this.writeHead = 0;
9177
+ }
9178
+ if (frame === void 0) continue;
9179
+ await this.writer.write(frame);
9180
+ this.bufferedBytes -= frame.byteLength;
9181
+ }
9182
+ } catch (error) {
9183
+ if (!this.closed)
9184
+ this.handlers.error(
9185
+ `WebTransport write failed: ${getErrorMessage(error)}`
9186
+ );
9187
+ } finally {
9188
+ this.writing = false;
9189
+ }
9190
+ }
9061
9191
  startReadLoop() {
9062
9192
  void this.readLoop().catch((error) => {
9063
9193
  if (!this.closed) {
@@ -9068,41 +9198,46 @@ var WebTransportMessageConnection = class _WebTransportMessageConnection {
9068
9198
  });
9069
9199
  }
9070
9200
  async readLoop() {
9071
- const reader = this.stream.readable.getReader();
9072
9201
  try {
9073
9202
  for (; ; ) {
9074
- const result = await reader.read();
9203
+ const result = await this.reader.read();
9204
+ if (this.closed) return;
9075
9205
  if (result.done) {
9076
- if (!this.closed) this.handlers.close();
9206
+ if (this.decoder.incomplete)
9207
+ throw new Error("Incomplete WebTTY frame at end of stream.");
9208
+ this.handlers.close();
9077
9209
  return;
9078
9210
  }
9079
- this.appendReadChunk(result.value);
9211
+ for (const payload of this.decoder.push(result.value)) {
9212
+ if (this.closed) return;
9213
+ await this.handlers.message(payload);
9214
+ if (this.closed) return;
9215
+ }
9080
9216
  }
9081
9217
  } finally {
9082
- reader.releaseLock();
9083
- }
9084
- }
9085
- appendReadChunk(chunk) {
9086
- const next = new Uint8Array(this.readBuffer.byteLength + chunk.byteLength);
9087
- next.set(this.readBuffer);
9088
- next.set(chunk, this.readBuffer.byteLength);
9089
- this.readBuffer = next;
9090
- for (; ; ) {
9091
- if (this.readBuffer.byteLength < 4) return;
9092
- const view = new DataView(
9093
- this.readBuffer.buffer,
9094
- this.readBuffer.byteOffset,
9095
- this.readBuffer.byteLength
9096
- );
9097
- const size = view.getUint32(0, false);
9098
- if (this.readBuffer.byteLength < 4 + size) return;
9099
- const payload = this.readBuffer.slice(4, 4 + size);
9100
- this.readBuffer = this.readBuffer.slice(4 + size);
9101
- this.handlers.message(payload);
9218
+ this.reader.releaseLock();
9102
9219
  }
9103
9220
  }
9104
9221
  };
9222
+ function waitForWebTransportOpen(pending, signal) {
9223
+ return new Promise((resolve, reject) => {
9224
+ const abort = () => reject(new Error("WebTransport connection cancelled."));
9225
+ signal.addEventListener("abort", abort, { once: true });
9226
+ if (signal.aborted) abort();
9227
+ pending.then(
9228
+ (value) => {
9229
+ signal.removeEventListener("abort", abort);
9230
+ resolve(value);
9231
+ },
9232
+ (error) => {
9233
+ signal.removeEventListener("abort", abort);
9234
+ reject(error);
9235
+ }
9236
+ );
9237
+ });
9238
+ }
9105
9239
  var WebTTY = class {
9240
+ connectionAbort = new AbortController();
9106
9241
  connection = null;
9107
9242
  connectionState = "preparing";
9108
9243
  heartbeatTimer = null;
@@ -9110,6 +9245,11 @@ var WebTTY = class {
9110
9245
  execConfig;
9111
9246
  events;
9112
9247
  receiveQueue = null;
9248
+ receivedBytes = 0;
9249
+ receivedMessages = 0;
9250
+ stdinClosed = false;
9251
+ stderrClosed = false;
9252
+ stdoutClosed = false;
9113
9253
  /**
9114
9254
  * Creates a new WebTTY instance.
9115
9255
  *
@@ -9118,6 +9258,12 @@ var WebTTY = class {
9118
9258
  * @param events - Event callbacks for the session.
9119
9259
  */
9120
9260
  constructor(clientConfig2, execConfig, events) {
9261
+ const maxMessageSize = clientConfig2.maxMessageSize ?? 1024 * 1024;
9262
+ if (!Number.isSafeInteger(maxMessageSize) || maxMessageSize < 1 || maxMessageSize > 4294967295) {
9263
+ throw new Error(
9264
+ "WebTTY maxMessageSize must be a positive 32-bit integer."
9265
+ );
9266
+ }
9121
9267
  const transport = resolveWebTTYClientTransport(
9122
9268
  clientConfig2.url,
9123
9269
  clientConfig2.transport
@@ -9141,9 +9287,11 @@ var WebTTY = class {
9141
9287
  endpointIdentity: clientConfig2.endpointIdentity,
9142
9288
  expectedServerIdentity: clientConfig2.expectedServerIdentity,
9143
9289
  heartbeatIntervalMs: clientConfig2.heartbeatIntervalMs ?? 5e3,
9290
+ maxMessageSize,
9144
9291
  sendHeartbeat: clientConfig2.sendHeartbeat ?? true,
9145
9292
  transport,
9146
9293
  url: clientConfig2.url,
9294
+ webSocketFactory: clientConfig2.webSocketFactory,
9147
9295
  webTransportOptions: clientConfig2.webTransportOptions
9148
9296
  };
9149
9297
  this.execConfig = {
@@ -9172,12 +9320,18 @@ var WebTTY = class {
9172
9320
  return;
9173
9321
  }
9174
9322
  const wsUrl = normalizeWebSocketURL(this.clientConfig.url);
9175
- this.connection = new WebSocketMessageConnection(wsUrl, {
9176
- close: this.handleClose,
9177
- error: this.handleError,
9178
- message: this.handleConnectionMessage,
9179
- open: this.handleOpen
9180
- });
9323
+ this.connection = new WebSocketMessageConnection(
9324
+ wsUrl,
9325
+ {
9326
+ close: this.handleClose,
9327
+ error: this.handleError,
9328
+ message: this.handleConnectionMessage,
9329
+ open: this.handleOpen
9330
+ },
9331
+ this.clientConfig.maxMessageSize * 4,
9332
+ this.clientConfig.webSocketFactory,
9333
+ this.clientConfig.maxMessageSize
9334
+ );
9181
9335
  }
9182
9336
  /**
9183
9337
  * Sends data to the remote server's STDIN.
@@ -9215,6 +9369,7 @@ var WebTTY = class {
9215
9369
  return;
9216
9370
  }
9217
9371
  const encrypted = await encrypt(data);
9372
+ this.assertCanWriteStdin();
9218
9373
  this.sendStdinPayload({
9219
9374
  encryptedData: encryptedPayloadToProto(encrypted)
9220
9375
  });
@@ -9226,6 +9381,9 @@ var WebTTY = class {
9226
9381
  if (this.execConfig.interactive === false) {
9227
9382
  throw new Error("STDIN is unavailable in non-interactive mode.");
9228
9383
  }
9384
+ if (this.stdinClosed) {
9385
+ throw new Error("WebTTY STDIN is already closed.");
9386
+ }
9229
9387
  }
9230
9388
  sendStdinPayload(payload) {
9231
9389
  this.send(
@@ -9247,6 +9405,8 @@ var WebTTY = class {
9247
9405
  if (this.execConfig.interactive === false) {
9248
9406
  throw new Error("STDIN is unavailable in non-interactive mode.");
9249
9407
  }
9408
+ if (this.stdinClosed) return;
9409
+ this.stdinClosed = true;
9250
9410
  this.send(
9251
9411
  new rstream.webtty.protobuf.Message({
9252
9412
  data: new rstream.webtty.protobuf.Data({
@@ -9584,6 +9744,8 @@ var WebTTY = class {
9584
9744
  const connection = await WebTransportMessageConnection.open(
9585
9745
  url,
9586
9746
  this.clientConfig.webTransportOptions,
9747
+ this.connectionAbort.signal,
9748
+ this.clientConfig.maxMessageSize,
9587
9749
  {
9588
9750
  close: this.handleClose,
9589
9751
  error: this.handleTransportError,
@@ -9601,16 +9763,46 @@ var WebTTY = class {
9601
9763
  }
9602
9764
  }
9603
9765
  handleConnectionMessage = (data) => {
9604
- const run = () => this.processMessage(data);
9766
+ if (this.connectionState === "closed") return;
9767
+ const payload = this.boundedMessagePayload(data);
9768
+ if (payload === null) return;
9769
+ this.receivedBytes += payload.byteLength;
9770
+ this.receivedMessages += 1;
9771
+ const run = () => this.processMessage(payload);
9772
+ const release = () => {
9773
+ this.receivedBytes -= payload.byteLength;
9774
+ this.receivedMessages -= 1;
9775
+ };
9605
9776
  if (this.receiveQueue) {
9606
- this.trackReceiveQueue(this.receiveQueue.then(run, run));
9607
- return;
9777
+ return this.trackReceiveQueue(
9778
+ this.receiveQueue.then(run, run).finally(release)
9779
+ );
9608
9780
  }
9609
9781
  const result = run();
9610
9782
  if (isPromiseLike(result)) {
9611
- this.trackReceiveQueue(result);
9783
+ return this.trackReceiveQueue(result.finally(release));
9612
9784
  }
9785
+ release();
9613
9786
  };
9787
+ boundedMessagePayload(data) {
9788
+ try {
9789
+ const payload = messagePayloadBytes(data);
9790
+ if (payload.byteLength > this.clientConfig.maxMessageSize) {
9791
+ this.close(
9792
+ `WebTTY message exceeds the ${this.clientConfig.maxMessageSize} byte limit.`
9793
+ );
9794
+ return null;
9795
+ }
9796
+ if (this.receivedBytes + payload.byteLength > this.clientConfig.maxMessageSize * 4 || this.receivedMessages >= 1024) {
9797
+ this.close("WebTTY receive buffer limit exceeded.");
9798
+ return null;
9799
+ }
9800
+ return payload;
9801
+ } catch (error) {
9802
+ this.close(`Failed to decode message: ${getErrorMessage(error)}`);
9803
+ return null;
9804
+ }
9805
+ }
9614
9806
  trackReceiveQueue(promise) {
9615
9807
  const queued = promise.catch((error) => {
9616
9808
  this.close(`Failed to decode message: ${getErrorMessage(error)}`);
@@ -9618,6 +9810,7 @@ var WebTTY = class {
9618
9810
  if (this.receiveQueue === queued) this.receiveQueue = null;
9619
9811
  });
9620
9812
  this.receiveQueue = queued;
9813
+ return queued;
9621
9814
  }
9622
9815
  processMessage(data) {
9623
9816
  if (!data) return;
@@ -9666,41 +9859,47 @@ var WebTTY = class {
9666
9859
  }
9667
9860
  }
9668
9861
  processDataMessage(data) {
9669
- if (data.type === rstream.webtty.protobuf.Data.Type.TYPE_STDOUT) {
9670
- if (data.data) {
9671
- this.events.onStdout?.(data.data);
9672
- }
9673
- if (data.encryptedData) {
9674
- const decrypted = this.decryptData("stdout", data.encryptedData);
9675
- if (isPromiseLike(decrypted)) {
9676
- return decrypted.then((chunk) => {
9677
- if (chunk !== null) this.events.onStdout?.(chunk);
9678
- });
9679
- }
9680
- if (decrypted === null) return;
9681
- this.events.onStdout?.(decrypted);
9682
- }
9683
- if (data.eos) {
9862
+ const stream = data.type === rstream.webtty.protobuf.Data.Type.TYPE_STDOUT ? "stdout" : data.type === rstream.webtty.protobuf.Data.Type.TYPE_STDERR ? "stderr" : null;
9863
+ if (stream === null) {
9864
+ this.close(`Unexpected WebTTY data stream type ${String(data.type)}.`);
9865
+ return;
9866
+ }
9867
+ const hasData = data.data !== void 0 && data.data !== null;
9868
+ const hasEncryptedData = data.encryptedData !== void 0 && data.encryptedData !== null;
9869
+ const hasEos = data.eos !== void 0 && data.eos !== null;
9870
+ if (Number(hasData) + Number(hasEncryptedData) + Number(hasEos) !== 1) {
9871
+ this.close(`Unexpected WebTTY ${stream} payload.`);
9872
+ return;
9873
+ }
9874
+ const streamClosed = stream === "stdout" ? this.stdoutClosed : this.stderrClosed;
9875
+ if (streamClosed) {
9876
+ this.close(
9877
+ hasEos ? `Duplicate WebTTY ${stream} end of stream.` : `WebTTY ${stream} data received after end of stream.`
9878
+ );
9879
+ return;
9880
+ }
9881
+ if (hasEos) {
9882
+ if (stream === "stdout") {
9883
+ this.stdoutClosed = true;
9684
9884
  this.events.onStdoutEos?.();
9685
- }
9686
- } else if (data.type === rstream.webtty.protobuf.Data.Type.TYPE_STDERR) {
9687
- if (data.data) {
9688
- this.events.onStderr?.(data.data);
9689
- }
9690
- if (data.encryptedData) {
9691
- const decrypted = this.decryptData("stderr", data.encryptedData);
9692
- if (isPromiseLike(decrypted)) {
9693
- return decrypted.then((chunk) => {
9694
- if (chunk !== null) this.events.onStderr?.(chunk);
9695
- });
9696
- }
9697
- if (decrypted === null) return;
9698
- this.events.onStderr?.(decrypted);
9699
- }
9700
- if (data.eos) {
9885
+ } else {
9886
+ this.stderrClosed = true;
9701
9887
  this.events.onStderrEos?.();
9702
9888
  }
9889
+ return;
9890
+ }
9891
+ const emit = stream === "stdout" ? this.events.onStdout : this.events.onStderr;
9892
+ if (hasData) {
9893
+ emit?.(data.data);
9894
+ return;
9703
9895
  }
9896
+ const decrypted = this.decryptData(stream, data.encryptedData);
9897
+ if (isPromiseLike(decrypted)) {
9898
+ return decrypted.then((chunk) => {
9899
+ if (chunk !== null && this.connectionState !== "closed") emit?.(chunk);
9900
+ });
9901
+ }
9902
+ if (decrypted !== null) emit?.(decrypted);
9704
9903
  }
9705
9904
  decryptData(stream, payload) {
9706
9905
  const decrypt = stream === "stdout" ? this.execConfig.payloadCrypto?.decryptStdout : this.execConfig.payloadCrypto?.decryptStderr;
@@ -9751,7 +9950,19 @@ var WebTTY = class {
9751
9950
  if (this.connectionState === "preparing" || this.connectionState === "closed")
9752
9951
  return;
9753
9952
  const buffer = rstream.webtty.protobuf.Message.encode(message).finish();
9754
- this.connection.send(buffer);
9953
+ if (buffer.byteLength > this.clientConfig.maxMessageSize) {
9954
+ this.close(
9955
+ `WebTTY message exceeds the ${this.clientConfig.maxMessageSize} byte limit.`
9956
+ );
9957
+ return;
9958
+ }
9959
+ try {
9960
+ this.connection.send(buffer);
9961
+ } catch (error) {
9962
+ this.close(
9963
+ `${this.clientConfig.transport} write failed: ${getErrorMessage(error)}`
9964
+ );
9965
+ }
9755
9966
  }
9756
9967
  /**
9757
9968
  * Closes the WebTTY session and fires exactly one of:
@@ -9764,6 +9975,7 @@ var WebTTY = class {
9764
9975
  return;
9765
9976
  }
9766
9977
  this.connectionState = "closed";
9978
+ this.connectionAbort.abort();
9767
9979
  if (this.heartbeatTimer) {
9768
9980
  clearInterval(this.heartbeatTimer);
9769
9981
  this.heartbeatTimer = null;
@@ -10241,393 +10453,20 @@ var WebTTYRemoteExecutor = class {
10241
10453
  };
10242
10454
 
10243
10455
  // src/filesystem.ts
10244
- var WebTTYFileSystemError = class extends Error {
10245
- operation;
10246
- status;
10456
+ import { RemoteFileSystem } from "@rstreamlabs/filesystem";
10457
+ import { FileSystemError } from "@rstreamlabs/filesystem";
10458
+ import { resolveFileSystemURL } from "@rstreamlabs/filesystem";
10459
+ import { parseWebDAVMultiStatus } from "@rstreamlabs/filesystem";
10460
+ var resolveWebTTYFileSystemURL = resolveFileSystemURL;
10461
+ var WebTTYFileSystemError = class extends FileSystemError {
10247
10462
  constructor(operation, status, message) {
10248
- super(`${operation} failed with status ${status}: ${message}`);
10463
+ super(operation, status, message);
10249
10464
  this.name = "WebTTYFileSystemError";
10250
- this.operation = operation;
10251
- this.status = status;
10252
10465
  }
10253
10466
  };
10254
- var webDAVPropfindBody = '<?xml version="1.0" encoding="utf-8"?><propfind xmlns="DAV:"><prop><resourcetype/><getcontentlength/><getlastmodified/></prop></propfind>';
10255
- function cleanTrailingSlashes2(value) {
10256
- return value.replace(/\/+$/, "");
10257
- }
10258
- function normalizeRemotePath(remotePath) {
10259
- const trimmed = remotePath.trim();
10260
- const absolute = trimmed === "" || trimmed === "." ? "/" : trimmed;
10261
- return new URL(
10262
- absolute.startsWith("/") ? absolute : `/${absolute}`,
10263
- "http://rstream.local"
10264
- ).pathname;
10265
- }
10266
- function comparableRemotePath(remotePath) {
10267
- const normalized = cleanTrailingSlashes2(normalizeRemotePath(remotePath));
10268
- return normalized === "" ? "/" : normalized;
10269
- }
10270
- function sidecarPath(fsPath) {
10271
- return normalizeRemotePath(fsPath ?? "/fs");
10272
- }
10273
- function filesystemBasePath(pathname, fsPath) {
10274
- const sidecar = sidecarPath(fsPath);
10275
- const basePath = cleanTrailingSlashes2(pathname);
10276
- if (basePath === "") return sidecar;
10277
- if (basePath === "/") return sidecar;
10278
- if (basePath === sidecar || basePath.startsWith(`${sidecar}/`))
10279
- return basePath;
10280
- return `${basePath}${sidecar}`;
10281
- }
10282
- function filesystemPath(pathname, remotePath, fsPath) {
10283
- const basePath = filesystemBasePath(pathname, fsPath);
10284
- const normalized = normalizeRemotePath(remotePath);
10285
- return normalized === "/" ? basePath : `${cleanTrailingSlashes2(basePath)}${normalized}`;
10286
- }
10287
- function resolveWebTTYFileSystemURL(input, remotePath = "/", fsPath) {
10288
- const url = new URL(input.toString());
10289
- if (url.protocol === "rstrm:") {
10290
- throw new Error(
10291
- "rstrm:// WebTTY filesystem URLs require the native rstream dialer."
10292
- );
10293
- }
10294
- if (url.protocol === "ws:") url.protocol = "http:";
10295
- if (url.protocol === "wss:") url.protocol = "https:";
10296
- if (url.protocol !== "http:" && url.protocol !== "https:") {
10297
- throw new Error(
10298
- `Unsupported WebTTY filesystem URL scheme "${url.protocol}".`
10299
- );
10300
- }
10301
- url.pathname = filesystemPath(url.pathname, remotePath, fsPath);
10302
- url.hash = "";
10303
- return url;
10304
- }
10305
- function responseAllowed(response, expectedStatuses) {
10306
- return expectedStatuses.includes(response.status);
10307
- }
10308
- async function responseErrorMessage(response) {
10309
- const text = (await response.text()).trim().slice(0, 4096);
10310
- return text === "" ? response.statusText : text;
10311
- }
10312
- async function requireResponseStatus(response, expectedStatuses, operation) {
10313
- if (responseAllowed(response, expectedStatuses)) return response;
10314
- throw new WebTTYFileSystemError(
10315
- operation,
10316
- response.status,
10317
- await responseErrorMessage(response)
10318
- );
10319
- }
10320
- function requireResponseBody(response, operation) {
10321
- if (response.body) return response.body;
10322
- throw new Error(
10323
- `${operation} failed because the response body is unavailable.`
10324
- );
10325
- }
10326
- function resolveFetch(config) {
10327
- if (config.fetch) return config.fetch;
10328
- if (typeof fetch === "undefined") {
10329
- throw new Error("fetch is unavailable in this runtime.");
10330
- }
10331
- return fetch;
10332
- }
10333
- function applyHeaders(target, source) {
10334
- const sourceHeaders = new Headers(source);
10335
- sourceHeaders.forEach((value, key) => target.set(key, value));
10336
- return target;
10337
- }
10338
- function requestHeaders(config, headers) {
10339
- const result = applyHeaders(new Headers(config.headers), headers);
10340
- if (config.authToken && config.authToken.trim() !== "") {
10341
- result.set("Authorization", `Bearer ${config.authToken.trim()}`);
10342
- }
10343
- return result;
10344
- }
10345
- function contentHeaders(contentType) {
10346
- return contentType === void 0 ? void 0 : { "Content-Type": contentType };
10347
- }
10348
- function deleteStatuses(force) {
10349
- return force ? [200, 204, 404] : [200, 204];
10350
- }
10351
- function isNotFound(error) {
10352
- return error instanceof WebTTYFileSystemError && error.status === 404;
10353
- }
10354
- function pathBaseName(path) {
10355
- const normalized = normalizeRemotePath(path);
10356
- const cleaned = cleanTrailingSlashes2(normalized);
10357
- return cleaned.slice(cleaned.lastIndexOf("/") + 1);
10358
- }
10359
- function parentPath(path) {
10360
- const normalized = cleanTrailingSlashes2(normalizeRemotePath(path));
10361
- const index = normalized.lastIndexOf("/");
10362
- if (index <= 0) return "/";
10363
- return normalized.slice(0, index);
10364
- }
10365
- function readFileEncoding(options) {
10366
- if (typeof options === "string") return options;
10367
- return options?.encoding === void 0 ? null : options.encoding;
10368
- }
10369
- function readFileSignal(options) {
10370
- return typeof options === "string" ? void 0 : options?.signal;
10371
- }
10372
- function textContentHeaders(contentType, data) {
10373
- if (contentType !== void 0) return { "Content-Type": contentType };
10374
- return typeof data === "string" ? { "Content-Type": "text/plain; charset=utf-8" } : void 0;
10375
- }
10376
- function bodyRequiresDuplex(body) {
10377
- return typeof ReadableStream !== "undefined" && body instanceof ReadableStream;
10378
- }
10379
- function requestInit(config, method, options) {
10380
- return {
10381
- body: options.body,
10382
- duplex: bodyRequiresDuplex(options.body) ? "half" : void 0,
10383
- headers: requestHeaders(config, options.headers),
10384
- method,
10385
- signal: options.signal
10386
- };
10387
- }
10388
- async function resolveURL2(url) {
10389
- return typeof url === "function" ? await url() : url;
10390
- }
10391
- function elementBodies(xml, name) {
10392
- return Array.from(
10393
- xml.matchAll(
10394
- new RegExp(
10395
- `<[^>]*:?${name}\\b[^>]*>([\\s\\S]*?)<\\/[^>]*:?${name}>`,
10396
- "gi"
10397
- )
10398
- ),
10399
- (match) => match[1] ?? ""
10400
- );
10401
- }
10402
- function hasElement(xml, name) {
10403
- return new RegExp(`<[^>]*:?${name}(\\s|/|>)`, "i").test(xml);
10404
- }
10405
- function stripTags(xml) {
10406
- return xml.replace(/<[^>]*>/g, "");
10407
- }
10408
- function decodeNumericEntity(value) {
10409
- const parsed = value.startsWith("&#x") ? Number.parseInt(value.slice(3, -1), 16) : Number.parseInt(value.slice(2, -1), 10);
10410
- return Number.isFinite(parsed) ? String.fromCodePoint(parsed) : value;
10411
- }
10412
- function decodeXmlText(value) {
10413
- 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, "&");
10414
- }
10415
- function elementText(xml, name) {
10416
- return decodeXmlText(stripTags(elementBodies(xml, name)[0] ?? "")).trim();
10417
- }
10418
- function okPropstat(response) {
10419
- return elementBodies(response, "propstat").find(
10420
- (propstat) => elementText(propstat, "status").includes(" 200 ")
10421
- ) ?? "";
10422
- }
10423
- function safeDecodePath(path) {
10424
- try {
10425
- return decodeURIComponent(path);
10426
- } catch {
10427
- return path;
10428
- }
10429
- }
10430
- function hrefPath(href) {
10431
- return safeDecodePath(new URL(href, "http://rstream.local").pathname);
10432
- }
10433
- function displayPath(href, fsPath) {
10434
- const value = hrefPath(href);
10435
- const sidecar = cleanTrailingSlashes2(sidecarPath(fsPath));
10436
- const withoutFS = value === sidecar ? "/" : value.startsWith(`${sidecar}/`) ? value.slice(sidecar.length) : value;
10437
- return withoutFS === "" ? "/" : withoutFS;
10438
- }
10439
- function itemSize(value) {
10440
- const parsed = Number.parseInt(value, 10);
10441
- return Number.isFinite(parsed) ? parsed : void 0;
10442
- }
10443
- function itemFromResponse(response, fsPath) {
10444
- const propstat = okPropstat(response);
10445
- const path = displayPath(elementText(response, "href"), fsPath);
10446
- if (propstat === "" || path === "") return null;
10447
- return {
10448
- kind: hasElement(
10449
- elementBodies(propstat, "resourcetype")[0] ?? "",
10450
- "collection"
10451
- ) ? "directory" : "file",
10452
- modified: elementText(propstat, "getlastmodified") || void 0,
10453
- path,
10454
- size: itemSize(elementText(propstat, "getcontentlength"))
10455
- };
10456
- }
10457
- function presentItems(items) {
10458
- return items.filter((item) => item !== null);
10459
- }
10460
- function parseWebDAVMultiStatus(xml, fsPath = "/fs") {
10461
- return presentItems(
10462
- elementBodies(xml, "response").map(
10463
- (response) => itemFromResponse(response, fsPath)
10464
- )
10465
- );
10466
- }
10467
- var WebTTYFileSystem = class {
10468
- config;
10469
- constructor(config) {
10470
- this.config = config;
10471
- }
10472
- async list(path = "/", options = {}) {
10473
- const response = await this.request("PROPFIND", path, {
10474
- body: webDAVPropfindBody,
10475
- expectedStatuses: [207],
10476
- headers: { "Content-Type": "application/xml; charset=utf-8", Depth: "1" },
10477
- operation: "WebTTY filesystem list",
10478
- signal: options.signal
10479
- });
10480
- return parseWebDAVMultiStatus(
10481
- await response.text(),
10482
- sidecarPath(this.config.fsPath)
10483
- );
10484
- }
10485
- async readBytes(path, options = {}) {
10486
- const response = await this.request("GET", path, {
10487
- expectedStatuses: [200],
10488
- operation: "WebTTY filesystem read",
10489
- signal: options.signal
10490
- });
10491
- return new Uint8Array(await response.arrayBuffer());
10492
- }
10493
- async readFile(path, options) {
10494
- const bytes = await this.readBytes(path, {
10495
- signal: readFileSignal(options)
10496
- });
10497
- const encoding = readFileEncoding(options);
10498
- return encoding === null ? bytes : new TextDecoder(encoding).decode(bytes);
10499
- }
10500
- async readText(path, options = {}) {
10501
- return new TextDecoder().decode(await this.readBytes(path, options));
10502
- }
10503
- async readStream(path, options = {}) {
10504
- return requireResponseBody(
10505
- await this.request("GET", path, {
10506
- expectedStatuses: [200],
10507
- operation: "WebTTY filesystem read",
10508
- signal: options.signal
10509
- }),
10510
- "WebTTY filesystem read"
10511
- );
10512
- }
10513
- async writeFile(path, data, options = {}) {
10514
- await this.request("PUT", path, {
10515
- body: data,
10516
- expectedStatuses: [200, 201, 204],
10517
- headers: textContentHeaders(options.contentType, data),
10518
- operation: "WebTTY filesystem write",
10519
- signal: options.signal
10520
- });
10521
- }
10522
- async writeBytes(path, data, options = {}) {
10523
- await this.writeFile(path, data, options);
10524
- }
10525
- async writeStream(path, data, options = {}) {
10526
- await this.request("PUT", path, {
10527
- body: data,
10528
- expectedStatuses: [200, 201, 204],
10529
- headers: contentHeaders(options.contentType),
10530
- operation: "WebTTY filesystem write",
10531
- signal: options.signal
10532
- });
10533
- }
10534
- async writeText(path, data, options = {}) {
10535
- await this.writeFile(path, data, options);
10536
- }
10537
- async copyFile(sourcePath, targetPath, options = {}) {
10538
- await this.request("COPY", sourcePath, {
10539
- expectedStatuses: [200, 201, 204],
10540
- headers: { Destination: (await this.resourceURL(targetPath)).toString() },
10541
- operation: "WebTTY filesystem copy",
10542
- signal: options.signal
10543
- });
10544
- }
10545
- async createDirectory(path, options = {}) {
10546
- await this.request("MKCOL", path, {
10547
- expectedStatuses: [201, 405],
10548
- operation: "WebTTY filesystem mkdir",
10549
- signal: options.signal
10550
- });
10551
- }
10552
- async exists(path, options = {}) {
10553
- return await this.stat(path, options).then(() => true).catch((error) => {
10554
- if (isNotFound(error)) return false;
10555
- throw error;
10556
- });
10557
- }
10558
- async mkdir(path, options = {}) {
10559
- if (options.recursive) {
10560
- await this.createDirectoryRecursive(path, options.signal);
10561
- return normalizeRemotePath(path);
10562
- }
10563
- await this.createDirectory(path, options);
10564
- return void 0;
10565
- }
10566
- async readdir(path = "/", options = {}) {
10567
- const items = (await this.list(path, options)).filter(
10568
- (item) => comparableRemotePath(item.path) !== comparableRemotePath(path)
10569
- );
10570
- return options.withFileTypes ? items : items.map((item) => pathBaseName(item.path));
10571
- }
10572
- async rename(oldPath, newPath, options = {}) {
10573
- await this.request("MOVE", oldPath, {
10574
- expectedStatuses: [200, 201, 204],
10575
- headers: { Destination: (await this.resourceURL(newPath)).toString() },
10576
- operation: "WebTTY filesystem rename",
10577
- signal: options.signal
10578
- });
10579
- }
10580
- async rm(path, options = {}) {
10581
- void options.recursive;
10582
- await this.request("DELETE", path, {
10583
- expectedStatuses: deleteStatuses(options.force),
10584
- operation: "WebTTY filesystem delete",
10585
- signal: options.signal
10586
- });
10587
- }
10588
- async stat(path, options = {}) {
10589
- const response = await this.request("PROPFIND", path, {
10590
- body: webDAVPropfindBody,
10591
- expectedStatuses: [207],
10592
- headers: { "Content-Type": "application/xml; charset=utf-8", Depth: "0" },
10593
- operation: "WebTTY filesystem stat",
10594
- signal: options.signal
10595
- });
10596
- const item = parseWebDAVMultiStatus(
10597
- await response.text(),
10598
- sidecarPath(this.config.fsPath)
10599
- )[0];
10600
- if (item) return item;
10601
- throw new Error(`WebTTY filesystem stat did not return ${path}.`);
10602
- }
10603
- async delete(path, options = {}) {
10604
- await this.rm(path, options);
10605
- }
10606
- async createDirectoryRecursive(path, signal) {
10607
- const normalized = normalizeRemotePath(path);
10608
- if (normalized === "/") return;
10609
- const parent = parentPath(normalized);
10610
- if (parent !== normalized) {
10611
- await this.createDirectoryRecursive(parent, signal);
10612
- }
10613
- await this.createDirectory(normalized, { signal });
10614
- }
10615
- async resourceURL(path) {
10616
- return resolveWebTTYFileSystemURL(
10617
- await resolveURL2(this.config.url),
10618
- path,
10619
- this.config.fsPath
10620
- );
10621
- }
10622
- async request(method, path, options) {
10623
- return await requireResponseStatus(
10624
- await resolveFetch(this.config)(
10625
- await this.resourceURL(path),
10626
- requestInit(this.config, method, options)
10627
- ),
10628
- options.expectedStatuses,
10629
- options.operation
10630
- );
10467
+ var WebTTYFileSystem = class extends RemoteFileSystem {
10468
+ createError(operation, status, message) {
10469
+ return new WebTTYFileSystemError(operation, status, message);
10631
10470
  }
10632
10471
  };
10633
10472
 
@@ -10890,7 +10729,7 @@ function payloadCryptoMetadataFromRecordedMetadata(metadata) {
10890
10729
  }
10891
10730
  return {
10892
10731
  aadContext: keyContextFromRecordedMetadata(metadata),
10893
- nonce: bytesFromBase64URL(metadata.nonce),
10732
+ nonce: metadata.payload_suite === "aes-256-gcm-random-nonce" && (metadata.nonce === void 0 || metadata.nonce === "") ? new Uint8Array() : bytesFromBase64URL(metadata.nonce),
10894
10733
  payloadKeyId: bytesFromBase64URL(metadata.payload_key_id),
10895
10734
  payloadSuite: metadata.payload_suite
10896
10735
  };
@@ -11217,10 +11056,10 @@ export {
11217
11056
  runWebTTYCommand,
11218
11057
  executeWebTTYCommand,
11219
11058
  WebTTYRemoteExecutor,
11220
- WebTTYFileSystemError,
11221
11059
  resolveWebTTYFileSystemURL,
11222
- parseWebDAVMultiStatus,
11060
+ WebTTYFileSystemError,
11223
11061
  WebTTYFileSystem,
11062
+ parseWebDAVMultiStatus,
11224
11063
  webTTYRecordedEventEncryptedPayload,
11225
11064
  decryptWebTTYRecordedEvent,
11226
11065
  decryptWebTTYRecordedTextLog,