rwebtransport 0.2.1 → 0.2.3

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.
@@ -0,0 +1,119 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ //! Real QUIC pairs for native protocol regression tests.
3
+ use crate::config::{build_config, build_server_config, ClientConfigParams};
4
+ use boring::{
5
+ asn1::Asn1Time,
6
+ bn::BigNum,
7
+ ec::{EcGroup, EcKey},
8
+ hash::MessageDigest,
9
+ nid::Nid,
10
+ pkey::PKey,
11
+ x509::{
12
+ extension::{BasicConstraints, SubjectAlternativeName},
13
+ X509NameBuilder, X509,
14
+ },
15
+ };
16
+ use std::sync::atomic::{AtomicU64, Ordering};
17
+
18
+ pub fn pair(
19
+ expected_ip: Option<std::net::IpAddr>,
20
+ name: Option<&str>,
21
+ ip_san: bool,
22
+ ) -> (quiche::Connection, quiche::Connection) {
23
+ let group = EcGroup::from_curve_name(Nid::X9_62_PRIME256V1).unwrap();
24
+ let key = PKey::from_ec_key(EcKey::generate(&group).unwrap()).unwrap();
25
+ let mut subject = X509NameBuilder::new().unwrap();
26
+ subject.append_entry_by_text("CN", "wrong.example").unwrap();
27
+ let subject = subject.build();
28
+ let mut cert = X509::builder().unwrap();
29
+ cert.set_version(2).unwrap();
30
+ cert.set_serial_number(&BigNum::from_u32(1).unwrap().to_asn1_integer().unwrap())
31
+ .unwrap();
32
+ cert.set_subject_name(&subject).unwrap();
33
+ cert.set_issuer_name(&subject).unwrap();
34
+ cert.set_pubkey(&key).unwrap();
35
+ cert.set_not_before(&Asn1Time::days_from_now(0).unwrap())
36
+ .unwrap();
37
+ cert.set_not_after(&Asn1Time::days_from_now(1).unwrap())
38
+ .unwrap();
39
+ cert.append_extension(BasicConstraints::new().critical().ca().build().unwrap())
40
+ .unwrap();
41
+ let mut san = SubjectAlternativeName::new();
42
+ san.dns("wrong.example");
43
+ if ip_san {
44
+ san.ip("127.0.0.1").ip("::1");
45
+ }
46
+ let san = san.build(&cert.x509v3_context(None, None)).unwrap();
47
+ cert.append_extension(san).unwrap();
48
+ cert.sign(&key, MessageDigest::sha256()).unwrap();
49
+ static NEXT: AtomicU64 = AtomicU64::new(0);
50
+ let dir = std::env::temp_dir().join(format!(
51
+ "rwt-native-test-{}-{}",
52
+ std::process::id(),
53
+ NEXT.fetch_add(1, Ordering::Relaxed)
54
+ ));
55
+ std::fs::create_dir(&dir).unwrap();
56
+ let cert_path = dir.join("cert.pem");
57
+ let key_path = dir.join("key.pem");
58
+ std::fs::write(&cert_path, cert.build().to_pem().unwrap()).unwrap();
59
+ std::fs::write(&key_path, key.private_key_to_pem_pkcs8().unwrap()).unwrap();
60
+ let mut cc = build_config(&ClientConfigParams {
61
+ expected_ip,
62
+ ..Default::default()
63
+ })
64
+ .unwrap();
65
+ cc.load_verify_locations_from_file(cert_path.to_str().unwrap())
66
+ .unwrap();
67
+ let mut sc =
68
+ build_server_config(cert_path.to_str().unwrap(), key_path.to_str().unwrap()).unwrap();
69
+ std::fs::remove_dir_all(&dir).unwrap();
70
+ let ca = "127.0.0.1:1234".parse().unwrap();
71
+ let sa = "127.0.0.1:4433".parse().unwrap();
72
+ let client = quiche::connect(
73
+ name,
74
+ &quiche::ConnectionId::from_ref(&[1; 16]),
75
+ ca,
76
+ sa,
77
+ &mut cc,
78
+ )
79
+ .unwrap();
80
+ let server = quiche::accept(
81
+ &quiche::ConnectionId::from_ref(&[2; 16]),
82
+ None,
83
+ sa,
84
+ ca,
85
+ &mut sc,
86
+ )
87
+ .unwrap();
88
+ (client, server)
89
+ }
90
+
91
+ pub fn exchange(client: &mut quiche::Connection, server: &mut quiche::Connection) {
92
+ let mut buf = [0; 1350];
93
+ for _ in 0..100 {
94
+ let mut moved = false;
95
+ while let Ok((n, info)) = client.send(&mut buf) {
96
+ moved = true;
97
+ let _ = server.recv(
98
+ &mut buf[..n],
99
+ quiche::RecvInfo {
100
+ from: info.from,
101
+ to: info.to,
102
+ },
103
+ );
104
+ }
105
+ while let Ok((n, info)) = server.send(&mut buf) {
106
+ moved = true;
107
+ let _ = client.recv(
108
+ &mut buf[..n],
109
+ quiche::RecvInfo {
110
+ from: info.from,
111
+ to: info.to,
112
+ },
113
+ );
114
+ }
115
+ if !moved {
116
+ break;
117
+ }
118
+ }
119
+ }
@@ -13,3 +13,4 @@ path = "src/lib.rs"
13
13
  [dependencies]
