@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.
package/dist/node.js CHANGED
@@ -55,8 +55,9 @@ __export(node_exports, {
55
55
  hashWebTTYServerProofTranscript: () => hashWebTTYServerProofTranscript,
56
56
  hashWebTTYSessionKeyGrant: () => hashWebTTYSessionKeyGrant,
57
57
  loadWebTTYKnownServerKeysFile: () => loadWebTTYKnownServerKeysFile,
58
+ nodeWebSocketFactory: () => nodeWebSocketFactory,
58
59
  openWebTTYCommand: () => openWebTTYCommand,
59
- parseWebDAVMultiStatus: () => parseWebDAVMultiStatus,
60
+ parseWebDAVMultiStatus: () => import_filesystem4.parseWebDAVMultiStatus,
60
61
  parseWebTTYKnownServerKey: () => parseWebTTYKnownServerKey,
61
62
  readWebTTYKnownServerKeysFile: () => readWebTTYKnownServerKeysFile,
62
63
  renderWebTTYRecordedTextLog: () => renderWebTTYRecordedTextLog,
@@ -69,6 +70,8 @@ __export(node_exports, {
69
70
  verifyWebTTYServerProofTranscript: () => verifyWebTTYServerProofTranscript,
70
71
  webTTYClientProofTranscriptBytes: () => webTTYClientProofTranscriptBytes,
71
72
  webTTYE2EKeyID: () => webTTYE2EKeyID,
73
+ webTTYFIPSCompatibleKeyEnvelopeSuite: () => webTTYFIPSCompatibleKeyEnvelopeSuite,
74
+ webTTYFIPSCompatiblePayloadSuite: () => webTTYFIPSCompatiblePayloadSuite,
72
75
  webTTYRecordedEventEncryptedPayload: () => webTTYRecordedEventEncryptedPayload,
73
76
  webTTYServerProofTranscriptBytes: () => webTTYServerProofTranscriptBytes,
74
77
  webTTYSigningKeyID: () => webTTYSigningKeyID
@@ -985,6 +988,7 @@ var rstream = $root.rstream = (() => {
985
988
  values[valuesById[0] = "PAYLOAD_CIPHER_SUITE_UNSPECIFIED"] = 0;
986
989
  values[valuesById[1] = "PAYLOAD_CIPHER_SUITE_AES_256_GCM"] = 1;
987
990
  values[valuesById[2] = "PAYLOAD_CIPHER_SUITE_CHACHA20_POLY1305"] = 2;
991
+ values[valuesById[3] = "PAYLOAD_CIPHER_SUITE_AES_256_GCM_RANDOM_NONCE"] = 3;
988
992
  return values;
989
993
  })();
990
994
  protobuf.KeyEnvelopeSuite = (function() {
@@ -992,6 +996,7 @@ var rstream = $root.rstream = (() => {
992
996
  values[valuesById[0] = "KEY_ENVELOPE_SUITE_UNSPECIFIED"] = 0;
993
997
  values[valuesById[1] = "KEY_ENVELOPE_SUITE_HPKE_X25519_HKDF_SHA256_AES_256_GCM"] = 1;
994
998
  values[valuesById[2] = "KEY_ENVELOPE_SUITE_HPKE_X25519_HKDF_SHA256_CHACHA20_POLY1305"] = 2;
999
+ values[valuesById[3] = "KEY_ENVELOPE_SUITE_P256_HKDF_SHA256_AES_256_GCM_RANDOM_NONCE"] = 3;
995
1000
  return values;
996
1001
  })();
997
1002
  protobuf.ProtocolVersion = (function() {
@@ -1494,6 +1499,10 @@ var rstream = $root.rstream = (() => {
1494
1499
  case 2:
1495
1500
  message.keyEnvelopeSuite = 2;
1496
1501
  break;
1502
+ case "KEY_ENVELOPE_SUITE_P256_HKDF_SHA256_AES_256_GCM_RANDOM_NONCE":
1503
+ case 3:
1504
+ message.keyEnvelopeSuite = 3;
1505
+ break;
1497
1506
  default:
1498
1507
  if (typeof object.keyEnvelopeSuite === "number" && (object.keyEnvelopeSuite | 0) === object.keyEnvelopeSuite)
1499
1508
  message.keyEnvelopeSuite = object.keyEnvelopeSuite;
@@ -2178,6 +2187,10 @@ var rstream = $root.rstream = (() => {
2178
2187
  case 2:
2179
2188
  message.payloadSuites[message.payloadSuites.length] = 2;
2180
2189
  break;
2190
+ case "PAYLOAD_CIPHER_SUITE_AES_256_GCM_RANDOM_NONCE":
2191
+ case 3:
2192
+ message.payloadSuites[message.payloadSuites.length] = 3;
2193
+ break;
2181
2194
  default:
2182
2195
  if (typeof object.payloadSuites[i] === "number" && (object.payloadSuites[i] | 0) === object.payloadSuites[i])
2183
2196
  message.payloadSuites[message.payloadSuites.length] = object.payloadSuites[i];
@@ -2201,6 +2214,10 @@ var rstream = $root.rstream = (() => {
2201
2214
  case 2:
2202
2215
  message.keyEnvelopeSuites[message.keyEnvelopeSuites.length] = 2;
2203
2216
  break;
2217
+ case "KEY_ENVELOPE_SUITE_P256_HKDF_SHA256_AES_256_GCM_RANDOM_NONCE":
2218
+ case 3:
2219
+ message.keyEnvelopeSuites[message.keyEnvelopeSuites.length] = 3;
2220
+ break;
2204
2221
  default:
2205
2222
  if (typeof object.keyEnvelopeSuites[i] === "number" && (object.keyEnvelopeSuites[i] | 0) === object.keyEnvelopeSuites[i])
2206
2223
  message.keyEnvelopeSuites[message.keyEnvelopeSuites.length] = object.keyEnvelopeSuites[i];
@@ -2674,6 +2691,10 @@ var rstream = $root.rstream = (() => {
2674
2691
  case 2:
2675
2692
  message.payloadSuite = 2;
2676
2693
  break;
2694
+ case "PAYLOAD_CIPHER_SUITE_AES_256_GCM_RANDOM_NONCE":
2695
+ case 3:
2696
+ message.payloadSuite = 3;
2697
+ break;
2677
2698
  default:
2678
2699
  if (typeof object.payloadSuite === "number" && (object.payloadSuite | 0) === object.payloadSuite)
2679
2700
  message.payloadSuite = object.payloadSuite;
@@ -2718,6 +2739,10 @@ var rstream = $root.rstream = (() => {
2718
2739
  case 2:
2719
2740
  message.keyEnvelopeSuite = 2;
2720
2741
  break;
2742
+ case "KEY_ENVELOPE_SUITE_P256_HKDF_SHA256_AES_256_GCM_RANDOM_NONCE":
2743
+ case 3:
2744
+ message.keyEnvelopeSuite = 3;
2745
+ break;
2721
2746
  default:
2722
2747
  if (typeof object.keyEnvelopeSuite === "number" && (object.keyEnvelopeSuite | 0) === object.keyEnvelopeSuite)
2723
2748
  message.keyEnvelopeSuite = object.keyEnvelopeSuite;
@@ -2945,6 +2970,10 @@ var rstream = $root.rstream = (() => {
2945
2970
  case 2:
2946
2971
  message.payloadSuite = 2;
2947
2972
  break;
2973
+ case "PAYLOAD_CIPHER_SUITE_AES_256_GCM_RANDOM_NONCE":
2974
+ case 3:
2975
+ message.payloadSuite = 3;
2976
+ break;
2948
2977
  default:
2949
2978
  if (typeof object.payloadSuite === "number" && (object.payloadSuite | 0) === object.payloadSuite)
2950
2979
  message.payloadSuite = object.payloadSuite;
@@ -7455,6 +7484,7 @@ function authRequirementCode(value) {
7455
7484
  function payloadSuiteCode(value) {
7456
7485
  if (value === "aes-256-gcm" || value === void 0) return 1;
7457
7486
  if (value === "chacha20-poly1305") return 2;
7487
+ if (value === "aes-256-gcm-random-nonce") return 3;
7458
7488
  return 0;
7459
7489
  }
7460
7490
  function keyEnvelopeSuiteCode(value) {
@@ -7462,6 +7492,7 @@ function keyEnvelopeSuiteCode(value) {
7462
7492
  return 1;
7463
7493
  }
7464
7494
  if (value === "hpke-x25519-hkdf-sha256-chacha20-poly1305") return 2;
7495
+ if (value === "p256-hkdf-sha256-aes-256-gcm-random-nonce") return 3;
7465
7496
  return 0;
7466
7497
  }
7467
7498
  function signatureSuiteCode(value) {
@@ -7662,6 +7693,8 @@ function normalizeSessionKeyGrant(grant) {
7662
7693
  // src/e2e-crypto.ts
7663
7694
  var x25519PublicKeySize = 32;
7664
7695
  var x25519PrivateKeySize = 32;
7696
+ var p256PublicKeySize = 65;
7697
+ var p256PrivateKeySize = 32;
7665
7698
  var payloadKeySize = 32;
7666
7699
  var payloadKeyIDSize = 16;
7667
7700
  var aesGCMNonceSize = 12;
@@ -7674,21 +7707,24 @@ var keyIDDomain = "rstream-webtty-e2e-key-id/v1";
7674
7707
  var hpkeVersionLabel = "HPKE-v1";
7675
7708
  var nominalPayloadSuite = "aes-256-gcm";
7676
7709
  var nominalKeyEnvelopeSuite = "hpke-x25519-hkdf-sha256-aes-256-gcm";
7677
- async function generateWebTTYE2EIdentity() {
7678
- const pair = await getSubtle().generateKey({ name: "X25519" }, true, [
7679
- "deriveBits"
7680
- ]);
7681
- if (!isX25519KeyPair(pair)) {
7682
- throw new Error("WebCrypto returned an unexpected X25519 key pair");
7710
+ var webTTYFIPSCompatiblePayloadSuite = "aes-256-gcm-random-nonce";
7711
+ var webTTYFIPSCompatibleKeyEnvelopeSuite = "p256-hkdf-sha256-aes-256-gcm-random-nonce";
7712
+ async function generateWebTTYE2EIdentity(keyEnvelopeSuite = nominalKeyEnvelopeSuite) {
7713
+ payloadSuiteForKeyEnvelopeSuite(keyEnvelopeSuite);
7714
+ const algorithm = keyEnvelopeSuite === webTTYFIPSCompatibleKeyEnvelopeSuite ? { name: "ECDH", namedCurve: "P-256" } : { name: "X25519" };
7715
+ const pair = await getSubtle().generateKey(algorithm, true, ["deriveBits"]);
7716
+ if (!isCryptoKeyPair(pair)) {
7717
+ throw new Error("WebCrypto returned an unexpected E2E key pair");
7683
7718
  }
7684
7719
  const publicKey = new Uint8Array(
7685
7720
  await getSubtle().exportKey("raw", pair.publicKey)
7686
7721
  );
7687
7722
  const jwk = await getSubtle().exportKey("jwk", pair.privateKey);
7688
7723
  if (typeof jwk.d !== "string") {
7689
- throw new Error("WebCrypto X25519 private JWK is missing d");
7724
+ throw new Error("WebCrypto E2E private JWK is missing d");
7690
7725
  }
7691
7726
  return {
7727
+ keyEnvelopeSuite,
7692
7728
  keyId: await webTTYE2EKeyID(publicKey),
7693
7729
  privateKey: base64URLDecode(jwk.d),
7694
7730
  publicKey
@@ -7729,8 +7765,8 @@ function createWebTTYE2EKeyContext(config) {
7729
7765
  );
7730
7766
  }
7731
7767
  async function createWebTTYE2EClientPayloadCrypto(config) {
7732
- const payloadSuite = config.payloadSuite ?? nominalPayloadSuite;
7733
- const keyEnvelopeSuite = config.keyEnvelopeSuite ?? nominalKeyEnvelopeSuite;
7768
+ const keyEnvelopeSuite = config.keyEnvelopeSuite ?? inferRecipientSuite(config.recipients);
7769
+ const payloadSuite = config.payloadSuite ?? payloadSuiteForKeyEnvelopeSuite(keyEnvelopeSuite);
7734
7770
  validateSuites(payloadSuite, keyEnvelopeSuite);
7735
7771
  const payloadKey = config.payloadKey ? cloneKeyMaterial(config.payloadKey) : randomBytes(payloadKeySize);
7736
7772
  if (payloadKey.byteLength !== payloadKeySize) {
@@ -7822,7 +7858,7 @@ function createPayloadCrypto(options) {
7822
7858
  payloadSuite: options.payloadSuite
7823
7859
  };
7824
7860
  const cryptoInfo = {
7825
- keyAgreement: "HPKE X25519",
7861
+ keyAgreement: options.keyEnvelopeSuite === webTTYFIPSCompatibleKeyEnvelopeSuite ? "ECDH P-256" : "HPKE X25519",
7826
7862
  keyDerivation: "HKDF-SHA256",
7827
7863
  keyEncryption: "AES-256-GCM",
7828
7864
  keyEnvelopeSuite: options.keyEnvelopeSuite,
@@ -7837,7 +7873,7 @@ function createPayloadCrypto(options) {
7837
7873
  if (chunk.byteLength > 4294967295) {
7838
7874
  throw new Error(`E2E payload is too large: ${chunk.byteLength} bytes`);
7839
7875
  }
7840
- const nonce = randomBytes(aesGCMNonceSize);
7876
+ const nonce = options.payloadSuite === webTTYFIPSCompatiblePayloadSuite ? new Uint8Array() : randomBytes(aesGCMNonceSize);
7841
7877
  const payloadCrypto = {
7842
7878
  aadContext: cloneBytes(options.keyContext),
7843
7879
  nonce,
@@ -7845,7 +7881,8 @@ function createPayloadCrypto(options) {
7845
7881
  payloadSuite: options.payloadSuite
7846
7882
  };
7847
7883
  return {
7848
- ciphertext: await aesGCMEncrypt(
7884
+ ciphertext: await encryptPayloadForSuite(
7885
+ options.payloadSuite,
7849
7886
  options.payloadKey,
7850
7887
  nonce,
7851
7888
  cloneBytes(chunk),
@@ -7865,19 +7902,21 @@ function createPayloadCrypto(options) {
7865
7902
  const decrypt = (stream) => async (payload) => {
7866
7903
  validatePayloadEnvelope(payload, options);
7867
7904
  const crypto = payload.payloadCrypto;
7868
- if (crypto === void 0 || crypto.nonce === void 0) {
7869
- throw new Error("missing E2E payload nonce");
7905
+ if (crypto === void 0) {
7906
+ throw new Error("missing E2E payload crypto");
7870
7907
  }
7871
- const plaintext = await aesGCMDecrypt(
7908
+ const nonce = crypto.nonce ?? new Uint8Array();
7909
+ const plaintext = await decryptPayloadForSuite(
7910
+ options.payloadSuite,
7872
7911
  options.payloadKey,
7873
- crypto.nonce,
7912
+ nonce,
7874
7913
  payload.ciphertext,
7875
7914
  payloadAAD(
7876
7915
  stream,
7877
7916
  options.payloadSuite,
7878
7917
  options.payloadKeyId,
7879
7918
  options.keyContext,
7880
- crypto.nonce,
7919
+ nonce,
7881
7920
  payload.plaintextLength
7882
7921
  )
7883
7922
  );
@@ -7922,21 +7961,29 @@ async function implicitKeyContextFromRecipients(recipients) {
7922
7961
  }
7923
7962
  async function wrapPayloadKey(payloadKey, payloadSuite, payloadKeyId, keyContext, suite, recipient) {
7924
7963
  const recipientPublicKey = cloneKeyMaterial(recipient.publicKey);
7925
- if (recipientPublicKey.byteLength !== x25519PublicKeySize) {
7964
+ const recipientSuite = recipient.keyEnvelopeSuite ?? inferKeyEnvelopeSuite(recipientPublicKey);
7965
+ if (recipientSuite !== suite) {
7966
+ throw new Error("E2E recipient suite does not match key envelope suite");
7967
+ }
7968
+ const expectedPublicKeySize = publicKeySizeForSuite(suite);
7969
+ if (recipientPublicKey.byteLength !== expectedPublicKeySize) {
7926
7970
  throw new Error(
7927
- `E2E recipient public key must be ${x25519PublicKeySize} bytes`
7971
+ `E2E recipient public key must be ${expectedPublicKeySize} bytes`
7928
7972
  );
7929
7973
  }
7930
7974
  const recipientKeyId = recipient.keyId ? cloneKeyMaterial(recipient.keyId) : await webTTYE2EKeyID(recipientPublicKey);
7931
7975
  if (recipientKeyId.byteLength !== payloadKeyIDSize) {
7932
7976
  throw new Error(`E2E recipient key id must be ${payloadKeyIDSize} bytes`);
7933
7977
  }
7934
- const sealed = await hpkeSeal(
7935
- recipientPublicKey,
7936
- hpkeInfo(payloadSuite, payloadKeyId, keyContext, suite),
7937
- hpkeAAD(recipientKeyId, payloadSuite, payloadKeyId, keyContext, suite),
7938
- payloadKey
7978
+ const info = hpkeInfo(payloadSuite, payloadKeyId, keyContext, suite);
7979
+ const aad = hpkeAAD(
7980
+ recipientKeyId,
7981
+ payloadSuite,
7982
+ payloadKeyId,
7983
+ keyContext,
7984
+ suite
7939
7985
  );
7986
+ const sealed = suite === webTTYFIPSCompatibleKeyEnvelopeSuite ? await p256Seal(recipientPublicKey, info, aad, payloadKey) : await hpkeSeal(recipientPublicKey, info, aad, payloadKey);
7940
7987
  return {
7941
7988
  encapsulatedKey: sealed.encapsulatedKey,
7942
7989
  recipientKeyId,
@@ -7953,17 +8000,28 @@ async function unwrapPayloadKey(envelope, payloadSuite, payloadKeyId, keyContext
7953
8000
  if (envelope.wrappedKey === void 0) {
7954
8001
  throw new Error("E2E key envelope is missing wrapped key");
7955
8002
  }
7956
- const payloadKey = await hpkeOpen(
8003
+ if (identity.keyEnvelopeSuite !== suite) {
8004
+ throw new Error("E2E identity suite does not match key envelope suite");
8005
+ }
8006
+ const info = hpkeInfo(payloadSuite, payloadKeyId, keyContext, suite);
8007
+ const aad = hpkeAAD(
8008
+ envelope.recipientKeyId,
8009
+ payloadSuite,
8010
+ payloadKeyId,
8011
+ keyContext,
8012
+ suite
8013
+ );
8014
+ const payloadKey = suite === webTTYFIPSCompatibleKeyEnvelopeSuite ? await p256Open(
7957
8015
  identity,
7958
8016
  envelope.encapsulatedKey,
7959
- hpkeInfo(payloadSuite, payloadKeyId, keyContext, suite),
7960
- hpkeAAD(
7961
- envelope.recipientKeyId,
7962
- payloadSuite,
7963
- payloadKeyId,
7964
- keyContext,
7965
- suite
7966
- ),
8017
+ info,
8018
+ aad,
8019
+ envelope.wrappedKey
8020
+ ) : await hpkeOpen(
8021
+ identity,
8022
+ envelope.encapsulatedKey,
8023
+ info,
8024
+ aad,
7967
8025
  envelope.wrappedKey
7968
8026
  );
7969
8027
  if (payloadKey.byteLength !== payloadKeySize) {
@@ -8045,6 +8103,95 @@ async function hpkeOpen(identity, encapsulatedKey, info, aad, ciphertext) {
8045
8103
  const schedule = await hpkeKeySchedule(sharedSecret, info);
8046
8104
  return aesGCMDecrypt(schedule.key, schedule.baseNonce, ciphertext, aad);
8047
8105
  }
8106
+ async function p256Seal(publicKey, info, aad, plaintext) {
8107
+ const recipientPublic = await getSubtle().importKey(
8108
+ "raw",
8109
+ bufferSource(publicKey),
8110
+ { name: "ECDH", namedCurve: "P-256" },
8111
+ false,
8112
+ []
8113
+ );
8114
+ const ephemeral = await getSubtle().generateKey(
8115
+ { name: "ECDH", namedCurve: "P-256" },
8116
+ true,
8117
+ ["deriveBits"]
8118
+ );
8119
+ if (!isCryptoKeyPair(ephemeral)) {
8120
+ throw new Error("WebCrypto returned an unexpected P-256 key pair");
8121
+ }
8122
+ const encapsulatedKey = new Uint8Array(
8123
+ await getSubtle().exportKey("raw", ephemeral.publicKey)
8124
+ );
8125
+ const sharedSecret = new Uint8Array(
8126
+ await getSubtle().deriveBits(
8127
+ { name: "ECDH", public: recipientPublic },
8128
+ ephemeral.privateKey,
8129
+ 256
8130
+ )
8131
+ );
8132
+ const wrappingKey = await p256WrappingKey(sharedSecret, info);
8133
+ return {
8134
+ encapsulatedKey,
8135
+ wrappedKey: await aesGCMEncryptWithPrefixedRandomNonce(
8136
+ wrappingKey,
8137
+ plaintext,
8138
+ aad
8139
+ )
8140
+ };
8141
+ }
8142
+ async function p256Open(identity, encapsulatedKey, info, aad, ciphertext) {
8143
+ if (identity.privateKey.byteLength !== p256PrivateKeySize) {
8144
+ throw new Error(
8145
+ `E2E identity private key must be ${p256PrivateKeySize} bytes`
8146
+ );
8147
+ }
8148
+ if (identity.publicKey.byteLength !== p256PublicKeySize || identity.publicKey[0] !== 4) {
8149
+ throw new Error(
8150
+ `E2E identity public key must be an uncompressed ${p256PublicKeySize}-byte P-256 point`
8151
+ );
8152
+ }
8153
+ const recipientPrivate = await importP256PrivateKey(identity);
8154
+ const ephemeralPublic = await getSubtle().importKey(
8155
+ "raw",
8156
+ bufferSource(encapsulatedKey),
8157
+ { name: "ECDH", namedCurve: "P-256" },
8158
+ false,
8159
+ []
8160
+ );
8161
+ const sharedSecret = new Uint8Array(
8162
+ await getSubtle().deriveBits(
8163
+ { name: "ECDH", public: ephemeralPublic },
8164
+ recipientPrivate,
8165
+ 256
8166
+ )
8167
+ );
8168
+ return aesGCMDecryptWithPrefixedRandomNonce(
8169
+ await p256WrappingKey(sharedSecret, info),
8170
+ ciphertext,
8171
+ aad
8172
+ );
8173
+ }
8174
+ async function p256WrappingKey(sharedSecret, info) {
8175
+ const key = await getSubtle().importKey(
8176
+ "raw",
8177
+ bufferSource(sharedSecret),
8178
+ "HKDF",
8179
+ false,
8180
+ ["deriveBits"]
8181
+ );
8182
+ return new Uint8Array(
8183
+ await getSubtle().deriveBits(
8184
+ {
8185
+ hash: "SHA-256",
8186
+ info: bufferSource(info),
8187
+ name: "HKDF",
8188
+ salt: new Uint8Array()
8189
+ },
8190
+ key,
8191
+ 256
8192
+ )
8193
+ );
8194
+ }
8048
8195
  async function dhkemExtractAndExpand(dh, kemContext) {
8049
8196
  const eaePRK = await labeledExtract(
8050
8197
  dhkemSuiteID(),
@@ -8197,6 +8344,33 @@ async function aesGCMDecrypt(key, nonce, ciphertext, aad) {
8197
8344
  )
8198
8345
  );
8199
8346
  }
8347
+ async function aesGCMEncryptWithPrefixedRandomNonce(key, plaintext, aad) {
8348
+ const nonce = randomBytes(aesGCMNonceSize);
8349
+ return concat2(nonce, await aesGCMEncrypt(key, nonce, plaintext, aad));
8350
+ }
8351
+ async function aesGCMDecryptWithPrefixedRandomNonce(key, ciphertext, aad) {
8352
+ if (ciphertext.byteLength < aesGCMNonceSize + 16) {
8353
+ throw new Error("E2E random-nonce AES-GCM ciphertext is too short");
8354
+ }
8355
+ return aesGCMDecrypt(
8356
+ key,
8357
+ ciphertext.slice(0, aesGCMNonceSize),
8358
+ ciphertext.slice(aesGCMNonceSize),
8359
+ aad
8360
+ );
8361
+ }
8362
+ async function encryptPayloadForSuite(suite, key, nonce, plaintext, aad) {
8363
+ if (suite === webTTYFIPSCompatiblePayloadSuite) {
8364
+ return aesGCMEncryptWithPrefixedRandomNonce(key, plaintext, aad);
8365
+ }
8366
+ return aesGCMEncrypt(key, nonce, plaintext, aad);
8367
+ }
8368
+ async function decryptPayloadForSuite(suite, key, nonce, ciphertext, aad) {
8369
+ if (suite === webTTYFIPSCompatiblePayloadSuite) {
8370
+ return aesGCMDecryptWithPrefixedRandomNonce(key, ciphertext, aad);
8371
+ }
8372
+ return aesGCMDecrypt(key, nonce, ciphertext, aad);
8373
+ }
8200
8374
  async function importX25519PrivateKey(identity) {
8201
8375
  return getSubtle().importKey(
8202
8376
  "jwk",
@@ -8213,6 +8387,23 @@ async function importX25519PrivateKey(identity) {
8213
8387
  ["deriveBits"]
8214
8388
  );
8215
8389
  }
8390
+ async function importP256PrivateKey(identity) {
8391
+ return getSubtle().importKey(
8392
+ "jwk",
8393
+ {
8394
+ crv: "P-256",
8395
+ d: base64URLEncode(identity.privateKey),
8396
+ ext: true,
8397
+ key_ops: ["deriveBits"],
8398
+ kty: "EC",
8399
+ x: base64URLEncode(identity.publicKey.slice(1, 33)),
8400
+ y: base64URLEncode(identity.publicKey.slice(33, 65))
8401
+ },
8402
+ { name: "ECDH", namedCurve: "P-256" },
8403
+ false,
8404
+ ["deriveBits"]
8405
+ );
8406
+ }
8216
8407
  function validatePayloadEnvelope(payload, options) {
8217
8408
  const crypto = payload.payloadCrypto;
8218
8409
  if (crypto === void 0) throw new Error("missing E2E payload crypto");
@@ -8225,18 +8416,64 @@ function validatePayloadEnvelope(payload, options) {
8225
8416
  if (!bytesEqual(crypto.aadContext, options.keyContext)) {
8226
8417
  throw new Error("unexpected E2E key context");
8227
8418
  }
8228
- if (crypto.nonce === void 0 || crypto.nonce.byteLength !== aesGCMNonceSize) {
8229
- throw new Error(`E2E AES-GCM nonce must be ${aesGCMNonceSize} bytes`);
8419
+ const expectedNonceSize = options.payloadSuite === webTTYFIPSCompatiblePayloadSuite ? 0 : aesGCMNonceSize;
8420
+ if (crypto.nonce === void 0 || crypto.nonce.byteLength !== expectedNonceSize) {
8421
+ throw new Error(`E2E AES-GCM nonce must be ${expectedNonceSize} bytes`);
8230
8422
  }
8231
8423
  }
8232
- function validateSuites(payloadSuite, keyEnvelopeSuite) {
8233
- if (payloadSuite !== nominalPayloadSuite) {
8234
- throw new Error(`unsupported E2E payload suite ${payloadSuite}`);
8424
+ function inferRecipientSuite(recipients) {
8425
+ if (recipients.length === 0) {
8426
+ throw new Error(
8427
+ "E2E client payload crypto requires at least one recipient"
8428
+ );
8429
+ }
8430
+ const suites = recipients.map(
8431
+ (recipient) => recipient.keyEnvelopeSuite ?? inferKeyEnvelopeSuite(cloneKeyMaterial(recipient.publicKey))
8432
+ );
8433
+ const suite = suites[0];
8434
+ if (suite === void 0 || suites.some((candidate) => candidate !== suite)) {
8435
+ throw new Error("E2E recipients must use the same key envelope suite");
8436
+ }
8437
+ return suite;
8438
+ }
8439
+ function inferKeyEnvelopeSuite(publicKey) {
8440
+ if (publicKey.byteLength === x25519PublicKeySize) {
8441
+ return nominalKeyEnvelopeSuite;
8235
8442
  }
8236
- if (keyEnvelopeSuite !== nominalKeyEnvelopeSuite) {
8237
- throw new Error(`unsupported E2E key envelope suite ${keyEnvelopeSuite}`);
8443
+ if (publicKey.byteLength === p256PublicKeySize && publicKey[0] === 4) {
8444
+ return webTTYFIPSCompatibleKeyEnvelopeSuite;
8445
+ }
8446
+ throw new Error(
8447
+ `unsupported E2E recipient public key length ${publicKey.byteLength}`
8448
+ );
8449
+ }
8450
+ function payloadSuiteForKeyEnvelopeSuite(suite) {
8451
+ switch (suite) {
8452
+ case nominalKeyEnvelopeSuite:
8453
+ return nominalPayloadSuite;
8454
+ case webTTYFIPSCompatibleKeyEnvelopeSuite:
8455
+ return webTTYFIPSCompatiblePayloadSuite;
8456
+ default:
8457
+ throw new Error(`unsupported E2E key envelope suite ${suite}`);
8238
8458
  }
8239
- return { keyEnvelopeSuite, payloadSuite };
8459
+ }
8460
+ function publicKeySizeForSuite(suite) {
8461
+ switch (suite) {
8462
+ case nominalKeyEnvelopeSuite:
8463
+ return x25519PublicKeySize;
8464
+ case webTTYFIPSCompatibleKeyEnvelopeSuite:
8465
+ return p256PublicKeySize;
8466
+ default:
8467
+ throw new Error(`unsupported E2E key envelope suite ${suite}`);
8468
+ }
8469
+ }
8470
+ function validateSuites(payloadSuite, keyEnvelopeSuite) {
8471
+ if (payloadSuite === nominalPayloadSuite && keyEnvelopeSuite === nominalKeyEnvelopeSuite || payloadSuite === webTTYFIPSCompatiblePayloadSuite && keyEnvelopeSuite === webTTYFIPSCompatibleKeyEnvelopeSuite) {
8472
+ return { keyEnvelopeSuite, payloadSuite };
8473
+ }
8474
+ throw new Error(
8475
+ `unsupported E2E suite pair ${payloadSuite}/${keyEnvelopeSuite}`
8476
+ );
8240
8477
  }
8241
8478
  function hpkeInfo(payloadSuite, payloadKeyId, keyContext, suite) {
8242
8479
  return concat2(
@@ -8271,11 +8508,13 @@ function payloadAAD(stream, suite, payloadKeyId, keyContext, nonce, plaintextLen
8271
8508
  function payloadSuiteCode2(suite) {
8272
8509
  if (suite === "aes-256-gcm") return 1;
8273
8510
  if (suite === "chacha20-poly1305") return 2;
8511
+ if (suite === "aes-256-gcm-random-nonce") return 3;
8274
8512
  return unsupportedPayloadSuite(suite);
8275
8513
  }
8276
8514
  function keyEnvelopeSuiteCode2(suite) {
8277
8515
  if (suite === "hpke-x25519-hkdf-sha256-aes-256-gcm") return 1;
8278
8516
  if (suite === "hpke-x25519-hkdf-sha256-chacha20-poly1305") return 2;
8517
+ if (suite === "p256-hkdf-sha256-aes-256-gcm-random-nonce") return 3;
8279
8518
  return unsupportedKeyEnvelopeSuite(suite);
8280
8519
  }
8281
8520
  function unsupportedPayloadSuite(suite) {
@@ -8351,10 +8590,12 @@ function nonEmptyString(value, label) {
8351
8590
  return void 0;
8352
8591
  }
8353
8592
  function normalizeIdentity(identity) {
8593
+ const publicKey = cloneKeyMaterial(identity.publicKey);
8354
8594
  return {
8595
+ keyEnvelopeSuite: identity.keyEnvelopeSuite ?? inferKeyEnvelopeSuite(publicKey),
8355
8596
  keyId: cloneKeyMaterial(identity.keyId),
8356
8597
  privateKey: cloneKeyMaterial(identity.privateKey),
8357
- publicKey: cloneKeyMaterial(identity.publicKey)
8598
+ publicKey
8358
8599
  };
8359
8600
  }
8360
8601
  function bufferSource(value) {
@@ -8408,9 +8649,10 @@ function getSubtle() {
8408
8649
  }
8409
8650
  return subtle;
8410
8651
  }
8411
- function isX25519KeyPair(value) {
8652
+ function isCryptoKeyPair(value) {
8412
8653
  return "privateKey" in value && "publicKey" in value;
8413
8654
  }
8655
+ var isX25519KeyPair = isCryptoKeyPair;
8414
8656
  function base64URLEncode(value) {
8415
8657
  const binary = String.fromCharCode(...value);
8416
8658
  return btoa(binary).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, "");
@@ -8428,6 +8670,74 @@ function base64URLDecode(value) {
8428
8670
  return out;
8429
8671
  }
8430
8672
 
8673
+ // src/transport-frames.ts
8674
+ var WebTTYFrameDecoder = class {
8675
+ constructor(maxMessageSize) {
8676
+ this.maxMessageSize = maxMessageSize;
8677
+ }
8678
+ maxMessageSize;
8679
+ header = new Uint8Array(4);
8680
+ headerBytes = 0;
8681
+ payload = null;
8682
+ payloadBytes = 0;
8683
+ get incomplete() {
8684
+ return this.headerBytes !== 0 || this.payload !== null;
8685
+ }
8686
+ reset() {
8687
+ this.headerBytes = 0;
8688
+ this.payload = null;
8689
+ this.payloadBytes = 0;
8690
+ }
8691
+ *push(chunk) {
8692
+ const cursor = { offset: 0 };
8693
+ while (cursor.offset < chunk.byteLength) {
8694
+ if (this.payload === null) {
8695
+ const count2 = Math.min(
8696
+ 4 - this.headerBytes,
8697
+ chunk.byteLength - cursor.offset
8698
+ );
8699
+ this.header.set(
8700
+ chunk.subarray(cursor.offset, cursor.offset + count2),
8701
+ this.headerBytes
8702
+ );
8703
+ this.headerBytes += count2;
8704
+ cursor.offset += count2;
8705
+ if (this.headerBytes !== 4) return;
8706
+ const size = new DataView(this.header.buffer).getUint32(0, false);
8707
+ if (size > this.maxMessageSize)
8708
+ throw new Error(
8709
+ `WebTTY message exceeds the ${this.maxMessageSize} byte limit.`
8710
+ );
8711
+ this.headerBytes = 0;
8712
+ if (chunk.byteLength - cursor.offset >= size) {
8713
+ const payload = chunk.subarray(cursor.offset, cursor.offset + size);
8714
+ cursor.offset += size;
8715
+ yield payload;
8716
+ continue;
8717
+ }
8718
+ this.payload = new Uint8Array(size);
8719
+ this.payloadBytes = 0;
8720
+ }
8721
+ const count = Math.min(
8722
+ this.payload.byteLength - this.payloadBytes,
8723
+ chunk.byteLength - cursor.offset
8724
+ );
8725
+ this.payload.set(
8726
+ chunk.subarray(cursor.offset, cursor.offset + count),
8727
+ this.payloadBytes
8728
+ );
8729
+ this.payloadBytes += count;
8730
+ cursor.offset += count;
8731
+ if (this.payloadBytes === this.payload.byteLength) {
8732
+ const payload = this.payload;
8733
+ this.payload = null;
8734
+ this.payloadBytes = 0;
8735
+ yield payload;
8736
+ }
8737
+ }
8738
+ }
8739
+ };
8740
+
8431
8741
  // src/webtty.ts
8432
8742
  function getErrorMessage(error) {
8433
8743
  return error instanceof Error ? error.message : String(error);
@@ -8475,6 +8785,8 @@ function payloadCipherSuiteToProto(suite) {
8475
8785
  return rstream.webtty.protobuf.PayloadCipherSuite.PAYLOAD_CIPHER_SUITE_AES_256_GCM;
8476
8786
  case "chacha20-poly1305":
8477
8787
  return rstream.webtty.protobuf.PayloadCipherSuite.PAYLOAD_CIPHER_SUITE_CHACHA20_POLY1305;
8788
+ case "aes-256-gcm-random-nonce":
8789
+ return rstream.webtty.protobuf.PayloadCipherSuite.PAYLOAD_CIPHER_SUITE_AES_256_GCM_RANDOM_NONCE;
8478
8790
  default:
8479
8791
  return rstream.webtty.protobuf.PayloadCipherSuite.PAYLOAD_CIPHER_SUITE_UNSPECIFIED;
8480
8792
  }
@@ -8485,6 +8797,8 @@ function payloadCipherSuiteFromProto(suite) {
8485
8797
  return "aes-256-gcm";
8486
8798
  case rstream.webtty.protobuf.PayloadCipherSuite.PAYLOAD_CIPHER_SUITE_CHACHA20_POLY1305:
8487
8799
  return "chacha20-poly1305";
8800
+ case rstream.webtty.protobuf.PayloadCipherSuite.PAYLOAD_CIPHER_SUITE_AES_256_GCM_RANDOM_NONCE:
8801
+ return "aes-256-gcm-random-nonce";
8488
8802
  default:
8489
8803
  return void 0;
8490
8804
  }
@@ -8495,6 +8809,8 @@ function keyEnvelopeSuiteToProto(suite) {
8495
8809
  return rstream.webtty.protobuf.KeyEnvelopeSuite.KEY_ENVELOPE_SUITE_HPKE_X25519_HKDF_SHA256_AES_256_GCM;
8496
8810
  case "hpke-x25519-hkdf-sha256-chacha20-poly1305":
8497
8811
  return rstream.webtty.protobuf.KeyEnvelopeSuite.KEY_ENVELOPE_SUITE_HPKE_X25519_HKDF_SHA256_CHACHA20_POLY1305;
8812
+ case "p256-hkdf-sha256-aes-256-gcm-random-nonce":
8813
+ return rstream.webtty.protobuf.KeyEnvelopeSuite.KEY_ENVELOPE_SUITE_P256_HKDF_SHA256_AES_256_GCM_RANDOM_NONCE;
8498
8814
  default:
8499
8815
  return rstream.webtty.protobuf.KeyEnvelopeSuite.KEY_ENVELOPE_SUITE_UNSPECIFIED;
8500
8816
  }
@@ -8505,10 +8821,72 @@ function keyEnvelopeSuiteFromProto(suite) {
8505
8821
  return "hpke-x25519-hkdf-sha256-aes-256-gcm";
8506
8822
  case rstream.webtty.protobuf.KeyEnvelopeSuite.KEY_ENVELOPE_SUITE_HPKE_X25519_HKDF_SHA256_CHACHA20_POLY1305:
8507
8823
  return "hpke-x25519-hkdf-sha256-chacha20-poly1305";
8824
+ case rstream.webtty.protobuf.KeyEnvelopeSuite.KEY_ENVELOPE_SUITE_P256_HKDF_SHA256_AES_256_GCM_RANDOM_NONCE:
8825
+ return "p256-hkdf-sha256-aes-256-gcm-random-nonce";
8508
8826
  default:
8509
8827
  return void 0;
8510
8828
  }
8511
8829
  }
8830
+ var defaultE2EPayloadSuite = "aes-256-gcm";
8831
+ var defaultE2EKeyEnvelopeSuite = "hpke-x25519-hkdf-sha256-aes-256-gcm";
8832
+ var fipsCompatibleE2EPayloadSuite = "aes-256-gcm-random-nonce";
8833
+ var fipsCompatibleE2EKeyEnvelopeSuite = "p256-hkdf-sha256-aes-256-gcm-random-nonce";
8834
+ function payloadSuiteForKeyEnvelopeSuite2(suite) {
8835
+ switch (suite) {
8836
+ case defaultE2EKeyEnvelopeSuite:
8837
+ return defaultE2EPayloadSuite;
8838
+ case fipsCompatibleE2EKeyEnvelopeSuite:
8839
+ return fipsCompatibleE2EPayloadSuite;
8840
+ default:
8841
+ throw new Error(`Unsupported WebTTY E2E key envelope suite ${suite}.`);
8842
+ }
8843
+ }
8844
+ function asE2EKeyEnvelopeSuite(suite) {
8845
+ if (suite === defaultE2EKeyEnvelopeSuite || suite === fipsCompatibleE2EKeyEnvelopeSuite) {
8846
+ return suite;
8847
+ }
8848
+ throw new Error(`Unsupported WebTTY E2E key envelope suite ${suite}.`);
8849
+ }
8850
+ function inferE2EKeyEnvelopeSuite(publicKey) {
8851
+ if (publicKey?.byteLength === 32) return defaultE2EKeyEnvelopeSuite;
8852
+ if (publicKey?.byteLength === 65 && publicKey[0] === 4) {
8853
+ return fipsCompatibleE2EKeyEnvelopeSuite;
8854
+ }
8855
+ return void 0;
8856
+ }
8857
+ function proofSuitesFromGrant(grant) {
8858
+ const rawKeyEnvelopeSuite = keyEnvelopeSuiteFromProto(
8859
+ grant?.keyEnvelopeSuite
8860
+ );
8861
+ const payloadSuite = payloadCipherSuiteFromProto(grant?.payloadSuite);
8862
+ if (rawKeyEnvelopeSuite === void 0 && payloadSuite === void 0) {
8863
+ return {
8864
+ keyEnvelopeSuite: defaultE2EKeyEnvelopeSuite,
8865
+ payloadSuite: defaultE2EPayloadSuite
8866
+ };
8867
+ }
8868
+ if (rawKeyEnvelopeSuite === void 0 || payloadSuite === void 0) {
8869
+ throw new Error("WebTTY session key grant uses an unsupported suite pair.");
8870
+ }
8871
+ const keyEnvelopeSuite = asE2EKeyEnvelopeSuite(rawKeyEnvelopeSuite);
8872
+ const expectedPayloadSuite = payloadSuiteForKeyEnvelopeSuite2(keyEnvelopeSuite);
8873
+ if (expectedPayloadSuite !== payloadSuite) {
8874
+ throw new Error("WebTTY session key grant uses an unsupported suite pair.");
8875
+ }
8876
+ return { keyEnvelopeSuite, payloadSuite: expectedPayloadSuite };
8877
+ }
8878
+ function proofSuitesFromClientConfig(config) {
8879
+ const configured = config.endpointIdentity?.keyEnvelopeSuite;
8880
+ const expected = config.expectedServerIdentity;
8881
+ const expectedSuite = expected?.keyEnvelopeSuite ?? inferE2EKeyEnvelopeSuite(expected?.encryptionPublicKey);
8882
+ const keyEnvelopeSuite = asE2EKeyEnvelopeSuite(
8883
+ configured ?? expectedSuite ?? defaultE2EKeyEnvelopeSuite
8884
+ );
8885
+ return {
8886
+ keyEnvelopeSuite,
8887
+ payloadSuite: payloadSuiteForKeyEnvelopeSuite2(keyEnvelopeSuite)
8888
+ };
8889
+ }
8512
8890
  function signatureSuiteFromProto(suite) {
8513
8891
  switch (suite) {
8514
8892
  case rstream.webtty.protobuf.SignatureSuite.SIGNATURE_SUITE_ECDSA_P256_SHA256:
@@ -8749,12 +9127,15 @@ function resolveWebTransportConstructor() {
8749
9127
  function webTransportGlobal(value) {
8750
9128
  return "WebTransport" in value;
8751
9129
  }
9130
+ function browserWebSocket(url) {
9131
+ const socket = new WebSocket(url);
9132
+ socket.binaryType = "arraybuffer";
9133
+ return socket;
9134
+ }
8752
9135
  var WebSocketMessageConnection = class {
8753
- ws;
8754
- handlers;
8755
- constructor(url, handlers) {
8756
- this.ws = new WebSocket(url);
8757
- this.ws.binaryType = "arraybuffer";
9136
+ constructor(url, handlers, maxBufferedBytes, factory, maxMessageSize) {
9137
+ this.maxBufferedBytes = maxBufferedBytes;
9138
+ this.ws = factory ? factory(url, { maxMessageSize }) : browserWebSocket(url);
8758
9139
  this.handlers = {
8759
9140
  close: handlers.close,
8760
9141
  error: handlers.error,
@@ -8766,7 +9147,13 @@ var WebSocketMessageConnection = class {
8766
9147
  this.ws.addEventListener("error", this.handlers.error);
8767
9148
  this.ws.addEventListener("close", this.handlers.close);
8768
9149
  }
9150
+ maxBufferedBytes;
9151
+ ws;
9152
+ handlers;
8769
9153
  send(payload) {
9154
+ if (this.ws.bufferedAmount + payload.byteLength > this.maxBufferedBytes) {
9155
+ throw new Error("WebSocket write buffer limit exceeded.");
9156
+ }
8770
9157
  this.ws.send(getWebSocketPayload(payload));
8771
9158
  }
8772
9159
  close() {
@@ -8778,56 +9165,109 @@ var WebSocketMessageConnection = class {
8778
9165
  }
8779
9166
  };
8780
9167
  var WebTransportMessageConnection = class _WebTransportMessageConnection {
8781
- constructor(transport, stream, writer, handlers) {
9168
+ constructor(transport, stream, writer, maxMessageSize, handlers) {
8782
9169
  this.transport = transport;
8783
- this.stream = stream;
8784
9170
  this.writer = writer;
9171
+ this.maxMessageSize = maxMessageSize;
8785
9172
  this.handlers = handlers;
9173
+ this.decoder = new WebTTYFrameDecoder(maxMessageSize);
9174
+ this.reader = stream.readable.getReader();
8786
9175
  }
8787
9176
  transport;
8788
- stream;
8789
9177
  writer;
9178
+ maxMessageSize;
8790
9179
  handlers;
8791
9180
  closed = false;
8792
- readBuffer = new Uint8Array();
8793
- writeQueue = Promise.resolve();
8794
- static async open(url, options, handlers) {
9181
+ decoder;
9182
+ reader;
9183
+ writeQueue = [];
9184
+ writeHead = 0;
9185
+ bufferedBytes = 0;
9186
+ writing = false;
9187
+ static async open(url, options, signal, maxMessageSize, handlers) {
9188
+ signal.throwIfAborted();
8795
9189
  const Transport = resolveWebTransportConstructor();
8796
9190
  const transport = new Transport(url, options);
8797
- await transport.ready;
8798
- const stream = await transport.createBidirectionalStream();
8799
- const writer = stream.writable.getWriter();
8800
- const connection = new _WebTransportMessageConnection(
8801
- transport,
8802
- stream,
8803
- writer,
8804
- handlers
8805
- );
8806
- connection.startReadLoop();
8807
9191
  transport.closed.catch((error) => {
8808
- if (!connection.closed) {
9192
+ if (!signal.aborted) {
8809
9193
  handlers.error(`WebTransport closed: ${getErrorMessage(error)}`);
8810
9194
  }
8811
9195
  });
8812
- return connection;
9196
+ try {
9197
+ await waitForWebTransportOpen(transport.ready, signal);
9198
+ signal.throwIfAborted();
9199
+ const stream = await waitForWebTransportOpen(
9200
+ transport.createBidirectionalStream(),
9201
+ signal
9202
+ );
9203
+ signal.throwIfAborted();
9204
+ const writer = stream.writable.getWriter();
9205
+ const connection = new _WebTransportMessageConnection(
9206
+ transport,
9207
+ stream,
9208
+ writer,
9209
+ maxMessageSize,
9210
+ handlers
9211
+ );
9212
+ connection.startReadLoop();
9213
+ return connection;
9214
+ } catch (error) {
9215
+ transport.close({ closeCode: 0, reason: "open failed" });
9216
+ throw error;
9217
+ }
8813
9218
  }
8814
9219
  send(payload) {
8815
9220
  if (this.closed) return;
9221
+ if (payload.byteLength > this.maxMessageSize) {
9222
+ this.handlers.error(
9223
+ `WebTTY message exceeds the ${this.maxMessageSize} byte limit.`
9224
+ );
9225
+ return;
9226
+ }
9227
+ if (this.bufferedBytes + payload.byteLength + 4 > this.maxMessageSize * 4 || this.writeQueue.length - this.writeHead >= 1024) {
9228
+ this.handlers.error("WebTransport write buffer limit exceeded.");
9229
+ return;
9230
+ }
8816
9231
  const frame = getFramePayload(payload);
8817
- this.writeQueue = this.writeQueue.then(() => this.writer.write(frame)).catch((error) => {
8818
- if (!this.closed) {
8819
- this.handlers.error(
8820
- `WebTransport write failed: ${getErrorMessage(error)}`
8821
- );
8822
- }
8823
- });
9232
+ this.writeQueue.push(frame);
9233
+ this.bufferedBytes += frame.byteLength;
9234
+ if (!this.writing) {
9235
+ this.writing = true;
9236
+ void this.writeLoop();
9237
+ }
8824
9238
  }
8825
9239
  close() {
8826
9240
  if (this.closed) return;
8827
9241
  this.closed = true;
8828
- this.writer.releaseLock();
9242
+ this.writeQueue = [];
9243
+ this.writeHead = 0;
9244
+ this.decoder.reset();
9245
+ void this.reader.cancel().catch(() => void 0).finally(() => this.reader.releaseLock());
9246
+ void this.writer.abort().catch(() => void 0).finally(() => this.writer.releaseLock());
8829
9247
  this.transport.close({ closeCode: 0, reason: "closed" });
8830
9248
  }
9249
+ async writeLoop() {
9250
+ try {
9251
+ while (!this.closed && this.writeHead < this.writeQueue.length) {
9252
+ const frame = this.writeQueue[this.writeHead];
9253
+ this.writeQueue[this.writeHead++] = void 0;
9254
+ if (this.writeHead === this.writeQueue.length || this.writeHead >= 512) {
9255
+ this.writeQueue = this.writeQueue.slice(this.writeHead);
9256
+ this.writeHead = 0;
9257
+ }
9258
+ if (frame === void 0) continue;
9259
+ await this.writer.write(frame);
9260
+ this.bufferedBytes -= frame.byteLength;
9261
+ }
9262
+ } catch (error) {
9263
+ if (!this.closed)
9264
+ this.handlers.error(
9265
+ `WebTransport write failed: ${getErrorMessage(error)}`
9266
+ );
9267
+ } finally {
9268
+ this.writing = false;
9269
+ }
9270
+ }
8831
9271
  startReadLoop() {
8832
9272
  void this.readLoop().catch((error) => {
8833
9273
  if (!this.closed) {
@@ -8838,41 +9278,46 @@ var WebTransportMessageConnection = class _WebTransportMessageConnection {
8838
9278
  });
8839
9279
  }
8840
9280
  async readLoop() {
8841
- const reader = this.stream.readable.getReader();
8842
9281
  try {
8843
9282
  for (; ; ) {
8844
- const result = await reader.read();
9283
+ const result = await this.reader.read();
9284
+ if (this.closed) return;
8845
9285
  if (result.done) {
8846
- if (!this.closed) this.handlers.close();
9286
+ if (this.decoder.incomplete)
9287
+ throw new Error("Incomplete WebTTY frame at end of stream.");
9288
+ this.handlers.close();
8847
9289
  return;
8848
9290
  }
8849
- this.appendReadChunk(result.value);
9291
+ for (const payload of this.decoder.push(result.value)) {
9292
+ if (this.closed) return;
9293
+ await this.handlers.message(payload);
9294
+ if (this.closed) return;
9295
+ }
8850
9296
  }
8851
9297
  } finally {
8852
- reader.releaseLock();
8853
- }
8854
- }
8855
- appendReadChunk(chunk) {
8856
- const next = new Uint8Array(this.readBuffer.byteLength + chunk.byteLength);
8857
- next.set(this.readBuffer);
8858
- next.set(chunk, this.readBuffer.byteLength);
8859
- this.readBuffer = next;
8860
- for (; ; ) {
8861
- if (this.readBuffer.byteLength < 4) return;
8862
- const view = new DataView(
8863
- this.readBuffer.buffer,
8864
- this.readBuffer.byteOffset,
8865
- this.readBuffer.byteLength
8866
- );
8867
- const size = view.getUint32(0, false);
8868
- if (this.readBuffer.byteLength < 4 + size) return;
8869
- const payload = this.readBuffer.slice(4, 4 + size);
8870
- this.readBuffer = this.readBuffer.slice(4 + size);
8871
- this.handlers.message(payload);
9298
+ this.reader.releaseLock();
8872
9299
  }
8873
9300
  }
8874
9301
  };
9302
+ function waitForWebTransportOpen(pending, signal) {
9303
+ return new Promise((resolve, reject) => {
9304
+ const abort = () => reject(new Error("WebTransport connection cancelled."));
9305
+ signal.addEventListener("abort", abort, { once: true });
9306
+ if (signal.aborted) abort();
9307
+ pending.then(
9308
+ (value) => {
9309
+ signal.removeEventListener("abort", abort);
9310
+ resolve(value);
9311
+ },
9312
+ (error) => {
9313
+ signal.removeEventListener("abort", abort);
9314
+ reject(error);
9315
+ }
9316
+ );
9317
+ });
9318
+ }
8875
9319
  var WebTTY = class {
9320
+ connectionAbort = new AbortController();
8876
9321
  connection = null;
8877
9322
  connectionState = "preparing";
8878
9323
  heartbeatTimer = null;
@@ -8880,6 +9325,11 @@ var WebTTY = class {
8880
9325
  execConfig;
8881
9326
  events;
8882
9327
  receiveQueue = null;
9328
+ receivedBytes = 0;
9329
+ receivedMessages = 0;
9330
+ stdinClosed = false;
9331
+ stderrClosed = false;
9332
+ stdoutClosed = false;
8883
9333
  /**
8884
9334
  * Creates a new WebTTY instance.
8885
9335
  *
@@ -8888,6 +9338,12 @@ var WebTTY = class {
8888
9338
  * @param events - Event callbacks for the session.
8889
9339
  */
8890
9340
  constructor(clientConfig2, execConfig, events) {
9341
+ const maxMessageSize = clientConfig2.maxMessageSize ?? 1024 * 1024;
9342
+ if (!Number.isSafeInteger(maxMessageSize) || maxMessageSize < 1 || maxMessageSize > 4294967295) {
9343
+ throw new Error(
9344
+ "WebTTY maxMessageSize must be a positive 32-bit integer."
9345
+ );
9346
+ }
8891
9347
  const transport = resolveWebTTYClientTransport(
8892
9348
  clientConfig2.url,
8893
9349
  clientConfig2.transport
@@ -8911,9 +9367,11 @@ var WebTTY = class {
8911
9367
  endpointIdentity: clientConfig2.endpointIdentity,
8912
9368
  expectedServerIdentity: clientConfig2.expectedServerIdentity,
8913
9369
  heartbeatIntervalMs: clientConfig2.heartbeatIntervalMs ?? 5e3,
9370
+ maxMessageSize,
8914
9371
  sendHeartbeat: clientConfig2.sendHeartbeat ?? true,
8915
9372
  transport,
8916
9373
  url: clientConfig2.url,
9374
+ webSocketFactory: clientConfig2.webSocketFactory,
8917
9375
  webTransportOptions: clientConfig2.webTransportOptions
8918
9376
  };
8919
9377
  this.execConfig = {
@@ -8942,12 +9400,18 @@ var WebTTY = class {
8942
9400
  return;
8943
9401
  }
8944
9402
  const wsUrl = normalizeWebSocketURL(this.clientConfig.url);
8945
- this.connection = new WebSocketMessageConnection(wsUrl, {
8946
- close: this.handleClose,
8947
- error: this.handleError,
8948
- message: this.handleConnectionMessage,
8949
- open: this.handleOpen
8950
- });
9403
+ this.connection = new WebSocketMessageConnection(
9404
+ wsUrl,
9405
+ {
9406
+ close: this.handleClose,
9407
+ error: this.handleError,
9408
+ message: this.handleConnectionMessage,
9409
+ open: this.handleOpen
9410
+ },
9411
+ this.clientConfig.maxMessageSize * 4,
9412
+ this.clientConfig.webSocketFactory,
9413
+ this.clientConfig.maxMessageSize
9414
+ );
8951
9415
  }
8952
9416
  /**
8953
9417
  * Sends data to the remote server's STDIN.
@@ -8985,6 +9449,7 @@ var WebTTY = class {
8985
9449
  return;
8986
9450
  }
8987
9451
  const encrypted = await encrypt(data);
9452
+ this.assertCanWriteStdin();
8988
9453
  this.sendStdinPayload({
8989
9454
  encryptedData: encryptedPayloadToProto(encrypted)
8990
9455
  });
@@ -8996,6 +9461,9 @@ var WebTTY = class {
8996
9461
  if (this.execConfig.interactive === false) {
8997
9462
  throw new Error("STDIN is unavailable in non-interactive mode.");
8998
9463
  }
9464
+ if (this.stdinClosed) {
9465
+ throw new Error("WebTTY STDIN is already closed.");
9466
+ }
8999
9467
  }
9000
9468
  sendStdinPayload(payload) {
9001
9469
  this.send(
@@ -9017,6 +9485,8 @@ var WebTTY = class {
9017
9485
  if (this.execConfig.interactive === false) {
9018
9486
  throw new Error("STDIN is unavailable in non-interactive mode.");
9019
9487
  }
9488
+ if (this.stdinClosed) return;
9489
+ this.stdinClosed = true;
9020
9490
  this.send(
9021
9491
  new rstream.webtty.protobuf.Message({
9022
9492
  data: new rstream.webtty.protobuf.Data({
@@ -9189,6 +9659,16 @@ var WebTTY = class {
9189
9659
  if (!bytesEqual2(actual.signingKeyId, expected.signingKeyId) || !bytesEqual2(actual.signingPublicKey, expected.signingPublicKey) || !bytesEqual2(actual.encryptionKeyId, expected.encryptionKeyId) || !bytesEqual2(actual.encryptionPublicKey, expected.encryptionPublicKey)) {
9190
9660
  return false;
9191
9661
  }
9662
+ const expectedKeyEnvelopeSuite = expected.keyEnvelopeSuite ?? inferE2EKeyEnvelopeSuite(expected.encryptionPublicKey) ?? defaultE2EKeyEnvelopeSuite;
9663
+ const advertisedKeyEnvelopeSuites = (serverHello.keyEnvelopeSuites ?? []).map(keyEnvelopeSuiteFromProto).filter((value) => value !== void 0);
9664
+ const advertisedPayloadSuites = (serverHello.payloadSuites ?? []).map(payloadCipherSuiteFromProto).filter(
9665
+ (value) => value !== void 0
9666
+ );
9667
+ if (!advertisedKeyEnvelopeSuites.includes(expectedKeyEnvelopeSuite) || !advertisedPayloadSuites.includes(
9668
+ payloadSuiteForKeyEnvelopeSuite2(expectedKeyEnvelopeSuite)
9669
+ )) {
9670
+ return false;
9671
+ }
9192
9672
  const transcript = {
9193
9673
  authRequirement: authRequirementFromProto(serverHello.authRequirement),
9194
9674
  keyEnvelopeSuites: (serverHello.keyEnvelopeSuites ?? []).map(keyEnvelopeSuiteFromProto).filter(
@@ -9243,6 +9723,7 @@ var WebTTY = class {
9243
9723
  }
9244
9724
  const clientPrincipalId = trimOptional(this.clientConfig.clientPrincipalId);
9245
9725
  const clientCredential = this.clientConfig.clientCredential;
9726
+ const proofSuites = proofSuitesFromGrant(open.sessionKeyGrant);
9246
9727
  const transcript = {
9247
9728
  authRequirement: "client-proof",
9248
9729
  clientCredentialHash: await hashWebTTYClientCredential(clientCredential),
@@ -9251,8 +9732,8 @@ var WebTTY = class {
9251
9732
  commandConfigHash,
9252
9733
  expiresAt: expiresAt.toISOString().replace(".000Z", "Z"),
9253
9734
  issuedAt: issuedAt.toISOString().replace(".000Z", "Z"),
9254
- keyEnvelopeSuite: "hpke-x25519-hkdf-sha256-aes-256-gcm",
9255
- payloadSuite: "aes-256-gcm",
9735
+ keyEnvelopeSuite: proofSuites.keyEnvelopeSuite,
9736
+ payloadSuite: proofSuites.payloadSuite,
9256
9737
  projectId: optionalString(serverHello.projectId),
9257
9738
  protocolVersion: "webtty-1",
9258
9739
  serverEncryptionKeyId: optionalBytes(serverIdentity.encryptionKeyId),
@@ -9301,6 +9782,7 @@ var WebTTY = class {
9301
9782
  issuedAt.setMilliseconds(0);
9302
9783
  const expiresAt = new Date(issuedAt.getTime() + 3e4);
9303
9784
  const clientPrincipalId = trimOptional(this.clientConfig.clientPrincipalId);
9785
+ const proofSuites = proofSuitesFromClientConfig(this.clientConfig);
9304
9786
  const transcript = {
9305
9787
  attachGrantHash: await hashWebTTYAttachGrant(attach.attachGrant),
9306
9788
  authRequirement: "client-proof",
@@ -9309,8 +9791,8 @@ var WebTTY = class {
9309
9791
  clientSigningKeyId: signing.keyId,
9310
9792
  expiresAt: expiresAt.toISOString().replace(".000Z", "Z"),
9311
9793
  issuedAt: issuedAt.toISOString().replace(".000Z", "Z"),
9312
- keyEnvelopeSuite: "hpke-x25519-hkdf-sha256-aes-256-gcm",
9313
- payloadSuite: "aes-256-gcm",
9794
+ keyEnvelopeSuite: proofSuites.keyEnvelopeSuite,
9795
+ payloadSuite: proofSuites.payloadSuite,
9314
9796
  projectId: attachConfig.projectId,
9315
9797
  protocolVersion: "webtty-1",
9316
9798
  requestedRole: attachRoleTranscriptValue(attach.requestedRole),
@@ -9342,6 +9824,8 @@ var WebTTY = class {
9342
9824
  const connection = await WebTransportMessageConnection.open(
9343
9825
  url,
9344
9826
  this.clientConfig.webTransportOptions,
9827
+ this.connectionAbort.signal,
9828
+ this.clientConfig.maxMessageSize,
9345
9829
  {
9346
9830
  close: this.handleClose,
9347
9831
  error: this.handleTransportError,
@@ -9359,16 +9843,46 @@ var WebTTY = class {
9359
9843
  }
9360
9844
  }
9361
9845
  handleConnectionMessage = (data) => {
9362
- const run = () => this.processMessage(data);
9846
+ if (this.connectionState === "closed") return;
9847
+ const payload = this.boundedMessagePayload(data);
9848
+ if (payload === null) return;
9849
+ this.receivedBytes += payload.byteLength;
9850
+ this.receivedMessages += 1;
9851
+ const run = () => this.processMessage(payload);
9852
+ const release = () => {
9853
+ this.receivedBytes -= payload.byteLength;
9854
+ this.receivedMessages -= 1;
9855
+ };
9363
9856
  if (this.receiveQueue) {
9364
- this.trackReceiveQueue(this.receiveQueue.then(run, run));
9365
- return;
9857
+ return this.trackReceiveQueue(
9858
+ this.receiveQueue.then(run, run).finally(release)
9859
+ );
9366
9860
  }
9367
9861
  const result = run();
9368
9862
  if (isPromiseLike(result)) {
9369
- this.trackReceiveQueue(result);
9863
+ return this.trackReceiveQueue(result.finally(release));
9370
9864
  }
9865
+ release();
9371
9866
  };
9867
+ boundedMessagePayload(data) {
9868
+ try {
9869
+ const payload = messagePayloadBytes(data);
9870
+ if (payload.byteLength > this.clientConfig.maxMessageSize) {
9871
+ this.close(
9872
+ `WebTTY message exceeds the ${this.clientConfig.maxMessageSize} byte limit.`
9873
+ );
9874
+ return null;
9875
+ }
9876
+ if (this.receivedBytes + payload.byteLength > this.clientConfig.maxMessageSize * 4 || this.receivedMessages >= 1024) {
9877
+ this.close("WebTTY receive buffer limit exceeded.");
9878
+ return null;
9879
+ }
9880
+ return payload;
9881
+ } catch (error) {
9882
+ this.close(`Failed to decode message: ${getErrorMessage(error)}`);
9883
+ return null;
9884
+ }
9885
+ }
9372
9886
  trackReceiveQueue(promise) {
9373
9887
  const queued = promise.catch((error) => {
9374
9888
  this.close(`Failed to decode message: ${getErrorMessage(error)}`);
@@ -9376,6 +9890,7 @@ var WebTTY = class {
9376
9890
  if (this.receiveQueue === queued) this.receiveQueue = null;
9377
9891
  });
9378
9892
  this.receiveQueue = queued;
9893
+ return queued;
9379
9894
  }
9380
9895
  processMessage(data) {
9381
9896
  if (!data) return;
@@ -9424,41 +9939,47 @@ var WebTTY = class {
9424
9939
  }
9425
9940
  }
9426
9941
  processDataMessage(data) {
9427
- if (data.type === rstream.webtty.protobuf.Data.Type.TYPE_STDOUT) {
9428
- if (data.data) {
9429
- this.events.onStdout?.(data.data);
9430
- }
9431
- if (data.encryptedData) {
9432
- const decrypted = this.decryptData("stdout", data.encryptedData);
9433
- if (isPromiseLike(decrypted)) {
9434
- return decrypted.then((chunk) => {
9435
- if (chunk !== null) this.events.onStdout?.(chunk);
9436
- });
9437
- }
9438
- if (decrypted === null) return;
9439
- this.events.onStdout?.(decrypted);
9440
- }
9441
- if (data.eos) {
9942
+ const stream = data.type === rstream.webtty.protobuf.Data.Type.TYPE_STDOUT ? "stdout" : data.type === rstream.webtty.protobuf.Data.Type.TYPE_STDERR ? "stderr" : null;
9943
+ if (stream === null) {
9944
+ this.close(`Unexpected WebTTY data stream type ${String(data.type)}.`);
9945
+ return;
9946
+ }
9947
+ const hasData = data.data !== void 0 && data.data !== null;
9948
+ const hasEncryptedData = data.encryptedData !== void 0 && data.encryptedData !== null;
9949
+ const hasEos = data.eos !== void 0 && data.eos !== null;
9950
+ if (Number(hasData) + Number(hasEncryptedData) + Number(hasEos) !== 1) {
9951
+ this.close(`Unexpected WebTTY ${stream} payload.`);
9952
+ return;
9953
+ }
9954
+ const streamClosed = stream === "stdout" ? this.stdoutClosed : this.stderrClosed;
9955
+ if (streamClosed) {
9956
+ this.close(
9957
+ hasEos ? `Duplicate WebTTY ${stream} end of stream.` : `WebTTY ${stream} data received after end of stream.`
9958
+ );
9959
+ return;
9960
+ }
9961
+ if (hasEos) {
9962
+ if (stream === "stdout") {
9963
+ this.stdoutClosed = true;
9442
9964
  this.events.onStdoutEos?.();
9443
- }
9444
- } else if (data.type === rstream.webtty.protobuf.Data.Type.TYPE_STDERR) {
9445
- if (data.data) {
9446
- this.events.onStderr?.(data.data);
9447
- }
9448
- if (data.encryptedData) {
9449
- const decrypted = this.decryptData("stderr", data.encryptedData);
9450
- if (isPromiseLike(decrypted)) {
9451
- return decrypted.then((chunk) => {
9452
- if (chunk !== null) this.events.onStderr?.(chunk);
9453
- });
9454
- }
9455
- if (decrypted === null) return;
9456
- this.events.onStderr?.(decrypted);
9457
- }
9458
- if (data.eos) {
9965
+ } else {
9966
+ this.stderrClosed = true;
9459
9967
  this.events.onStderrEos?.();
9460
9968
  }
9969
+ return;
9970
+ }
9971
+ const emit = stream === "stdout" ? this.events.onStdout : this.events.onStderr;
9972
+ if (hasData) {
9973
+ emit?.(data.data);
9974
+ return;
9461
9975
  }
9976
+ const decrypted = this.decryptData(stream, data.encryptedData);
9977
+ if (isPromiseLike(decrypted)) {
9978
+ return decrypted.then((chunk) => {
9979
+ if (chunk !== null && this.connectionState !== "closed") emit?.(chunk);
9980
+ });
9981
+ }
9982
+ if (decrypted !== null) emit?.(decrypted);
9462
9983
  }
9463
9984
  decryptData(stream, payload) {
9464
9985
  const decrypt = stream === "stdout" ? this.execConfig.payloadCrypto?.decryptStdout : this.execConfig.payloadCrypto?.decryptStderr;
@@ -9509,7 +10030,19 @@ var WebTTY = class {
9509
10030
  if (this.connectionState === "preparing" || this.connectionState === "closed")
9510
10031
  return;
9511
10032
  const buffer = rstream.webtty.protobuf.Message.encode(message).finish();
9512
- this.connection.send(buffer);
10033
+ if (buffer.byteLength > this.clientConfig.maxMessageSize) {
10034
+ this.close(
10035
+ `WebTTY message exceeds the ${this.clientConfig.maxMessageSize} byte limit.`
10036
+ );
10037
+ return;
10038
+ }
10039
+ try {
10040
+ this.connection.send(buffer);
10041
+ } catch (error) {
10042
+ this.close(
10043
+ `${this.clientConfig.transport} write failed: ${getErrorMessage(error)}`
10044
+ );
10045
+ }
9513
10046
  }
9514
10047
  /**
9515
10048
  * Closes the WebTTY session and fires exactly one of:
@@ -9522,6 +10055,7 @@ var WebTTY = class {
9522
10055
  return;
9523
10056
  }
9524
10057
  this.connectionState = "closed";
10058
+ this.connectionAbort.abort();
9525
10059
  if (this.heartbeatTimer) {
9526
10060
  clearInterval(this.heartbeatTimer);
9527
10061
  this.heartbeatTimer = null;
@@ -9999,393 +10533,20 @@ var WebTTYRemoteExecutor = class {
9999
10533
  };
10000
10534
 
10001
10535
  // src/filesystem.ts
10002
- var WebTTYFileSystemError = class extends Error {
10003
- operation;
10004
- status;
10536
+ var import_filesystem = require("@rstreamlabs/filesystem");
10537
+ var import_filesystem2 = require("@rstreamlabs/filesystem");
10538
+ var import_filesystem3 = require("@rstreamlabs/filesystem");
10539
+ var import_filesystem4 = require("@rstreamlabs/filesystem");
10540
+ var resolveWebTTYFileSystemURL = import_filesystem3.resolveFileSystemURL;
10541
+ var WebTTYFileSystemError = class extends import_filesystem2.FileSystemError {
10005
10542
  constructor(operation, status, message) {
10006
- super(`${operation} failed with status ${status}: ${message}`);
10543
+ super(operation, status, message);
10007
10544
  this.name = "WebTTYFileSystemError";
10008
- this.operation = operation;
10009
- this.status = status;
10010
10545
  }
10011
10546
  };
10012
- var webDAVPropfindBody = '<?xml version="1.0" encoding="utf-8"?><propfind xmlns="DAV:"><prop><resourcetype/><getcontentlength/><getlastmodified/></prop></propfind>';
10013
- function cleanTrailingSlashes2(value) {
10014
- return value.replace(/\/+$/, "");
10015
- }
10016
- function normalizeRemotePath(remotePath) {
10017
- const trimmed = remotePath.trim();
10018
- const absolute = trimmed === "" || trimmed === "." ? "/" : trimmed;
10019
- return new URL(
10020
- absolute.startsWith("/") ? absolute : `/${absolute}`,
10021
- "http://rstream.local"
10022
- ).pathname;
10023
- }
10024
- function comparableRemotePath(remotePath) {
10025
- const normalized = cleanTrailingSlashes2(normalizeRemotePath(remotePath));
10026
- return normalized === "" ? "/" : normalized;
10027
- }
10028
- function sidecarPath(fsPath) {
10029
- return normalizeRemotePath(fsPath ?? "/fs");
10030
- }
10031
- function filesystemBasePath(pathname, fsPath) {
10032
- const sidecar = sidecarPath(fsPath);
10033
- const basePath = cleanTrailingSlashes2(pathname);
10034
- if (basePath === "") return sidecar;
10035
- if (basePath === "/") return sidecar;
10036
- if (basePath === sidecar || basePath.startsWith(`${sidecar}/`))
10037
- return basePath;
10038
- return `${basePath}${sidecar}`;
10039
- }
10040
- function filesystemPath(pathname, remotePath, fsPath) {
10041
- const basePath = filesystemBasePath(pathname, fsPath);
10042
- const normalized = normalizeRemotePath(remotePath);
10043
- return normalized === "/" ? basePath : `${cleanTrailingSlashes2(basePath)}${normalized}`;
10044
- }
10045
- function resolveWebTTYFileSystemURL(input, remotePath = "/", fsPath) {
10046
- const url = new URL(input.toString());
10047
- if (url.protocol === "rstrm:") {
10048
- throw new Error(
10049
- "rstrm:// WebTTY filesystem URLs require the native rstream dialer."
10050
- );
10051
- }
10052
- if (url.protocol === "ws:") url.protocol = "http:";
10053
- if (url.protocol === "wss:") url.protocol = "https:";
10054
- if (url.protocol !== "http:" && url.protocol !== "https:") {
10055
- throw new Error(
10056
- `Unsupported WebTTY filesystem URL scheme "${url.protocol}".`
10057
- );
10058
- }
10059
- url.pathname = filesystemPath(url.pathname, remotePath, fsPath);
10060
- url.hash = "";
10061
- return url;
10062
- }
10063
- function responseAllowed(response, expectedStatuses) {
10064
- return expectedStatuses.includes(response.status);
10065
- }
10066
- async function responseErrorMessage(response) {
10067
- const text = (await response.text()).trim().slice(0, 4096);
10068
- return text === "" ? response.statusText : text;
10069
- }
10070
- async function requireResponseStatus(response, expectedStatuses, operation) {
10071
- if (responseAllowed(response, expectedStatuses)) return response;
10072
- throw new WebTTYFileSystemError(
10073
- operation,
10074
- response.status,
10075
- await responseErrorMessage(response)
10076
- );
10077
- }
10078
- function requireResponseBody(response, operation) {
10079
- if (response.body) return response.body;
10080
- throw new Error(
10081
- `${operation} failed because the response body is unavailable.`
10082
- );
10083
- }
10084
- function resolveFetch(config) {
10085
- if (config.fetch) return config.fetch;
10086
- if (typeof fetch === "undefined") {
10087
- throw new Error("fetch is unavailable in this runtime.");
10088
- }
10089
- return fetch;
10090
- }
10091
- function applyHeaders(target, source) {
10092
- const sourceHeaders = new Headers(source);
10093
- sourceHeaders.forEach((value, key) => target.set(key, value));
10094
- return target;
10095
- }
10096
- function requestHeaders(config, headers) {
10097
- const result = applyHeaders(new Headers(config.headers), headers);
10098
- if (config.authToken && config.authToken.trim() !== "") {
10099
- result.set("Authorization", `Bearer ${config.authToken.trim()}`);
10100
- }
10101
- return result;
10102
- }
10103
- function contentHeaders(contentType) {
10104
- return contentType === void 0 ? void 0 : { "Content-Type": contentType };
10105
- }
10106
- function deleteStatuses(force) {
10107
- return force ? [200, 204, 404] : [200, 204];
10108
- }
10109
- function isNotFound(error) {
10110
- return error instanceof WebTTYFileSystemError && error.status === 404;
10111
- }
10112
- function pathBaseName(path) {
10113
- const normalized = normalizeRemotePath(path);
10114
- const cleaned = cleanTrailingSlashes2(normalized);
10115
- return cleaned.slice(cleaned.lastIndexOf("/") + 1);
10116
- }
10117
- function parentPath(path) {
10118
- const normalized = cleanTrailingSlashes2(normalizeRemotePath(path));
10119
- const index = normalized.lastIndexOf("/");
10120
- if (index <= 0) return "/";
10121
- return normalized.slice(0, index);
10122
- }
10123
- function readFileEncoding(options) {
10124
- if (typeof options === "string") return options;
10125
- return options?.encoding === void 0 ? null : options.encoding;
10126
- }
10127
- function readFileSignal(options) {
10128
- return typeof options === "string" ? void 0 : options?.signal;
10129
- }
10130
- function textContentHeaders(contentType, data) {
10131
- if (contentType !== void 0) return { "Content-Type": contentType };
10132
- return typeof data === "string" ? { "Content-Type": "text/plain; charset=utf-8" } : void 0;
10133
- }
10134
- function bodyRequiresDuplex(body) {
10135
- return typeof ReadableStream !== "undefined" && body instanceof ReadableStream;
10136
- }
10137
- function requestInit(config, method, options) {
10138
- return {
10139
- body: options.body,
10140
- duplex: bodyRequiresDuplex(options.body) ? "half" : void 0,
10141
- headers: requestHeaders(config, options.headers),
10142
- method,
10143
- signal: options.signal
10144
- };
10145
- }
10146
- async function resolveURL2(url) {
10147
- return typeof url === "function" ? await url() : url;
10148
- }
10149
- function elementBodies(xml, name) {
10150
- return Array.from(
10151
- xml.matchAll(
10152
- new RegExp(
10153
- `<[^>]*:?${name}\\b[^>]*>([\\s\\S]*?)<\\/[^>]*:?${name}>`,
10154
- "gi"
10155
- )
10156
- ),
10157
- (match) => match[1] ?? ""
10158
- );
10159
- }
10160
- function hasElement(xml, name) {
10161
- return new RegExp(`<[^>]*:?${name}(\\s|/|>)`, "i").test(xml);
10162
- }
10163
- function stripTags(xml) {
10164
- return xml.replace(/<[^>]*>/g, "");
10165
- }
10166
- function decodeNumericEntity(value) {
10167
- const parsed = value.startsWith("&#x") ? Number.parseInt(value.slice(3, -1), 16) : Number.parseInt(value.slice(2, -1), 10);
10168
- return Number.isFinite(parsed) ? String.fromCodePoint(parsed) : value;
10169
- }
10170
- function decodeXmlText(value) {
10171
- 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, "&");
10172
- }
10173
- function elementText(xml, name) {
10174
- return decodeXmlText(stripTags(elementBodies(xml, name)[0] ?? "")).trim();
10175
- }
10176
- function okPropstat(response) {
10177
- return elementBodies(response, "propstat").find(
10178
- (propstat) => elementText(propstat, "status").includes(" 200 ")
10179
- ) ?? "";
10180
- }
10181
- function safeDecodePath(path) {
10182
- try {
10183
- return decodeURIComponent(path);
10184
- } catch {
10185
- return path;
10186
- }
10187
- }
10188
- function hrefPath(href) {
10189
- return safeDecodePath(new URL(href, "http://rstream.local").pathname);
10190
- }
10191
- function displayPath(href, fsPath) {
10192
- const value = hrefPath(href);
10193
- const sidecar = cleanTrailingSlashes2(sidecarPath(fsPath));
10194
- const withoutFS = value === sidecar ? "/" : value.startsWith(`${sidecar}/`) ? value.slice(sidecar.length) : value;
10195
- return withoutFS === "" ? "/" : withoutFS;
10196
- }
10197
- function itemSize(value) {
10198
- const parsed = Number.parseInt(value, 10);
10199
- return Number.isFinite(parsed) ? parsed : void 0;
10200
- }
10201
- function itemFromResponse(response, fsPath) {
10202
- const propstat = okPropstat(response);
10203
- const path = displayPath(elementText(response, "href"), fsPath);
10204
- if (propstat === "" || path === "") return null;
10205
- return {
10206
- kind: hasElement(
10207
- elementBodies(propstat, "resourcetype")[0] ?? "",
10208
- "collection"
10209
- ) ? "directory" : "file",
10210
- modified: elementText(propstat, "getlastmodified") || void 0,
10211
- path,
10212
- size: itemSize(elementText(propstat, "getcontentlength"))
10213
- };
10214
- }
10215
- function presentItems(items) {
10216
- return items.filter((item) => item !== null);
10217
- }
10218
- function parseWebDAVMultiStatus(xml, fsPath = "/fs") {
10219
- return presentItems(
10220
- elementBodies(xml, "response").map(
10221
- (response) => itemFromResponse(response, fsPath)
10222
- )
10223
- );
10224
- }
10225
- var WebTTYFileSystem = class {
10226
- config;
10227
- constructor(config) {
10228
- this.config = config;
10229
- }
10230
- async list(path = "/", options = {}) {
10231
- const response = await this.request("PROPFIND", path, {
10232
- body: webDAVPropfindBody,
10233
- expectedStatuses: [207],
10234
- headers: { "Content-Type": "application/xml; charset=utf-8", Depth: "1" },
10235
- operation: "WebTTY filesystem list",
10236
- signal: options.signal
10237
- });
10238
- return parseWebDAVMultiStatus(
10239
- await response.text(),
10240
- sidecarPath(this.config.fsPath)
10241
- );
10242
- }
10243
- async readBytes(path, options = {}) {
10244
- const response = await this.request("GET", path, {
10245
- expectedStatuses: [200],
10246
- operation: "WebTTY filesystem read",
10247
- signal: options.signal
10248
- });
10249
- return new Uint8Array(await response.arrayBuffer());
10250
- }
10251
- async readFile(path, options) {
10252
- const bytes = await this.readBytes(path, {
10253
- signal: readFileSignal(options)
10254
- });
10255
- const encoding = readFileEncoding(options);
10256
- return encoding === null ? bytes : new TextDecoder(encoding).decode(bytes);
10257
- }
10258
- async readText(path, options = {}) {
10259
- return new TextDecoder().decode(await this.readBytes(path, options));
10260
- }
10261
- async readStream(path, options = {}) {
10262
- return requireResponseBody(
10263
- await this.request("GET", path, {
10264
- expectedStatuses: [200],
10265
- operation: "WebTTY filesystem read",
10266
- signal: options.signal
10267
- }),
10268
- "WebTTY filesystem read"
10269
- );
10270
- }
10271
- async writeFile(path, data, options = {}) {
10272
- await this.request("PUT", path, {
10273
- body: data,
10274
- expectedStatuses: [200, 201, 204],
10275
- headers: textContentHeaders(options.contentType, data),
10276
- operation: "WebTTY filesystem write",
10277
- signal: options.signal
10278
- });
10279
- }
10280
- async writeBytes(path, data, options = {}) {
10281
- await this.writeFile(path, data, options);
10282
- }
10283
- async writeStream(path, data, options = {}) {
10284
- await this.request("PUT", path, {
10285
- body: data,
10286
- expectedStatuses: [200, 201, 204],
10287
- headers: contentHeaders(options.contentType),
10288
- operation: "WebTTY filesystem write",
10289
- signal: options.signal
10290
- });
10291
- }
10292
- async writeText(path, data, options = {}) {
10293
- await this.writeFile(path, data, options);
10294
- }
10295
- async copyFile(sourcePath, targetPath, options = {}) {
10296
- await this.request("COPY", sourcePath, {
10297
- expectedStatuses: [200, 201, 204],
10298
- headers: { Destination: (await this.resourceURL(targetPath)).toString() },
10299
- operation: "WebTTY filesystem copy",
10300
- signal: options.signal
10301
- });
10302
- }
10303
- async createDirectory(path, options = {}) {
10304
- await this.request("MKCOL", path, {
10305
- expectedStatuses: [201, 405],
10306
- operation: "WebTTY filesystem mkdir",
10307
- signal: options.signal
10308
- });
10309
- }
10310
- async exists(path, options = {}) {
10311
- return await this.stat(path, options).then(() => true).catch((error) => {
10312
- if (isNotFound(error)) return false;
10313
- throw error;
10314
- });
10315
- }
10316
- async mkdir(path, options = {}) {
10317
- if (options.recursive) {
10318
- await this.createDirectoryRecursive(path, options.signal);
10319
- return normalizeRemotePath(path);
10320
- }
10321
- await this.createDirectory(path, options);
10322
- return void 0;
10323
- }
10324
- async readdir(path = "/", options = {}) {
10325
- const items = (await this.list(path, options)).filter(
10326
- (item) => comparableRemotePath(item.path) !== comparableRemotePath(path)
10327
- );
10328
- return options.withFileTypes ? items : items.map((item) => pathBaseName(item.path));
10329
- }
10330
- async rename(oldPath, newPath, options = {}) {
10331
- await this.request("MOVE", oldPath, {
10332
- expectedStatuses: [200, 201, 204],
10333
- headers: { Destination: (await this.resourceURL(newPath)).toString() },
10334
- operation: "WebTTY filesystem rename",
10335
- signal: options.signal
10336
- });
10337
- }
10338
- async rm(path, options = {}) {
10339
- void options.recursive;
10340
- await this.request("DELETE", path, {
10341
- expectedStatuses: deleteStatuses(options.force),
10342
- operation: "WebTTY filesystem delete",
10343
- signal: options.signal
10344
- });
10345
- }
10346
- async stat(path, options = {}) {
10347
- const response = await this.request("PROPFIND", path, {
10348
- body: webDAVPropfindBody,
10349
- expectedStatuses: [207],
10350
- headers: { "Content-Type": "application/xml; charset=utf-8", Depth: "0" },
10351
- operation: "WebTTY filesystem stat",
10352
- signal: options.signal
10353
- });
10354
- const item = parseWebDAVMultiStatus(
10355
- await response.text(),
10356
- sidecarPath(this.config.fsPath)
10357
- )[0];
10358
- if (item) return item;
10359
- throw new Error(`WebTTY filesystem stat did not return ${path}.`);
10360
- }
10361
- async delete(path, options = {}) {
10362
- await this.rm(path, options);
10363
- }
10364
- async createDirectoryRecursive(path, signal) {
10365
- const normalized = normalizeRemotePath(path);
10366
- if (normalized === "/") return;
10367
- const parent = parentPath(normalized);
10368
- if (parent !== normalized) {
10369
- await this.createDirectoryRecursive(parent, signal);
10370
- }
10371
- await this.createDirectory(normalized, { signal });
10372
- }
10373
- async resourceURL(path) {
10374
- return resolveWebTTYFileSystemURL(
10375
- await resolveURL2(this.config.url),
10376
- path,
10377
- this.config.fsPath
10378
- );
10379
- }
10380
- async request(method, path, options) {
10381
- return await requireResponseStatus(
10382
- await resolveFetch(this.config)(
10383
- await this.resourceURL(path),
10384
- requestInit(this.config, method, options)
10385
- ),
10386
- options.expectedStatuses,
10387
- options.operation
10388
- );
10547
+ var WebTTYFileSystem = class extends import_filesystem.RemoteFileSystem {
10548
+ createError(operation, status, message) {
10549
+ return new WebTTYFileSystemError(operation, status, message);
10389
10550
  }
10390
10551
  };
10391
10552
 
@@ -10648,7 +10809,7 @@ function payloadCryptoMetadataFromRecordedMetadata(metadata) {
10648
10809
  }
10649
10810
  return {
10650
10811
  aadContext: keyContextFromRecordedMetadata(metadata),
10651
- nonce: bytesFromBase64URL(metadata.nonce),
10812
+ nonce: metadata.payload_suite === "aes-256-gcm-random-nonce" && (metadata.nonce === void 0 || metadata.nonce === "") ? new Uint8Array() : bytesFromBase64URL(metadata.nonce),
10652
10813
  payloadKeyId: bytesFromBase64URL(metadata.payload_key_id),
10653
10814
  payloadSuite: metadata.payload_suite
10654
10815
  };
@@ -10947,12 +11108,20 @@ function numberValue(value) {
10947
11108
  // src/local-e2e.ts
10948
11109
  var localKeyFileVersion = 1;
10949
11110
  var localKeyFileCryptoSuite = "webtty-e2e-x25519-hpke-aes-256-gcm-v1";
11111
+ var localKeyFileFIPSCompatibleCryptoSuite = "webtty-e2e-p256-hkdf-sha256-aes-256-gcm-random-nonce-v1";
10950
11112
  var x25519PublicKeySize2 = 32;
11113
+ var p256PublicKeySize2 = 65;
10951
11114
  var payloadKeyIDSize2 = 16;
10952
11115
  var knownServerKeyEnv = "RSTREAM_WEBTTY_KNOWN_SERVER_KEY";
10953
11116
  var knownServersFileEnv = "RSTREAM_WEBTTY_KNOWN_SERVERS_FILE";
10954
11117
  async function defaultWebTTYKnownServersPath(env) {
10955
11118
  const path = await nodePath();
11119
+ const dataDir = cleanString((env ?? defaultEnv()).RSTREAM_DATA_DIR);
11120
+ if (dataDir !== void 0) {
11121
+ if (!path.isAbsolute(dataDir))
11122
+ throw new Error("RSTREAM_DATA_DIR must be an absolute path.");
11123
+ return path.join(dataDir, "webtty", "known_servers.json");
11124
+ }
10956
11125
  return path.join(
10957
11126
  await homeDir(env ?? defaultEnv()),
10958
11127
  ".rstream",
@@ -10975,9 +11144,8 @@ async function parseWebTTYKnownServerKey(value) {
10975
11144
  validateSigningKeyMaterial(parts[2] ?? "", parts[3] ?? "");
10976
11145
  }
10977
11146
  if (parts.length === 1) {
10978
- const publicKey2 = decodeFixedKeyMaterial(
11147
+ const publicKey2 = decodeEncryptionPublicKey(
10979
11148
  parts[0] ?? "",
10980
- x25519PublicKeySize2,
10981
11149
  "known WebTTY server public key"
10982
11150
  );
10983
11151
  return { keyId: await webTTYE2EKeyID(publicKey2), publicKey: publicKey2 };
@@ -10987,9 +11155,8 @@ async function parseWebTTYKnownServerKey(value) {
10987
11155
  payloadKeyIDSize2,
10988
11156
  "known WebTTY server key id"
10989
11157
  );
10990
- const publicKey = decodeFixedKeyMaterial(
11158
+ const publicKey = decodeEncryptionPublicKey(
10991
11159
  parts[1] ?? "",
10992
- x25519PublicKeySize2,
10993
11160
  "known WebTTY server public key"
10994
11161
  );
10995
11162
  const expectedKeyId = await webTTYE2EKeyID(publicKey);
@@ -11084,7 +11251,7 @@ function decodeWebTTYKnownServerKeysFile(data, filePath) {
11084
11251
  );
11085
11252
  }
11086
11253
  const cryptoSuite = parsed.crypto_suite;
11087
- if (cryptoSuite !== localKeyFileCryptoSuite) {
11254
+ if (cryptoSuite !== localKeyFileCryptoSuite && cryptoSuite !== localKeyFileFIPSCompatibleCryptoSuite) {
11088
11255
  throw new Error(
11089
11256
  `unsupported known WebTTY server keys crypto suite ${String(cryptoSuite)}`
11090
11257
  );
@@ -11194,6 +11361,16 @@ function decodeFixedKeyMaterial(value, size, label) {
11194
11361
  }
11195
11362
  return decoded;
11196
11363
  }
11364
+ function decodeEncryptionPublicKey(value, label) {
11365
+ const decoded = decodeWebTTYE2EKeyMaterial(value.trim());
11366
+ if (decoded.byteLength === x25519PublicKeySize2) return decoded;
11367
+ if (decoded.byteLength === p256PublicKeySize2 && decoded[0] === 4) {
11368
+ return decoded;
11369
+ }
11370
+ throw new Error(
11371
+ `${label} must decode to a ${x25519PublicKeySize2}-byte X25519 key or an uncompressed ${p256PublicKeySize2}-byte P-256 point`
11372
+ );
11373
+ }
11197
11374
  function validateSigningKeyMaterial(keyID, publicKey) {
11198
11375
  decodeFixedKeyMaterial(keyID, 32, "known WebTTY server signing key id");
11199
11376
  decodeWebTTYE2EKeyMaterial(publicKey.trim());
@@ -11296,7 +11473,7 @@ function objectField(value, key) {
11296
11473
  if (typeof value !== "object" || value === null || Array.isArray(value)) {
11297
11474
  return void 0;
11298
11475
  }
11299
- return Object.fromEntries(Object.entries(value))[key];
11476
+ return Reflect.get(value, key);
11300
11477
  }
11301
11478
  function stringRecord(value) {
11302
11479
  if (typeof value !== "object" || value === null || Array.isArray(value)) {
@@ -11311,6 +11488,21 @@ function stringRecord(value) {
11311
11488
  function errorMessage(error) {
11312
11489
  return error instanceof Error ? error.message : String(error);
11313
11490
  }
11491
+
11492
+ // src/node-websocket.ts
11493
+ var import_ws = __toESM(require("ws"));
11494
+ var nodeWebSocketFactory = (url, options) => {
11495
+ const socketOptions = {
11496
+ closeTimeout: 1e3,
11497
+ handshakeTimeout: 1e4,
11498
+ maxPayload: options.maxMessageSize,
11499
+ perMessageDeflate: false
11500
+ };
11501
+ const socket = new import_ws.default(url, socketOptions);
11502
+ socket.binaryType = "arraybuffer";
11503
+ socket.on("error", () => void 0);
11504
+ return socket;
11505
+ };
11314
11506
  // Annotate the CommonJS export names for ESM import in node:
11315
11507
  0 && (module.exports = {
11316
11508
  WebTTY,
@@ -11338,6 +11530,7 @@ function errorMessage(error) {
11338
11530
  hashWebTTYServerProofTranscript,
11339
11531
  hashWebTTYSessionKeyGrant,
11340
11532
  loadWebTTYKnownServerKeysFile,
11533
+ nodeWebSocketFactory,
11341
11534
  openWebTTYCommand,
11342
11535
  parseWebDAVMultiStatus,
11343
11536
  parseWebTTYKnownServerKey,
@@ -11352,6 +11545,8 @@ function errorMessage(error) {
11352
11545
  verifyWebTTYServerProofTranscript,
11353
11546
  webTTYClientProofTranscriptBytes,
11354
11547
  webTTYE2EKeyID,
11548
+ webTTYFIPSCompatibleKeyEnvelopeSuite,
11549
+ webTTYFIPSCompatiblePayloadSuite,
11355
11550
  webTTYRecordedEventEncryptedPayload,
11356
11551
  webTTYServerProofTranscriptBytes,
11357
11552
  webTTYSigningKeyID