@rstreamlabs/webtty 1.9.1 → 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.
@@ -908,6 +908,7 @@ var rstream = $root.rstream = (() => {
908
908
  values[valuesById[0] = "PAYLOAD_CIPHER_SUITE_UNSPECIFIED"] = 0;
909
909
  values[valuesById[1] = "PAYLOAD_CIPHER_SUITE_AES_256_GCM"] = 1;
910
910
  values[valuesById[2] = "PAYLOAD_CIPHER_SUITE_CHACHA20_POLY1305"] = 2;
911
+ values[valuesById[3] = "PAYLOAD_CIPHER_SUITE_AES_256_GCM_RANDOM_NONCE"] = 3;
911
912
  return values;
912
913
  })();
913
914
  protobuf.KeyEnvelopeSuite = (function() {
@@ -915,6 +916,7 @@ var rstream = $root.rstream = (() => {
915
916
  values[valuesById[0] = "KEY_ENVELOPE_SUITE_UNSPECIFIED"] = 0;
916
917
  values[valuesById[1] = "KEY_ENVELOPE_SUITE_HPKE_X25519_HKDF_SHA256_AES_256_GCM"] = 1;
917
918
  values[valuesById[2] = "KEY_ENVELOPE_SUITE_HPKE_X25519_HKDF_SHA256_CHACHA20_POLY1305"] = 2;
919
+ values[valuesById[3] = "KEY_ENVELOPE_SUITE_P256_HKDF_SHA256_AES_256_GCM_RANDOM_NONCE"] = 3;
918
920
  return values;
919
921
  })();
920
922
  protobuf.ProtocolVersion = (function() {
@@ -1417,6 +1419,10 @@ var rstream = $root.rstream = (() => {
1417
1419
  case 2:
1418
1420
  message.keyEnvelopeSuite = 2;
1419
1421
  break;
1422
+ case "KEY_ENVELOPE_SUITE_P256_HKDF_SHA256_AES_256_GCM_RANDOM_NONCE":
1423
+ case 3:
1424
+ message.keyEnvelopeSuite = 3;
1425
+ break;
1420
1426
  default:
1421
1427
  if (typeof object.keyEnvelopeSuite === "number" && (object.keyEnvelopeSuite | 0) === object.keyEnvelopeSuite)
1422
1428
  message.keyEnvelopeSuite = object.keyEnvelopeSuite;
@@ -2101,6 +2107,10 @@ var rstream = $root.rstream = (() => {
2101
2107
  case 2:
2102
2108
  message.payloadSuites[message.payloadSuites.length] = 2;
2103
2109
  break;
2110
+ case "PAYLOAD_CIPHER_SUITE_AES_256_GCM_RANDOM_NONCE":
2111
+ case 3:
2112
+ message.payloadSuites[message.payloadSuites.length] = 3;
2113
+ break;
2104
2114
  default:
2105
2115
  if (typeof object.payloadSuites[i] === "number" && (object.payloadSuites[i] | 0) === object.payloadSuites[i])
2106
2116
  message.payloadSuites[message.payloadSuites.length] = object.payloadSuites[i];
@@ -2124,6 +2134,10 @@ var rstream = $root.rstream = (() => {
2124
2134
  case 2:
2125
2135
  message.keyEnvelopeSuites[message.keyEnvelopeSuites.length] = 2;
2126
2136
  break;
2137
+ case "KEY_ENVELOPE_SUITE_P256_HKDF_SHA256_AES_256_GCM_RANDOM_NONCE":
2138
+ case 3:
2139
+ message.keyEnvelopeSuites[message.keyEnvelopeSuites.length] = 3;
2140
+ break;
2127
2141
  default:
2128
2142
  if (typeof object.keyEnvelopeSuites[i] === "number" && (object.keyEnvelopeSuites[i] | 0) === object.keyEnvelopeSuites[i])
2129
2143
  message.keyEnvelopeSuites[message.keyEnvelopeSuites.length] = object.keyEnvelopeSuites[i];
@@ -2597,6 +2611,10 @@ var rstream = $root.rstream = (() => {
2597
2611
  case 2:
2598
2612
  message.payloadSuite = 2;
2599
2613
  break;
2614
+ case "PAYLOAD_CIPHER_SUITE_AES_256_GCM_RANDOM_NONCE":
2615
+ case 3:
2616
+ message.payloadSuite = 3;
2617
+ break;
2600
2618
  default:
2601
2619
  if (typeof object.payloadSuite === "number" && (object.payloadSuite | 0) === object.payloadSuite)
2602
2620
  message.payloadSuite = object.payloadSuite;
@@ -2641,6 +2659,10 @@ var rstream = $root.rstream = (() => {
2641
2659
  case 2:
2642
2660
  message.keyEnvelopeSuite = 2;
2643
2661
  break;
2662
+ case "KEY_ENVELOPE_SUITE_P256_HKDF_SHA256_AES_256_GCM_RANDOM_NONCE":
2663
+ case 3:
2664
+ message.keyEnvelopeSuite = 3;
2665
+ break;
2644
2666
  default:
2645
2667
  if (typeof object.keyEnvelopeSuite === "number" && (object.keyEnvelopeSuite | 0) === object.keyEnvelopeSuite)
2646
2668
  message.keyEnvelopeSuite = object.keyEnvelopeSuite;
@@ -2868,6 +2890,10 @@ var rstream = $root.rstream = (() => {
2868
2890
  case 2:
2869
2891
  message.payloadSuite = 2;
2870
2892
  break;
2893
+ case "PAYLOAD_CIPHER_SUITE_AES_256_GCM_RANDOM_NONCE":
2894
+ case 3:
2895
+ message.payloadSuite = 3;
2896
+ break;
2871
2897
  default:
2872
2898
  if (typeof object.payloadSuite === "number" && (object.payloadSuite | 0) === object.payloadSuite)
2873
2899
  message.payloadSuite = object.payloadSuite;
@@ -7378,6 +7404,7 @@ function authRequirementCode(value) {
7378
7404
  function payloadSuiteCode(value) {
7379
7405
  if (value === "aes-256-gcm" || value === void 0) return 1;
7380
7406
  if (value === "chacha20-poly1305") return 2;
7407
+ if (value === "aes-256-gcm-random-nonce") return 3;
7381
7408
  return 0;
7382
7409
  }
7383
7410
  function keyEnvelopeSuiteCode(value) {
@@ -7385,6 +7412,7 @@ function keyEnvelopeSuiteCode(value) {
7385
7412
  return 1;
7386
7413
  }
7387
7414
  if (value === "hpke-x25519-hkdf-sha256-chacha20-poly1305") return 2;
7415
+ if (value === "p256-hkdf-sha256-aes-256-gcm-random-nonce") return 3;
7388
7416
  return 0;
7389
7417
  }
7390
7418
  function signatureSuiteCode(value) {
@@ -7585,6 +7613,8 @@ function normalizeSessionKeyGrant(grant) {
7585
7613
  // src/e2e-crypto.ts
7586
7614
  var x25519PublicKeySize = 32;
7587
7615
  var x25519PrivateKeySize = 32;
7616
+ var p256PublicKeySize = 65;
7617
+ var p256PrivateKeySize = 32;
7588
7618
  var payloadKeySize = 32;
7589
7619
  var payloadKeyIDSize = 16;
7590
7620
  var aesGCMNonceSize = 12;
@@ -7597,21 +7627,24 @@ var keyIDDomain = "rstream-webtty-e2e-key-id/v1";
7597
7627
  var hpkeVersionLabel = "HPKE-v1";
7598
7628
  var nominalPayloadSuite = "aes-256-gcm";
7599
7629
  var nominalKeyEnvelopeSuite = "hpke-x25519-hkdf-sha256-aes-256-gcm";
7600
- async function generateWebTTYE2EIdentity() {
7601
- const pair = await getSubtle().generateKey({ name: "X25519" }, true, [
7602
- "deriveBits"
7603
- ]);
7604
- if (!isX25519KeyPair(pair)) {
7605
- throw new Error("WebCrypto returned an unexpected X25519 key pair");
7630
+ var webTTYFIPSCompatiblePayloadSuite = "aes-256-gcm-random-nonce";
7631
+ var webTTYFIPSCompatibleKeyEnvelopeSuite = "p256-hkdf-sha256-aes-256-gcm-random-nonce";
7632
+ async function generateWebTTYE2EIdentity(keyEnvelopeSuite = nominalKeyEnvelopeSuite) {
7633
+ payloadSuiteForKeyEnvelopeSuite(keyEnvelopeSuite);
7634
+ const algorithm = keyEnvelopeSuite === webTTYFIPSCompatibleKeyEnvelopeSuite ? { name: "ECDH", namedCurve: "P-256" } : { name: "X25519" };
7635
+ const pair = await getSubtle().generateKey(algorithm, true, ["deriveBits"]);
7636
+ if (!isCryptoKeyPair(pair)) {
7637
+ throw new Error("WebCrypto returned an unexpected E2E key pair");
7606
7638
  }
7607
7639
  const publicKey = new Uint8Array(
7608
7640
  await getSubtle().exportKey("raw", pair.publicKey)
7609
7641
  );
7610
7642
  const jwk = await getSubtle().exportKey("jwk", pair.privateKey);
7611
7643
  if (typeof jwk.d !== "string") {
7612
- throw new Error("WebCrypto X25519 private JWK is missing d");
7644
+ throw new Error("WebCrypto E2E private JWK is missing d");
7613
7645
  }
7614
7646
  return {
7647
+ keyEnvelopeSuite,
7615
7648
  keyId: await webTTYE2EKeyID(publicKey),
7616
7649
  privateKey: base64URLDecode(jwk.d),
7617
7650
  publicKey
@@ -7652,8 +7685,8 @@ function createWebTTYE2EKeyContext(config) {
7652
7685
  );
7653
7686
  }
7654
7687
  async function createWebTTYE2EClientPayloadCrypto(config) {
7655
- const payloadSuite = config.payloadSuite ?? nominalPayloadSuite;
7656
- const keyEnvelopeSuite = config.keyEnvelopeSuite ?? nominalKeyEnvelopeSuite;
7688
+ const keyEnvelopeSuite = config.keyEnvelopeSuite ?? inferRecipientSuite(config.recipients);
7689
+ const payloadSuite = config.payloadSuite ?? payloadSuiteForKeyEnvelopeSuite(keyEnvelopeSuite);
7657
7690
  validateSuites(payloadSuite, keyEnvelopeSuite);
7658
7691
  const payloadKey = config.payloadKey ? cloneKeyMaterial(config.payloadKey) : randomBytes(payloadKeySize);
7659
7692
  if (payloadKey.byteLength !== payloadKeySize) {
@@ -7745,7 +7778,7 @@ function createPayloadCrypto(options) {
7745
7778
  payloadSuite: options.payloadSuite
7746
7779
  };
7747
7780
  const cryptoInfo = {
7748
- keyAgreement: "HPKE X25519",
7781
+ keyAgreement: options.keyEnvelopeSuite === webTTYFIPSCompatibleKeyEnvelopeSuite ? "ECDH P-256" : "HPKE X25519",
7749
7782
  keyDerivation: "HKDF-SHA256",
7750
7783
  keyEncryption: "AES-256-GCM",
7751
7784
  keyEnvelopeSuite: options.keyEnvelopeSuite,
@@ -7760,7 +7793,7 @@ function createPayloadCrypto(options) {
7760
7793
  if (chunk.byteLength > 4294967295) {
7761
7794
  throw new Error(`E2E payload is too large: ${chunk.byteLength} bytes`);
7762
7795
  }
7763
- const nonce = randomBytes(aesGCMNonceSize);
7796
+ const nonce = options.payloadSuite === webTTYFIPSCompatiblePayloadSuite ? new Uint8Array() : randomBytes(aesGCMNonceSize);
7764
7797
  const payloadCrypto = {
7765
7798
  aadContext: cloneBytes(options.keyContext),
7766
7799
  nonce,
@@ -7768,7 +7801,8 @@ function createPayloadCrypto(options) {
7768
7801
  payloadSuite: options.payloadSuite
7769
7802
  };
7770
7803
  return {
7771
- ciphertext: await aesGCMEncrypt(
7804
+ ciphertext: await encryptPayloadForSuite(
7805
+ options.payloadSuite,
7772
7806
  options.payloadKey,
7773
7807
  nonce,
7774
7808
  cloneBytes(chunk),
@@ -7788,19 +7822,21 @@ function createPayloadCrypto(options) {
7788
7822
  const decrypt = (stream) => async (payload) => {
7789
7823
  validatePayloadEnvelope(payload, options);
7790
7824
  const crypto = payload.payloadCrypto;
7791
- if (crypto === void 0 || crypto.nonce === void 0) {
7792
- throw new Error("missing E2E payload nonce");
7825
+ if (crypto === void 0) {
7826
+ throw new Error("missing E2E payload crypto");
7793
7827
  }
7794
- const plaintext = await aesGCMDecrypt(
7828
+ const nonce = crypto.nonce ?? new Uint8Array();
7829
+ const plaintext = await decryptPayloadForSuite(
7830
+ options.payloadSuite,
7795
7831
  options.payloadKey,
7796
- crypto.nonce,
7832
+ nonce,
7797
7833
  payload.ciphertext,
7798
7834
  payloadAAD(
7799
7835
  stream,
7800
7836
  options.payloadSuite,
7801
7837
  options.payloadKeyId,
7802
7838
  options.keyContext,
7803
- crypto.nonce,
7839
+ nonce,
7804
7840
  payload.plaintextLength
7805
7841
  )
7806
7842
  );
@@ -7845,21 +7881,29 @@ async function implicitKeyContextFromRecipients(recipients) {
7845
7881
  }
7846
7882
  async function wrapPayloadKey(payloadKey, payloadSuite, payloadKeyId, keyContext, suite, recipient) {
7847
7883
  const recipientPublicKey = cloneKeyMaterial(recipient.publicKey);
7848
- if (recipientPublicKey.byteLength !== x25519PublicKeySize) {
7884
+ const recipientSuite = recipient.keyEnvelopeSuite ?? inferKeyEnvelopeSuite(recipientPublicKey);
7885
+ if (recipientSuite !== suite) {
7886
+ throw new Error("E2E recipient suite does not match key envelope suite");
7887
+ }
7888
+ const expectedPublicKeySize = publicKeySizeForSuite(suite);
7889
+ if (recipientPublicKey.byteLength !== expectedPublicKeySize) {
7849
7890
  throw new Error(
7850
- `E2E recipient public key must be ${x25519PublicKeySize} bytes`
7891
+ `E2E recipient public key must be ${expectedPublicKeySize} bytes`
7851
7892
  );
7852
7893
  }
7853
7894
  const recipientKeyId = recipient.keyId ? cloneKeyMaterial(recipient.keyId) : await webTTYE2EKeyID(recipientPublicKey);
7854
7895
  if (recipientKeyId.byteLength !== payloadKeyIDSize) {
7855
7896
  throw new Error(`E2E recipient key id must be ${payloadKeyIDSize} bytes`);
7856
7897
  }
7857
- const sealed = await hpkeSeal(
7858
- recipientPublicKey,
7859
- hpkeInfo(payloadSuite, payloadKeyId, keyContext, suite),
7860
- hpkeAAD(recipientKeyId, payloadSuite, payloadKeyId, keyContext, suite),
7861
- payloadKey
7898
+ const info = hpkeInfo(payloadSuite, payloadKeyId, keyContext, suite);
7899
+ const aad = hpkeAAD(
7900
+ recipientKeyId,
7901
+ payloadSuite,
7902
+ payloadKeyId,
7903
+ keyContext,
7904
+ suite
7862
7905
  );
7906
+ const sealed = suite === webTTYFIPSCompatibleKeyEnvelopeSuite ? await p256Seal(recipientPublicKey, info, aad, payloadKey) : await hpkeSeal(recipientPublicKey, info, aad, payloadKey);
7863
7907
  return {
7864
7908
  encapsulatedKey: sealed.encapsulatedKey,
7865
7909
  recipientKeyId,
@@ -7876,17 +7920,28 @@ async function unwrapPayloadKey(envelope, payloadSuite, payloadKeyId, keyContext
7876
7920
  if (envelope.wrappedKey === void 0) {
7877
7921
  throw new Error("E2E key envelope is missing wrapped key");
7878
7922
  }
7879
- const payloadKey = await hpkeOpen(
7923
+ if (identity.keyEnvelopeSuite !== suite) {
7924
+ throw new Error("E2E identity suite does not match key envelope suite");
7925
+ }
7926
+ const info = hpkeInfo(payloadSuite, payloadKeyId, keyContext, suite);
7927
+ const aad = hpkeAAD(
7928
+ envelope.recipientKeyId,
7929
+ payloadSuite,
7930
+ payloadKeyId,
7931
+ keyContext,
7932
+ suite
7933
+ );
7934
+ const payloadKey = suite === webTTYFIPSCompatibleKeyEnvelopeSuite ? await p256Open(
7880
7935
  identity,
7881
7936
  envelope.encapsulatedKey,
7882
- hpkeInfo(payloadSuite, payloadKeyId, keyContext, suite),
7883
- hpkeAAD(
7884
- envelope.recipientKeyId,
7885
- payloadSuite,
7886
- payloadKeyId,
7887
- keyContext,
7888
- suite
7889
- ),
7937
+ info,
7938
+ aad,
7939
+ envelope.wrappedKey
7940
+ ) : await hpkeOpen(
7941
+ identity,
7942
+ envelope.encapsulatedKey,
7943
+ info,
7944
+ aad,
7890
7945
  envelope.wrappedKey
7891
7946
  );
7892
7947
  if (payloadKey.byteLength !== payloadKeySize) {
@@ -7968,6 +8023,95 @@ async function hpkeOpen(identity, encapsulatedKey, info, aad, ciphertext) {
7968
8023
  const schedule = await hpkeKeySchedule(sharedSecret, info);
7969
8024
  return aesGCMDecrypt(schedule.key, schedule.baseNonce, ciphertext, aad);
7970
8025
  }
8026
+ async function p256Seal(publicKey, info, aad, plaintext) {
8027
+ const recipientPublic = await getSubtle().importKey(
8028
+ "raw",
8029
+ bufferSource(publicKey),
8030
+ { name: "ECDH", namedCurve: "P-256" },
8031
+ false,
8032
+ []
8033
+ );
8034
+ const ephemeral = await getSubtle().generateKey(
8035
+ { name: "ECDH", namedCurve: "P-256" },
8036
+ true,
8037
+ ["deriveBits"]
8038
+ );
8039
+ if (!isCryptoKeyPair(ephemeral)) {
8040
+ throw new Error("WebCrypto returned an unexpected P-256 key pair");
8041
+ }
8042
+ const encapsulatedKey = new Uint8Array(
8043
+ await getSubtle().exportKey("raw", ephemeral.publicKey)
8044
+ );
8045
+ const sharedSecret = new Uint8Array(
8046
+ await getSubtle().deriveBits(
8047
+ { name: "ECDH", public: recipientPublic },
8048
+ ephemeral.privateKey,
8049
+ 256
8050
+ )
8051
+ );
8052
+ const wrappingKey = await p256WrappingKey(sharedSecret, info);
8053
+ return {
8054
+ encapsulatedKey,
8055
+ wrappedKey: await aesGCMEncryptWithPrefixedRandomNonce(
8056
+ wrappingKey,
8057
+ plaintext,
8058
+ aad
8059
+ )
8060
+ };
8061
+ }
8062
+ async function p256Open(identity, encapsulatedKey, info, aad, ciphertext) {
8063
+ if (identity.privateKey.byteLength !== p256PrivateKeySize) {
8064
+ throw new Error(
8065
+ `E2E identity private key must be ${p256PrivateKeySize} bytes`
8066
+ );
8067
+ }
8068
+ if (identity.publicKey.byteLength !== p256PublicKeySize || identity.publicKey[0] !== 4) {
8069
+ throw new Error(
8070
+ `E2E identity public key must be an uncompressed ${p256PublicKeySize}-byte P-256 point`
8071
+ );
8072
+ }
8073
+ const recipientPrivate = await importP256PrivateKey(identity);
8074
+ const ephemeralPublic = await getSubtle().importKey(
8075
+ "raw",
8076
+ bufferSource(encapsulatedKey),
8077
+ { name: "ECDH", namedCurve: "P-256" },
8078
+ false,
8079
+ []
8080
+ );
8081
+ const sharedSecret = new Uint8Array(
8082
+ await getSubtle().deriveBits(
8083
+ { name: "ECDH", public: ephemeralPublic },
8084
+ recipientPrivate,
8085
+ 256
8086
+ )
8087
+ );
8088
+ return aesGCMDecryptWithPrefixedRandomNonce(
8089
+ await p256WrappingKey(sharedSecret, info),
8090
+ ciphertext,
8091
+ aad
8092
+ );
8093
+ }
8094
+ async function p256WrappingKey(sharedSecret, info) {
8095
+ const key = await getSubtle().importKey(
8096
+ "raw",
8097
+ bufferSource(sharedSecret),
8098
+ "HKDF",
8099
+ false,
8100
+ ["deriveBits"]
8101
+ );
8102
+ return new Uint8Array(
8103
+ await getSubtle().deriveBits(
8104
+ {
8105
+ hash: "SHA-256",
8106
+ info: bufferSource(info),
8107
+ name: "HKDF",
8108
+ salt: new Uint8Array()
8109
+ },
8110
+ key,
8111
+ 256
8112
+ )
8113
+ );
8114
+ }
7971
8115
  async function dhkemExtractAndExpand(dh, kemContext) {
7972
8116
  const eaePRK = await labeledExtract(
7973
8117
  dhkemSuiteID(),
@@ -8120,6 +8264,33 @@ async function aesGCMDecrypt(key, nonce, ciphertext, aad) {
8120
8264
  )
8121
8265
  );
8122
8266
  }
8267
+ async function aesGCMEncryptWithPrefixedRandomNonce(key, plaintext, aad) {
8268
+ const nonce = randomBytes(aesGCMNonceSize);
8269
+ return concat2(nonce, await aesGCMEncrypt(key, nonce, plaintext, aad));
8270
+ }
8271
+ async function aesGCMDecryptWithPrefixedRandomNonce(key, ciphertext, aad) {
8272
+ if (ciphertext.byteLength < aesGCMNonceSize + 16) {
8273
+ throw new Error("E2E random-nonce AES-GCM ciphertext is too short");
8274
+ }
8275
+ return aesGCMDecrypt(
8276
+ key,
8277
+ ciphertext.slice(0, aesGCMNonceSize),
8278
+ ciphertext.slice(aesGCMNonceSize),
8279
+ aad
8280
+ );
8281
+ }
8282
+ async function encryptPayloadForSuite(suite, key, nonce, plaintext, aad) {
8283
+ if (suite === webTTYFIPSCompatiblePayloadSuite) {
8284
+ return aesGCMEncryptWithPrefixedRandomNonce(key, plaintext, aad);
8285
+ }
8286
+ return aesGCMEncrypt(key, nonce, plaintext, aad);
8287
+ }
8288
+ async function decryptPayloadForSuite(suite, key, nonce, ciphertext, aad) {
8289
+ if (suite === webTTYFIPSCompatiblePayloadSuite) {
8290
+ return aesGCMDecryptWithPrefixedRandomNonce(key, ciphertext, aad);
8291
+ }
8292
+ return aesGCMDecrypt(key, nonce, ciphertext, aad);
8293
+ }
8123
8294
  async function importX25519PrivateKey(identity) {
8124
8295
  return getSubtle().importKey(
8125
8296
  "jwk",
@@ -8136,6 +8307,23 @@ async function importX25519PrivateKey(identity) {
8136
8307
  ["deriveBits"]
8137
8308
  );
8138
8309
  }
8310
+ async function importP256PrivateKey(identity) {
8311
+ return getSubtle().importKey(
8312
+ "jwk",
8313
+ {
8314
+ crv: "P-256",
8315
+ d: base64URLEncode(identity.privateKey),
8316
+ ext: true,
8317
+ key_ops: ["deriveBits"],
8318
+ kty: "EC",
8319
+ x: base64URLEncode(identity.publicKey.slice(1, 33)),
8320
+ y: base64URLEncode(identity.publicKey.slice(33, 65))
8321
+ },
8322
+ { name: "ECDH", namedCurve: "P-256" },
8323
+ false,
8324
+ ["deriveBits"]
8325
+ );
8326
+ }
8139
8327
  function validatePayloadEnvelope(payload, options) {
8140
8328
  const crypto = payload.payloadCrypto;
8141
8329
  if (crypto === void 0) throw new Error("missing E2E payload crypto");
@@ -8148,18 +8336,64 @@ function validatePayloadEnvelope(payload, options) {
8148
8336
  if (!bytesEqual(crypto.aadContext, options.keyContext)) {
8149
8337
  throw new Error("unexpected E2E key context");
8150
8338
  }
8151
- if (crypto.nonce === void 0 || crypto.nonce.byteLength !== aesGCMNonceSize) {
8152
- throw new Error(`E2E AES-GCM nonce must be ${aesGCMNonceSize} bytes`);
8339
+ const expectedNonceSize = options.payloadSuite === webTTYFIPSCompatiblePayloadSuite ? 0 : aesGCMNonceSize;
8340
+ if (crypto.nonce === void 0 || crypto.nonce.byteLength !== expectedNonceSize) {
8341
+ throw new Error(`E2E AES-GCM nonce must be ${expectedNonceSize} bytes`);
8153
8342
  }
8154
8343
  }
8155
- function validateSuites(payloadSuite, keyEnvelopeSuite) {
8156
- if (payloadSuite !== nominalPayloadSuite) {
8157
- throw new Error(`unsupported E2E payload suite ${payloadSuite}`);
8344
+ function inferRecipientSuite(recipients) {
8345
+ if (recipients.length === 0) {
8346
+ throw new Error(
8347
+ "E2E client payload crypto requires at least one recipient"
8348
+ );
8349
+ }
8350
+ const suites = recipients.map(
8351
+ (recipient) => recipient.keyEnvelopeSuite ?? inferKeyEnvelopeSuite(cloneKeyMaterial(recipient.publicKey))
8352
+ );
8353
+ const suite = suites[0];
8354
+ if (suite === void 0 || suites.some((candidate) => candidate !== suite)) {
8355
+ throw new Error("E2E recipients must use the same key envelope suite");
8356
+ }
8357
+ return suite;
8358
+ }
8359
+ function inferKeyEnvelopeSuite(publicKey) {
8360
+ if (publicKey.byteLength === x25519PublicKeySize) {
8361
+ return nominalKeyEnvelopeSuite;
8362
+ }
8363
+ if (publicKey.byteLength === p256PublicKeySize && publicKey[0] === 4) {
8364
+ return webTTYFIPSCompatibleKeyEnvelopeSuite;
8365
+ }
8366
+ throw new Error(
8367
+ `unsupported E2E recipient public key length ${publicKey.byteLength}`
8368
+ );
8369
+ }
8370
+ function payloadSuiteForKeyEnvelopeSuite(suite) {
8371
+ switch (suite) {
8372
+ case nominalKeyEnvelopeSuite:
8373
+ return nominalPayloadSuite;
8374
+ case webTTYFIPSCompatibleKeyEnvelopeSuite:
8375
+ return webTTYFIPSCompatiblePayloadSuite;
8376
+ default:
8377
+ throw new Error(`unsupported E2E key envelope suite ${suite}`);
8378
+ }
8379
+ }
8380
+ function publicKeySizeForSuite(suite) {
8381
+ switch (suite) {
8382
+ case nominalKeyEnvelopeSuite:
8383
+ return x25519PublicKeySize;
8384
+ case webTTYFIPSCompatibleKeyEnvelopeSuite:
8385
+ return p256PublicKeySize;
8386
+ default:
8387
+ throw new Error(`unsupported E2E key envelope suite ${suite}`);
8158
8388
  }
8159
- if (keyEnvelopeSuite !== nominalKeyEnvelopeSuite) {
8160
- throw new Error(`unsupported E2E key envelope suite ${keyEnvelopeSuite}`);
8389
+ }
8390
+ function validateSuites(payloadSuite, keyEnvelopeSuite) {
8391
+ if (payloadSuite === nominalPayloadSuite && keyEnvelopeSuite === nominalKeyEnvelopeSuite || payloadSuite === webTTYFIPSCompatiblePayloadSuite && keyEnvelopeSuite === webTTYFIPSCompatibleKeyEnvelopeSuite) {
8392
+ return { keyEnvelopeSuite, payloadSuite };
8161
8393
  }
8162
- return { keyEnvelopeSuite, payloadSuite };
8394
+ throw new Error(
8395
+ `unsupported E2E suite pair ${payloadSuite}/${keyEnvelopeSuite}`
8396
+ );
8163
8397
  }
8164
8398
  function hpkeInfo(payloadSuite, payloadKeyId, keyContext, suite) {
8165
8399
  return concat2(
@@ -8194,11 +8428,13 @@ function payloadAAD(stream, suite, payloadKeyId, keyContext, nonce, plaintextLen
8194
8428
  function payloadSuiteCode2(suite) {
8195
8429
  if (suite === "aes-256-gcm") return 1;
8196
8430
  if (suite === "chacha20-poly1305") return 2;
8431
+ if (suite === "aes-256-gcm-random-nonce") return 3;
8197
8432
  return unsupportedPayloadSuite(suite);
8198
8433
  }
8199
8434
  function keyEnvelopeSuiteCode2(suite) {
8200
8435
  if (suite === "hpke-x25519-hkdf-sha256-aes-256-gcm") return 1;
8201
8436
  if (suite === "hpke-x25519-hkdf-sha256-chacha20-poly1305") return 2;
8437
+ if (suite === "p256-hkdf-sha256-aes-256-gcm-random-nonce") return 3;
8202
8438
  return unsupportedKeyEnvelopeSuite(suite);
8203
8439
  }
8204
8440
  function unsupportedPayloadSuite(suite) {
@@ -8274,10 +8510,12 @@ function nonEmptyString(value, label) {
8274
8510
  return void 0;
8275
8511
  }
8276
8512
  function normalizeIdentity(identity) {
8513
+ const publicKey = cloneKeyMaterial(identity.publicKey);
8277
8514
  return {
8515
+ keyEnvelopeSuite: identity.keyEnvelopeSuite ?? inferKeyEnvelopeSuite(publicKey),
8278
8516
  keyId: cloneKeyMaterial(identity.keyId),
8279
8517
  privateKey: cloneKeyMaterial(identity.privateKey),
8280
- publicKey: cloneKeyMaterial(identity.publicKey)
8518
+ publicKey
8281
8519
  };
8282
8520
  }
8283
8521
  function bufferSource(value) {
@@ -8331,9 +8569,10 @@ function getSubtle() {
8331
8569
  }
8332
8570
  return subtle;
8333
8571
  }
8334
- function isX25519KeyPair(value) {
8572
+ function isCryptoKeyPair(value) {
8335
8573
  return "privateKey" in value && "publicKey" in value;
8336
8574
  }
8575
+ var isX25519KeyPair = isCryptoKeyPair;
8337
8576
  function base64URLEncode(value) {
8338
8577
  const binary = String.fromCharCode(...value);
8339
8578
  return btoa(binary).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, "");
@@ -8351,6 +8590,74 @@ function base64URLDecode(value) {
8351
8590
  return out;
8352
8591
  }
8353
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
+
8354
8661
  // src/webtty.ts
8355
8662
  function getErrorMessage(error) {
8356
8663
  return error instanceof Error ? error.message : String(error);
@@ -8398,6 +8705,8 @@ function payloadCipherSuiteToProto(suite) {
8398
8705
  return rstream.webtty.protobuf.PayloadCipherSuite.PAYLOAD_CIPHER_SUITE_AES_256_GCM;
8399
8706
  case "chacha20-poly1305":
8400
8707
  return rstream.webtty.protobuf.PayloadCipherSuite.PAYLOAD_CIPHER_SUITE_CHACHA20_POLY1305;
8708
+ case "aes-256-gcm-random-nonce":
8709
+ return rstream.webtty.protobuf.PayloadCipherSuite.PAYLOAD_CIPHER_SUITE_AES_256_GCM_RANDOM_NONCE;
8401
8710
  default:
8402
8711
  return rstream.webtty.protobuf.PayloadCipherSuite.PAYLOAD_CIPHER_SUITE_UNSPECIFIED;
8403
8712
  }
@@ -8408,6 +8717,8 @@ function payloadCipherSuiteFromProto(suite) {
8408
8717
  return "aes-256-gcm";
8409
8718
  case rstream.webtty.protobuf.PayloadCipherSuite.PAYLOAD_CIPHER_SUITE_CHACHA20_POLY1305:
8410
8719
  return "chacha20-poly1305";
8720
+ case rstream.webtty.protobuf.PayloadCipherSuite.PAYLOAD_CIPHER_SUITE_AES_256_GCM_RANDOM_NONCE:
8721
+ return "aes-256-gcm-random-nonce";
8411
8722
  default:
8412
8723
  return void 0;
8413
8724
  }
@@ -8418,6 +8729,8 @@ function keyEnvelopeSuiteToProto(suite) {
8418
8729
  return rstream.webtty.protobuf.KeyEnvelopeSuite.KEY_ENVELOPE_SUITE_HPKE_X25519_HKDF_SHA256_AES_256_GCM;
8419
8730
  case "hpke-x25519-hkdf-sha256-chacha20-poly1305":
8420
8731
  return rstream.webtty.protobuf.KeyEnvelopeSuite.KEY_ENVELOPE_SUITE_HPKE_X25519_HKDF_SHA256_CHACHA20_POLY1305;
8732
+ case "p256-hkdf-sha256-aes-256-gcm-random-nonce":
8733
+ return rstream.webtty.protobuf.KeyEnvelopeSuite.KEY_ENVELOPE_SUITE_P256_HKDF_SHA256_AES_256_GCM_RANDOM_NONCE;
8421
8734
  default:
8422
8735
  return rstream.webtty.protobuf.KeyEnvelopeSuite.KEY_ENVELOPE_SUITE_UNSPECIFIED;
8423
8736
  }
@@ -8428,10 +8741,72 @@ function keyEnvelopeSuiteFromProto(suite) {
8428
8741
  return "hpke-x25519-hkdf-sha256-aes-256-gcm";
8429
8742
  case rstream.webtty.protobuf.KeyEnvelopeSuite.KEY_ENVELOPE_SUITE_HPKE_X25519_HKDF_SHA256_CHACHA20_POLY1305:
8430
8743
  return "hpke-x25519-hkdf-sha256-chacha20-poly1305";
8744
+ case rstream.webtty.protobuf.KeyEnvelopeSuite.KEY_ENVELOPE_SUITE_P256_HKDF_SHA256_AES_256_GCM_RANDOM_NONCE:
8745
+ return "p256-hkdf-sha256-aes-256-gcm-random-nonce";
8431
8746
  default:
8432
8747
  return void 0;
8433
8748
  }
8434
8749
  }
8750
+ var defaultE2EPayloadSuite = "aes-256-gcm";
8751
+ var defaultE2EKeyEnvelopeSuite = "hpke-x25519-hkdf-sha256-aes-256-gcm";
8752
+ var fipsCompatibleE2EPayloadSuite = "aes-256-gcm-random-nonce";
8753
+ var fipsCompatibleE2EKeyEnvelopeSuite = "p256-hkdf-sha256-aes-256-gcm-random-nonce";
8754
+ function payloadSuiteForKeyEnvelopeSuite2(suite) {
8755
+ switch (suite) {
8756
+ case defaultE2EKeyEnvelopeSuite:
8757
+ return defaultE2EPayloadSuite;
8758
+ case fipsCompatibleE2EKeyEnvelopeSuite:
8759
+ return fipsCompatibleE2EPayloadSuite;
8760
+ default:
8761
+ throw new Error(`Unsupported WebTTY E2E key envelope suite ${suite}.`);
8762
+ }
8763
+ }
8764
+ function asE2EKeyEnvelopeSuite(suite) {
8765
+ if (suite === defaultE2EKeyEnvelopeSuite || suite === fipsCompatibleE2EKeyEnvelopeSuite) {
8766
+ return suite;
8767
+ }
8768
+ throw new Error(`Unsupported WebTTY E2E key envelope suite ${suite}.`);
8769
+ }
8770
+ function inferE2EKeyEnvelopeSuite(publicKey) {
8771
+ if (publicKey?.byteLength === 32) return defaultE2EKeyEnvelopeSuite;
8772
+ if (publicKey?.byteLength === 65 && publicKey[0] === 4) {
8773
+ return fipsCompatibleE2EKeyEnvelopeSuite;
8774
+ }
8775
+ return void 0;
8776
+ }
8777
+ function proofSuitesFromGrant(grant) {
8778
+ const rawKeyEnvelopeSuite = keyEnvelopeSuiteFromProto(
8779
+ grant?.keyEnvelopeSuite
8780
+ );
8781
+ const payloadSuite = payloadCipherSuiteFromProto(grant?.payloadSuite);
8782
+ if (rawKeyEnvelopeSuite === void 0 && payloadSuite === void 0) {
8783
+ return {
8784
+ keyEnvelopeSuite: defaultE2EKeyEnvelopeSuite,
8785
+ payloadSuite: defaultE2EPayloadSuite
8786
+ };
8787
+ }
8788
+ if (rawKeyEnvelopeSuite === void 0 || payloadSuite === void 0) {
8789
+ throw new Error("WebTTY session key grant uses an unsupported suite pair.");
8790
+ }
8791
+ const keyEnvelopeSuite = asE2EKeyEnvelopeSuite(rawKeyEnvelopeSuite);
8792
+ const expectedPayloadSuite = payloadSuiteForKeyEnvelopeSuite2(keyEnvelopeSuite);
8793
+ if (expectedPayloadSuite !== payloadSuite) {
8794
+ throw new Error("WebTTY session key grant uses an unsupported suite pair.");
8795
+ }
8796
+ return { keyEnvelopeSuite, payloadSuite: expectedPayloadSuite };
8797
+ }
8798
+ function proofSuitesFromClientConfig(config) {
8799
+ const configured = config.endpointIdentity?.keyEnvelopeSuite;
8800
+ const expected = config.expectedServerIdentity;
8801
+ const expectedSuite = expected?.keyEnvelopeSuite ?? inferE2EKeyEnvelopeSuite(expected?.encryptionPublicKey);
8802
+ const keyEnvelopeSuite = asE2EKeyEnvelopeSuite(
8803
+ configured ?? expectedSuite ?? defaultE2EKeyEnvelopeSuite
8804
+ );
8805
+ return {
8806
+ keyEnvelopeSuite,
8807
+ payloadSuite: payloadSuiteForKeyEnvelopeSuite2(keyEnvelopeSuite)
8808
+ };
8809
+ }
8435
8810
  function signatureSuiteFromProto(suite) {
8436
8811
  switch (suite) {
8437
8812
  case rstream.webtty.protobuf.SignatureSuite.SIGNATURE_SUITE_ECDSA_P256_SHA256:
@@ -8672,12 +9047,15 @@ function resolveWebTransportConstructor() {
8672
9047
  function webTransportGlobal(value) {
8673
9048
  return "WebTransport" in value;
8674
9049
  }
9050
+ function browserWebSocket(url) {
9051
+ const socket = new WebSocket(url);
9052
+ socket.binaryType = "arraybuffer";
9053
+ return socket;
9054
+ }
8675
9055
  var WebSocketMessageConnection = class {
8676
- ws;
8677
- handlers;
8678
- constructor(url, handlers) {
8679
- this.ws = new WebSocket(url);
8680
- this.ws.binaryType = "arraybuffer";
9056
+ constructor(url, handlers, maxBufferedBytes, factory, maxMessageSize) {
9057
+ this.maxBufferedBytes = maxBufferedBytes;
9058
+ this.ws = factory ? factory(url, { maxMessageSize }) : browserWebSocket(url);
8681
9059
  this.handlers = {
8682
9060
  close: handlers.close,
8683
9061
  error: handlers.error,
@@ -8689,7 +9067,13 @@ var WebSocketMessageConnection = class {
8689
9067
  this.ws.addEventListener("error", this.handlers.error);
8690
9068
  this.ws.addEventListener("close", this.handlers.close);
8691
9069
  }
9070
+ maxBufferedBytes;
9071
+ ws;
9072
+ handlers;
8692
9073
  send(payload) {
9074
+ if (this.ws.bufferedAmount + payload.byteLength > this.maxBufferedBytes) {
9075
+ throw new Error("WebSocket write buffer limit exceeded.");
9076
+ }
8693
9077
  this.ws.send(getWebSocketPayload(payload));
8694
9078
  }
8695
9079
  close() {
@@ -8701,56 +9085,109 @@ var WebSocketMessageConnection = class {
8701
9085
  }
8702
9086
  };
8703
9087
  var WebTransportMessageConnection = class _WebTransportMessageConnection {
8704
- constructor(transport, stream, writer, handlers) {
9088
+ constructor(transport, stream, writer, maxMessageSize, handlers) {
8705
9089
  this.transport = transport;
8706
- this.stream = stream;
8707
9090
  this.writer = writer;
9091
+ this.maxMessageSize = maxMessageSize;
8708
9092
  this.handlers = handlers;
9093
+ this.decoder = new WebTTYFrameDecoder(maxMessageSize);
9094
+ this.reader = stream.readable.getReader();
8709
9095
  }
8710
9096
  transport;
8711
- stream;
8712
9097
  writer;
9098
+ maxMessageSize;
8713
9099
  handlers;
8714
9100
  closed = false;
8715
- readBuffer = new Uint8Array();
8716
- writeQueue = Promise.resolve();
8717
- 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();
8718
9109
  const Transport = resolveWebTransportConstructor();
8719
9110
  const transport = new Transport(url, options);
8720
- await transport.ready;
8721
- const stream = await transport.createBidirectionalStream();
8722
- const writer = stream.writable.getWriter();
8723
- const connection = new _WebTransportMessageConnection(
8724
- transport,
8725
- stream,
8726
- writer,
8727
- handlers
8728
- );
8729
- connection.startReadLoop();
8730
9111
  transport.closed.catch((error) => {
8731
- if (!connection.closed) {
9112
+ if (!signal.aborted) {
8732
9113
  handlers.error(`WebTransport closed: ${getErrorMessage(error)}`);
8733
9114
  }
8734
9115
  });
8735
- 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
+ }
8736
9138
  }
8737
9139
  send(payload) {
8738
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
+ }
8739
9151
  const frame = getFramePayload(payload);
8740
- this.writeQueue = this.writeQueue.then(() => this.writer.write(frame)).catch((error) => {
8741
- if (!this.closed) {
8742
- this.handlers.error(
8743
- `WebTransport write failed: ${getErrorMessage(error)}`
8744
- );
8745
- }
8746
- });
9152
+ this.writeQueue.push(frame);
9153
+ this.bufferedBytes += frame.byteLength;
9154
+ if (!this.writing) {
9155
+ this.writing = true;
9156
+ void this.writeLoop();
9157
+ }
8747
9158
  }
8748
9159
  close() {
8749
9160
  if (this.closed) return;
8750
9161
  this.closed = true;
8751
- 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());
8752
9167
  this.transport.close({ closeCode: 0, reason: "closed" });
8753
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
+ }
8754
9191
  startReadLoop() {
8755
9192
  void this.readLoop().catch((error) => {
8756
9193
  if (!this.closed) {
@@ -8761,41 +9198,46 @@ var WebTransportMessageConnection = class _WebTransportMessageConnection {
8761
9198
  });
8762
9199
  }
8763
9200
  async readLoop() {
8764
- const reader = this.stream.readable.getReader();
8765
9201
  try {
8766
9202
  for (; ; ) {
8767
- const result = await reader.read();
9203
+ const result = await this.reader.read();
9204
+ if (this.closed) return;
8768
9205
  if (result.done) {
8769
- 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();
8770
9209
  return;
8771
9210
  }
8772
- 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
+ }
8773
9216
  }
8774
9217
  } finally {
8775
- reader.releaseLock();
8776
- }
8777
- }
8778
- appendReadChunk(chunk) {
8779
- const next = new Uint8Array(this.readBuffer.byteLength + chunk.byteLength);
8780
- next.set(this.readBuffer);
8781
- next.set(chunk, this.readBuffer.byteLength);
8782
- this.readBuffer = next;
8783
- for (; ; ) {
8784
- if (this.readBuffer.byteLength < 4) return;
8785
- const view = new DataView(
8786
- this.readBuffer.buffer,
8787
- this.readBuffer.byteOffset,
8788
- this.readBuffer.byteLength
8789
- );
8790
- const size = view.getUint32(0, false);
8791
- if (this.readBuffer.byteLength < 4 + size) return;
8792
- const payload = this.readBuffer.slice(4, 4 + size);
8793
- this.readBuffer = this.readBuffer.slice(4 + size);
8794
- this.handlers.message(payload);
9218
+ this.reader.releaseLock();
8795
9219
  }
8796
9220
  }
8797
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
+ }
8798
9239
  var WebTTY = class {
9240
+ connectionAbort = new AbortController();
8799
9241
  connection = null;
8800
9242
  connectionState = "preparing";
8801
9243
  heartbeatTimer = null;
@@ -8803,6 +9245,11 @@ var WebTTY = class {
8803
9245
  execConfig;
8804
9246
  events;
8805
9247
  receiveQueue = null;
9248
+ receivedBytes = 0;
9249
+ receivedMessages = 0;
9250
+ stdinClosed = false;
9251
+ stderrClosed = false;
9252
+ stdoutClosed = false;
8806
9253
  /**
8807
9254
  * Creates a new WebTTY instance.
8808
9255
  *
@@ -8811,6 +9258,12 @@ var WebTTY = class {
8811
9258
  * @param events - Event callbacks for the session.
8812
9259
  */
8813
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
+ }
8814
9267
  const transport = resolveWebTTYClientTransport(
8815
9268
  clientConfig2.url,
8816
9269
  clientConfig2.transport
@@ -8834,9 +9287,11 @@ var WebTTY = class {
8834
9287
  endpointIdentity: clientConfig2.endpointIdentity,
8835
9288
  expectedServerIdentity: clientConfig2.expectedServerIdentity,
8836
9289
  heartbeatIntervalMs: clientConfig2.heartbeatIntervalMs ?? 5e3,
9290
+ maxMessageSize,
8837
9291
  sendHeartbeat: clientConfig2.sendHeartbeat ?? true,
8838
9292
  transport,
8839
9293
  url: clientConfig2.url,
9294
+ webSocketFactory: clientConfig2.webSocketFactory,
8840
9295
  webTransportOptions: clientConfig2.webTransportOptions
8841
9296
  };
8842
9297
  this.execConfig = {
@@ -8865,12 +9320,18 @@ var WebTTY = class {
8865
9320
  return;
8866
9321
  }
8867
9322
  const wsUrl = normalizeWebSocketURL(this.clientConfig.url);
8868
- this.connection = new WebSocketMessageConnection(wsUrl, {
8869
- close: this.handleClose,
8870
- error: this.handleError,
8871
- message: this.handleConnectionMessage,
8872
- open: this.handleOpen
8873
- });
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
+ );
8874
9335
  }
8875
9336
  /**
8876
9337
  * Sends data to the remote server's STDIN.
@@ -8908,6 +9369,7 @@ var WebTTY = class {
8908
9369
  return;
8909
9370
  }
8910
9371
  const encrypted = await encrypt(data);
9372
+ this.assertCanWriteStdin();
8911
9373
  this.sendStdinPayload({
8912
9374
  encryptedData: encryptedPayloadToProto(encrypted)
8913
9375
  });
@@ -8919,6 +9381,9 @@ var WebTTY = class {
8919
9381
  if (this.execConfig.interactive === false) {
8920
9382
  throw new Error("STDIN is unavailable in non-interactive mode.");
8921
9383
  }
9384
+ if (this.stdinClosed) {
9385
+ throw new Error("WebTTY STDIN is already closed.");
9386
+ }
8922
9387
  }
8923
9388
  sendStdinPayload(payload) {
8924
9389
  this.send(
@@ -8940,6 +9405,8 @@ var WebTTY = class {
8940
9405
  if (this.execConfig.interactive === false) {
8941
9406
  throw new Error("STDIN is unavailable in non-interactive mode.");
8942
9407
  }
9408
+ if (this.stdinClosed) return;
9409
+ this.stdinClosed = true;
8943
9410
  this.send(
8944
9411
  new rstream.webtty.protobuf.Message({
8945
9412
  data: new rstream.webtty.protobuf.Data({
@@ -9112,6 +9579,16 @@ var WebTTY = class {
9112
9579
  if (!bytesEqual2(actual.signingKeyId, expected.signingKeyId) || !bytesEqual2(actual.signingPublicKey, expected.signingPublicKey) || !bytesEqual2(actual.encryptionKeyId, expected.encryptionKeyId) || !bytesEqual2(actual.encryptionPublicKey, expected.encryptionPublicKey)) {
9113
9580
  return false;
9114
9581
  }
9582
+ const expectedKeyEnvelopeSuite = expected.keyEnvelopeSuite ?? inferE2EKeyEnvelopeSuite(expected.encryptionPublicKey) ?? defaultE2EKeyEnvelopeSuite;
9583
+ const advertisedKeyEnvelopeSuites = (serverHello.keyEnvelopeSuites ?? []).map(keyEnvelopeSuiteFromProto).filter((value) => value !== void 0);
9584
+ const advertisedPayloadSuites = (serverHello.payloadSuites ?? []).map(payloadCipherSuiteFromProto).filter(
9585
+ (value) => value !== void 0
9586
+ );
9587
+ if (!advertisedKeyEnvelopeSuites.includes(expectedKeyEnvelopeSuite) || !advertisedPayloadSuites.includes(
9588
+ payloadSuiteForKeyEnvelopeSuite2(expectedKeyEnvelopeSuite)
9589
+ )) {
9590
+ return false;
9591
+ }
9115
9592
  const transcript = {
9116
9593
  authRequirement: authRequirementFromProto(serverHello.authRequirement),
9117
9594
  keyEnvelopeSuites: (serverHello.keyEnvelopeSuites ?? []).map(keyEnvelopeSuiteFromProto).filter(
@@ -9166,6 +9643,7 @@ var WebTTY = class {
9166
9643
  }
9167
9644
  const clientPrincipalId = trimOptional(this.clientConfig.clientPrincipalId);
9168
9645
  const clientCredential = this.clientConfig.clientCredential;
9646
+ const proofSuites = proofSuitesFromGrant(open.sessionKeyGrant);
9169
9647
  const transcript = {
9170
9648
  authRequirement: "client-proof",
9171
9649
  clientCredentialHash: await hashWebTTYClientCredential(clientCredential),
@@ -9174,8 +9652,8 @@ var WebTTY = class {
9174
9652
  commandConfigHash,
9175
9653
  expiresAt: expiresAt.toISOString().replace(".000Z", "Z"),
9176
9654
  issuedAt: issuedAt.toISOString().replace(".000Z", "Z"),
9177
- keyEnvelopeSuite: "hpke-x25519-hkdf-sha256-aes-256-gcm",
9178
- payloadSuite: "aes-256-gcm",
9655
+ keyEnvelopeSuite: proofSuites.keyEnvelopeSuite,
9656
+ payloadSuite: proofSuites.payloadSuite,
9179
9657
  projectId: optionalString(serverHello.projectId),
9180
9658
  protocolVersion: "webtty-1",
9181
9659
  serverEncryptionKeyId: optionalBytes(serverIdentity.encryptionKeyId),
@@ -9224,6 +9702,7 @@ var WebTTY = class {
9224
9702
  issuedAt.setMilliseconds(0);
9225
9703
  const expiresAt = new Date(issuedAt.getTime() + 3e4);
9226
9704
  const clientPrincipalId = trimOptional(this.clientConfig.clientPrincipalId);
9705
+ const proofSuites = proofSuitesFromClientConfig(this.clientConfig);
9227
9706
  const transcript = {
9228
9707
  attachGrantHash: await hashWebTTYAttachGrant(attach.attachGrant),
9229
9708
  authRequirement: "client-proof",
@@ -9232,8 +9711,8 @@ var WebTTY = class {
9232
9711
  clientSigningKeyId: signing.keyId,
9233
9712
  expiresAt: expiresAt.toISOString().replace(".000Z", "Z"),
9234
9713
  issuedAt: issuedAt.toISOString().replace(".000Z", "Z"),
9235
- keyEnvelopeSuite: "hpke-x25519-hkdf-sha256-aes-256-gcm",
9236
- payloadSuite: "aes-256-gcm",
9714
+ keyEnvelopeSuite: proofSuites.keyEnvelopeSuite,
9715
+ payloadSuite: proofSuites.payloadSuite,
9237
9716
  projectId: attachConfig.projectId,
9238
9717
  protocolVersion: "webtty-1",
9239
9718
  requestedRole: attachRoleTranscriptValue(attach.requestedRole),
@@ -9265,6 +9744,8 @@ var WebTTY = class {
9265
9744
  const connection = await WebTransportMessageConnection.open(
9266
9745
  url,
9267
9746
  this.clientConfig.webTransportOptions,
9747
+ this.connectionAbort.signal,
9748
+ this.clientConfig.maxMessageSize,
9268
9749
  {
9269
9750
  close: this.handleClose,
9270
9751
  error: this.handleTransportError,
@@ -9282,16 +9763,46 @@ var WebTTY = class {
9282
9763
  }
9283
9764
  }
9284
9765
  handleConnectionMessage = (data) => {
9285
- 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
+ };
9286
9776
  if (this.receiveQueue) {
9287
- this.trackReceiveQueue(this.receiveQueue.then(run, run));
9288
- return;
9777
+ return this.trackReceiveQueue(
9778
+ this.receiveQueue.then(run, run).finally(release)
9779
+ );
9289
9780
  }
9290
9781
  const result = run();
9291
9782
  if (isPromiseLike(result)) {
9292
- this.trackReceiveQueue(result);
9783
+ return this.trackReceiveQueue(result.finally(release));
9293
9784
  }
9785
+ release();
9294
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
+ }
9295
9806
  trackReceiveQueue(promise) {
9296
9807
  const queued = promise.catch((error) => {
9297
9808
  this.close(`Failed to decode message: ${getErrorMessage(error)}`);
@@ -9299,6 +9810,7 @@ var WebTTY = class {
9299
9810
  if (this.receiveQueue === queued) this.receiveQueue = null;
9300
9811
  });
9301
9812
  this.receiveQueue = queued;
9813
+ return queued;
9302
9814
  }
9303
9815
  processMessage(data) {
9304
9816
  if (!data) return;
@@ -9347,41 +9859,47 @@ var WebTTY = class {
9347
9859
  }
9348
9860
  }
9349
9861
  processDataMessage(data) {
9350
- if (data.type === rstream.webtty.protobuf.Data.Type.TYPE_STDOUT) {
9351
- if (data.data) {
9352
- this.events.onStdout?.(data.data);
9353
- }
9354
- if (data.encryptedData) {
9355
- const decrypted = this.decryptData("stdout", data.encryptedData);
9356
- if (isPromiseLike(decrypted)) {
9357
- return decrypted.then((chunk) => {
9358
- if (chunk !== null) this.events.onStdout?.(chunk);
9359
- });
9360
- }
9361
- if (decrypted === null) return;
9362
- this.events.onStdout?.(decrypted);
9363
- }
9364
- 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;
9365
9884
  this.events.onStdoutEos?.();
9366
- }
9367
- } else if (data.type === rstream.webtty.protobuf.Data.Type.TYPE_STDERR) {
9368
- if (data.data) {
9369
- this.events.onStderr?.(data.data);
9370
- }
9371
- if (data.encryptedData) {
9372
- const decrypted = this.decryptData("stderr", data.encryptedData);
9373
- if (isPromiseLike(decrypted)) {
9374
- return decrypted.then((chunk) => {
9375
- if (chunk !== null) this.events.onStderr?.(chunk);
9376
- });
9377
- }
9378
- if (decrypted === null) return;
9379
- this.events.onStderr?.(decrypted);
9380
- }
9381
- if (data.eos) {
9885
+ } else {
9886
+ this.stderrClosed = true;
9382
9887
  this.events.onStderrEos?.();
9383
9888
  }
9889
+ return;
9890
+ }
9891
+ const emit = stream === "stdout" ? this.events.onStdout : this.events.onStderr;
9892
+ if (hasData) {
9893
+ emit?.(data.data);
9894
+ return;
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
+ });
9384
9901
  }
9902
+ if (decrypted !== null) emit?.(decrypted);
9385
9903
  }
9386
9904
  decryptData(stream, payload) {
9387
9905
  const decrypt = stream === "stdout" ? this.execConfig.payloadCrypto?.decryptStdout : this.execConfig.payloadCrypto?.decryptStderr;
@@ -9432,7 +9950,19 @@ var WebTTY = class {
9432
9950
  if (this.connectionState === "preparing" || this.connectionState === "closed")
9433
9951
  return;
9434
9952
  const buffer = rstream.webtty.protobuf.Message.encode(message).finish();
9435
- 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
+ }
9436
9966
  }
9437
9967
  /**
9438
9968
  * Closes the WebTTY session and fires exactly one of:
@@ -9445,6 +9975,7 @@ var WebTTY = class {
9445
9975
  return;
9446
9976
  }
9447
9977
  this.connectionState = "closed";
9978
+ this.connectionAbort.abort();
9448
9979
  if (this.heartbeatTimer) {
9449
9980
  clearInterval(this.heartbeatTimer);
9450
9981
  this.heartbeatTimer = null;
@@ -9922,393 +10453,20 @@ var WebTTYRemoteExecutor = class {
9922
10453
  };
9923
10454
 
9924
10455
  // src/filesystem.ts
9925
- var WebTTYFileSystemError = class extends Error {
9926
- operation;
9927
- 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 {
9928
10462
  constructor(operation, status, message) {
9929
- super(`${operation} failed with status ${status}: ${message}`);
10463
+ super(operation, status, message);
9930
10464
  this.name = "WebTTYFileSystemError";
9931
- this.operation = operation;
9932
- this.status = status;
9933
10465
  }
9934
10466
  };
9935
- var webDAVPropfindBody = '<?xml version="1.0" encoding="utf-8"?><propfind xmlns="DAV:"><prop><resourcetype/><getcontentlength/><getlastmodified/></prop></propfind>';
9936
- function cleanTrailingSlashes2(value) {
9937
- return value.replace(/\/+$/, "");
9938
- }
9939
- function normalizeRemotePath(remotePath) {
9940
- const trimmed = remotePath.trim();
9941
- const absolute = trimmed === "" || trimmed === "." ? "/" : trimmed;
9942
- return new URL(
9943
- absolute.startsWith("/") ? absolute : `/${absolute}`,
9944
- "http://rstream.local"
9945
- ).pathname;
9946
- }
9947
- function comparableRemotePath(remotePath) {
9948
- const normalized = cleanTrailingSlashes2(normalizeRemotePath(remotePath));
9949
- return normalized === "" ? "/" : normalized;
9950
- }
9951
- function sidecarPath(fsPath) {
9952
- return normalizeRemotePath(fsPath ?? "/fs");
9953
- }
9954
- function filesystemBasePath(pathname, fsPath) {
9955
- const sidecar = sidecarPath(fsPath);
9956
- const basePath = cleanTrailingSlashes2(pathname);
9957
- if (basePath === "") return sidecar;
9958
- if (basePath === "/") return sidecar;
9959
- if (basePath === sidecar || basePath.startsWith(`${sidecar}/`))
9960
- return basePath;
9961
- return `${basePath}${sidecar}`;
9962
- }
9963
- function filesystemPath(pathname, remotePath, fsPath) {
9964
- const basePath = filesystemBasePath(pathname, fsPath);
9965
- const normalized = normalizeRemotePath(remotePath);
9966
- return normalized === "/" ? basePath : `${cleanTrailingSlashes2(basePath)}${normalized}`;
9967
- }
9968
- function resolveWebTTYFileSystemURL(input, remotePath = "/", fsPath) {
9969
- const url = new URL(input.toString());
9970
- if (url.protocol === "rstrm:") {
9971
- throw new Error(
9972
- "rstrm:// WebTTY filesystem URLs require the native rstream dialer."
9973
- );
9974
- }
9975
- if (url.protocol === "ws:") url.protocol = "http:";
9976
- if (url.protocol === "wss:") url.protocol = "https:";
9977
- if (url.protocol !== "http:" && url.protocol !== "https:") {
9978
- throw new Error(
9979
- `Unsupported WebTTY filesystem URL scheme "${url.protocol}".`
9980
- );
9981
- }
9982
- url.pathname = filesystemPath(url.pathname, remotePath, fsPath);
9983
- url.hash = "";
9984
- return url;
9985
- }
9986
- function responseAllowed(response, expectedStatuses) {
9987
- return expectedStatuses.includes(response.status);
9988
- }
9989
- async function responseErrorMessage(response) {
9990
- const text = (await response.text()).trim().slice(0, 4096);
9991
- return text === "" ? response.statusText : text;
9992
- }
9993
- async function requireResponseStatus(response, expectedStatuses, operation) {
9994
- if (responseAllowed(response, expectedStatuses)) return response;
9995
- throw new WebTTYFileSystemError(
9996
- operation,
9997
- response.status,
9998
- await responseErrorMessage(response)
9999
- );
10000
- }
10001
- function requireResponseBody(response, operation) {
10002
- if (response.body) return response.body;
10003
- throw new Error(
10004
- `${operation} failed because the response body is unavailable.`
10005
- );
10006
- }
10007
- function resolveFetch(config) {
10008
- if (config.fetch) return config.fetch;
10009
- if (typeof fetch === "undefined") {
10010
- throw new Error("fetch is unavailable in this runtime.");
10011
- }
10012
- return fetch;
10013
- }
10014
- function applyHeaders(target, source) {
10015
- const sourceHeaders = new Headers(source);
10016
- sourceHeaders.forEach((value, key) => target.set(key, value));
10017
- return target;
10018
- }
10019
- function requestHeaders(config, headers) {
10020
- const result = applyHeaders(new Headers(config.headers), headers);
10021
- if (config.authToken && config.authToken.trim() !== "") {
10022
- result.set("Authorization", `Bearer ${config.authToken.trim()}`);
10023
- }
10024
- return result;
10025
- }
10026
- function contentHeaders(contentType) {
10027
- return contentType === void 0 ? void 0 : { "Content-Type": contentType };
10028
- }
10029
- function deleteStatuses(force) {
10030
- return force ? [200, 204, 404] : [200, 204];
10031
- }
10032
- function isNotFound(error) {
10033
- return error instanceof WebTTYFileSystemError && error.status === 404;
10034
- }
10035
- function pathBaseName(path) {
10036
- const normalized = normalizeRemotePath(path);
10037
- const cleaned = cleanTrailingSlashes2(normalized);
10038
- return cleaned.slice(cleaned.lastIndexOf("/") + 1);
10039
- }
10040
- function parentPath(path) {
10041
- const normalized = cleanTrailingSlashes2(normalizeRemotePath(path));
10042
- const index = normalized.lastIndexOf("/");
10043
- if (index <= 0) return "/";
10044
- return normalized.slice(0, index);
10045
- }
10046
- function readFileEncoding(options) {
10047
- if (typeof options === "string") return options;
10048
- return options?.encoding === void 0 ? null : options.encoding;
10049
- }
10050
- function readFileSignal(options) {
10051
- return typeof options === "string" ? void 0 : options?.signal;
10052
- }
10053
- function textContentHeaders(contentType, data) {
10054
- if (contentType !== void 0) return { "Content-Type": contentType };
10055
- return typeof data === "string" ? { "Content-Type": "text/plain; charset=utf-8" } : void 0;
10056
- }
10057
- function bodyRequiresDuplex(body) {
10058
- return typeof ReadableStream !== "undefined" && body instanceof ReadableStream;
10059
- }
10060
- function requestInit(config, method, options) {
10061
- return {
10062
- body: options.body,
10063
- duplex: bodyRequiresDuplex(options.body) ? "half" : void 0,
10064
- headers: requestHeaders(config, options.headers),
10065
- method,
10066
- signal: options.signal
10067
- };
10068
- }
10069
- async function resolveURL2(url) {
10070
- return typeof url === "function" ? await url() : url;
10071
- }
10072
- function elementBodies(xml, name) {
10073
- return Array.from(
10074
- xml.matchAll(
10075
- new RegExp(
10076
- `<[^>]*:?${name}\\b[^>]*>([\\s\\S]*?)<\\/[^>]*:?${name}>`,
10077
- "gi"
10078
- )
10079
- ),
10080
- (match) => match[1] ?? ""
10081
- );
10082
- }
10083
- function hasElement(xml, name) {
10084
- return new RegExp(`<[^>]*:?${name}(\\s|/|>)`, "i").test(xml);
10085
- }
10086
- function stripTags(xml) {
10087
- return xml.replace(/<[^>]*>/g, "");
10088
- }
10089
- function decodeNumericEntity(value) {
10090
- const parsed = value.startsWith("&#x") ? Number.parseInt(value.slice(3, -1), 16) : Number.parseInt(value.slice(2, -1), 10);
10091
- return Number.isFinite(parsed) ? String.fromCodePoint(parsed) : value;
10092
- }
10093
- function decodeXmlText(value) {
10094
- 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, "&");
10095
- }
10096
- function elementText(xml, name) {
10097
- return decodeXmlText(stripTags(elementBodies(xml, name)[0] ?? "")).trim();
10098
- }
10099
- function okPropstat(response) {
10100
- return elementBodies(response, "propstat").find(
10101
- (propstat) => elementText(propstat, "status").includes(" 200 ")
10102
- ) ?? "";
10103
- }
10104
- function safeDecodePath(path) {
10105
- try {
10106
- return decodeURIComponent(path);
10107
- } catch {
10108
- return path;
10109
- }
10110
- }
10111
- function hrefPath(href) {
10112
- return safeDecodePath(new URL(href, "http://rstream.local").pathname);
10113
- }
10114
- function displayPath(href, fsPath) {
10115
- const value = hrefPath(href);
10116
- const sidecar = cleanTrailingSlashes2(sidecarPath(fsPath));
10117
- const withoutFS = value === sidecar ? "/" : value.startsWith(`${sidecar}/`) ? value.slice(sidecar.length) : value;
10118
- return withoutFS === "" ? "/" : withoutFS;
10119
- }
10120
- function itemSize(value) {
10121
- const parsed = Number.parseInt(value, 10);
10122
- return Number.isFinite(parsed) ? parsed : void 0;
10123
- }
10124
- function itemFromResponse(response, fsPath) {
10125
- const propstat = okPropstat(response);
10126
- const path = displayPath(elementText(response, "href"), fsPath);
10127
- if (propstat === "" || path === "") return null;
10128
- return {
10129
- kind: hasElement(
10130
- elementBodies(propstat, "resourcetype")[0] ?? "",
10131
- "collection"
10132
- ) ? "directory" : "file",
10133
- modified: elementText(propstat, "getlastmodified") || void 0,
10134
- path,
10135
- size: itemSize(elementText(propstat, "getcontentlength"))
10136
- };
10137
- }
10138
- function presentItems(items) {
10139
- return items.filter((item) => item !== null);
10140
- }
10141
- function parseWebDAVMultiStatus(xml, fsPath = "/fs") {
10142
- return presentItems(
10143
- elementBodies(xml, "response").map(
10144
- (response) => itemFromResponse(response, fsPath)
10145
- )
10146
- );
10147
- }
10148
- var WebTTYFileSystem = class {
10149
- config;
10150
- constructor(config) {
10151
- this.config = config;
10152
- }
10153
- async list(path = "/", options = {}) {
10154
- const response = await this.request("PROPFIND", path, {
10155
- body: webDAVPropfindBody,
10156
- expectedStatuses: [207],
10157
- headers: { "Content-Type": "application/xml; charset=utf-8", Depth: "1" },
10158
- operation: "WebTTY filesystem list",
10159
- signal: options.signal
10160
- });
10161
- return parseWebDAVMultiStatus(
10162
- await response.text(),
10163
- sidecarPath(this.config.fsPath)
10164
- );
10165
- }
10166
- async readBytes(path, options = {}) {
10167
- const response = await this.request("GET", path, {
10168
- expectedStatuses: [200],
10169
- operation: "WebTTY filesystem read",
10170
- signal: options.signal
10171
- });
10172
- return new Uint8Array(await response.arrayBuffer());
10173
- }
10174
- async readFile(path, options) {
10175
- const bytes = await this.readBytes(path, {
10176
- signal: readFileSignal(options)
10177
- });
10178
- const encoding = readFileEncoding(options);
10179
- return encoding === null ? bytes : new TextDecoder(encoding).decode(bytes);
10180
- }
10181
- async readText(path, options = {}) {
10182
- return new TextDecoder().decode(await this.readBytes(path, options));
10183
- }
10184
- async readStream(path, options = {}) {
10185
- return requireResponseBody(
10186
- await this.request("GET", path, {
10187
- expectedStatuses: [200],
10188
- operation: "WebTTY filesystem read",
10189
- signal: options.signal
10190
- }),
10191
- "WebTTY filesystem read"
10192
- );
10193
- }
10194
- async writeFile(path, data, options = {}) {
10195
- await this.request("PUT", path, {
10196
- body: data,
10197
- expectedStatuses: [200, 201, 204],
10198
- headers: textContentHeaders(options.contentType, data),
10199
- operation: "WebTTY filesystem write",
10200
- signal: options.signal
10201
- });
10202
- }
10203
- async writeBytes(path, data, options = {}) {
10204
- await this.writeFile(path, data, options);
10205
- }
10206
- async writeStream(path, data, options = {}) {
10207
- await this.request("PUT", path, {
10208
- body: data,
10209
- expectedStatuses: [200, 201, 204],
10210
- headers: contentHeaders(options.contentType),
10211
- operation: "WebTTY filesystem write",
10212
- signal: options.signal
10213
- });
10214
- }
10215
- async writeText(path, data, options = {}) {
10216
- await this.writeFile(path, data, options);
10217
- }
10218
- async copyFile(sourcePath, targetPath, options = {}) {
10219
- await this.request("COPY", sourcePath, {
10220
- expectedStatuses: [200, 201, 204],
10221
- headers: { Destination: (await this.resourceURL(targetPath)).toString() },
10222
- operation: "WebTTY filesystem copy",
10223
- signal: options.signal
10224
- });
10225
- }
10226
- async createDirectory(path, options = {}) {
10227
- await this.request("MKCOL", path, {
10228
- expectedStatuses: [201, 405],
10229
- operation: "WebTTY filesystem mkdir",
10230
- signal: options.signal
10231
- });
10232
- }
10233
- async exists(path, options = {}) {
10234
- return await this.stat(path, options).then(() => true).catch((error) => {
10235
- if (isNotFound(error)) return false;
10236
- throw error;
10237
- });
10238
- }
10239
- async mkdir(path, options = {}) {
10240
- if (options.recursive) {
10241
- await this.createDirectoryRecursive(path, options.signal);
10242
- return normalizeRemotePath(path);
10243
- }
10244
- await this.createDirectory(path, options);
10245
- return void 0;
10246
- }
10247
- async readdir(path = "/", options = {}) {
10248
- const items = (await this.list(path, options)).filter(
10249
- (item) => comparableRemotePath(item.path) !== comparableRemotePath(path)
10250
- );
10251
- return options.withFileTypes ? items : items.map((item) => pathBaseName(item.path));
10252
- }
10253
- async rename(oldPath, newPath, options = {}) {
10254
- await this.request("MOVE", oldPath, {
10255
- expectedStatuses: [200, 201, 204],
10256
- headers: { Destination: (await this.resourceURL(newPath)).toString() },
10257
- operation: "WebTTY filesystem rename",
10258
- signal: options.signal
10259
- });
10260
- }
10261
- async rm(path, options = {}) {
10262
- void options.recursive;
10263
- await this.request("DELETE", path, {
10264
- expectedStatuses: deleteStatuses(options.force),
10265
- operation: "WebTTY filesystem delete",
10266
- signal: options.signal
10267
- });
10268
- }
10269
- async stat(path, options = {}) {
10270
- const response = await this.request("PROPFIND", path, {
10271
- body: webDAVPropfindBody,
10272
- expectedStatuses: [207],
10273
- headers: { "Content-Type": "application/xml; charset=utf-8", Depth: "0" },
10274
- operation: "WebTTY filesystem stat",
10275
- signal: options.signal
10276
- });
10277
- const item = parseWebDAVMultiStatus(
10278
- await response.text(),
10279
- sidecarPath(this.config.fsPath)
10280
- )[0];
10281
- if (item) return item;
10282
- throw new Error(`WebTTY filesystem stat did not return ${path}.`);
10283
- }
10284
- async delete(path, options = {}) {
10285
- await this.rm(path, options);
10286
- }
10287
- async createDirectoryRecursive(path, signal) {
10288
- const normalized = normalizeRemotePath(path);
10289
- if (normalized === "/") return;
10290
- const parent = parentPath(normalized);
10291
- if (parent !== normalized) {
10292
- await this.createDirectoryRecursive(parent, signal);
10293
- }
10294
- await this.createDirectory(normalized, { signal });
10295
- }
10296
- async resourceURL(path) {
10297
- return resolveWebTTYFileSystemURL(
10298
- await resolveURL2(this.config.url),
10299
- path,
10300
- this.config.fsPath
10301
- );
10302
- }
10303
- async request(method, path, options) {
10304
- return await requireResponseStatus(
10305
- await resolveFetch(this.config)(
10306
- await this.resourceURL(path),
10307
- requestInit(this.config, method, options)
10308
- ),
10309
- options.expectedStatuses,
10310
- options.operation
10311
- );
10467
+ var WebTTYFileSystem = class extends RemoteFileSystem {
10468
+ createError(operation, status, message) {
10469
+ return new WebTTYFileSystemError(operation, status, message);
10312
10470
  }
10313
10471
  };
10314
10472
 
@@ -10571,7 +10729,7 @@ function payloadCryptoMetadataFromRecordedMetadata(metadata) {
10571
10729
  }
10572
10730
  return {
10573
10731
  aadContext: keyContextFromRecordedMetadata(metadata),
10574
- 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),
10575
10733
  payloadKeyId: bytesFromBase64URL(metadata.payload_key_id),
10576
10734
  payloadSuite: metadata.payload_suite
10577
10735
  };
@@ -10882,6 +11040,8 @@ export {
10882
11040
  hashWebTTYSessionKeyGrant,
10883
11041
  webTTYServerProofTranscriptBytes,
10884
11042
  hashWebTTYServerProofTranscript,
11043
+ webTTYFIPSCompatiblePayloadSuite,
11044
+ webTTYFIPSCompatibleKeyEnvelopeSuite,
10885
11045
  generateWebTTYE2EIdentity,
10886
11046
  webTTYE2EKeyID,
10887
11047
  encodeWebTTYE2EKeyMaterial,
@@ -10896,10 +11056,10 @@ export {
10896
11056
  runWebTTYCommand,
10897
11057
  executeWebTTYCommand,
10898
11058
  WebTTYRemoteExecutor,
10899
- WebTTYFileSystemError,
10900
11059
  resolveWebTTYFileSystemURL,
10901
- parseWebDAVMultiStatus,
11060
+ WebTTYFileSystemError,
10902
11061
  WebTTYFileSystem,
11062
+ parseWebDAVMultiStatus,
10903
11063
  webTTYRecordedEventEncryptedPayload,
10904
11064
  decryptWebTTYRecordedEvent,
10905
11065
  decryptWebTTYRecordedTextLog,