14
14
  quiche.workspace = true
15
15
  octets.workspace = true
16
+ sfv = "0.16"
@@ -225,15 +225,29 @@ impl PeerSettings {
225
225
  }
226
226
 
227
227
  /// Parse a SETTINGS frame payload. Unknown identifiers are ignored (as required).
228
- pub fn parse_settings(mut payload: &[u8]) -> PeerSettings {
228
+ pub fn parse_settings(mut payload: &[u8]) -> Result<PeerSettings, String> {
229
+ let mut seen = std::collections::HashSet::new();
229
230
  let mut s = PeerSettings::default();
230
231
  while !payload.is_empty() {
231
- let Some((id, n1)) = read_varint(payload) else {
232
- break;
233
- };
234
- let Some((val, n2)) = read_varint(&payload[n1..]) else {
235
- break;
236
- };
232
+ let (id, n1) = read_varint(payload).ok_or("truncated SETTINGS identifier")?;
233
+ let (val, n2) = read_varint(&payload[n1..]).ok_or("truncated SETTINGS value")?;
234
+ if !seen.insert(id) || matches!(id, 0x2..=0x5) {
235
+ return Err("duplicate or reserved SETTINGS identifier".into());
236
+ }
237
+ if matches!(
238
+ id,
239
+ SETTINGS_ENABLE_CONNECT_PROTOCOL | SETTINGS_H3_DATAGRAM | SETTINGS_ENABLE_WEBTRANSPORT
240
+ ) && val > 1
241
+ {
242
+ return Err("invalid boolean SETTINGS value".into());
243
+ }
244
+ if matches!(
245
+ id,
246
+ SETTINGS_WT_INITIAL_MAX_STREAMS_BIDI | SETTINGS_WT_INITIAL_MAX_STREAMS_UNI
247
+ ) && val > (1 << 60)
248
+ {
249
+ return Err("invalid WebTransport stream limit".into());
250
+ }
237
251
  match id {
238
252
  SETTINGS_ENABLE_CONNECT_PROTOCOL => s.enable_connect_protocol = val != 0,
239
253
  SETTINGS_H3_DATAGRAM => s.h3_datagram = val != 0,
@@ -246,7 +260,7 @@ pub fn parse_settings(mut payload: &[u8]) -> PeerSettings {
246
260
  }
247
261
  payload = &payload[n1 + n2..];
248
262
  }
249
- s
263
+ Ok(s)
250
264
  }
251
265
 
252
266
  /// Request header carrying the client's offered WebTransport subprotocols
@@ -313,37 +327,29 @@ pub fn serialize_sf_string_list(items: &[String]) -> String {
313
327
  /// Parse a single RFC 9651 Structured-Field String item (a double-quoted,
314
328
  /// backslash-escaped token). Returns `None` if it is not a well-formed sf-string.
315
329
  pub fn parse_sf_string_item(value: &str) -> Option<String> {
316
- let bytes = value.as_bytes();
317
- if bytes.len() < 2 || bytes[0] != b'"' {
318
- return None;
319
- }
320
- let mut out = String::new();
321
- let mut i = 1;
322
- while i < bytes.len() {
323
- match bytes[i] {
324
- b'\\' => {
325
- i += 1;
326
- match bytes.get(i) {
327
- Some(&e) if e == b'"' || e == b'\\' => out.push(e as char),
328
- _ => return None,
329
- }
330
- }
331
- b'"' => return (i == bytes.len() - 1).then_some(out),
332
- b @ 0x20..=0x7e => out.push(b as char),
333
- _ => return None,
334
- }
335
- i += 1;
330
+ let item: sfv::Item = sfv::Parser::new(value).parse().ok()?;
331
+ match item.bare_item {
332
+ sfv::BareItem::String(value) => Some(value.to_string()),
333
+ _ => None,
336
334
  }
337
- None
338
335
  }
339
336
 
340
- /// Parse an RFC 9651 Structured-Field List of Strings into tokens, tolerating
341
- /// surrounding whitespace and skipping malformed items.
337
+ /// Parse an RFC 9651 Structured-Field List of Strings into tokens, ignoring item parameters.
338
+ /// A malformed field is ignored in its entirety.
342
339
  pub fn parse_sf_string_list(value: &str) -> Vec<String> {
343
- value
344
- .split(',')
345
- .filter_map(|part| parse_sf_string_item(part.trim()))
346
- .collect()
340
+ let Ok(list) = sfv::Parser::new(value).parse::<sfv::List>() else {
341
+ return Vec::new();
342
+ };
343
+ list.into_iter()
344
+ .map(|entry| match entry {
345
+ sfv::ListEntry::Item(item) => match item.bare_item {
346
+ sfv::BareItem::String(value) => Some(value.to_string()),
347
+ _ => None,
348
+ },
349
+ _ => None,
350
+ })
351
+ .collect::<Option<Vec<_>>>()
352
+ .unwrap_or_default()
347
353
  }
348
354
 
349
355
  /// Find the first header value for a (lowercase) name.
@@ -353,7 +359,11 @@ pub fn header_value<'a>(headers: &'a [Header], name: &[u8]) -> Option<&'a [u8]>
353
359
 
354
360
  /// Parse the `wt-protocol` response header into the selected subprotocol token.
355
361
  pub fn wt_protocol_of(headers: &[Header]) -> Option<String> {
356
- let v = header_value(headers, WT_PROTOCOL)?;
362
+ let mut values = headers.iter().filter(|h| h.name() == WT_PROTOCOL);
363
+ let v = values.next()?.value();
364
+ if values.next().is_some() {
365
+ return None;
366
+ }
357
367
  parse_sf_string_item(std::str::from_utf8(v).ok()?.trim())
358
368
  }
359
369
 
@@ -410,6 +420,44 @@ pub fn status_of(headers: &[Header]) -> Option<u16> {
410
420
  mod tests {
411
421
  use super::*;
412
422
 
423
+ #[test]
424
+ fn settings_reject_truncation_duplicates_and_invalid_boolean_values() {
425
+ for pairs in [
426
+ vec![(SETTINGS_ENABLE_CONNECT_PROTOCOL, 2)],
427
+ vec![(SETTINGS_H3_DATAGRAM, 1), (SETTINGS_H3_DATAGRAM, 1)],
428
+ vec![(SETTINGS_WT_INITIAL_MAX_STREAMS_UNI, (1 << 60) + 1)],
429
+ vec![(0x2, 0)],
430
+ ] {
431
+ let mut payload = Vec::new();
432
+ for (id, value) in pairs {
433
+ put_varint(id, &mut payload);
434
+ put_varint(value, &mut payload);
435
+ }
436
+ assert!(parse_settings(&payload).is_err());
437
+ }
438
+ assert!(parse_settings(&[0x40]).is_err());
439
+ assert!(parse_settings(&[0x1]).is_err());
440
+ }
441
+
442
+ #[test]
443
+ fn structured_fields_preserve_commas_ignore_parameters_and_reject_whole_invalid_lists() {
444
+ assert_eq!(
445
+ parse_sf_string_list(r#""a,b";q=1, "c";ignored="x,y""#),
446
+ vec!["a,b", "c"]
447
+ );
448
+ assert_eq!(
449
+ parse_sf_string_item(r#""a,b";ignored=?1"#).as_deref(),
450
+ Some("a,b")
451
+ );
452
+ for value in [
453
+ r#""valid", invalid"#,
454
+ r#""valid", "unterminated"#,
455
+ r#""valid", ("inner")"#,
456
+ ] {
457
+ assert!(parse_sf_string_list(value).is_empty());
458
+ }
459
+ }
460
+
413
461
  #[test]
414
462
  fn error_code_mapping_roundtrips() {
415
463
  assert_eq!(webtransport_code_to_http_code(0), WT_APP_ERROR_FIRST);
@@ -476,7 +524,7 @@ mod tests {
476
524
 
477
525
  #[test]
478
526
  fn settings_advertise_and_parse_wt_flow_control() {
479
- let s = parse_settings(&settings_payload());
527
+ let s = parse_settings(&settings_payload()).unwrap();
480
528
  assert!(s.webtransport_ok());
481
529
  assert_eq!(s.wt_max_sessions, 256);
482
530
  assert_eq!(s.wt_initial_max_data, WT_INITIAL_MAX_DATA);
package/dist/index.js CHANGED
@@ -1,3 +1,5 @@
1
+ 'use strict';
2
+ const __rwebtransportImportMetaUrl = require('node:url').pathToFileURL(__filename).href;
1
3
  "use strict";
2
4
  var __defProp = Object.defineProperty;
3
5
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
@@ -33,18 +35,14 @@ __export(index_exports, {
33
35
  });
34
36
  module.exports = __toCommonJS(index_exports);
35
37
 
36
- // node_modules/tsup/assets/cjs_shims.js
37
- var getImportMetaUrl = () => typeof document === "undefined" ? new URL(`file:${__filename}`).href : document.currentScript && document.currentScript.tagName.toUpperCase() === "SCRIPT" ? document.currentScript.src : new URL("main.js", document.baseURI).href;
38
- var importMetaUrl = /* @__PURE__ */ getImportMetaUrl();
39
-
40
38
  // src/loader.ts
41
- var import_node_module = require("module");
42
- var import_node_child_process = require("child_process");
43
- var import_node_fs = require("fs");
44
- var import_node_path = require("path");
45
- var import_node_url = require("url");
46
- var require2 = (0, import_node_module.createRequire)(importMetaUrl);
47
- var moduleDir = (0, import_node_path.dirname)((0, import_node_url.fileURLToPath)(importMetaUrl));
39
+ var import_node_module = require("node:module");
40
+ var import_node_child_process = require("node:child_process");
41
+ var import_node_fs = require("node:fs");
42
+ var import_node_path = require("node:path");
43
+ var import_node_url = require("node:url");
44
+ var require2 = (0, import_node_module.createRequire)(__rwebtransportImportMetaUrl);
45
+ var moduleDir = (0, import_node_path.dirname)((0, import_node_url.fileURLToPath)(__rwebtransportImportMetaUrl));
48
46
  var PACKAGE_ROOT = (0, import_node_path.join)(moduleDir, "..");
49
47
  function assertSupportedRuntime() {
50
48
  const major = Number(process.versions.node.split(".")[0]);
@@ -253,7 +251,7 @@ var SessionCore = class {
253
251
  if (!this.usable()) return Promise.reject(this.deadError());
254
252
  const requestId = this.nextId();
255
253
  const d = deferred();
256
- this.writes.set(requestId, d);
254
+ this.writes.set(requestId, { streamId, deferred: d });
257
255
  this.transport.write(streamId, chunk, requestId);
258
256
  return d.promise;
259
257
  }
@@ -273,6 +271,17 @@ var SessionCore = class {
273
271
  */
274
272
  resetStream(streamId, code) {
275
273
  this.transport?.reset(streamId, code >>> 0);
274
+ for (const [requestId, write] of this.writes) {
275
+ if (write.streamId === streamId) {
276
+ write.deferred.reject(
277
+ new WebTransportError("stream aborted", {
278
+ source: "stream",
279
+ streamErrorCode: code >>> 0
280
+ })
281
+ );
282
+ this.writes.delete(requestId);
283
+ }
284
+ }
276
285
  }
277
286
  /**
278
287
  * Ask the peer to stop sending on a stream. No-op if not attached.
@@ -323,6 +332,12 @@ var SessionCore = class {
323
332
  if (this.closedState || !this.transport) return;
324
333
  this.transport.closeSession(code >>> 0, new TextEncoder().encode(reason));
325
334
  }
335
+ /** End a session that exceeded a local resource limit, releasing its sinks. */
336
+ abort(message) {
337
+ if (this.closedState) return;
338
+ this.close(0, message);
339
+ this.finish(null, new WebTransportError(message, { source: "session" }));
340
+ }
326
341
  /** Tell the peer this session is draining (send a DRAIN capsule). */
327
342
  drain() {
328
343
  this.transport?.drain();
@@ -352,6 +367,11 @@ var SessionCore = class {
352
367
  * session is not usable or the TLS export fails.
353
368
  */
354
369
  exportKeyingMaterial(label, context, length) {
370
+ if (!Number.isInteger(length) || length < 1 || length > 4096) {
371
+ return Promise.reject(
372
+ new RangeError("outputLength must be an integer between 1 and 4096")
373
+ );
374
+ }
355
375
  if (!this.usable()) return Promise.reject(this.deadError());
356
376
  const requestId = this.nextId();
357
377
  const d = deferred();
@@ -447,6 +467,7 @@ var SessionCore = class {
447
467
  * for their `requestId`.
448
468
  */
449
469
  dispatch(ev) {
470
+ if (this.closedState) return;
450
471
  switch (ev.type) {
451
472
  case "ready" /* Ready */: {
452
473
  this.readyState = true;
@@ -506,7 +527,7 @@ var SessionCore = class {
506
527
  break;
507
528
  }
508
529
  case "writeAck" /* WriteAck */: {
509
- this.writes.get(ev.requestId)?.resolve();
530
+ this.writes.get(ev.requestId)?.deferred.resolve();
510
531
  this.writes.delete(ev.requestId);
511
532
  break;
512
533
  }
@@ -589,7 +610,7 @@ var SessionCore = class {
589
610
  }
590
611
  const err = error ?? new WebTransportError("session closed", { source: "session" });
591
612
  for (const d of this.opens.values()) d.reject(err);
592
- for (const d of this.writes.values()) d.reject(err);
613
+ for (const write of this.writes.values()) write.deferred.reject(err);
593
614
  for (const d of this.datagramAcks.values()) d.resolve(false);
594
615
  for (const d of this.statsRequests.values()) d.reject(err);
595
616
  for (const d of this.keyingMaterialRequests.values()) d.reject(err);
@@ -1154,10 +1175,20 @@ var WebTransportSendStream = class extends WritableStream {
1154
1175
  */
1155
1176
  constructor(session, streamId, options = {}) {
1156
1177
  let controller;
1178
+ let reset = false;
1179
+ const abortNative = (reason) => {
1180
+ if (reset) return;
1181
+ reset = true;
1182
+ session.resetStream(streamId, errorCode(reason));
1183
+ session.unregisterSend(streamId);
1184
+ };
1157
1185
  super(
1158
1186
  {
1159
1187
  start(c) {
1160
1188
  controller = c;
1189
+ c.signal.addEventListener("abort", () => abortNative(c.signal.reason), {
1190
+ once: true
1191
+ });
1161
1192
  },
1162
1193
  write(chunk) {
1163
1194
  return session.write(streamId, chunk);
@@ -1167,8 +1198,7 @@ var WebTransportSendStream = class extends WritableStream {
1167
1198
  session.unregisterSend(streamId);
1168
1199
  },
1169
1200
  abort(reason) {
1170
- session.resetStream(streamId, errorCode(reason));
1171
- session.unregisterSend(streamId);
1201
+ abortNative(reason);
1172
1202
  }
1173
1203
  },
1174
1204
  new ByteLengthQueuingStrategy({ highWaterMark: 1024 * 1024 })
@@ -1217,14 +1247,27 @@ var WebTransportBidirectionalStream = class {
1217
1247
  };
1218
1248
 
1219
1249
  // src/webtransport.ts
1250
+ var MAX_PENDING_INCOMING_STREAMS = 128;
1220
1251
  function toBytes(src) {
1221
1252
  if (src instanceof ArrayBuffer) return new Uint8Array(src);
1222
1253
  return new Uint8Array(src.buffer, src.byteOffset, src.byteLength);
1223
1254
  }
1224
1255
  function buildConfig(url, options) {
1225
- if (typeof url !== "string" || !url.startsWith("https://")) {
1256
+ let parsed;
1257
+ try {
1258
+ parsed = new URL(url);
1259
+ } catch {
1260
+ throw new WebTransportError(`invalid WebTransport URL: ${url}`, { source: "session" });
1261
+ }
1262
+ if (typeof url !== "string" || parsed.protocol !== "https:" || parsed.hash || url.includes("#") || parsed.username || parsed.password) {
1226
1263
  throw new WebTransportError(`invalid WebTransport URL: ${url}`, { source: "session" });
1227
1264
  }
1265
+ const protocols = options.protocols ?? [];
1266
+ if (new Set(protocols).size !== protocols.length || protocols.some((protocol) => !/^[\x20-\x7e]{1,512}$/.test(protocol))) {
1267
+ throw new WebTransportError("protocols must be distinct ASCII strings of 1 to 512 bytes", {
1268
+ source: "session"
1269
+ });
1270
+ }
1228
1271
  const hashes = [];
1229
1272
  for (const hash of options.serverCertificateHashes ?? []) {
1230
1273
  const algorithm = hash.algorithm.toLowerCase();
@@ -1249,13 +1292,13 @@ function buildConfig(url, options) {
1249
1292
  headerValues.push(value);
1250
1293
  }
1251
1294
  return {
1252
- url,
1295
+ url: parsed.href,
1253
1296
  hashes,
1254
1297
  insecure: options.insecure ?? false,
1255
1298
  origin: options.origin ?? null,
1256
1299
  headerNames,
1257
1300
  headerValues,
1258
- protocols: options.protocols ?? []
1301
+ protocols
1259
1302
  };
1260
1303
  }
1261
1304
  var WebTransportSession = class {
@@ -1304,6 +1347,8 @@ var WebTransportSession = class {
1304
1347
  * constructs the two incoming-stream `ReadableStream`s and captures their
1305
1348
  * controllers via the `start` callback. Registers an incoming handler on
1306
1349
  * `core` so each peer-opened bidi/uni stream is wrapped and enqueued;
1350
+ * checks the 128-stream queue limit before allocating each wrapper and
1351
+ * aborts the session on overflow. Cancelled directions stop new peer streams.
1307
1352
  * `enqueue` is wrapped in try/catch because it throws once the consumer has
1308
1353
  * cancelled the reader, and that error must not escape native event dispatch.
1309
1354
  * Finally it observes `core.closed`: on clean close both controllers are
@@ -1315,24 +1360,55 @@ var WebTransportSession = class {
1315
1360
  this.datagrams = new WebTransportDatagramDuplexStream(core);
1316
1361
  let bidiController;
1317
1362
  let uniController;
1318
- this.incomingBidirectionalStreams = new ReadableStream({
1319
- start: (c) => {
1320
- bidiController = c;
1321
- }
1322
- });
1323
- this.incomingUnidirectionalStreams = new ReadableStream({
1324
- start: (c) => {
1325
- uniController = c;
1326
- }
1327
- });
1363
+ let bidiCancelled = false;
1364
+ let uniCancelled = false;
1365
+ this.incomingBidirectionalStreams = new ReadableStream(
1366
+ {
1367
+ start: (c) => {
1368
+ bidiController = c;
1369
+ },
1370
+ cancel: () => {
1371
+ bidiCancelled = true;
1372
+ }
1373
+ },
1374
+ new CountQueuingStrategy({ highWaterMark: MAX_PENDING_INCOMING_STREAMS })
1375
+ );
1376
+ this.incomingUnidirectionalStreams = new ReadableStream(
1377
+ {
1378
+ start: (c) => {
1379
+ uniController = c;
1380
+ },
1381
+ cancel: () => {
1382
+ uniCancelled = true;
1383
+ }
1384
+ },
1385
+ new CountQueuingStrategy({ highWaterMark: MAX_PENDING_INCOMING_STREAMS })
1386
+ );
1328
1387
  core.setIncomingHandler({
1329
1388
  onBidi: (id) => {
1389
+ if (bidiCancelled) {
1390
+ core.stopSending(id, 0);
1391
+ core.resetStream(id, 0);
1392
+ return;
1393
+ }
1394
+ if ((bidiController.desiredSize ?? 0) <= 0) {
1395
+ core.abort("incoming stream queue limit exceeded (bidirectional)");
1396
+ return;
1397
+ }
1330
1398
  try {
1331
1399
  bidiController.enqueue(new WebTransportBidirectionalStream(core, id));
1332
1400
  } catch {
1333
1401
  }
1334
1402
  },
1335
1403
  onUni: (id) => {
1404
+ if (uniCancelled) {
1405
+ core.stopSending(id, 0);
1406
+ return;
1407
+ }
1408
+ if ((uniController.desiredSize ?? 0) <= 0) {
1409
+ core.abort("incoming stream queue limit exceeded (unidirectional)");
1410
+ return;
1411
+ }
1336
1412
  try {
1337
1413
  uniController.enqueue(new WebTransportReceiveStream(core, id));
1338
1414
  } catch {
@@ -1526,6 +1602,7 @@ function safeError(controller, reason) {
1526
1602
  }
1527
1603
 
1528
1604
  // src/server.ts
1605
+ var MAX_PENDING_SESSIONS = 128;
1529
1606
  function deferred2() {
1530
1607
  let resolve;
1531
1608
  let reject;
@@ -1595,6 +1672,7 @@ var WebTransportServer = class {
1595
1672
  boundPort = 0;
1596
1673
  /** Guards {@link close} so shutdown is issued at most once. */
1597
1674
  closeCalled = false;
1675
+ incomingCancelled = false;
1598
1676
  /**
1599
1677
  * The sessions clients open, delivered as they are established. Each pull
1600
1678
  * yields a {@link WebTransportServerSession}. The stream is closed when the
@@ -1620,11 +1698,17 @@ var WebTransportServer = class {
1620
1698
  });
1621
1699
  void this.closedD.promise.catch(() => {
1622
1700
  });
1623
- this.incomingSessions = new ReadableStream({
1624
- start: (c) => {
1625
- this.incomingController = c;
1626
- }
1627
- });
1701
+ this.incomingSessions = new ReadableStream(
1702
+ {
1703
+ start: (c) => {
1704
+ this.incomingController = c;
1705
+ },
1706
+ cancel: () => {
1707
+ this.incomingCancelled = true;
1708
+ }
1709
+ },
1710
+ new CountQueuingStrategy({ highWaterMark: MAX_PENDING_SESSIONS })
1711
+ );
1628
1712
  const responseHeaderNames = [];
1629
1713
  const responseHeaderValues = [];
1630
1714
  for (const [name, value] of Object.entries(options.responseHeaders ?? {})) {
@@ -1713,10 +1797,22 @@ var WebTransportServer = class {
1713
1797
  }
1714
1798
  const sessionId = ev.session;
1715
1799
  if (ev.type === "serverReady" /* ServerReady */) {
1800
+ if (this.closeCalled || this.incomingCancelled || (this.incomingController.desiredSize ?? 0) <= 0) {
1801
+ this.native.serverCloseSession(
1802
+ this.handle,
1803
+ sessionId,
1804
+ 0,
1805
+ new TextEncoder().encode("incoming session queue limit exceeded")
1806
+ );
1807
+ return;
1808
+ }
1716
1809
  const core = new SessionCore();
1717
1810
  core.attach(new ServerTransport(this.native, this.handle, sessionId));
1718
1811
  this.sessions.set(sessionId, core);
1719
- void core.closed.promise.finally(() => this.sessions.delete(sessionId));
1812
+ const forget = () => {
1813
+ this.sessions.delete(sessionId);
1814
+ };
1815
+ void core.closed.promise.then(forget, forget);
1720
1816
  const session = new WebTransportServerSession(core, {
1721
1817
  authority: ev.authority,
1722
1818
  path: ev.path,
@@ -1740,7 +1836,7 @@ var WebTransportServer = class {
1740
1836
  *
1741
1837
  * @remarks Dispatches a synthetic clean `closed` event (code `0`, empty
1742
1838
  * reason, `remote: false`) to each session core, then clears the map. The
1743
- * per-core `closed.finally` handler registered in {@link onEvent} would
1839
+ * per-core `closed.then` handlers registered in {@link onEvent} would
1744
1840
  * also remove entries, but the map is cleared here unconditionally.
1745
1841
  */
1746
1842
  finishAllSessions() {
@@ -1797,4 +1893,4 @@ function safeCloseController(controller) {
1797
1893
  //! const wt = new WebTransport('https://example.com:4433/echo');
1798
1894
  //! await wt.ready;
1799
1895
  //! ```
1800
- //# sourceMappingURL=index.js.map
1896
+ //# sourceMappingURL=index.js.map