rwebtransport 0.2.2 → 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.
package/dist/index.mjs CHANGED
@@ -1,9 +1,9 @@
1
1
  // src/loader.ts
2
- import { createRequire } from "module";
3
- import { execFileSync } from "child_process";
4
- import { existsSync } from "fs";
5
- import { dirname, join } from "path";
6
- import { fileURLToPath } from "url";
2
+ import { createRequire } from "node:module";
3
+ import { execFileSync } from "node:child_process";
4
+ import { existsSync } from "node:fs";
5
+ import { dirname, join } from "node:path";
6
+ import { fileURLToPath } from "node:url";
7
7
  var require2 = createRequire(import.meta.url);
8
8
  var moduleDir = dirname(fileURLToPath(import.meta.url));
9
9
  var PACKAGE_ROOT = join(moduleDir, "..");
@@ -214,7 +214,7 @@ var SessionCore = class {
214
214
  if (!this.usable()) return Promise.reject(this.deadError());
215
215
  const requestId = this.nextId();
216
216
  const d = deferred();
217
- this.writes.set(requestId, d);
217
+ this.writes.set(requestId, { streamId, deferred: d });
218
218
  this.transport.write(streamId, chunk, requestId);
219
219
  return d.promise;
220
220
  }
@@ -234,6 +234,17 @@ var SessionCore = class {
234
234
  */
235
235
  resetStream(streamId, code) {
236
236
  this.transport?.reset(streamId, code >>> 0);
237
+ for (const [requestId, write] of this.writes) {
238
+ if (write.streamId === streamId) {
239
+ write.deferred.reject(
240
+ new WebTransportError("stream aborted", {
241
+ source: "stream",
242
+ streamErrorCode: code >>> 0
243
+ })
244
+ );
245
+ this.writes.delete(requestId);
246
+ }
247
+ }
237
248
  }
238
249
  /**
239
250
  * Ask the peer to stop sending on a stream. No-op if not attached.
@@ -284,6 +295,12 @@ var SessionCore = class {
284
295
  if (this.closedState || !this.transport) return;
285
296
  this.transport.closeSession(code >>> 0, new TextEncoder().encode(reason));
286
297
  }
298
+ /** End a session that exceeded a local resource limit, releasing its sinks. */
299
+ abort(message) {
300
+ if (this.closedState) return;
301
+ this.close(0, message);
302
+ this.finish(null, new WebTransportError(message, { source: "session" }));
303
+ }
287
304
  /** Tell the peer this session is draining (send a DRAIN capsule). */
288
305
  drain() {
289
306
  this.transport?.drain();
@@ -313,6 +330,11 @@ var SessionCore = class {
313
330
  * session is not usable or the TLS export fails.
314
331
  */
315
332
  exportKeyingMaterial(label, context, length) {
333
+ if (!Number.isInteger(length) || length < 1 || length > 4096) {
334
+ return Promise.reject(
335
+ new RangeError("outputLength must be an integer between 1 and 4096")
336
+ );
337
+ }
316
338
  if (!this.usable()) return Promise.reject(this.deadError());
317
339
  const requestId = this.nextId();
318
340
  const d = deferred();
@@ -408,6 +430,7 @@ var SessionCore = class {
408
430
  * for their `requestId`.
409
431
  */
410
432
  dispatch(ev) {
433
+ if (this.closedState) return;
411
434
  switch (ev.type) {
412
435
  case "ready" /* Ready */: {
413
436
  this.readyState = true;
@@ -467,7 +490,7 @@ var SessionCore = class {
467
490
  break;
468
491
  }
469
492
  case "writeAck" /* WriteAck */: {
470
- this.writes.get(ev.requestId)?.resolve();
493
+ this.writes.get(ev.requestId)?.deferred.resolve();
471
494
  this.writes.delete(ev.requestId);
472
495
  break;
473
496
  }
@@ -550,7 +573,7 @@ var SessionCore = class {
550
573
  }
551
574
  const err = error ?? new WebTransportError("session closed", { source: "session" });
552
575
  for (const d of this.opens.values()) d.reject(err);
553
- for (const d of this.writes.values()) d.reject(err);
576
+ for (const write of this.writes.values()) write.deferred.reject(err);
554
577
  for (const d of this.datagramAcks.values()) d.resolve(false);
555
578
  for (const d of this.statsRequests.values()) d.reject(err);
556
579
  for (const d of this.keyingMaterialRequests.values()) d.reject(err);
@@ -1115,10 +1138,20 @@ var WebTransportSendStream = class extends WritableStream {
1115
1138
  */
1116
1139
  constructor(session, streamId, options = {}) {
1117
1140
  let controller;
1141
+ let reset = false;
1142
+ const abortNative = (reason) => {
1143
+ if (reset) return;
1144
+ reset = true;
1145
+ session.resetStream(streamId, errorCode(reason));
1146
+ session.unregisterSend(streamId);
1147
+ };
1118
1148
  super(
1119
1149
  {
1120
1150
  start(c) {
1121
1151
  controller = c;
1152
+ c.signal.addEventListener("abort", () => abortNative(c.signal.reason), {
1153
+ once: true
1154
+ });
1122
1155
  },
1123
1156
  write(chunk) {
1124
1157
  return session.write(streamId, chunk);
@@ -1128,8 +1161,7 @@ var WebTransportSendStream = class extends WritableStream {
1128
1161
  session.unregisterSend(streamId);
1129
1162
  },
1130
1163
  abort(reason) {
1131
- session.resetStream(streamId, errorCode(reason));
1132
- session.unregisterSend(streamId);
1164
+ abortNative(reason);
1133
1165
  }
1134
1166
  },
1135
1167
  new ByteLengthQueuingStrategy({ highWaterMark: 1024 * 1024 })
@@ -1178,14 +1210,27 @@ var WebTransportBidirectionalStream = class {
1178
1210
  };
1179
1211
 
1180
1212
  // src/webtransport.ts
1213
+ var MAX_PENDING_INCOMING_STREAMS = 128;
1181
1214
  function toBytes(src) {
1182
1215
  if (src instanceof ArrayBuffer) return new Uint8Array(src);
1183
1216
  return new Uint8Array(src.buffer, src.byteOffset, src.byteLength);
1184
1217
  }
1185
1218
  function buildConfig(url, options) {
1186
- if (typeof url !== "string" || !url.startsWith("https://")) {
1219
+ let parsed;
1220
+ try {
1221
+ parsed = new URL(url);
1222
+ } catch {
1223
+ throw new WebTransportError(`invalid WebTransport URL: ${url}`, { source: "session" });
1224
+ }
1225
+ if (typeof url !== "string" || parsed.protocol !== "https:" || parsed.hash || url.includes("#") || parsed.username || parsed.password) {
1187
1226
  throw new WebTransportError(`invalid WebTransport URL: ${url}`, { source: "session" });
1188
1227
  }
1228
+ const protocols = options.protocols ?? [];
1229
+ if (new Set(protocols).size !== protocols.length || protocols.some((protocol) => !/^[\x20-\x7e]{1,512}$/.test(protocol))) {
1230
+ throw new WebTransportError("protocols must be distinct ASCII strings of 1 to 512 bytes", {
1231
+ source: "session"
1232
+ });
1233
+ }
1189
1234
  const hashes = [];
1190
1235
  for (const hash of options.serverCertificateHashes ?? []) {
1191
1236
  const algorithm = hash.algorithm.toLowerCase();
@@ -1210,13 +1255,13 @@ function buildConfig(url, options) {
1210
1255
  headerValues.push(value);
1211
1256
  }
1212
1257
  return {
1213
- url,
1258
+ url: parsed.href,
1214
1259
  hashes,
1215
1260
  insecure: options.insecure ?? false,
1216
1261
  origin: options.origin ?? null,
1217
1262
  headerNames,
1218
1263
  headerValues,
1219
- protocols: options.protocols ?? []
1264
+ protocols
1220
1265
  };
1221
1266
  }
1222
1267
  var WebTransportSession = class {
@@ -1265,6 +1310,8 @@ var WebTransportSession = class {
1265
1310
  * constructs the two incoming-stream `ReadableStream`s and captures their
1266
1311
  * controllers via the `start` callback. Registers an incoming handler on
1267
1312
  * `core` so each peer-opened bidi/uni stream is wrapped and enqueued;
1313
+ * checks the 128-stream queue limit before allocating each wrapper and
1314
+ * aborts the session on overflow. Cancelled directions stop new peer streams.
1268
1315
  * `enqueue` is wrapped in try/catch because it throws once the consumer has
1269
1316
  * cancelled the reader, and that error must not escape native event dispatch.
1270
1317
  * Finally it observes `core.closed`: on clean close both controllers are
@@ -1276,24 +1323,55 @@ var WebTransportSession = class {
1276
1323
  this.datagrams = new WebTransportDatagramDuplexStream(core);
1277
1324
  let bidiController;
1278
1325
  let uniController;
1279
- this.incomingBidirectionalStreams = new ReadableStream({
1280
- start: (c) => {
1281
- bidiController = c;
1282
- }
1283
- });
1284
- this.incomingUnidirectionalStreams = new ReadableStream({
1285
- start: (c) => {
1286
- uniController = c;
1287
- }
1288
- });
1326
+ let bidiCancelled = false;
1327
+ let uniCancelled = false;
1328
+ this.incomingBidirectionalStreams = new ReadableStream(
1329
+ {
1330
+ start: (c) => {
1331
+ bidiController = c;
1332
+ },
1333
+ cancel: () => {
1334
+ bidiCancelled = true;
1335
+ }
1336
+ },
1337
+ new CountQueuingStrategy({ highWaterMark: MAX_PENDING_INCOMING_STREAMS })
1338
+ );
1339
+ this.incomingUnidirectionalStreams = new ReadableStream(
1340
+ {
1341
+ start: (c) => {
1342
+ uniController = c;
1343
+ },
1344
+ cancel: () => {
1345
+ uniCancelled = true;
1346
+ }
1347
+ },
1348
+ new CountQueuingStrategy({ highWaterMark: MAX_PENDING_INCOMING_STREAMS })
1349
+ );
1289
1350
  core.setIncomingHandler({
1290
1351
  onBidi: (id) => {
1352
+ if (bidiCancelled) {
1353
+ core.stopSending(id, 0);
1354
+ core.resetStream(id, 0);
1355
+ return;
1356
+ }
1357
+ if ((bidiController.desiredSize ?? 0) <= 0) {
1358
+ core.abort("incoming stream queue limit exceeded (bidirectional)");
1359
+ return;
1360
+ }
1291
1361
  try {
1292
1362
  bidiController.enqueue(new WebTransportBidirectionalStream(core, id));
1293
1363
  } catch {
1294
1364
  }
1295
1365
  },
1296
1366
  onUni: (id) => {
1367
+ if (uniCancelled) {
1368
+ core.stopSending(id, 0);
1369
+ return;
1370
+ }
1371
+ if ((uniController.desiredSize ?? 0) <= 0) {
1372
+ core.abort("incoming stream queue limit exceeded (unidirectional)");
1373
+ return;
1374
+ }
1297
1375
  try {
1298
1376
  uniController.enqueue(new WebTransportReceiveStream(core, id));
1299
1377
  } catch {
@@ -1487,6 +1565,7 @@ function safeError(controller, reason) {
1487
1565
  }
1488
1566
 
1489
1567
  // src/server.ts
1568
+ var MAX_PENDING_SESSIONS = 128;
1490
1569
  function deferred2() {
1491
1570
  let resolve;
1492
1571
  let reject;
@@ -1556,6 +1635,7 @@ var WebTransportServer = class {
1556
1635
  boundPort = 0;
1557
1636
  /** Guards {@link close} so shutdown is issued at most once. */
1558
1637
  closeCalled = false;
1638
+ incomingCancelled = false;
1559
1639
  /**
1560
1640
  * The sessions clients open, delivered as they are established. Each pull
1561
1641
  * yields a {@link WebTransportServerSession}. The stream is closed when the
@@ -1581,11 +1661,17 @@ var WebTransportServer = class {
1581
1661
  });
1582
1662
  void this.closedD.promise.catch(() => {
1583
1663
  });
1584
- this.incomingSessions = new ReadableStream({
1585
- start: (c) => {
1586
- this.incomingController = c;
1587
- }
1588
- });
1664
+ this.incomingSessions = new ReadableStream(
1665
+ {
1666
+ start: (c) => {
1667
+ this.incomingController = c;
1668
+ },
1669
+ cancel: () => {
1670
+ this.incomingCancelled = true;
1671
+ }
1672
+ },
1673
+ new CountQueuingStrategy({ highWaterMark: MAX_PENDING_SESSIONS })
1674
+ );
1589
1675
  const responseHeaderNames = [];
1590
1676
  const responseHeaderValues = [];
1591
1677
  for (const [name, value] of Object.entries(options.responseHeaders ?? {})) {
@@ -1674,10 +1760,22 @@ var WebTransportServer = class {
1674
1760
  }
1675
1761
  const sessionId = ev.session;
1676
1762
  if (ev.type === "serverReady" /* ServerReady */) {
1763
+ if (this.closeCalled || this.incomingCancelled || (this.incomingController.desiredSize ?? 0) <= 0) {
1764
+ this.native.serverCloseSession(
1765
+ this.handle,
1766
+ sessionId,
1767
+ 0,
1768
+ new TextEncoder().encode("incoming session queue limit exceeded")
1769
+ );
1770
+ return;
1771
+ }
1677
1772
  const core = new SessionCore();
1678
1773
  core.attach(new ServerTransport(this.native, this.handle, sessionId));
1679
1774
  this.sessions.set(sessionId, core);
1680
- void core.closed.promise.finally(() => this.sessions.delete(sessionId));
1775
+ const forget = () => {
1776
+ this.sessions.delete(sessionId);
1777
+ };
1778
+ void core.closed.promise.then(forget, forget);
1681
1779
  const session = new WebTransportServerSession(core, {
1682
1780
  authority: ev.authority,
1683
1781
  path: ev.path,
@@ -1701,7 +1799,7 @@ var WebTransportServer = class {
1701
1799
  *
1702
1800
  * @remarks Dispatches a synthetic clean `closed` event (code `0`, empty
1703
1801
  * reason, `remote: false`) to each session core, then clears the map. The
1704
- * per-core `closed.finally` handler registered in {@link onEvent} would
1802
+ * per-core `closed.then` handlers registered in {@link onEvent} would
1705
1803
  * also remove entries, but the map is cleared here unconditionally.
1706
1804
  */
1707
1805
  finishAllSessions() {
@@ -1757,4 +1855,4 @@ export {
1757
1855
  //! const wt = new WebTransport('https://example.com:4433/echo');
1758
1856
  //! await wt.ready;
1759
1857
  //! ```
1760
- //# sourceMappingURL=index.mjs.map
1858
+ //# sourceMappingURL=index.mjs.map