@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/index.js CHANGED
@@ -53,7 +53,7 @@ __export(index_exports, {
53
53
  hashWebTTYServerProofTranscript: () => hashWebTTYServerProofTranscript,
54
54
  hashWebTTYSessionKeyGrant: () => hashWebTTYSessionKeyGrant,
55
55
  openWebTTYCommand: () => openWebTTYCommand,
56
- parseWebDAVMultiStatus: () => parseWebDAVMultiStatus,
56
+ parseWebDAVMultiStatus: () => import_filesystem4.parseWebDAVMultiStatus,
57
57
  renderWebTTYRecordedTextLog: () => renderWebTTYRecordedTextLog,
58
58
  resolveWebTTYExecutionURL: () => resolveWebTTYExecutionURL,
59
59
  resolveWebTTYFileSystemURL: () => resolveWebTTYFileSystemURL,
@@ -64,6 +64,8 @@ __export(index_exports, {
64
64
  verifyWebTTYServerProofTranscript: () => verifyWebTTYServerProofTranscript,
65
65
  webTTYClientProofTranscriptBytes: () => webTTYClientProofTranscriptBytes,
66
66
  webTTYE2EKeyID: () => webTTYE2EKeyID,
67
+ webTTYFIPSCompatibleKeyEnvelopeSuite: () => webTTYFIPSCompatibleKeyEnvelopeSuite,
68
+ webTTYFIPSCompatiblePayloadSuite: () => webTTYFIPSCompatiblePayloadSuite,
67
69
  webTTYRecordedEventEncryptedPayload: () => webTTYRecordedEventEncryptedPayload,
68
70
  webTTYServerProofTranscriptBytes: () => webTTYServerProofTranscriptBytes,
69
71
  webTTYSigningKeyID: () => webTTYSigningKeyID
@@ -980,6 +982,7 @@ var rstream = $root.rstream = (() => {
980
982
  values[valuesById[0] = "PAYLOAD_CIPHER_SUITE_UNSPECIFIED"] = 0;
981
983
  values[valuesById[1] = "PAYLOAD_CIPHER_SUITE_AES_256_GCM"] = 1;
982
984
  values[valuesById[2] = "PAYLOAD_CIPHER_SUITE_CHACHA20_POLY1305"] = 2;
985
+ values[valuesById[3] = "PAYLOAD_CIPHER_SUITE_AES_256_GCM_RANDOM_NONCE"] = 3;
983
986
  return values;
984
987
  })();
985
988
  protobuf.KeyEnvelopeSuite = (function() {
@@ -987,6 +990,7 @@ var rstream = $root.rstream = (() => {
987
990
  values[valuesById[0] = "KEY_ENVELOPE_SUITE_UNSPECIFIED"] = 0;
988
991
  values[valuesById[1] = "KEY_ENVELOPE_SUITE_HPKE_X25519_HKDF_SHA256_AES_256_GCM"] = 1;
989
992
  values[valuesById[2] = "KEY_ENVELOPE_SUITE_HPKE_X25519_HKDF_SHA256_CHACHA20_POLY1305"] = 2;
993
+ values[valuesById[3] = "KEY_ENVELOPE_SUITE_P256_HKDF_SHA256_AES_256_GCM_RANDOM_NONCE"] = 3;
990
994
  return values;
991
995
  })();
992
996
  protobuf.ProtocolVersion = (function() {
@@ -1489,6 +1493,10 @@ var rstream = $root.rstream = (() => {
1489
1493
  case 2:
1490
1494
  message.keyEnvelopeSuite = 2;
1491
1495
  break;
1496
+ case "KEY_ENVELOPE_SUITE_P256_HKDF_SHA256_AES_256_GCM_RANDOM_NONCE":
1497
+ case 3:
1498
+ message.keyEnvelopeSuite = 3;
1499
+ break;
1492
1500
  default:
1493
1501
  if (typeof object.keyEnvelopeSuite === "number" && (object.keyEnvelopeSuite | 0) === object.keyEnvelopeSuite)
1494
1502
  message.keyEnvelopeSuite = object.keyEnvelopeSuite;
@@ -2173,6 +2181,10 @@ var rstream = $root.rstream = (() => {
2173
2181
  case 2:
2174
2182
  message.payloadSuites[message.payloadSuites.length] = 2;
2175
2183
  break;
2184
+ case "PAYLOAD_CIPHER_SUITE_AES_256_GCM_RANDOM_NONCE":
2185
+ case 3:
2186
+ message.payloadSuites[message.payloadSuites.length] = 3;
2187
+ break;
2176
2188
  default:
2177
2189
  if (typeof object.payloadSuites[i] === "number" && (object.payloadSuites[i] | 0) === object.payloadSuites[i])
2178
2190
  message.payloadSuites[message.payloadSuites.length] = object.payloadSuites[i];
@@ -2196,6 +2208,10 @@ var rstream = $root.rstream = (() => {
2196
2208
  case 2:
2197
2209
  message.keyEnvelopeSuites[message.keyEnvelopeSuites.length] = 2;
2198
2210
  break;
2211
+ case "KEY_ENVELOPE_SUITE_P256_HKDF_SHA256_AES_256_GCM_RANDOM_NONCE":
2212
+ case 3:
2213
+ message.keyEnvelopeSuites[message.keyEnvelopeSuites.length] = 3;
2214
+ break;
2199
2215
  default:
2200
2216
  if (typeof object.keyEnvelopeSuites[i] === "number" && (object.keyEnvelopeSuites[i] | 0) === object.keyEnvelopeSuites[i])
2201
2217
  message.keyEnvelopeSuites[message.keyEnvelopeSuites.length] = object.keyEnvelopeSuites[i];
@@ -2669,6 +2685,10 @@ var rstream = $root.rstream = (() => {
2669
2685
  case 2:
2670
2686
  message.payloadSuite = 2;
2671
2687
  break;
2688
+ case "PAYLOAD_CIPHER_SUITE_AES_256_GCM_RANDOM_NONCE":
2689
+ case 3:
2690
+ message.payloadSuite = 3;
2691
+ break;
2672
2692
  default:
2673
2693
  if (typeof object.payloadSuite === "number" && (object.payloadSuite | 0) === object.payloadSuite)
2674
2694
  message.payloadSuite = object.payloadSuite;
@@ -2713,6 +2733,10 @@ var rstream = $root.rstream = (() => {
2713
2733
  case 2:
2714
2734
  message.keyEnvelopeSuite = 2;
2715
2735
  break;
2736
+ case "KEY_ENVELOPE_SUITE_P256_HKDF_SHA256_AES_256_GCM_RANDOM_NONCE":
2737
+ case 3:
2738
+ message.keyEnvelopeSuite = 3;
2739
+ break;
2716
2740
  default:
2717
2741
  if (typeof object.keyEnvelopeSuite === "number" && (object.keyEnvelopeSuite | 0) === object.keyEnvelopeSuite)
2718
2742
  message.keyEnvelopeSuite = object.keyEnvelopeSuite;
@@ -2940,6 +2964,10 @@ var rstream = $root.rstream = (() => {
2940
2964
  case 2:
2941
2965
  message.payloadSuite = 2;
2942
2966
  break;
2967
+ case "PAYLOAD_CIPHER_SUITE_AES_256_GCM_RANDOM_NONCE":
2968
+ case 3:
2969
+ message.payloadSuite = 3;
2970
+ break;
2943
2971
  default:
2944
2972
  if (typeof object.payloadSuite === "number" && (object.payloadSuite | 0) === object.payloadSuite)
2945
2973
  message.payloadSuite = object.payloadSuite;
@@ -7450,6 +7478,7 @@ function authRequirementCode(value) {
7450
7478
  function payloadSuiteCode(value) {
7451
7479
  if (value === "aes-256-gcm" || value === void 0) return 1;
7452
7480
  if (value === "chacha20-poly1305") return 2;
7481
+ if (value === "aes-256-gcm-random-nonce") return 3;
7453
7482
  return 0;
7454
7483
  }
7455
7484
  function keyEnvelopeSuiteCode(value) {
@@ -7457,6 +7486,7 @@ function keyEnvelopeSuiteCode(value) {
7457
7486
  return 1;
7458
7487
  }
7459
7488
  if (value === "hpke-x25519-hkdf-sha256-chacha20-poly1305") return 2;
7489
+ if (value === "p256-hkdf-sha256-aes-256-gcm-random-nonce") return 3;
7460
7490
  return 0;
7461
7491
  }
7462
7492
  function signatureSuiteCode(value) {
@@ -7657,6 +7687,8 @@ function normalizeSessionKeyGrant(grant) {
7657
7687
  // src/e2e-crypto.ts
7658
7688
  var x25519PublicKeySize = 32;
7659
7689
  var x25519PrivateKeySize = 32;
7690
+ var p256PublicKeySize = 65;
7691
+ var p256PrivateKeySize = 32;
7660
7692
  var payloadKeySize = 32;
7661
7693
  var payloadKeyIDSize = 16;
7662
7694
  var aesGCMNonceSize = 12;
@@ -7669,21 +7701,24 @@ var keyIDDomain = "rstream-webtty-e2e-key-id/v1";
7669
7701
  var hpkeVersionLabel = "HPKE-v1";
7670
7702
  var nominalPayloadSuite = "aes-256-gcm";
7671
7703
  var nominalKeyEnvelopeSuite = "hpke-x25519-hkdf-sha256-aes-256-gcm";
7672
- async function generateWebTTYE2EIdentity() {
7673
- const pair = await getSubtle().generateKey({ name: "X25519" }, true, [
7674
- "deriveBits"
7675
- ]);
7676
- if (!isX25519KeyPair(pair)) {
7677
- throw new Error("WebCrypto returned an unexpected X25519 key pair");
7704
+ var webTTYFIPSCompatiblePayloadSuite = "aes-256-gcm-random-nonce";
7705
+ var webTTYFIPSCompatibleKeyEnvelopeSuite = "p256-hkdf-sha256-aes-256-gcm-random-nonce";
7706
+ async function generateWebTTYE2EIdentity(keyEnvelopeSuite = nominalKeyEnvelopeSuite) {
7707
+ payloadSuiteForKeyEnvelopeSuite(keyEnvelopeSuite);
7708
+ const algorithm = keyEnvelopeSuite === webTTYFIPSCompatibleKeyEnvelopeSuite ? { name: "ECDH", namedCurve: "P-256" } : { name: "X25519" };
7709
+ const pair = await getSubtle().generateKey(algorithm, true, ["deriveBits"]);
7710
+ if (!isCryptoKeyPair(pair)) {
7711
+ throw new Error("WebCrypto returned an unexpected E2E key pair");
7678
7712
  }
7679
7713
  const publicKey = new Uint8Array(
7680
7714
  await getSubtle().exportKey("raw", pair.publicKey)
7681
7715
  );
7682
7716
  const jwk = await getSubtle().exportKey("jwk", pair.privateKey);
7683
7717
  if (typeof jwk.d !== "string") {
7684
- throw new Error("WebCrypto X25519 private JWK is missing d");
7718
+ throw new Error("WebCrypto E2E private JWK is missing d");
7685
7719
  }
7686
7720
  return {
7721
+ keyEnvelopeSuite,
7687
7722
  keyId: await webTTYE2EKeyID(publicKey),
7688
7723
  privateKey: base64URLDecode(jwk.d),
7689
7724
  publicKey
@@ -7724,8 +7759,8 @@ function createWebTTYE2EKeyContext(config) {
7724
7759
  );
7725
7760
  }
7726
7761
  async function createWebTTYE2EClientPayloadCrypto(config) {
7727
- const payloadSuite = config.payloadSuite ?? nominalPayloadSuite;
7728
- const keyEnvelopeSuite = config.keyEnvelopeSuite ?? nominalKeyEnvelopeSuite;
7762
+ const keyEnvelopeSuite = config.keyEnvelopeSuite ?? inferRecipientSuite(config.recipients);
7763
+ const payloadSuite = config.payloadSuite ?? payloadSuiteForKeyEnvelopeSuite(keyEnvelopeSuite);
7729
7764
  validateSuites(payloadSuite, keyEnvelopeSuite);
7730
7765
  const payloadKey = config.payloadKey ? cloneKeyMaterial(config.payloadKey) : randomBytes(payloadKeySize);
7731
7766
  if (payloadKey.byteLength !== payloadKeySize) {
@@ -7817,7 +7852,7 @@ function createPayloadCrypto(options) {
7817
7852
  payloadSuite: options.payloadSuite
7818
7853
  };
7819
7854
  const cryptoInfo = {
7820
- keyAgreement: "HPKE X25519",
7855
+ keyAgreement: options.keyEnvelopeSuite === webTTYFIPSCompatibleKeyEnvelopeSuite ? "ECDH P-256" : "HPKE X25519",
7821
7856
  keyDerivation: "HKDF-SHA256",
7822
7857
  keyEncryption: "AES-256-GCM",
7823
7858
  keyEnvelopeSuite: options.keyEnvelopeSuite,
@@ -7832,7 +7867,7 @@ function createPayloadCrypto(options) {
7832
7867
  if (chunk.byteLength > 4294967295) {
7833
7868
  throw new Error(`E2E payload is too large: ${chunk.byteLength} bytes`);
7834
7869
  }
7835
- const nonce = randomBytes(aesGCMNonceSize);
7870
+ const nonce = options.payloadSuite === webTTYFIPSCompatiblePayloadSuite ? new Uint8Array() : randomBytes(aesGCMNonceSize);
7836
7871
  const payloadCrypto = {
7837
7872
  aadContext: cloneBytes(options.keyContext),
7838
7873
  nonce,
@@ -7840,7 +7875,8 @@ function createPayloadCrypto(options) {
7840
7875
  payloadSuite: options.payloadSuite
7841
7876
  };
7842
7877
  return {
7843
- ciphertext: await aesGCMEncrypt(
7878
+ ciphertext: await encryptPayloadForSuite(
7879
+ options.payloadSuite,
7844
7880
  options.payloadKey,
7845
7881
  nonce,
7846
7882
  cloneBytes(chunk),
@@ -7860,19 +7896,21 @@ function createPayloadCrypto(options) {
7860
7896
  const decrypt = (stream) => async (payload) => {
7861
7897
  validatePayloadEnvelope(payload, options);
7862
7898
  const crypto = payload.payloadCrypto;
7863
- if (crypto === void 0 || crypto.nonce === void 0) {
7864
- throw new Error("missing E2E payload nonce");
7899
+ if (crypto === void 0) {
7900
+ throw new Error("missing E2E payload crypto");
7865
7901
  }
7866
- const plaintext = await aesGCMDecrypt(
7902
+ const nonce = crypto.nonce ?? new Uint8Array();
7903
+ const plaintext = await decryptPayloadForSuite(
7904
+ options.payloadSuite,
7867
7905
  options.payloadKey,
7868
- crypto.nonce,
7906
+ nonce,
7869
7907
  payload.ciphertext,
7870
7908
  payloadAAD(
7871
7909
  stream,
7872
7910
  options.payloadSuite,
7873
7911
  options.payloadKeyId,
7874
7912
  options.keyContext,
7875
- crypto.nonce,
7913
+ nonce,
7876
7914
  payload.plaintextLength
7877
7915
  )
7878
7916
  );
@@ -7917,21 +7955,29 @@ async function implicitKeyContextFromRecipients(recipients) {
7917
7955
  }
7918
7956
  async function wrapPayloadKey(payloadKey, payloadSuite, payloadKeyId, keyContext, suite, recipient) {
7919
7957
  const recipientPublicKey = cloneKeyMaterial(recipient.publicKey);
7920
- if (recipientPublicKey.byteLength !== x25519PublicKeySize) {
7958
+ const recipientSuite = recipient.keyEnvelopeSuite ?? inferKeyEnvelopeSuite(recipientPublicKey);
7959
+ if (recipientSuite !== suite) {
7960
+ throw new Error("E2E recipient suite does not match key envelope suite");
7961
+ }
7962
+ const expectedPublicKeySize = publicKeySizeForSuite(suite);
7963
+ if (recipientPublicKey.byteLength !== expectedPublicKeySize) {
7921
7964
  throw new Error(
7922
- `E2E recipient public key must be ${x25519PublicKeySize} bytes`
7965
+ `E2E recipient public key must be ${expectedPublicKeySize} bytes`
7923
7966
  );
7924
7967
  }
7925
7968
  const recipientKeyId = recipient.keyId ? cloneKeyMaterial(recipient.keyId) : await webTTYE2EKeyID(recipientPublicKey);
7926
7969
  if (recipientKeyId.byteLength !== payloadKeyIDSize) {
7927
7970
  throw new Error(`E2E recipient key id must be ${payloadKeyIDSize} bytes`);
7928
7971
  }
7929
- const sealed = await hpkeSeal(
7930
- recipientPublicKey,
7931
- hpkeInfo(payloadSuite, payloadKeyId, keyContext, suite),
7932
- hpkeAAD(recipientKeyId, payloadSuite, payloadKeyId, keyContext, suite),
7933
- payloadKey
7972
+ const info = hpkeInfo(payloadSuite, payloadKeyId, keyContext, suite);
7973
+ const aad = hpkeAAD(
7974
+ recipientKeyId,
7975
+ payloadSuite,
7976
+ payloadKeyId,
7977
+ keyContext,
7978
+ suite
7934
7979
  );
7980
+ const sealed = suite === webTTYFIPSCompatibleKeyEnvelopeSuite ? await p256Seal(recipientPublicKey, info, aad, payloadKey) : await hpkeSeal(recipientPublicKey, info, aad, payloadKey);
7935
7981
  return {
7936
7982
  encapsulatedKey: sealed.encapsulatedKey,
7937
7983
  recipientKeyId,
@@ -7948,17 +7994,28 @@ async function unwrapPayloadKey(envelope, payloadSuite, payloadKeyId, keyContext
7948
7994
  if (envelope.wrappedKey === void 0) {
7949
7995
  throw new Error("E2E key envelope is missing wrapped key");
7950
7996
  }
7951
- const payloadKey = await hpkeOpen(
7997
+ if (identity.keyEnvelopeSuite !== suite) {
7998
+ throw new Error("E2E identity suite does not match key envelope suite");
7999
+ }
8000
+ const info = hpkeInfo(payloadSuite, payloadKeyId, keyContext, suite);
8001
+ const aad = hpkeAAD(
8002
+ envelope.recipientKeyId,
8003
+ payloadSuite,
8004
+ payloadKeyId,
8005
+ keyContext,
8006
+ suite
8007
+ );
8008
+ const payloadKey = suite === webTTYFIPSCompatibleKeyEnvelopeSuite ? await p256Open(
7952
8009
  identity,
7953
8010
  envelope.encapsulatedKey,
7954
- hpkeInfo(payloadSuite, payloadKeyId, keyContext, suite),
7955
- hpkeAAD(
7956
- envelope.recipientKeyId,
7957
- payloadSuite,
7958
- payloadKeyId,
7959
- keyContext,
7960
- suite
7961
- ),
8011
+ info,
8012
+ aad,
8013
+ envelope.wrappedKey
8014
+ ) : await hpkeOpen(
8015
+ identity,
8016
+ envelope.encapsulatedKey,
8017
+ info,
8018
+ aad,
7962
8019
  envelope.wrappedKey
7963
8020
  );
7964
8021
  if (payloadKey.byteLength !== payloadKeySize) {
@@ -8040,6 +8097,95 @@ async function hpkeOpen(identity, encapsulatedKey, info, aad, ciphertext) {
8040
8097
  const schedule = await hpkeKeySchedule(sharedSecret, info);
8041
8098
  return aesGCMDecrypt(schedule.key, schedule.baseNonce, ciphertext, aad);
8042
8099
  }
8100
+ async function p256Seal(publicKey, info, aad, plaintext) {
8101
+ const recipientPublic = await getSubtle().importKey(
8102
+ "raw",
8103
+ bufferSource(publicKey),
8104
+ { name: "ECDH", namedCurve: "P-256" },
8105
+ false,
8106
+ []
8107
+ );
8108
+ const ephemeral = await getSubtle().generateKey(
8109
+ { name: "ECDH", namedCurve: "P-256" },
8110
+ true,
8111
+ ["deriveBits"]
8112
+ );
8113
+ if (!isCryptoKeyPair(ephemeral)) {
8114
+ throw new Error("WebCrypto returned an unexpected P-256 key pair");
8115
+ }
8116
+ const encapsulatedKey = new Uint8Array(
8117
+ await getSubtle().exportKey("raw", ephemeral.publicKey)
8118
+ );
8119
+ const sharedSecret = new Uint8Array(
8120
+ await getSubtle().deriveBits(
8121
+ { name: "ECDH", public: recipientPublic },
8122
+ ephemeral.privateKey,
8123
+ 256
8124
+ )
8125
+ );
8126
+ const wrappingKey = await p256WrappingKey(sharedSecret, info);
8127
+ return {
8128
+ encapsulatedKey,
8129
+ wrappedKey: await aesGCMEncryptWithPrefixedRandomNonce(
8130
+ wrappingKey,
8131
+ plaintext,
8132
+ aad
8133
+ )
8134
+ };
8135
+ }
8136
+ async function p256Open(identity, encapsulatedKey, info, aad, ciphertext) {
8137
+ if (identity.privateKey.byteLength !== p256PrivateKeySize) {
8138
+ throw new Error(
8139
+ `E2E identity private key must be ${p256PrivateKeySize} bytes`
8140
+ );
8141
+ }
8142
+ if (identity.publicKey.byteLength !== p256PublicKeySize || identity.publicKey[0] !== 4) {
8143
+ throw new Error(
8144
+ `E2E identity public key must be an uncompressed ${p256PublicKeySize}-byte P-256 point`
8145
+ );
8146
+ }
8147
+ const recipientPrivate = await importP256PrivateKey(identity);
8148
+ const ephemeralPublic = await getSubtle().importKey(
8149
+ "raw",
8150
+ bufferSource(encapsulatedKey),
8151
+ { name: "ECDH", namedCurve: "P-256" },
8152
+ false,
8153
+ []
8154
+ );
8155
+ const sharedSecret = new Uint8Array(
8156
+ await getSubtle().deriveBits(
8157
+ { name: "ECDH", public: ephemeralPublic },
8158
+ recipientPrivate,
8159
+ 256
8160
+ )
8161
+ );
8162
+ return aesGCMDecryptWithPrefixedRandomNonce(
8163
+ await p256WrappingKey(sharedSecret, info),
8164
+ ciphertext,
8165
+ aad
8166
+ );
8167
+ }
8168
+ async function p256WrappingKey(sharedSecret, info) {
8169
+ const key = await getSubtle().importKey(
8170
+ "raw",
8171
+ bufferSource(sharedSecret),
8172
+ "HKDF",
8173
+ false,
8174
+ ["deriveBits"]
8175
+ );
8176
+ return new Uint8Array(
8177
+ await getSubtle().deriveBits(
8178
+ {
8179
+ hash: "SHA-256",
8180
+ info: bufferSource(info),
8181
+ name: "HKDF",
8182
+ salt: new Uint8Array()
8183
+ },
8184
+ key,
8185
+ 256
8186
+ )
8187
+ );
8188
+ }
8043
8189
  async function dhkemExtractAndExpand(dh, kemContext) {
8044
8190
  const eaePRK = await labeledExtract(
8045
8191
  dhkemSuiteID(),
@@ -8192,6 +8338,33 @@ async function aesGCMDecrypt(key, nonce, ciphertext, aad) {
8192
8338
  )
8193
8339
  );
8194
8340
  }
8341
+ async function aesGCMEncryptWithPrefixedRandomNonce(key, plaintext, aad) {
8342
+ const nonce = randomBytes(aesGCMNonceSize);
8343
+ return concat2(nonce, await aesGCMEncrypt(key, nonce, plaintext, aad));
8344
+ }
8345
+ async function aesGCMDecryptWithPrefixedRandomNonce(key, ciphertext, aad) {
8346
+ if (ciphertext.byteLength < aesGCMNonceSize + 16) {
8347
+ throw new Error("E2E random-nonce AES-GCM ciphertext is too short");
8348
+ }
8349
+ return aesGCMDecrypt(
8350
+ key,
8351
+ ciphertext.slice(0, aesGCMNonceSize),
8352
+ ciphertext.slice(aesGCMNonceSize),
8353
+ aad
8354
+ );
8355
+ }
8356
+ async function encryptPayloadForSuite(suite, key, nonce, plaintext, aad) {
8357
+ if (suite === webTTYFIPSCompatiblePayloadSuite) {
8358
+ return aesGCMEncryptWithPrefixedRandomNonce(key, plaintext, aad);
8359
+ }
8360
+ return aesGCMEncrypt(key, nonce, plaintext, aad);
8361
+ }
8362
+ async function decryptPayloadForSuite(suite, key, nonce, ciphertext, aad) {
8363
+ if (suite === webTTYFIPSCompatiblePayloadSuite) {
8364
+ return aesGCMDecryptWithPrefixedRandomNonce(key, ciphertext, aad);
8365
+ }
8366
+ return aesGCMDecrypt(key, nonce, ciphertext, aad);
8367
+ }
8195
8368
  async function importX25519PrivateKey(identity) {
8196
8369
  return getSubtle().importKey(
8197
8370
  "jwk",
@@ -8208,6 +8381,23 @@ async function importX25519PrivateKey(identity) {
8208
8381
  ["deriveBits"]
8209
8382
  );
8210
8383
  }
8384
+ async function importP256PrivateKey(identity) {
8385
+ return getSubtle().importKey(
8386
+ "jwk",
8387
+ {
8388
+ crv: "P-256",
8389
+ d: base64URLEncode(identity.privateKey),
8390
+ ext: true,
8391
+ key_ops: ["deriveBits"],
8392
+ kty: "EC",
8393
+ x: base64URLEncode(identity.publicKey.slice(1, 33)),
8394
+ y: base64URLEncode(identity.publicKey.slice(33, 65))
8395
+ },
8396
+ { name: "ECDH", namedCurve: "P-256" },
8397
+ false,
8398
+ ["deriveBits"]
8399
+ );
8400
+ }
8211
8401
  function validatePayloadEnvelope(payload, options) {
8212
8402
  const crypto = payload.payloadCrypto;
8213
8403
  if (crypto === void 0) throw new Error("missing E2E payload crypto");
@@ -8220,18 +8410,64 @@ function validatePayloadEnvelope(payload, options) {
8220
8410
  if (!bytesEqual(crypto.aadContext, options.keyContext)) {
8221
8411
  throw new Error("unexpected E2E key context");
8222
8412
  }
8223
- if (crypto.nonce === void 0 || crypto.nonce.byteLength !== aesGCMNonceSize) {
8224
- throw new Error(`E2E AES-GCM nonce must be ${aesGCMNonceSize} bytes`);
8413
+ const expectedNonceSize = options.payloadSuite === webTTYFIPSCompatiblePayloadSuite ? 0 : aesGCMNonceSize;
8414
+ if (crypto.nonce === void 0 || crypto.nonce.byteLength !== expectedNonceSize) {
8415
+ throw new Error(`E2E AES-GCM nonce must be ${expectedNonceSize} bytes`);
8225
8416
  }
8226
8417
  }
8227
- function validateSuites(payloadSuite, keyEnvelopeSuite) {
8228
- if (payloadSuite !== nominalPayloadSuite) {
8229
- throw new Error(`unsupported E2E payload suite ${payloadSuite}`);
8418
+ function inferRecipientSuite(recipients) {
8419
+ if (recipients.length === 0) {
8420
+ throw new Error(
8421
+ "E2E client payload crypto requires at least one recipient"
8422
+ );
8423
+ }
8424
+ const suites = recipients.map(
8425
+ (recipient) => recipient.keyEnvelopeSuite ?? inferKeyEnvelopeSuite(cloneKeyMaterial(recipient.publicKey))
8426
+ );
8427
+ const suite = suites[0];
8428
+ if (suite === void 0 || suites.some((candidate) => candidate !== suite)) {
8429
+ throw new Error("E2E recipients must use the same key envelope suite");
8430
+ }
8431
+ return suite;
8432
+ }
8433
+ function inferKeyEnvelopeSuite(publicKey) {
8434
+ if (publicKey.byteLength === x25519PublicKeySize) {
8435
+ return nominalKeyEnvelopeSuite;
8436
+ }
8437
+ if (publicKey.byteLength === p256PublicKeySize && publicKey[0] === 4) {
8438
+ return webTTYFIPSCompatibleKeyEnvelopeSuite;
8439
+ }
8440
+ throw new Error(
8441
+ `unsupported E2E recipient public key length ${publicKey.byteLength}`
8442
+ );
8443
+ }
8444
+ function payloadSuiteForKeyEnvelopeSuite(suite) {
8445
+ switch (suite) {
8446
+ case nominalKeyEnvelopeSuite:
8447
+ return nominalPayloadSuite;
8448
+ case webTTYFIPSCompatibleKeyEnvelopeSuite:
8449
+ return webTTYFIPSCompatiblePayloadSuite;
8450
+ default:
8451
+ throw new Error(`unsupported E2E key envelope suite ${suite}`);
8452
+ }
8453
+ }
8454
+ function publicKeySizeForSuite(suite) {
8455
+ switch (suite) {
8456
+ case nominalKeyEnvelopeSuite:
8457
+ return x25519PublicKeySize;
8458
+ case webTTYFIPSCompatibleKeyEnvelopeSuite:
8459
+ return p256PublicKeySize;
8460
+ default:
8461
+ throw new Error(`unsupported E2E key envelope suite ${suite}`);
8230
8462
  }
8231
- if (keyEnvelopeSuite !== nominalKeyEnvelopeSuite) {
8232
- throw new Error(`unsupported E2E key envelope suite ${keyEnvelopeSuite}`);
8463
+ }
8464
+ function validateSuites(payloadSuite, keyEnvelopeSuite) {
8465
+ if (payloadSuite === nominalPayloadSuite && keyEnvelopeSuite === nominalKeyEnvelopeSuite || payloadSuite === webTTYFIPSCompatiblePayloadSuite && keyEnvelopeSuite === webTTYFIPSCompatibleKeyEnvelopeSuite) {
8466
+ return { keyEnvelopeSuite, payloadSuite };
8233
8467
  }
8234
- return { keyEnvelopeSuite, payloadSuite };
8468
+ throw new Error(
8469
+ `unsupported E2E suite pair ${payloadSuite}/${keyEnvelopeSuite}`
8470
+ );
8235
8471
  }
8236
8472
  function hpkeInfo(payloadSuite, payloadKeyId, keyContext, suite) {
8237
8473
  return concat2(
@@ -8266,11 +8502,13 @@ function payloadAAD(stream, suite, payloadKeyId, keyContext, nonce, plaintextLen
8266
8502
  function payloadSuiteCode2(suite) {
8267
8503
  if (suite === "aes-256-gcm") return 1;
8268
8504
  if (suite === "chacha20-poly1305") return 2;
8505
+ if (suite === "aes-256-gcm-random-nonce") return 3;
8269
8506
  return unsupportedPayloadSuite(suite);
8270
8507
  }
8271
8508
  function keyEnvelopeSuiteCode2(suite) {
8272
8509
  if (suite === "hpke-x25519-hkdf-sha256-aes-256-gcm") return 1;
8273
8510
  if (suite === "hpke-x25519-hkdf-sha256-chacha20-poly1305") return 2;
8511
+ if (suite === "p256-hkdf-sha256-aes-256-gcm-random-nonce") return 3;
8274
8512
  return unsupportedKeyEnvelopeSuite(suite);
8275
8513
  }
8276
8514
  function unsupportedPayloadSuite(suite) {
@@ -8346,10 +8584,12 @@ function nonEmptyString(value, label) {
8346
8584
  return void 0;
8347
8585
  }
8348
8586
  function normalizeIdentity(identity) {
8587
+ const publicKey = cloneKeyMaterial(identity.publicKey);
8349
8588
  return {
8589
+ keyEnvelopeSuite: identity.keyEnvelopeSuite ?? inferKeyEnvelopeSuite(publicKey),
8350
8590
  keyId: cloneKeyMaterial(identity.keyId),
8351
8591
  privateKey: cloneKeyMaterial(identity.privateKey),
8352
- publicKey: cloneKeyMaterial(identity.publicKey)
8592
+ publicKey
8353
8593
  };
8354
8594
  }
8355
8595
  function bufferSource(value) {
@@ -8403,9 +8643,10 @@ function getSubtle() {
8403
8643
  }
8404
8644
  return subtle;
8405
8645
  }
8406
- function isX25519KeyPair(value) {
8646
+ function isCryptoKeyPair(value) {
8407
8647
  return "privateKey" in value && "publicKey" in value;
8408
8648
  }
8649
+ var isX25519KeyPair = isCryptoKeyPair;
8409
8650
  function base64URLEncode(value) {
8410
8651
  const binary = String.fromCharCode(...value);
8411
8652
  return btoa(binary).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, "");
@@ -8423,6 +8664,74 @@ function base64URLDecode(value) {
8423
8664
  return out;
8424
8665
  }
8425
8666
 
8667
+ // src/transport-frames.ts
8668
+ var WebTTYFrameDecoder = class {
8669
+ constructor(maxMessageSize) {
8670
+ this.maxMessageSize = maxMessageSize;
8671
+ }
8672
+ maxMessageSize;
8673
+ header = new Uint8Array(4);
8674
+ headerBytes = 0;
8675
+ payload = null;
8676
+ payloadBytes = 0;
8677
+ get incomplete() {
8678
+ return this.headerBytes !== 0 || this.payload !== null;
8679
+ }
8680
+ reset() {
8681
+ this.headerBytes = 0;
8682
+ this.payload = null;
8683
+ this.payloadBytes = 0;
8684
+ }
8685
+ *push(chunk) {
8686
+ const cursor = { offset: 0 };
8687
+ while (cursor.offset < chunk.byteLength) {
8688
+ if (this.payload === null) {
8689
+ const count2 = Math.min(
8690
+ 4 - this.headerBytes,
8691
+ chunk.byteLength - cursor.offset
8692
+ );
8693
+ this.header.set(
8694
+ chunk.subarray(cursor.offset, cursor.offset + count2),
8695
+ this.headerBytes
8696
+ );
8697
+ this.headerBytes += count2;
8698
+ cursor.offset += count2;
8699
+ if (this.headerBytes !== 4) return;
8700
+ const size = new DataView(this.header.buffer).getUint32(0, false);
8701
+ if (size > this.maxMessageSize)
8702
+ throw new Error(
8703
+ `WebTTY message exceeds the ${this.maxMessageSize} byte limit.`
8704
+ );
8705
+ this.headerBytes = 0;
8706
+ if (chunk.byteLength - cursor.offset >= size) {
8707
+ const payload = chunk.subarray(cursor.offset, cursor.offset + size);
8708
+ cursor.offset += size;
8709
+ yield payload;
8710
+ continue;
8711
+ }
8712
+ this.payload = new Uint8Array(size);
8713
+ this.payloadBytes = 0;
8714
+ }
8715
+ const count = Math.min(
8716
+ this.payload.byteLength - this.payloadBytes,
8717
+ chunk.byteLength - cursor.offset
8718
+ );
8719
+ this.payload.set(
8720
+ chunk.subarray(cursor.offset, cursor.offset + count),
8721
+ this.payloadBytes
8722
+ );
8723
+ this.payloadBytes += count;
8724
+ cursor.offset += count;
8725
+ if (this.payloadBytes === this.payload.byteLength) {
8726
+ const payload = this.payload;
8727
+ this.payload = null;
8728
+ this.payloadBytes = 0;
8729
+ yield payload;
8730
+ }
8731
+ }
8732
+ }
8733
+ };
8734
+
8426
8735
  // src/webtty.ts
8427
8736
  function getErrorMessage(error) {
8428
8737
  return error instanceof Error ? error.message : String(error);
@@ -8470,6 +8779,8 @@ function payloadCipherSuiteToProto(suite) {
8470
8779
  return rstream.webtty.protobuf.PayloadCipherSuite.PAYLOAD_CIPHER_SUITE_AES_256_GCM;
8471
8780
  case "chacha20-poly1305":
8472
8781
  return rstream.webtty.protobuf.PayloadCipherSuite.PAYLOAD_CIPHER_SUITE_CHACHA20_POLY1305;
8782
+ case "aes-256-gcm-random-nonce":
8783
+ return rstream.webtty.protobuf.PayloadCipherSuite.PAYLOAD_CIPHER_SUITE_AES_256_GCM_RANDOM_NONCE;
8473
8784
  default:
8474
8785
  return rstream.webtty.protobuf.PayloadCipherSuite.PAYLOAD_CIPHER_SUITE_UNSPECIFIED;
8475
8786
  }
@@ -8480,6 +8791,8 @@ function payloadCipherSuiteFromProto(suite) {
8480
8791
  return "aes-256-gcm";
8481
8792
  case rstream.webtty.protobuf.PayloadCipherSuite.PAYLOAD_CIPHER_SUITE_CHACHA20_POLY1305:
8482
8793
  return "chacha20-poly1305";
8794
+ case rstream.webtty.protobuf.PayloadCipherSuite.PAYLOAD_CIPHER_SUITE_AES_256_GCM_RANDOM_NONCE:
8795
+ return "aes-256-gcm-random-nonce";
8483
8796
  default:
8484
8797
  return void 0;
8485
8798
  }
@@ -8490,6 +8803,8 @@ function keyEnvelopeSuiteToProto(suite) {
8490
8803
  return rstream.webtty.protobuf.KeyEnvelopeSuite.KEY_ENVELOPE_SUITE_HPKE_X25519_HKDF_SHA256_AES_256_GCM;
8491
8804
  case "hpke-x25519-hkdf-sha256-chacha20-poly1305":
8492
8805
  return rstream.webtty.protobuf.KeyEnvelopeSuite.KEY_ENVELOPE_SUITE_HPKE_X25519_HKDF_SHA256_CHACHA20_POLY1305;
8806
+ case "p256-hkdf-sha256-aes-256-gcm-random-nonce":
8807
+ return rstream.webtty.protobuf.KeyEnvelopeSuite.KEY_ENVELOPE_SUITE_P256_HKDF_SHA256_AES_256_GCM_RANDOM_NONCE;
8493
8808
  default:
8494
8809
  return rstream.webtty.protobuf.KeyEnvelopeSuite.KEY_ENVELOPE_SUITE_UNSPECIFIED;
8495
8810
  }
@@ -8500,10 +8815,72 @@ function keyEnvelopeSuiteFromProto(suite) {
8500
8815
  return "hpke-x25519-hkdf-sha256-aes-256-gcm";
8501
8816
  case rstream.webtty.protobuf.KeyEnvelopeSuite.KEY_ENVELOPE_SUITE_HPKE_X25519_HKDF_SHA256_CHACHA20_POLY1305:
8502
8817
  return "hpke-x25519-hkdf-sha256-chacha20-poly1305";
8818
+ case rstream.webtty.protobuf.KeyEnvelopeSuite.KEY_ENVELOPE_SUITE_P256_HKDF_SHA256_AES_256_GCM_RANDOM_NONCE:
8819
+ return "p256-hkdf-sha256-aes-256-gcm-random-nonce";
8503
8820
  default:
8504
8821
  return void 0;
8505
8822
  }
8506
8823
  }
8824
+ var defaultE2EPayloadSuite = "aes-256-gcm";
8825
+ var defaultE2EKeyEnvelopeSuite = "hpke-x25519-hkdf-sha256-aes-256-gcm";
8826
+ var fipsCompatibleE2EPayloadSuite = "aes-256-gcm-random-nonce";
8827
+ var fipsCompatibleE2EKeyEnvelopeSuite = "p256-hkdf-sha256-aes-256-gcm-random-nonce";
8828
+ function payloadSuiteForKeyEnvelopeSuite2(suite) {
8829
+ switch (suite) {
8830
+ case defaultE2EKeyEnvelopeSuite:
8831
+ return defaultE2EPayloadSuite;
8832
+ case fipsCompatibleE2EKeyEnvelopeSuite:
8833
+ return fipsCompatibleE2EPayloadSuite;
8834
+ default:
8835
+ throw new Error(`Unsupported WebTTY E2E key envelope suite ${suite}.`);
8836
+ }
8837
+ }
8838
+ function asE2EKeyEnvelopeSuite(suite) {
8839
+ if (suite === defaultE2EKeyEnvelopeSuite || suite === fipsCompatibleE2EKeyEnvelopeSuite) {
8840
+ return suite;
8841
+ }
8842
+ throw new Error(`Unsupported WebTTY E2E key envelope suite ${suite}.`);
8843
+ }
8844
+ function inferE2EKeyEnvelopeSuite(publicKey) {
8845
+ if (publicKey?.byteLength === 32) return defaultE2EKeyEnvelopeSuite;
8846
+ if (publicKey?.byteLength === 65 && publicKey[0] === 4) {
8847
+ return fipsCompatibleE2EKeyEnvelopeSuite;
8848
+ }
8849
+ return void 0;
8850
+ }
8851
+ function proofSuitesFromGrant(grant) {
8852
+ const rawKeyEnvelopeSuite = keyEnvelopeSuiteFromProto(
8853
+ grant?.keyEnvelopeSuite
8854
+ );
8855
+ const payloadSuite = payloadCipherSuiteFromProto(grant?.payloadSuite);
8856
+ if (rawKeyEnvelopeSuite === void 0 && payloadSuite === void 0) {
8857
+ return {
8858
+ keyEnvelopeSuite: defaultE2EKeyEnvelopeSuite,
8859
+ payloadSuite: defaultE2EPayloadSuite
8860
+ };
8861
+ }
8862
+ if (rawKeyEnvelopeSuite === void 0 || payloadSuite === void 0) {
8863
+ throw new Error("WebTTY session key grant uses an unsupported suite pair.");
8864
+ }
8865
+ const keyEnvelopeSuite = asE2EKeyEnvelopeSuite(rawKeyEnvelopeSuite);
8866
+ const expectedPayloadSuite = payloadSuiteForKeyEnvelopeSuite2(keyEnvelopeSuite);
8867
+ if (expectedPayloadSuite !== payloadSuite) {
8868
+ throw new Error("WebTTY session key grant uses an unsupported suite pair.");
8869
+ }
8870
+ return { keyEnvelopeSuite, payloadSuite: expectedPayloadSuite };
8871
+ }
8872
+ function proofSuitesFromClientConfig(config) {
8873
+ const configured = config.endpointIdentity?.keyEnvelopeSuite;
8874
+ const expected = config.expectedServerIdentity;
8875
+ const expectedSuite = expected?.keyEnvelopeSuite ?? inferE2EKeyEnvelopeSuite(expected?.encryptionPublicKey);
8876
+ const keyEnvelopeSuite = asE2EKeyEnvelopeSuite(
8877
+ configured ?? expectedSuite ?? defaultE2EKeyEnvelopeSuite
8878
+ );
8879
+ return {
8880
+ keyEnvelopeSuite,
8881
+ payloadSuite: payloadSuiteForKeyEnvelopeSuite2(keyEnvelopeSuite)
8882
+ };
8883
+ }
8507
8884
  function signatureSuiteFromProto(suite) {
8508
8885
  switch (suite) {
8509
8886
  case rstream.webtty.protobuf.SignatureSuite.SIGNATURE_SUITE_ECDSA_P256_SHA256:
@@ -8744,12 +9121,15 @@ function resolveWebTransportConstructor() {
8744
9121
  function webTransportGlobal(value) {
8745
9122
  return "WebTransport" in value;
8746
9123
  }
9124
+ function browserWebSocket(url) {
9125
+ const socket = new WebSocket(url);
9126
+ socket.binaryType = "arraybuffer";
9127
+ return socket;
9128
+ }
8747
9129
  var WebSocketMessageConnection = class {
8748
- ws;
8749
- handlers;
8750
- constructor(url, handlers) {
8751
- this.ws = new WebSocket(url);
8752
- this.ws.binaryType = "arraybuffer";
9130
+ constructor(url, handlers, maxBufferedBytes, factory, maxMessageSize) {
9131
+ this.maxBufferedBytes = maxBufferedBytes;
9132
+ this.ws = factory ? factory(url, { maxMessageSize }) : browserWebSocket(url);
8753
9133
  this.handlers = {
8754
9134
  close: handlers.close,
8755
9135
  error: handlers.error,
@@ -8761,7 +9141,13 @@ var WebSocketMessageConnection = class {
8761
9141
  this.ws.addEventListener("error", this.handlers.error);
8762
9142
  this.ws.addEventListener("close", this.handlers.close);
8763
9143
  }
9144
+ maxBufferedBytes;
9145
+ ws;
9146
+ handlers;
8764
9147
  send(payload) {
9148
+ if (this.ws.bufferedAmount + payload.byteLength > this.maxBufferedBytes) {
9149
+ throw new Error("WebSocket write buffer limit exceeded.");
9150
+ }
8765
9151
  this.ws.send(getWebSocketPayload(payload));
8766
9152
  }
8767
9153
  close() {
@@ -8773,56 +9159,109 @@ var WebSocketMessageConnection = class {
8773
9159
  }
8774
9160
  };
8775
9161
  var WebTransportMessageConnection = class _WebTransportMessageConnection {
8776
- constructor(transport, stream, writer, handlers) {
9162
+ constructor(transport, stream, writer, maxMessageSize, handlers) {
8777
9163
  this.transport = transport;
8778
- this.stream = stream;
8779
9164
  this.writer = writer;
9165
+ this.maxMessageSize = maxMessageSize;
8780
9166
  this.handlers = handlers;
9167
+ this.decoder = new WebTTYFrameDecoder(maxMessageSize);
9168
+ this.reader = stream.readable.getReader();
8781
9169
  }
8782
9170
  transport;
8783
- stream;
8784
9171
  writer;
9172
+ maxMessageSize;
8785
9173
  handlers;
8786
9174
  closed = false;
8787
- readBuffer = new Uint8Array();
8788
- writeQueue = Promise.resolve();
8789
- static async open(url, options, handlers) {
9175
+ decoder;
9176
+ reader;
9177
+ writeQueue = [];
9178
+ writeHead = 0;
9179
+ bufferedBytes = 0;
9180
+ writing = false;
9181
+ static async open(url, options, signal, maxMessageSize, handlers) {
9182
+ signal.throwIfAborted();
8790
9183
  const Transport = resolveWebTransportConstructor();
8791
9184
  const transport = new Transport(url, options);
8792
- await transport.ready;
8793
- const stream = await transport.createBidirectionalStream();
8794
- const writer = stream.writable.getWriter();
8795
- const connection = new _WebTransportMessageConnection(
8796
- transport,
8797
- stream,
8798
- writer,
8799
- handlers
8800
- );
8801
- connection.startReadLoop();
8802
9185
  transport.closed.catch((error) => {
8803
- if (!connection.closed) {
9186
+ if (!signal.aborted) {
8804
9187
  handlers.error(`WebTransport closed: ${getErrorMessage(error)}`);
8805
9188
  }
8806
9189
  });
8807
- return connection;
9190
+ try {
9191
+ await waitForWebTransportOpen(transport.ready, signal);
9192
+ signal.throwIfAborted();
9193
+ const stream = await waitForWebTransportOpen(
9194
+ transport.createBidirectionalStream(),
9195
+ signal
9196
+ );
9197
+ signal.throwIfAborted();
9198
+ const writer = stream.writable.getWriter();
9199
+ const connection = new _WebTransportMessageConnection(
9200
+ transport,
9201
+ stream,
9202
+ writer,
9203
+ maxMessageSize,
9204
+ handlers
9205
+ );
9206
+ connection.startReadLoop();
9207
+ return connection;
9208
+ } catch (error) {
9209
+ transport.close({ closeCode: 0, reason: "open failed" });
9210
+ throw error;
9211
+ }
8808
9212
  }
8809
9213
  send(payload) {
8810
9214
  if (this.closed) return;
9215
+ if (payload.byteLength > this.maxMessageSize) {
9216
+ this.handlers.error(
9217
+ `WebTTY message exceeds the ${this.maxMessageSize} byte limit.`
9218
+ );
9219
+ return;
9220
+ }
9221
+ if (this.bufferedBytes + payload.byteLength + 4 > this.maxMessageSize * 4 || this.writeQueue.length - this.writeHead >= 1024) {
9222
+ this.handlers.error("WebTransport write buffer limit exceeded.");
9223
+ return;
9224
+ }
8811
9225
  const frame = getFramePayload(payload);
8812
- this.writeQueue = this.writeQueue.then(() => this.writer.write(frame)).catch((error) => {
8813
- if (!this.closed) {
8814
- this.handlers.error(
8815
- `WebTransport write failed: ${getErrorMessage(error)}`
8816
- );
8817
- }
8818
- });
9226
+ this.writeQueue.push(frame);
9227
+ this.bufferedBytes += frame.byteLength;
9228
+ if (!this.writing) {
9229
+ this.writing = true;
9230
+ void this.writeLoop();
9231
+ }
8819
9232
  }
8820
9233
  close() {
8821
9234
  if (this.closed) return;
8822
9235
  this.closed = true;
8823
- this.writer.releaseLock();
9236
+ this.writeQueue = [];
9237
+ this.writeHead = 0;
9238
+ this.decoder.reset();
9239
+ void this.reader.cancel().catch(() => void 0).finally(() => this.reader.releaseLock());
9240
+ void this.writer.abort().catch(() => void 0).finally(() => this.writer.releaseLock());
8824
9241
  this.transport.close({ closeCode: 0, reason: "closed" });
8825
9242
  }
9243
+ async writeLoop() {
9244
+ try {
9245
+ while (!this.closed && this.writeHead < this.writeQueue.length) {
9246
+ const frame = this.writeQueue[this.writeHead];
9247
+ this.writeQueue[this.writeHead++] = void 0;
9248
+ if (this.writeHead === this.writeQueue.length || this.writeHead >= 512) {
9249
+ this.writeQueue = this.writeQueue.slice(this.writeHead);
9250
+ this.writeHead = 0;
9251
+ }
9252
+ if (frame === void 0) continue;
9253
+ await this.writer.write(frame);
9254
+ this.bufferedBytes -= frame.byteLength;
9255
+ }
9256
+ } catch (error) {
9257
+ if (!this.closed)
9258
+ this.handlers.error(
9259
+ `WebTransport write failed: ${getErrorMessage(error)}`
9260
+ );
9261
+ } finally {
9262
+ this.writing = false;
9263
+ }
9264
+ }
8826
9265
  startReadLoop() {
8827
9266
  void this.readLoop().catch((error) => {
8828
9267
  if (!this.closed) {
@@ -8833,41 +9272,46 @@ var WebTransportMessageConnection = class _WebTransportMessageConnection {
8833
9272
  });
8834
9273
  }
8835
9274
  async readLoop() {
8836
- const reader = this.stream.readable.getReader();
8837
9275
  try {
8838
9276
  for (; ; ) {
8839
- const result = await reader.read();
9277
+ const result = await this.reader.read();
9278
+ if (this.closed) return;
8840
9279
  if (result.done) {
8841
- if (!this.closed) this.handlers.close();
9280
+ if (this.decoder.incomplete)
9281
+ throw new Error("Incomplete WebTTY frame at end of stream.");
9282
+ this.handlers.close();
8842
9283
  return;
8843
9284
  }
8844
- this.appendReadChunk(result.value);
9285
+ for (const payload of this.decoder.push(result.value)) {
9286
+ if (this.closed) return;
9287
+ await this.handlers.message(payload);
9288
+ if (this.closed) return;
9289
+ }
8845
9290
  }
8846
9291
  } finally {
8847
- reader.releaseLock();
8848
- }
8849
- }
8850
- appendReadChunk(chunk) {
8851
- const next = new Uint8Array(this.readBuffer.byteLength + chunk.byteLength);
8852
- next.set(this.readBuffer);
8853
- next.set(chunk, this.readBuffer.byteLength);
8854
- this.readBuffer = next;
8855
- for (; ; ) {
8856
- if (this.readBuffer.byteLength < 4) return;
8857
- const view = new DataView(
8858
- this.readBuffer.buffer,
8859
- this.readBuffer.byteOffset,
8860
- this.readBuffer.byteLength
8861
- );
8862
- const size = view.getUint32(0, false);
8863
- if (this.readBuffer.byteLength < 4 + size) return;
8864
- const payload = this.readBuffer.slice(4, 4 + size);
8865
- this.readBuffer = this.readBuffer.slice(4 + size);
8866
- this.handlers.message(payload);
9292
+ this.reader.releaseLock();
8867
9293
  }
8868
9294
  }
8869
9295
  };
9296
+ function waitForWebTransportOpen(pending, signal) {
9297
+ return new Promise((resolve, reject) => {
9298
+ const abort = () => reject(new Error("WebTransport connection cancelled."));
9299
+ signal.addEventListener("abort", abort, { once: true });
9300
+ if (signal.aborted) abort();
9301
+ pending.then(
9302
+ (value) => {
9303
+ signal.removeEventListener("abort", abort);
9304
+ resolve(value);
9305
+ },
9306
+ (error) => {
9307
+ signal.removeEventListener("abort", abort);
9308
+ reject(error);
9309
+ }
9310
+ );
9311
+ });
9312
+ }
8870
9313
  var WebTTY = class {
9314
+ connectionAbort = new AbortController();
8871
9315
  connection = null;
8872
9316
  connectionState = "preparing";
8873
9317
  heartbeatTimer = null;
@@ -8875,6 +9319,11 @@ var WebTTY = class {
8875
9319
  execConfig;
8876
9320
  events;
8877
9321
  receiveQueue = null;
9322
+ receivedBytes = 0;
9323
+ receivedMessages = 0;
9324
+ stdinClosed = false;
9325
+ stderrClosed = false;
9326
+ stdoutClosed = false;
8878
9327
  /**
8879
9328
  * Creates a new WebTTY instance.
8880
9329
  *
@@ -8883,6 +9332,12 @@ var WebTTY = class {
8883
9332
  * @param events - Event callbacks for the session.
8884
9333
  */
8885
9334
  constructor(clientConfig2, execConfig, events) {
9335
+ const maxMessageSize = clientConfig2.maxMessageSize ?? 1024 * 1024;
9336
+ if (!Number.isSafeInteger(maxMessageSize) || maxMessageSize < 1 || maxMessageSize > 4294967295) {
9337
+ throw new Error(
9338
+ "WebTTY maxMessageSize must be a positive 32-bit integer."
9339
+ );
9340
+ }
8886
9341
  const transport = resolveWebTTYClientTransport(
8887
9342
  clientConfig2.url,
8888
9343
  clientConfig2.transport
@@ -8906,9 +9361,11 @@ var WebTTY = class {
8906
9361
  endpointIdentity: clientConfig2.endpointIdentity,
8907
9362
  expectedServerIdentity: clientConfig2.expectedServerIdentity,
8908
9363
  heartbeatIntervalMs: clientConfig2.heartbeatIntervalMs ?? 5e3,
9364
+ maxMessageSize,
8909
9365
  sendHeartbeat: clientConfig2.sendHeartbeat ?? true,
8910
9366
  transport,
8911
9367
  url: clientConfig2.url,
9368
+ webSocketFactory: clientConfig2.webSocketFactory,
8912
9369
  webTransportOptions: clientConfig2.webTransportOptions
8913
9370
  };
8914
9371
  this.execConfig = {
@@ -8937,12 +9394,18 @@ var WebTTY = class {
8937
9394
  return;
8938
9395
  }
8939
9396
  const wsUrl = normalizeWebSocketURL(this.clientConfig.url);
8940
- this.connection = new WebSocketMessageConnection(wsUrl, {
8941
- close: this.handleClose,
8942
- error: this.handleError,
8943
- message: this.handleConnectionMessage,
8944
- open: this.handleOpen
8945
- });
9397
+ this.connection = new WebSocketMessageConnection(
9398
+ wsUrl,
9399
+ {
9400
+ close: this.handleClose,
9401
+ error: this.handleError,
9402
+ message: this.handleConnectionMessage,
9403
+ open: this.handleOpen
9404
+ },
9405
+ this.clientConfig.maxMessageSize * 4,
9406
+ this.clientConfig.webSocketFactory,
9407
+ this.clientConfig.maxMessageSize
9408
+ );
8946
9409
  }
8947
9410
  /**
8948
9411
  * Sends data to the remote server's STDIN.
@@ -8980,6 +9443,7 @@ var WebTTY = class {
8980
9443
  return;
8981
9444
  }
8982
9445
  const encrypted = await encrypt(data);
9446
+ this.assertCanWriteStdin();
8983
9447
  this.sendStdinPayload({
8984
9448
  encryptedData: encryptedPayloadToProto(encrypted)
8985
9449
  });
@@ -8991,6 +9455,9 @@ var WebTTY = class {
8991
9455
  if (this.execConfig.interactive === false) {
8992
9456
  throw new Error("STDIN is unavailable in non-interactive mode.");
8993
9457
  }
9458
+ if (this.stdinClosed) {
9459
+ throw new Error("WebTTY STDIN is already closed.");
9460
+ }
8994
9461
  }
8995
9462
  sendStdinPayload(payload) {
8996
9463
  this.send(
@@ -9012,6 +9479,8 @@ var WebTTY = class {
9012
9479
  if (this.execConfig.interactive === false) {
9013
9480
  throw new Error("STDIN is unavailable in non-interactive mode.");
9014
9481
  }
9482
+ if (this.stdinClosed) return;
9483
+ this.stdinClosed = true;
9015
9484
  this.send(
9016
9485
  new rstream.webtty.protobuf.Message({
9017
9486
  data: new rstream.webtty.protobuf.Data({
@@ -9184,6 +9653,16 @@ var WebTTY = class {
9184
9653
  if (!bytesEqual2(actual.signingKeyId, expected.signingKeyId) || !bytesEqual2(actual.signingPublicKey, expected.signingPublicKey) || !bytesEqual2(actual.encryptionKeyId, expected.encryptionKeyId) || !bytesEqual2(actual.encryptionPublicKey, expected.encryptionPublicKey)) {
9185
9654
  return false;
9186
9655
  }
9656
+ const expectedKeyEnvelopeSuite = expected.keyEnvelopeSuite ?? inferE2EKeyEnvelopeSuite(expected.encryptionPublicKey) ?? defaultE2EKeyEnvelopeSuite;
9657
+ const advertisedKeyEnvelopeSuites = (serverHello.keyEnvelopeSuites ?? []).map(keyEnvelopeSuiteFromProto).filter((value) => value !== void 0);
9658
+ const advertisedPayloadSuites = (serverHello.payloadSuites ?? []).map(payloadCipherSuiteFromProto).filter(
9659
+ (value) => value !== void 0
9660
+ );
9661
+ if (!advertisedKeyEnvelopeSuites.includes(expectedKeyEnvelopeSuite) || !advertisedPayloadSuites.includes(
9662
+ payloadSuiteForKeyEnvelopeSuite2(expectedKeyEnvelopeSuite)
9663
+ )) {
9664
+ return false;
9665
+ }
9187
9666
  const transcript = {
9188
9667
  authRequirement: authRequirementFromProto(serverHello.authRequirement),
9189
9668
  keyEnvelopeSuites: (serverHello.keyEnvelopeSuites ?? []).map(keyEnvelopeSuiteFromProto).filter(
@@ -9238,6 +9717,7 @@ var WebTTY = class {
9238
9717
  }
9239
9718
  const clientPrincipalId = trimOptional(this.clientConfig.clientPrincipalId);
9240
9719
  const clientCredential = this.clientConfig.clientCredential;
9720
+ const proofSuites = proofSuitesFromGrant(open.sessionKeyGrant);
9241
9721
  const transcript = {
9242
9722
  authRequirement: "client-proof",
9243
9723
  clientCredentialHash: await hashWebTTYClientCredential(clientCredential),
@@ -9246,8 +9726,8 @@ var WebTTY = class {
9246
9726
  commandConfigHash,
9247
9727
  expiresAt: expiresAt.toISOString().replace(".000Z", "Z"),
9248
9728
  issuedAt: issuedAt.toISOString().replace(".000Z", "Z"),
9249
- keyEnvelopeSuite: "hpke-x25519-hkdf-sha256-aes-256-gcm",
9250
- payloadSuite: "aes-256-gcm",
9729
+ keyEnvelopeSuite: proofSuites.keyEnvelopeSuite,
9730
+ payloadSuite: proofSuites.payloadSuite,
9251
9731
  projectId: optionalString(serverHello.projectId),
9252
9732
  protocolVersion: "webtty-1",
9253
9733
  serverEncryptionKeyId: optionalBytes(serverIdentity.encryptionKeyId),
@@ -9296,6 +9776,7 @@ var WebTTY = class {
9296
9776
  issuedAt.setMilliseconds(0);
9297
9777
  const expiresAt = new Date(issuedAt.getTime() + 3e4);
9298
9778
  const clientPrincipalId = trimOptional(this.clientConfig.clientPrincipalId);
9779
+ const proofSuites = proofSuitesFromClientConfig(this.clientConfig);
9299
9780
  const transcript = {
9300
9781
  attachGrantHash: await hashWebTTYAttachGrant(attach.attachGrant),
9301
9782
  authRequirement: "client-proof",
@@ -9304,8 +9785,8 @@ var WebTTY = class {
9304
9785
  clientSigningKeyId: signing.keyId,
9305
9786
  expiresAt: expiresAt.toISOString().replace(".000Z", "Z"),
9306
9787
  issuedAt: issuedAt.toISOString().replace(".000Z", "Z"),
9307
- keyEnvelopeSuite: "hpke-x25519-hkdf-sha256-aes-256-gcm",
9308
- payloadSuite: "aes-256-gcm",
9788
+ keyEnvelopeSuite: proofSuites.keyEnvelopeSuite,
9789
+ payloadSuite: proofSuites.payloadSuite,
9309
9790
  projectId: attachConfig.projectId,
9310
9791
  protocolVersion: "webtty-1",
9311
9792
  requestedRole: attachRoleTranscriptValue(attach.requestedRole),
@@ -9337,6 +9818,8 @@ var WebTTY = class {
9337
9818
  const connection = await WebTransportMessageConnection.open(
9338
9819
  url,
9339
9820
  this.clientConfig.webTransportOptions,
9821
+ this.connectionAbort.signal,
9822
+ this.clientConfig.maxMessageSize,
9340
9823
  {
9341
9824
  close: this.handleClose,
9342
9825
  error: this.handleTransportError,
@@ -9354,16 +9837,46 @@ var WebTTY = class {
9354
9837
  }
9355
9838
  }
9356
9839
  handleConnectionMessage = (data) => {
9357
- const run = () => this.processMessage(data);
9840
+ if (this.connectionState === "closed") return;
9841
+ const payload = this.boundedMessagePayload(data);
9842
+ if (payload === null) return;
9843
+ this.receivedBytes += payload.byteLength;
9844
+ this.receivedMessages += 1;
9845
+ const run = () => this.processMessage(payload);
9846
+ const release = () => {
9847
+ this.receivedBytes -= payload.byteLength;
9848
+ this.receivedMessages -= 1;
9849
+ };
9358
9850
  if (this.receiveQueue) {
9359
- this.trackReceiveQueue(this.receiveQueue.then(run, run));
9360
- return;
9851
+ return this.trackReceiveQueue(
9852
+ this.receiveQueue.then(run, run).finally(release)
9853
+ );
9361
9854
  }
9362
9855
  const result = run();
9363
9856
  if (isPromiseLike(result)) {
9364
- this.trackReceiveQueue(result);
9857
+ return this.trackReceiveQueue(result.finally(release));
9365
9858
  }
9859
+ release();
9366
9860
  };
9861
+ boundedMessagePayload(data) {
9862
+ try {
9863
+ const payload = messagePayloadBytes(data);
9864
+ if (payload.byteLength > this.clientConfig.maxMessageSize) {
9865
+ this.close(
9866
+ `WebTTY message exceeds the ${this.clientConfig.maxMessageSize} byte limit.`
9867
+ );
9868
+ return null;
9869
+ }
9870
+ if (this.receivedBytes + payload.byteLength > this.clientConfig.maxMessageSize * 4 || this.receivedMessages >= 1024) {
9871
+ this.close("WebTTY receive buffer limit exceeded.");
9872
+ return null;
9873
+ }
9874
+ return payload;
9875
+ } catch (error) {
9876
+ this.close(`Failed to decode message: ${getErrorMessage(error)}`);
9877
+ return null;
9878
+ }
9879
+ }
9367
9880
  trackReceiveQueue(promise) {
9368
9881
  const queued = promise.catch((error) => {
9369
9882
  this.close(`Failed to decode message: ${getErrorMessage(error)}`);
@@ -9371,6 +9884,7 @@ var WebTTY = class {
9371
9884
  if (this.receiveQueue === queued) this.receiveQueue = null;
9372
9885
  });
9373
9886
  this.receiveQueue = queued;
9887
+ return queued;
9374
9888
  }
9375
9889
  processMessage(data) {
9376
9890
  if (!data) return;
@@ -9419,41 +9933,47 @@ var WebTTY = class {
9419
9933
  }
9420
9934
  }
9421
9935
  processDataMessage(data) {
9422
- if (data.type === rstream.webtty.protobuf.Data.Type.TYPE_STDOUT) {
9423
- if (data.data) {
9424
- this.events.onStdout?.(data.data);
9425
- }
9426
- if (data.encryptedData) {
9427
- const decrypted = this.decryptData("stdout", data.encryptedData);
9428
- if (isPromiseLike(decrypted)) {
9429
- return decrypted.then((chunk) => {
9430
- if (chunk !== null) this.events.onStdout?.(chunk);
9431
- });
9432
- }
9433
- if (decrypted === null) return;
9434
- this.events.onStdout?.(decrypted);
9435
- }
9436
- if (data.eos) {
9936
+ const stream = data.type === rstream.webtty.protobuf.Data.Type.TYPE_STDOUT ? "stdout" : data.type === rstream.webtty.protobuf.Data.Type.TYPE_STDERR ? "stderr" : null;
9937
+ if (stream === null) {
9938
+ this.close(`Unexpected WebTTY data stream type ${String(data.type)}.`);
9939
+ return;
9940
+ }
9941
+ const hasData = data.data !== void 0 && data.data !== null;
9942
+ const hasEncryptedData = data.encryptedData !== void 0 && data.encryptedData !== null;
9943
+ const hasEos = data.eos !== void 0 && data.eos !== null;
9944
+ if (Number(hasData) + Number(hasEncryptedData) + Number(hasEos) !== 1) {
9945
+ this.close(`Unexpected WebTTY ${stream} payload.`);
9946
+ return;
9947
+ }
9948
+ const streamClosed = stream === "stdout" ? this.stdoutClosed : this.stderrClosed;
9949
+ if (streamClosed) {
9950
+ this.close(
9951
+ hasEos ? `Duplicate WebTTY ${stream} end of stream.` : `WebTTY ${stream} data received after end of stream.`
9952
+ );
9953
+ return;
9954
+ }
9955
+ if (hasEos) {
9956
+ if (stream === "stdout") {
9957
+ this.stdoutClosed = true;
9437
9958
  this.events.onStdoutEos?.();
9438
- }
9439
- } else if (data.type === rstream.webtty.protobuf.Data.Type.TYPE_STDERR) {
9440
- if (data.data) {
9441
- this.events.onStderr?.(data.data);
9442
- }
9443
- if (data.encryptedData) {
9444
- const decrypted = this.decryptData("stderr", data.encryptedData);
9445
- if (isPromiseLike(decrypted)) {
9446
- return decrypted.then((chunk) => {
9447
- if (chunk !== null) this.events.onStderr?.(chunk);
9448
- });
9449
- }
9450
- if (decrypted === null) return;
9451
- this.events.onStderr?.(decrypted);
9452
- }
9453
- if (data.eos) {
9959
+ } else {
9960
+ this.stderrClosed = true;
9454
9961
  this.events.onStderrEos?.();
9455
9962
  }
9963
+ return;
9964
+ }
9965
+ const emit = stream === "stdout" ? this.events.onStdout : this.events.onStderr;
9966
+ if (hasData) {
9967
+ emit?.(data.data);
9968
+ return;
9969
+ }
9970
+ const decrypted = this.decryptData(stream, data.encryptedData);
9971
+ if (isPromiseLike(decrypted)) {
9972
+ return decrypted.then((chunk) => {
9973
+ if (chunk !== null && this.connectionState !== "closed") emit?.(chunk);
9974
+ });
9456
9975
  }
9976
+ if (decrypted !== null) emit?.(decrypted);
9457
9977
  }
9458
9978
  decryptData(stream, payload) {
9459
9979
  const decrypt = stream === "stdout" ? this.execConfig.payloadCrypto?.decryptStdout : this.execConfig.payloadCrypto?.decryptStderr;
@@ -9504,7 +10024,19 @@ var WebTTY = class {
9504
10024
  if (this.connectionState === "preparing" || this.connectionState === "closed")
9505
10025
  return;
9506
10026
  const buffer = rstream.webtty.protobuf.Message.encode(message).finish();
9507
- this.connection.send(buffer);
10027
+ if (buffer.byteLength > this.clientConfig.maxMessageSize) {
10028
+ this.close(
10029
+ `WebTTY message exceeds the ${this.clientConfig.maxMessageSize} byte limit.`
10030
+ );
10031
+ return;
10032
+ }
10033
+ try {
10034
+ this.connection.send(buffer);
10035
+ } catch (error) {
10036
+ this.close(
10037
+ `${this.clientConfig.transport} write failed: ${getErrorMessage(error)}`
10038
+ );
10039
+ }
9508
10040
  }
9509
10041
  /**
9510
10042
  * Closes the WebTTY session and fires exactly one of:
@@ -9517,6 +10049,7 @@ var WebTTY = class {
9517
10049
  return;
9518
10050
  }
9519
10051
  this.connectionState = "closed";
10052
+ this.connectionAbort.abort();
9520
10053
  if (this.heartbeatTimer) {
9521
10054
  clearInterval(this.heartbeatTimer);
9522
10055
  this.heartbeatTimer = null;
@@ -9994,393 +10527,20 @@ var WebTTYRemoteExecutor = class {
9994
10527
  };
9995
10528
 
9996
10529
  // src/filesystem.ts
9997
- var WebTTYFileSystemError = class extends Error {
9998
- operation;
9999
- status;
10530
+ var import_filesystem = require("@rstreamlabs/filesystem");
10531
+ var import_filesystem2 = require("@rstreamlabs/filesystem");
10532
+ var import_filesystem3 = require("@rstreamlabs/filesystem");
10533
+ var import_filesystem4 = require("@rstreamlabs/filesystem");
10534
+ var resolveWebTTYFileSystemURL = import_filesystem3.resolveFileSystemURL;
10535
+ var WebTTYFileSystemError = class extends import_filesystem2.FileSystemError {
10000
10536
  constructor(operation, status, message) {
10001
- super(`${operation} failed with status ${status}: ${message}`);
10537
+ super(operation, status, message);
10002
10538
  this.name = "WebTTYFileSystemError";
10003
- this.operation = operation;
10004
- this.status = status;
10005
10539
  }
10006
10540
  };
10007
- var webDAVPropfindBody = '<?xml version="1.0" encoding="utf-8"?><propfind xmlns="DAV:"><prop><resourcetype/><getcontentlength/><getlastmodified/></prop></propfind>';
10008
- function cleanTrailingSlashes2(value) {
10009
- return value.replace(/\/+$/, "");
10010
- }
10011
- function normalizeRemotePath(remotePath) {
10012
- const trimmed = remotePath.trim();
10013
- const absolute = trimmed === "" || trimmed === "." ? "/" : trimmed;
10014
- return new URL(
10015
- absolute.startsWith("/") ? absolute : `/${absolute}`,
10016
- "http://rstream.local"
10017
- ).pathname;
10018
- }
10019
- function comparableRemotePath(remotePath) {
10020
- const normalized = cleanTrailingSlashes2(normalizeRemotePath(remotePath));
10021
- return normalized === "" ? "/" : normalized;
10022
- }
10023
- function sidecarPath(fsPath) {
10024
- return normalizeRemotePath(fsPath ?? "/fs");
10025
- }
10026
- function filesystemBasePath(pathname, fsPath) {
10027
- const sidecar = sidecarPath(fsPath);
10028
- const basePath = cleanTrailingSlashes2(pathname);
10029
- if (basePath === "") return sidecar;
10030
- if (basePath === "/") return sidecar;
10031
- if (basePath === sidecar || basePath.startsWith(`${sidecar}/`))
10032
- return basePath;
10033
- return `${basePath}${sidecar}`;
10034
- }
10035
- function filesystemPath(pathname, remotePath, fsPath) {
10036
- const basePath = filesystemBasePath(pathname, fsPath);
10037
- const normalized = normalizeRemotePath(remotePath);
10038
- return normalized === "/" ? basePath : `${cleanTrailingSlashes2(basePath)}${normalized}`;
10039
- }
10040
- function resolveWebTTYFileSystemURL(input, remotePath = "/", fsPath) {
10041
- const url = new URL(input.toString());
10042
- if (url.protocol === "rstrm:") {
10043
- throw new Error(
10044
- "rstrm:// WebTTY filesystem URLs require the native rstream dialer."
10045
- );
10046
- }
10047
- if (url.protocol === "ws:") url.protocol = "http:";
10048
- if (url.protocol === "wss:") url.protocol = "https:";
10049
- if (url.protocol !== "http:" && url.protocol !== "https:") {
10050
- throw new Error(
10051
- `Unsupported WebTTY filesystem URL scheme "${url.protocol}".`
10052
- );
10053
- }
10054
- url.pathname = filesystemPath(url.pathname, remotePath, fsPath);
10055
- url.hash = "";
10056
- return url;
10057
- }
10058
- function responseAllowed(response, expectedStatuses) {
10059
- return expectedStatuses.includes(response.status);
10060
- }
10061
- async function responseErrorMessage(response) {
10062
- const text = (await response.text()).trim().slice(0, 4096);
10063
- return text === "" ? response.statusText : text;
10064
- }
10065
- async function requireResponseStatus(response, expectedStatuses, operation) {
10066
- if (responseAllowed(response, expectedStatuses)) return response;
10067
- throw new WebTTYFileSystemError(
10068
- operation,
10069
- response.status,
10070
- await responseErrorMessage(response)
10071
- );
10072
- }
10073
- function requireResponseBody(response, operation) {
10074
- if (response.body) return response.body;
10075
- throw new Error(
10076
- `${operation} failed because the response body is unavailable.`
10077
- );
10078
- }
10079
- function resolveFetch(config) {
10080
- if (config.fetch) return config.fetch;
10081
- if (typeof fetch === "undefined") {
10082
- throw new Error("fetch is unavailable in this runtime.");
10083
- }
10084
- return fetch;
10085
- }
10086
- function applyHeaders(target, source) {
10087
- const sourceHeaders = new Headers(source);
10088
- sourceHeaders.forEach((value, key) => target.set(key, value));
10089
- return target;
10090
- }
10091
- function requestHeaders(config, headers) {
10092
- const result = applyHeaders(new Headers(config.headers), headers);
10093
- if (config.authToken && config.authToken.trim() !== "") {
10094
- result.set("Authorization", `Bearer ${config.authToken.trim()}`);
10095
- }
10096
- return result;
10097
- }
10098
- function contentHeaders(contentType) {
10099
- return contentType === void 0 ? void 0 : { "Content-Type": contentType };
10100
- }
10101
- function deleteStatuses(force) {
10102
- return force ? [200, 204, 404] : [200, 204];
10103
- }
10104
- function isNotFound(error) {
10105
- return error instanceof WebTTYFileSystemError && error.status === 404;
10106
- }
10107
- function pathBaseName(path) {
10108
- const normalized = normalizeRemotePath(path);
10109
- const cleaned = cleanTrailingSlashes2(normalized);
10110
- return cleaned.slice(cleaned.lastIndexOf("/") + 1);
10111
- }
10112
- function parentPath(path) {
10113
- const normalized = cleanTrailingSlashes2(normalizeRemotePath(path));
10114
- const index = normalized.lastIndexOf("/");
10115
- if (index <= 0) return "/";
10116
- return normalized.slice(0, index);
10117
- }
10118
- function readFileEncoding(options) {
10119
- if (typeof options === "string") return options;
10120
- return options?.encoding === void 0 ? null : options.encoding;
10121
- }
10122
- function readFileSignal(options) {
10123
- return typeof options === "string" ? void 0 : options?.signal;
10124
- }
10125
- function textContentHeaders(contentType, data) {
10126
- if (contentType !== void 0) return { "Content-Type": contentType };
10127
- return typeof data === "string" ? { "Content-Type": "text/plain; charset=utf-8" } : void 0;
10128
- }
10129
- function bodyRequiresDuplex(body) {
10130
- return typeof ReadableStream !== "undefined" && body instanceof ReadableStream;
10131
- }
10132
- function requestInit(config, method, options) {
10133
- return {
10134
- body: options.body,
10135
- duplex: bodyRequiresDuplex(options.body) ? "half" : void 0,
10136
- headers: requestHeaders(config, options.headers),
10137
- method,
10138
- signal: options.signal
10139
- };
10140
- }
10141
- async function resolveURL2(url) {
10142
- return typeof url === "function" ? await url() : url;
10143
- }
10144
- function elementBodies(xml, name) {
10145
- return Array.from(
10146
- xml.matchAll(
10147
- new RegExp(
10148
- `<[^>]*:?${name}\\b[^>]*>([\\s\\S]*?)<\\/[^>]*:?${name}>`,
10149
- "gi"
10150
- )
10151
- ),
10152
- (match) => match[1] ?? ""
10153
- );
10154
- }
10155
- function hasElement(xml, name) {
10156
- return new RegExp(`<[^>]*:?${name}(\\s|/|>)`, "i").test(xml);
10157
- }
10158
- function stripTags(xml) {
10159
- return xml.replace(/<[^>]*>/g, "");
10160
- }
10161
- function decodeNumericEntity(value) {
10162
- const parsed = value.startsWith("&#x") ? Number.parseInt(value.slice(3, -1), 16) : Number.parseInt(value.slice(2, -1), 10);
10163
- return Number.isFinite(parsed) ? String.fromCodePoint(parsed) : value;
10164
- }
10165
- function decodeXmlText(value) {
10166
- 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, "&");
10167
- }
10168
- function elementText(xml, name) {
10169
- return decodeXmlText(stripTags(elementBodies(xml, name)[0] ?? "")).trim();
10170
- }
10171
- function okPropstat(response) {
10172
- return elementBodies(response, "propstat").find(
10173
- (propstat) => elementText(propstat, "status").includes(" 200 ")
10174
- ) ?? "";
10175
- }
10176
- function safeDecodePath(path) {
10177
- try {
10178
- return decodeURIComponent(path);
10179
- } catch {
10180
- return path;
10181
- }
10182
- }
10183
- function hrefPath(href) {
10184
- return safeDecodePath(new URL(href, "http://rstream.local").pathname);
10185
- }
10186
- function displayPath(href, fsPath) {
10187
- const value = hrefPath(href);
10188
- const sidecar = cleanTrailingSlashes2(sidecarPath(fsPath));
10189
- const withoutFS = value === sidecar ? "/" : value.startsWith(`${sidecar}/`) ? value.slice(sidecar.length) : value;
10190
- return withoutFS === "" ? "/" : withoutFS;
10191
- }
10192
- function itemSize(value) {
10193
- const parsed = Number.parseInt(value, 10);
10194
- return Number.isFinite(parsed) ? parsed : void 0;
10195
- }
10196
- function itemFromResponse(response, fsPath) {
10197
- const propstat = okPropstat(response);
10198
- const path = displayPath(elementText(response, "href"), fsPath);
10199
- if (propstat === "" || path === "") return null;
10200
- return {
10201
- kind: hasElement(
10202
- elementBodies(propstat, "resourcetype")[0] ?? "",
10203
- "collection"
10204
- ) ? "directory" : "file",
10205
- modified: elementText(propstat, "getlastmodified") || void 0,
10206
- path,
10207
- size: itemSize(elementText(propstat, "getcontentlength"))
10208
- };
10209
- }
10210
- function presentItems(items) {
10211
- return items.filter((item) => item !== null);
10212
- }
10213
- function parseWebDAVMultiStatus(xml, fsPath = "/fs") {
10214
- return presentItems(
10215
- elementBodies(xml, "response").map(
10216
- (response) => itemFromResponse(response, fsPath)
10217
- )
10218
- );
10219
- }
10220
- var WebTTYFileSystem = class {
10221
- config;
10222
- constructor(config) {
10223
- this.config = config;
10224
- }
10225
- async list(path = "/", options = {}) {
10226
- const response = await this.request("PROPFIND", path, {
10227
- body: webDAVPropfindBody,
10228
- expectedStatuses: [207],
10229
- headers: { "Content-Type": "application/xml; charset=utf-8", Depth: "1" },
10230
- operation: "WebTTY filesystem list",
10231
- signal: options.signal
10232
- });
10233
- return parseWebDAVMultiStatus(
10234
- await response.text(),
10235
- sidecarPath(this.config.fsPath)
10236
- );
10237
- }
10238
- async readBytes(path, options = {}) {
10239
- const response = await this.request("GET", path, {
10240
- expectedStatuses: [200],
10241
- operation: "WebTTY filesystem read",
10242
- signal: options.signal
10243
- });
10244
- return new Uint8Array(await response.arrayBuffer());
10245
- }
10246
- async readFile(path, options) {
10247
- const bytes = await this.readBytes(path, {
10248
- signal: readFileSignal(options)
10249
- });
10250
- const encoding = readFileEncoding(options);
10251
- return encoding === null ? bytes : new TextDecoder(encoding).decode(bytes);
10252
- }
10253
- async readText(path, options = {}) {
10254
- return new TextDecoder().decode(await this.readBytes(path, options));
10255
- }
10256
- async readStream(path, options = {}) {
10257
- return requireResponseBody(
10258
- await this.request("GET", path, {
10259
- expectedStatuses: [200],
10260
- operation: "WebTTY filesystem read",
10261
- signal: options.signal
10262
- }),
10263
- "WebTTY filesystem read"
10264
- );
10265
- }
10266
- async writeFile(path, data, options = {}) {
10267
- await this.request("PUT", path, {
10268
- body: data,
10269
- expectedStatuses: [200, 201, 204],
10270
- headers: textContentHeaders(options.contentType, data),
10271
- operation: "WebTTY filesystem write",
10272
- signal: options.signal
10273
- });
10274
- }
10275
- async writeBytes(path, data, options = {}) {
10276
- await this.writeFile(path, data, options);
10277
- }
10278
- async writeStream(path, data, options = {}) {
10279
- await this.request("PUT", path, {
10280
- body: data,
10281
- expectedStatuses: [200, 201, 204],
10282
- headers: contentHeaders(options.contentType),
10283
- operation: "WebTTY filesystem write",
10284
- signal: options.signal
10285
- });
10286
- }
10287
- async writeText(path, data, options = {}) {
10288
- await this.writeFile(path, data, options);
10289
- }
10290
- async copyFile(sourcePath, targetPath, options = {}) {
10291
- await this.request("COPY", sourcePath, {
10292
- expectedStatuses: [200, 201, 204],
10293
- headers: { Destination: (await this.resourceURL(targetPath)).toString() },
10294
- operation: "WebTTY filesystem copy",
10295
- signal: options.signal
10296
- });
10297
- }
10298
- async createDirectory(path, options = {}) {
10299
- await this.request("MKCOL", path, {
10300
- expectedStatuses: [201, 405],
10301
- operation: "WebTTY filesystem mkdir",
10302
- signal: options.signal
10303
- });
10304
- }
10305
- async exists(path, options = {}) {
10306
- return await this.stat(path, options).then(() => true).catch((error) => {
10307
- if (isNotFound(error)) return false;
10308
- throw error;
10309
- });
10310
- }
10311
- async mkdir(path, options = {}) {
10312
- if (options.recursive) {
10313
- await this.createDirectoryRecursive(path, options.signal);
10314
- return normalizeRemotePath(path);
10315
- }
10316
- await this.createDirectory(path, options);
10317
- return void 0;
10318
- }
10319
- async readdir(path = "/", options = {}) {
10320
- const items = (await this.list(path, options)).filter(
10321
- (item) => comparableRemotePath(item.path) !== comparableRemotePath(path)
10322
- );
10323
- return options.withFileTypes ? items : items.map((item) => pathBaseName(item.path));
10324
- }
10325
- async rename(oldPath, newPath, options = {}) {
10326
- await this.request("MOVE", oldPath, {
10327
- expectedStatuses: [200, 201, 204],
10328
- headers: { Destination: (await this.resourceURL(newPath)).toString() },
10329
- operation: "WebTTY filesystem rename",
10330
- signal: options.signal
10331
- });
10332
- }
10333
- async rm(path, options = {}) {
10334
- void options.recursive;
10335
- await this.request("DELETE", path, {
10336
- expectedStatuses: deleteStatuses(options.force),
10337
- operation: "WebTTY filesystem delete",
10338
- signal: options.signal
10339
- });
10340
- }
10341
- async stat(path, options = {}) {
10342
- const response = await this.request("PROPFIND", path, {
10343
- body: webDAVPropfindBody,
10344
- expectedStatuses: [207],
10345
- headers: { "Content-Type": "application/xml; charset=utf-8", Depth: "0" },
10346
- operation: "WebTTY filesystem stat",
10347
- signal: options.signal
10348
- });
10349
- const item = parseWebDAVMultiStatus(
10350
- await response.text(),
10351
- sidecarPath(this.config.fsPath)
10352
- )[0];
10353
- if (item) return item;
10354
- throw new Error(`WebTTY filesystem stat did not return ${path}.`);
10355
- }
10356
- async delete(path, options = {}) {
10357
- await this.rm(path, options);
10358
- }
10359
- async createDirectoryRecursive(path, signal) {
10360
- const normalized = normalizeRemotePath(path);
10361
- if (normalized === "/") return;
10362
- const parent = parentPath(normalized);
10363
- if (parent !== normalized) {
10364
- await this.createDirectoryRecursive(parent, signal);
10365
- }
10366
- await this.createDirectory(normalized, { signal });
10367
- }
10368
- async resourceURL(path) {
10369
- return resolveWebTTYFileSystemURL(
10370
- await resolveURL2(this.config.url),
10371
- path,
10372
- this.config.fsPath
10373
- );
10374
- }
10375
- async request(method, path, options) {
10376
- return await requireResponseStatus(
10377
- await resolveFetch(this.config)(
10378
- await this.resourceURL(path),
10379
- requestInit(this.config, method, options)
10380
- ),
10381
- options.expectedStatuses,
10382
- options.operation
10383
- );
10541
+ var WebTTYFileSystem = class extends import_filesystem.RemoteFileSystem {
10542
+ createError(operation, status, message) {
10543
+ return new WebTTYFileSystemError(operation, status, message);
10384
10544
  }
10385
10545
  };
10386
10546
 
@@ -10643,7 +10803,7 @@ function payloadCryptoMetadataFromRecordedMetadata(metadata) {
10643
10803
  }
10644
10804
  return {
10645
10805
  aadContext: keyContextFromRecordedMetadata(metadata),
10646
- nonce: bytesFromBase64URL(metadata.nonce),
10806
+ nonce: metadata.payload_suite === "aes-256-gcm-random-nonce" && (metadata.nonce === void 0 || metadata.nonce === "") ? new Uint8Array() : bytesFromBase64URL(metadata.nonce),
10647
10807
  payloadKeyId: bytesFromBase64URL(metadata.payload_key_id),
10648
10808
  payloadSuite: metadata.payload_suite
10649
10809
  };
@@ -10974,6 +11134,8 @@ function numberValue(value) {
10974
11134
  verifyWebTTYServerProofTranscript,
10975
11135
  webTTYClientProofTranscriptBytes,
10976
11136
  webTTYE2EKeyID,
11137
+ webTTYFIPSCompatibleKeyEnvelopeSuite,
11138
+ webTTYFIPSCompatiblePayloadSuite,
10977
11139
  webTTYRecordedEventEncryptedPayload,
10978
11140
  webTTYServerProofTranscriptBytes,
10979
11141
  webTTYSigningKeyID