rwebtransport 0.2.0 → 0.2.2

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/README.md CHANGED
@@ -44,6 +44,7 @@
44
44
  4. [Reliable streams and unreliable datagrams](#reliable-streams-and-unreliable-datagrams)
45
45
  5. [The client API](#the-client-api)
46
46
  - [Connecting](#connecting)
47
+ - [Subprotocols, response headers, and keying material](#subprotocols-response-headers-and-keying-material)
47
48
  - [Bidirectional streams](#bidirectional-streams)
48
49
  - [Unidirectional streams](#unidirectional-streams)
49
50
  - [Datagrams](#datagrams)
@@ -307,10 +308,34 @@ await wt.closed; // resolves when the session ends cleanly, rejects on abnormal
307
308
  | `insecure` | `boolean` | Node extension. Disable **all** certificate verification. Development only. |
308
309
  | `headers` | `Record<string, string>` | Node extension. Extra request headers on the Extended CONNECT. |
309
310
  | `origin` | `string` | Node extension. Value for the `Origin` request header. |
311
+ | `protocols` | `string[]` | WebTransport subprotocols to offer, in preference order. Sent in the Extended CONNECT `wt-available-protocols` header; the server's choice is read back via `wt.protocol`. |
310
312
  | `allowPooling`, `requireUnreliable`, `congestionControl` | | Accepted for spec parity; currently informational. |
311
313
 
314
+ A pinned certificate is still validated beyond its fingerprint, matching what browsers enforce: it must be currently valid (now within `notBefore`..`notAfter`), have a total validity period of at most 14 days (`notAfter - notBefore`), and use an ECDSA key on the NIST P-256 (secp256r1) curve. A pinned cert that fails any of these is rejected: the handshake fails and `ready` rejects with a `WebTransportError`.
315
+
312
316
  When neither `serverCertificateHashes` nor `insecure` is set, the client performs full PKI validation against the system trust store with hostname checking.
313
317
 
318
+ ### Subprotocols, response headers, and keying material
319
+
320
+ Once `ready` resolves, a few more W3C session attributes are available:
321
+
322
+ - `wt.protocol` is the subprotocol the server negotiated from the `protocols` you offered, or `''` if none was negotiated.
323
+ - `wt.responseHeaders` is a `Headers` object holding the headers from the server's Extended CONNECT `2xx` response (empty until the session is established).
324
+ - `wt.exportKeyingMaterial(label, context, outputLength)` returns a `Promise<Uint8Array>` of RFC 5705 TLS keying material bound to this session. Both endpoints of the same session derive identical bytes for the same `label`, `context`, and length, and nobody outside the TLS session can, which makes it suitable for channel binding. `label` and `context` are required (`context` may be an empty buffer); the promise rejects if the session is closed or unusable or the TLS export fails (for example before the handshake completes). It is present on both client and server sessions.
325
+
326
+ ```ts
327
+ await wt.ready;
328
+ wt.protocol; // negotiated subprotocol, or '' if none
329
+ wt.responseHeaders; // Headers from the server's Extended CONNECT response
330
+
331
+ // RFC 5705 keying material for channel binding: identical bytes on both ends.
332
+ const keyingMaterial = await wt.exportKeyingMaterial(
333
+ new TextEncoder().encode('rwebtransport channel binding'),
334
+ new Uint8Array(0), // context (may be empty)
335
+ 32, // output length in bytes
336
+ );
337
+ ```
338
+
314
339
  ### Bidirectional streams
315
340
 
316
341
  ```ts
@@ -392,7 +417,9 @@ for (;;) {
392
417
  }
393
418
  ```
394
419
 
395
- `WebTransportServerSession` exposes `ready`, `closed`, `datagrams`, `createBidirectionalStream()`, `createUnidirectionalStream()`, `incomingBidirectionalStreams`, `incomingUnidirectionalStreams`, and `close()`, identical to the client, plus the request metadata (`authority`, `path`, `origin`, `headers`). The server runs on the same quiche engine and inherits the same panic containment and hostile-peer hardening as the client.
420
+ `WebTransportServerSession` exposes `ready`, `closed`, `datagrams`, `createBidirectionalStream()`, `createUnidirectionalStream()`, `incomingBidirectionalStreams`, `incomingUnidirectionalStreams`, `exportKeyingMaterial()`, and `close()`, identical to the client, plus the request metadata (`authority`, `path`, `origin`, `headers`, `requestedProtocols`, and the negotiated `protocol`). The server runs on the same quiche engine and inherits the same panic containment and hostile-peer hardening as the client.
421
+
422
+ `WebTransportServerOptions` also accepts a few negotiation fields alongside `host`, `port`, `cert`, and `key`. `supportedProtocols` lists the subprotocols the server supports, in preference order; for each CONNECT the server selects the first supported protocol the client also offered, echoes it (`wt-protocol`), and exposes it as `session.protocol` (`session.requestedProtocols` holds everything the client offered). `allowedOrigins`, when set, is a built-in origin gate: a CONNECT whose `Origin` header is not in the list is rejected with HTTP 403 before the session is surfaced, so the client's `ready` rejects; when omitted, any origin is accepted and the app can still inspect `session.origin`. `responseHeaders` is a `Record<string, string>` of static extra headers added to every `200` CONNECT response, visible to the client as `wt.responseHeaders`.
396
423
 
397
424
  ---
398
425
 
@@ -23,7 +23,12 @@ pub const WAKE_TOKEN: Token = Token(1);
23
23
  /// server flooding datagrams or stream data cannot grow it without limit (OOM).
24
24
  /// When exceeded, unread stream data stays in quiche (flow-controlling the peer)
25
25
  /// and excess datagrams are dropped by quiche's bounded recv queue.
26
- const MAX_INFLIGHT_BATCHES: i64 = 128;
26
+ ///
27
+ /// `pub` so the neon sinks can wake the driver the moment a batch is dequeued and the counter crosses
28
+ /// back below this cap: back-pressure is set on the driver thread but cleared on the JS thread, so
29
+ /// without that wake the driver would keep withholding data (including a terminal frame) until an
30
+ /// unrelated event happened to run another loop iteration.
31
+ pub const MAX_INFLIGHT_BATCHES: i64 = 128;
27
32
 
28
33
  /// State shared between the driver thread and the JS-facing handle so that
29
34
  /// synchronous property reads (e.g. `datagrams.maxDatagramSize`) don't require a
@@ -76,17 +76,32 @@ impl Finalize for SessionHandle {
76
76
  }
77
77
  }
78
78
 
79
+ /// Decrement the in-flight batch counter once the JS thread has dequeued (or failed to schedule) a
80
+ /// batch, and WAKE the driver when this decrement crosses back below the cap. Back-pressure
81
+ /// ([`driver::MAX_INFLIGHT_BATCHES`]) is set on the driver thread but cleared here on the JS thread, so
82
+ /// without this wake the driver would keep withholding stream data (a completed stream's terminal
83
+ /// bytes stranded in quiche, its JS consumer hung) until some unrelated event happened to run another
84
+ /// driver iteration. `fetch_sub` returns the PREVIOUS value, so `== cap` is exactly the crossing.
85
+ fn release_inflight_batch(shared: &DriverShared, waker: &mio::Waker) {
86
+ if shared.inflight.fetch_sub(1, Ordering::Relaxed) == driver::MAX_INFLIGHT_BATCHES {
87
+ let _ = waker.wake();
88
+ }
89
+ }
90
+
79
91
  /// Bridges driver events onto the JS event loop.
80
92
  struct NeonSink {
81
93
  channel: Channel,
82
94
  callback: Arc<Root<JsFunction>>,
83
95
  shared: Arc<DriverShared>,
96
+ /// Wakes the driver thread when a dequeued batch clears back-pressure (see `release_inflight_batch`).
97
+ waker: Arc<mio::Waker>,
84
98
  }
85
99
 
86
100
  impl EventSink for NeonSink {
87
101
  fn emit(&self, events: Vec<Ev>) {
88
102
  let cb = self.callback.clone();
89
103
  let shared = self.shared.clone();
104
+ let waker = self.waker.clone();
90
105
  // Count this batch as in flight to the JS loop; the driver reads this to
91
106
  // back off from pulling more data out of quiche when JS falls behind.
92
107
  self.shared.inflight.fetch_add(1, Ordering::Relaxed);
@@ -96,8 +111,9 @@ impl EventSink for NeonSink {
96
111
  // behaviour that aborts the process on some platforms). Failing the emit
97
112
  // silently is the correct behaviour during teardown.
98
113
  let result = self.channel.try_send(move |mut cx| {
99
- // Dequeued by the JS loop: no longer contributing to queue depth.
100
- shared.inflight.fetch_sub(1, Ordering::Relaxed);
114
+ // Dequeued by the JS loop: no longer contributing to queue depth. Wake
115
+ // the driver if this cleared back-pressure so it re-drains withheld data.
116
+ release_inflight_batch(&shared, &waker);
101
117
  let f = cb.to_inner(&mut cx);
102
118
  for ev in &events {
103
119
  let obj = ev_to_js(&mut cx, ev)?;
@@ -109,7 +125,7 @@ impl EventSink for NeonSink {
109
125
  });
110
126
  if result.is_err() {
111
127
  // The callback will never run, so undo the in-flight increment here.
112
- self.shared.inflight.fetch_sub(1, Ordering::Relaxed);
128
+ release_inflight_batch(&self.shared, &self.waker);
113
129
  }
114
130
  }
115
131
  }
@@ -294,6 +310,7 @@ fn connect(mut cx: FunctionContext) -> JsResult<JsBox<SessionHandle>> {
294
310
  channel: cx.channel(),
295
311
  callback: Arc::new(callback.root(&mut cx)),
296
312
  shared: shared.clone(),
313
+ waker: waker.clone(),
297
314
  });
298
315
 
299
316
  let setup = driver::SessionSetup {
@@ -483,19 +500,23 @@ struct NeonServerSink {
483
500
  channel: Channel,
484
501
  callback: Arc<Root<JsFunction>>,
485
502
  shared: Arc<DriverShared>,
503
+ /// Wakes the server driver when a dequeued batch clears back-pressure (see `release_inflight_batch`).
504
+ waker: Arc<mio::Waker>,
486
505
  }
487
506
 
488
507
  impl ServerEventSink for NeonServerSink {
489
508
  fn emit(&self, messages: Vec<ServerMsg>) {
490
509
  let cb = self.callback.clone();
491
510
  let shared = self.shared.clone();
511
+ let waker = self.waker.clone();
492
512
  // Balance every emit (setup, teardown, and per-loop batches) so the
493
513
  // backpressure counter can never underflow and silently disable itself.
494
514
  self.shared.inflight.fetch_add(1, Ordering::Relaxed);
495
515
  // `try_send`, not `send`: see NeonSink::emit. `send` would panic across
496
516
  // the N-API boundary if the environment is shutting down.
497
517
  let result = self.channel.try_send(move |mut cx| {
498
- shared.inflight.fetch_sub(1, Ordering::Relaxed);
518
+ // Dequeued: decrement and, if this cleared back-pressure, wake the driver.
519
+ release_inflight_batch(&shared, &waker);
499
520
  let f = cb.to_inner(&mut cx);
500
521
  for msg in &messages {
501
522
  let obj = server_msg_to_js(&mut cx, msg)?;
@@ -506,7 +527,7 @@ impl ServerEventSink for NeonServerSink {
506
527
  Ok(())
507
528
  });
508
529
  if result.is_err() {
509
- self.shared.inflight.fetch_sub(1, Ordering::Relaxed);
530
+ release_inflight_batch(&self.shared, &self.waker);
510
531
  }
511
532
  }
512
533
  }
@@ -569,6 +590,7 @@ fn server_listen(mut cx: FunctionContext) -> JsResult<JsBox<ServerHandle>> {
569
590
  channel: cx.channel(),
570
591
  callback: Arc::new(callback.root(&mut cx)),
571
592
  shared: shared.clone(),
593
+ waker: waker.clone(),
572
594
  });
573
595
 
574
596
  let setup = ServerSetup {
@@ -1011,3 +1033,44 @@ fn main(mut cx: ModuleContext) -> NeonResult<()> {
1011
1033
  cx.export_function("serverShutdown", server_shutdown)?;
1012
1034
  Ok(())
1013
1035
  }
1036
+
1037
+ #[cfg(test)]
1038
+ mod tests {
1039
+ use super::*;
1040
+
1041
+ fn shared_with_inflight(n: i64) -> Arc<DriverShared> {
1042
+ let shared = Arc::new(DriverShared::default());
1043
+ shared.inflight.store(n, Ordering::Relaxed);
1044
+ shared
1045
+ }
1046
+
1047
+ /// Whether the driver's waker fired: poll with a zero timeout and look for `WAKE_TOKEN`.
1048
+ fn waker_fired(poll: &mut mio::Poll) -> bool {
1049
+ let mut events = mio::Events::with_capacity(4);
1050
+ poll.poll(&mut events, Some(std::time::Duration::from_millis(0)))
1051
+ .expect("poll");
1052
+ events.iter().any(|e| e.token() == driver::WAKE_TOKEN)
1053
+ }
1054
+
1055
+ // Back-pressure is set on the driver thread but cleared here on the JS thread, so releasing a batch
1056
+ // must wake the driver EXACTLY when the decrement crosses back below the cap: not while still at or
1057
+ // above it (still back-pressured), and not when already below it (a spurious wake). Getting this
1058
+ // wrong is the stranded-terminal-frame hang.
1059
+ #[test]
1060
+ fn release_wakes_only_when_the_decrement_clears_backpressure() {
1061
+ let mut poll = mio::Poll::new().expect("poll");
1062
+ let waker = mio::Waker::new(poll.registry(), driver::WAKE_TOKEN).expect("waker");
1063
+
1064
+ // Already below the cap: not back-pressured, so no wake.
1065
+ release_inflight_batch(&shared_with_inflight(driver::MAX_INFLIGHT_BATCHES - 1), &waker);
1066
+ assert!(!waker_fired(&mut poll), "no wake when already below the cap");
1067
+
1068
+ // Still at/above the cap after the decrement: still back-pressured, so no wake.
1069
+ release_inflight_batch(&shared_with_inflight(driver::MAX_INFLIGHT_BATCHES + 1), &waker);
1070
+ assert!(!waker_fired(&mut poll), "no wake while still at or above the cap");
1071
+
1072
+ // Exactly at the cap: the decrement crosses below it, clearing back-pressure -> wake.
1073
+ release_inflight_batch(&shared_with_inflight(driver::MAX_INFLIGHT_BATCHES), &waker);
1074
+ assert!(waker_fired(&mut poll), "wake exactly when back-pressure clears");
1075
+ }
1076
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "rwebtransport",
3
- "version": "0.2.0",
3
+ "version": "0.2.2",
4
4
  "description": "A fully-compatible WebTransport client and server for Node.js, powered by Cloudflare quiche + BoringSSL via neon.",
5
5
  "author": "Dacely Cloud",
6
6
  "homepage": "https://github.com/dacely-cloud/rwebtransport#readme",