rwebtransport 0.1.2 → 0.2.1

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
@@ -1,6 +1,6 @@
1
1
  <div align="center">
2
2
 
3
- # rwebtransport
3
+ # rWebTransport
4
4
 
5
5
  ### WebTransport for Node.js. The real thing.
6
6
 
@@ -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
 
@@ -0,0 +1,82 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ //! Generate a short-lived EC P-256 self-signed certificate for the test suite.
3
+ //!
4
+ //! The WebTransport `serverCertificateHashes` contract requires a pinned leaf to
5
+ //! be currently valid and to span at most 14 days, so the client now enforces
6
+ //! that. A long-lived committed fixture cannot satisfy it, so the test cert is
7
+ //! minted fresh (13-day validity) on every run instead.
8
+ //!
9
+ //! Usage: `gen-test-cert <cert.pem> <key.pem> [days] [keyType]`. `days` defaults
10
+ //! to 13; `keyType` is `ec` (P-256, the default) or `rsa` (used by tests that
11
+ //! assert a non-P-256 pinned cert is rejected).
12
+
13
+ use std::fs;
14
+
15
+ use boring::asn1::Asn1Time;
16
+ use boring::bn::BigNum;
17
+ use boring::ec::{EcGroup, EcKey};
18
+ use boring::hash::MessageDigest;
19
+ use boring::nid::Nid;
20
+ use boring::pkey::PKey;
21
+ use boring::rsa::Rsa;
22
+ use boring::x509::extension::SubjectAlternativeName;
23
+ use boring::x509::{X509NameBuilder, X509};
24
+
25
+ fn main() {
26
+ let mut args = std::env::args().skip(1);
27
+ let (cert_path, key_path) = match (args.next(), args.next()) {
28
+ (Some(c), Some(k)) => (c, k),
29
+ _ => {
30
+ eprintln!("usage: gen-test-cert <cert.pem> <key.pem> [days] [ec|rsa]");
31
+ std::process::exit(2);
32
+ }
33
+ };
34
+ // Validity span in days; 13 keeps within the 14-day pinning ceiling. A larger
35
+ // value is used by tests that assert the client rejects an over-long cert.
36
+ let days: u32 = args.next().and_then(|d| d.parse().ok()).unwrap_or(13);
37
+ let key_type = args.next().unwrap_or_else(|| "ec".to_string());
38
+
39
+ let pkey = if key_type == "rsa" {
40
+ let rsa = Rsa::generate(2048).expect("generate RSA key");
41
+ PKey::from_rsa(rsa).expect("wrap RSA key")
42
+ } else {
43
+ let group = EcGroup::from_curve_name(Nid::X9_62_PRIME256V1).expect("P-256 group");
44
+ let ec = EcKey::generate(&group).expect("generate EC key");
45
+ PKey::from_ec_key(ec).expect("wrap EC key")
46
+ };
47
+
48
+ let mut name = X509NameBuilder::new().expect("name builder");
49
+ name.append_entry_by_text("CN", "localhost").expect("CN");
50
+ let name = name.build();
51
+
52
+ let mut b = X509::builder().expect("x509 builder");
53
+ b.set_version(2).expect("v3"); // X.509 v3 (0-indexed)
54
+
55
+ let serial = BigNum::from_u32(1)
56
+ .and_then(|n| n.to_asn1_integer())
57
+ .expect("serial");
58
+ b.set_serial_number(&serial).expect("serial");
59
+
60
+ b.set_subject_name(&name).expect("subject");
61
+ b.set_issuer_name(&name).expect("issuer");
62
+ b.set_pubkey(&pkey).expect("pubkey");
63
+
64
+ let not_before = Asn1Time::days_from_now(0).expect("not_before");
65
+ let not_after = Asn1Time::days_from_now(days).expect("not_after");
66
+ b.set_not_before(&not_before).expect("set not_before");
67
+ b.set_not_after(&not_after).expect("set not_after");
68
+
69
+ let san = SubjectAlternativeName::new()
70
+ .dns("localhost")
71
+ .ip("127.0.0.1")
72
+ .ip("::1")
73
+ .build(&b.x509v3_context(None, None))
74
+ .expect("SAN");
75
+ b.append_extension(san).expect("append SAN");
76
+
77
+ b.sign(&pkey, MessageDigest::sha256()).expect("sign");
78
+ let cert = b.build();
79
+
80
+ fs::write(&cert_path, cert.to_pem().expect("cert pem")).expect("write cert");
81
+ fs::write(&key_path, pkey.private_key_to_pem_pkcs8().expect("key pem")).expect("write key");
82
+ }
@@ -1,11 +1,11 @@
1
1
  // SPDX-License-Identifier: Apache-2.0
2
- //! WebTransport **echo** server — a test fixture for the rwebtransport client.
2
+ //! WebTransport **echo** server: a test fixture for the rwebtransport client.
3
3
  //!
4
4
  //! It speaks real QUIC/HTTP-3/WebTransport (Cloudflare quiche + BoringSSL,
5
5
  //! server role) and echoes everything a client sends:
6
- //! * bidirectional streams — bytes are written straight back on the same stream;
7
- //! * unidirectional streams — the server opens a matching uni stream and echoes;
8
- //! * datagrams — sent back verbatim.
6
+ //! * bidirectional streams: bytes are written straight back on the same stream;
7
+ //! * unidirectional streams: the server opens a matching uni stream and echoes;
8
+ //! * datagrams: sent back verbatim.
9
9
  //!
10
10
  //! Usage: `wt-echo-server --cert <pem> --key <pem> [--host 127.0.0.1] [--port 0]`.
11
11
  //! On startup it prints two machine-readable lines to stdout:
@@ -56,10 +56,10 @@ const CONNECT_ID: u64 = 0;
56
56
  #[derive(Clone, Copy, PartialEq, Eq)]
57
57
  enum Role {
58
58
  LocalControlPlane,
59
- PeerControlPlane, // client control/qpack uni streams — drain
59
+ PeerControlPlane, // client control/qpack uni streams (drain)
60
60
  Connect, // client CONNECT bidi (id 0)
61
- WtBidi, // client bidi WT stream — echo on the same stream
62
- WtUniIn, // client uni WT stream — echo via a new server uni stream
61
+ WtBidi, // client bidi WT stream: echo on the same stream
62
+ WtUniIn, // client uni WT stream: echo via a new server uni stream
63
63
  PendingUni, // client uni, type varint not yet read
64
64
  Ignored,
65
65
  }
@@ -65,7 +65,7 @@ pub fn build_config(p: &ClientConfigParams) -> Result<quiche::Config, String> {
65
65
  }
66
66
  CertVerification::Hashes(_) | CertVerification::Insecure => {
67
67
  // Verification is fully handled on the SSL context (custom callback /
68
- // NONE). Do NOT call verify_peer here — it would install quiche's own
68
+ // NONE). Do NOT call verify_peer here: it would install quiche's own
69
69
  // None-callback over ours.
70
70
  }
71
71
  }
@@ -7,7 +7,6 @@ use std::net::{SocketAddr, ToSocketAddrs};
7
7
  use std::sync::atomic::{AtomicBool, AtomicI64, AtomicUsize, Ordering};
8
8
  use std::sync::mpsc::Receiver;
9
9
  use std::sync::Arc;
10
- use std::time::Instant;
11
10
 
12
11
  use mio::net::UdpSocket;
13
12
  use mio::{Events, Poll, Token};
@@ -73,6 +72,20 @@ pub enum Command {
73
72
  code: u32,
74
73
  reason: Vec<u8>,
75
74
  },
75
+ /// Send a DRAIN_WEBTRANSPORT_SESSION capsule to the peer.
76
+ Drain,
77
+ /// Snapshot connection stats; the result arrives as a `stats` event.
78
+ GetStats {
79
+ request_id: u64,
80
+ },
81
+ /// Export TLS keying material (RFC 5705); the result arrives as a
82
+ /// `keyingMaterial` event.
83
+ ExportKeyingMaterial {
84
+ request_id: u64,
85
+ label: Vec<u8>,
86
+ context: Vec<u8>,
87
+ length: u32,
88
+ },
76
89
  /// Tear the driver down (the JS handle was closed/GC'd).
77
90
  Shutdown,
78
91
  }
@@ -95,6 +108,8 @@ pub struct SessionSetup {
95
108
  pub path: String,
96
109
  pub origin: Option<String>,
97
110
  pub extra_headers: Vec<(String, String)>,
111
+ /// WebTransport subprotocols the client offers (preference order).
112
+ pub protocols: Vec<String>,
98
113
  pub config: ClientConfigParams,
99
114
  }
100
115
 
@@ -165,7 +180,7 @@ fn setup_and_run(
165
180
  sink: &dyn EventSink,
166
181
  shared: &Arc<DriverShared>,
167
182
  ) {
168
- // DNS resolution — potentially blocking, so it runs here (driver thread),
183
+ // DNS resolution, potentially blocking, so it runs here (driver thread),
169
184
  // never on the JS event loop.
170
185
  let peer = match (setup.host.as_str(), setup.port)
171
186
  .to_socket_addrs()
@@ -226,13 +241,14 @@ fn setup_and_run(
226
241
  setup.path,
227
242
  setup.origin,
228
243
  setup.extra_headers,
244
+ setup.protocols,
229
245
  );
230
246
 
231
247
  run_inner(poll, socket, local_addr, conn, session, rx, sink, shared);
232
248
  }
233
249
 
234
250
  /// The actual event loop. Runs until the connection closes or a fatal error
235
- /// occurs. Never call this directly from the spawned thread — go through
251
+ /// occurs. Never call this directly from the spawned thread; go through
236
252
  /// [`run`], which contains the panic boundary.
237
253
  #[allow(clippy::too_many_arguments)]
238
254
  fn run_inner(
@@ -340,6 +356,18 @@ fn run_inner(
340
356
  session.send_datagram(&mut conn, &data, request_id, &mut evs)
341
357
  }
342
358
  Command::Close { code, reason } => session.close(code, reason),
359
+ Command::Drain => session.send_drain(),
360
+ Command::GetStats { request_id } => {
361
+ evs.push(crate::session::build_stats(&conn, request_id))
362
+ }
363
+ Command::ExportKeyingMaterial {
364
+ request_id,
365
+ label,
366
+ context,
367
+ length,
368
+ } => evs.push(crate::session::build_keying_material(
369
+ &mut conn, request_id, &label, &context, length,
370
+ )),
343
371
  Command::Shutdown => {
344
372
  shutdown = true;
345
373
  break;
@@ -368,7 +396,7 @@ fn run_inner(
368
396
  conn.application_proto()
369
397
  );
370
398
  }
371
- session.on_established(&mut evs);
399
+ session.on_established();
372
400
  }
373
401
 
374
402
  // Backpressure: if the JS thread is behind on processing events, stop
@@ -402,8 +430,18 @@ fn run_inner(
402
430
  // 6. Terminal state?
403
431
  if conn.is_closed() {
404
432
  if !session.is_closed() {
405
- let (code, reason, remote) = closure_info(&conn);
406
- session.mark_closed(&mut evs, code, reason, remote);
433
+ if let Some((code, reason)) = session.local_close_info() {
434
+ // We initiated a graceful WebTransport close: surface the WT
435
+ // code/reason (the wire close used H3_NO_ERROR), a clean local
436
+ // close, not an error.
437
+ session.mark_closed(&mut evs, code, reason, false);
438
+ } else {
439
+ let (code, reason, remote, err) = closure_info(&conn);
440
+ if let Some(msg) = err {
441
+ evs.push(Ev::Error(msg));
442
+ }
443
+ session.mark_closed(&mut evs, code, reason, remote);
444
+ }
407
445
  }
408
446
  shared.closed.store(true, Ordering::Relaxed);
409
447
  if !evs.is_empty() {
@@ -449,15 +487,55 @@ fn flush_send(conn: &mut quiche::Connection, socket: &UdpSocket, out: &mut [u8],
449
487
  }
450
488
  }
451
489
 
452
- /// Extract a close code/reason from a terminated connection.
453
- fn closure_info(conn: &quiche::Connection) -> (u32, Vec<u8>, bool) {
490
+ /// Extract a close code/reason from a terminated connection. The fourth element
491
+ /// is `Some(message)` when the termination was an abnormal transport-level event
492
+ /// (idle timeout, a transport CONNECTION_CLOSE with `is_app == false`, or a
493
+ /// stateless reset) rather than a clean WebTransport/HTTP-3 close; the driver
494
+ /// emits an `Ev::Error` for it so the JS `closed` promise rejects. A clean
495
+ /// application close keeps its WebTransport code/reason and returns `None`.
496
+ fn closure_info(conn: &quiche::Connection) -> (u32, Vec<u8>, bool, Option<String>) {
454
497
  if let Some(err) = conn.peer_error() {
455
- return (err.error_code as u32, err.reason.clone(), true);
498
+ if err.is_app {
499
+ return (err.error_code as u32, err.reason.clone(), true, None);
500
+ }
501
+ return (
502
+ 0,
503
+ Vec::new(),
504
+ true,
505
+ Some(format!(
506
+ "connection terminated by peer transport error {:#x}",
507
+ err.error_code
508
+ )),
509
+ );
456
510
  }
457
511
  if let Some(err) = conn.local_error() {
458
- return (err.error_code as u32, err.reason.clone(), false);
512
+ if err.is_app {
513
+ return (err.error_code as u32, err.reason.clone(), false, None);
514
+ }
515
+ return (
516
+ 0,
517
+ Vec::new(),
518
+ false,
519
+ Some(format!(
520
+ "connection closed by transport error {:#x}",
521
+ err.error_code
522
+ )),
523
+ );
524
+ }
525
+ if conn.is_timed_out() {
526
+ return (
527
+ 0,
528
+ Vec::new(),
529
+ false,
530
+ Some("connection timed out".to_string()),
531
+ );
459
532
  }
460
- // Idle timeout / no explicit error.
461
- let _ = Instant::now();
462
- (0, Vec::new(), true)
533
+ // No explicit error and not a timeout (for example a stateless reset): still
534
+ // an abnormal loss of the connection.
535
+ (
536
+ 0,
537
+ Vec::new(),
538
+ true,
539
+ Some("connection closed abnormally".to_string()),
540
+ )
463
541
  }
@@ -7,7 +7,7 @@
7
7
  //! layered on top in TypeScript. See the JS↔native contract below.
8
8
  //!
9
9
  //! ## JS-visible functions
10
- //! * `connect(url, hashes[], insecure, origin|null, hdrNames[], hdrVals[], onEvent) -> handle`
10
+ //! * `connect(url, hashes[], insecure, origin|null, hdrNames[], hdrVals[], protocols[], onEvent) -> handle`
11
11
  //! * `openStream(handle, bidi, requestId)`
12
12
  //! * `writeStream(handle, streamId, bytes, requestId)`
13
13
  //! * `finStream(handle, streamId)`
@@ -220,7 +220,8 @@ fn connect(mut cx: FunctionContext) -> JsResult<JsBox<SessionHandle>> {
220
220
  };
221
221
  let names_arr = cx.argument::<JsArray>(4)?;
222
222
  let vals_arr = cx.argument::<JsArray>(5)?;
223
- let callback = cx.argument::<JsFunction>(6)?;
223
+ let protocols_arr = cx.argument::<JsArray>(6)?;
224
+ let callback = cx.argument::<JsFunction>(7)?;
224
225
 
225
226
  // Certificate hashes.
226
227
  let mut hashes: Vec<[u8; 32]> = Vec::new();
@@ -246,6 +247,17 @@ fn connect(mut cx: FunctionContext) -> JsResult<JsBox<SessionHandle>> {
246
247
  extra_headers.push((k, v));
247
248
  }
248
249
 
250
+ // Offered WebTransport subprotocols.
251
+ let mut protocols: Vec<String> = Vec::new();
252
+ let plen = protocols_arr.len(&mut cx);
253
+ for i in 0..plen {
254
+ protocols.push(
255
+ protocols_arr
256
+ .get::<JsString, _, _>(&mut cx, i)?
257
+ .value(&mut cx),
258
+ );
259
+ }
260
+
249
261
  let parsed = match parse_url(&url) {
250
262
  Ok(p) => p,
251
263
  Err(e) => return cx.throw_error(e),
@@ -292,6 +304,7 @@ fn connect(mut cx: FunctionContext) -> JsResult<JsBox<SessionHandle>> {
292
304
  path: parsed.path,
293
305
  origin,
294
306
  extra_headers,
307
+ protocols,
295
308
  config: params,
296
309
  };
297
310
 
@@ -397,6 +410,34 @@ fn close_session(mut cx: FunctionContext) -> JsResult<JsUndefined> {
397
410
  Ok(cx.undefined())
398
411
  }
399
412
 
413
+ fn drain(mut cx: FunctionContext) -> JsResult<JsUndefined> {
414
+ let handle = cx.argument::<JsBox<SessionHandle>>(0)?;
415
+ handle.send(Command::Drain);
416
+ Ok(cx.undefined())
417
+ }
418
+
419
+ fn get_stats(mut cx: FunctionContext) -> JsResult<JsUndefined> {
420
+ let handle = cx.argument::<JsBox<SessionHandle>>(0)?;
421
+ let request_id = to_request_id(cx.argument::<JsNumber>(1)?.value(&mut cx));
422
+ handle.send(Command::GetStats { request_id });
423
+ Ok(cx.undefined())
424
+ }
425
+
426
+ fn export_keying_material(mut cx: FunctionContext) -> JsResult<JsUndefined> {
427
+ let handle = cx.argument::<JsBox<SessionHandle>>(0)?;
428
+ let request_id = to_request_id(cx.argument::<JsNumber>(1)?.value(&mut cx));
429
+ let label = cx.argument::<JsTypedArray<u8>>(2)?.as_slice(&cx).to_vec();
430
+ let context = cx.argument::<JsTypedArray<u8>>(3)?.as_slice(&cx).to_vec();
431
+ let length = cx.argument::<JsNumber>(4)?.value(&mut cx) as u32;
432
+ handle.send(Command::ExportKeyingMaterial {
433
+ request_id,
434
+ label,
435
+ context,
436
+ length,
437
+ });
438
+ Ok(cx.undefined())
439
+ }
440
+
400
441
  fn shutdown(mut cx: FunctionContext) -> JsResult<JsUndefined> {
401
442
  let handle = cx.argument::<JsBox<SessionHandle>>(0)?;
402
443
  handle.send(Command::Shutdown);
@@ -476,7 +517,42 @@ fn server_listen(mut cx: FunctionContext) -> JsResult<JsBox<ServerHandle>> {
476
517
  let host = cx.argument::<JsString>(2)?.value(&mut cx);
477
518
  let port = cx.argument::<JsNumber>(3)?.value(&mut cx) as u16;
478
519
  let reuse_port = cx.argument::<JsBoolean>(4)?.value(&mut cx);
479
- let callback = cx.argument::<JsFunction>(5)?;
520
+ let supported_arr = cx.argument::<JsArray>(5)?;
521
+ let origins_val = cx.argument::<JsValue>(6)?;
522
+ let resp_names = cx.argument::<JsArray>(7)?;
523
+ let resp_vals = cx.argument::<JsArray>(8)?;
524
+ let callback = cx.argument::<JsFunction>(9)?;
525
+
526
+ let mut supported_protocols: Vec<String> = Vec::new();
527
+ let slen = supported_arr.len(&mut cx);
528
+ for i in 0..slen {
529
+ supported_protocols.push(
530
+ supported_arr
531
+ .get::<JsString, _, _>(&mut cx, i)?
532
+ .value(&mut cx),
533
+ );
534
+ }
535
+
536
+ // `allowedOrigins` is an array (allowlist) or null (allow any).
537
+ let allowed_origins: Option<Vec<String>> = if origins_val.is_a::<JsArray, _>(&mut cx) {
538
+ let arr = origins_val.downcast_or_throw::<JsArray, _>(&mut cx)?;
539
+ let olen = arr.len(&mut cx);
540
+ let mut v = Vec::with_capacity(olen as usize);
541
+ for i in 0..olen {
542
+ v.push(arr.get::<JsString, _, _>(&mut cx, i)?.value(&mut cx));
543
+ }
544
+ Some(v)
545
+ } else {
546
+ None
547
+ };
548
+
549
+ let mut response_headers: Vec<(String, String)> = Vec::new();
550
+ let rlen = resp_names.len(&mut cx).min(resp_vals.len(&mut cx));
551
+ for i in 0..rlen {
552
+ let k = resp_names.get::<JsString, _, _>(&mut cx, i)?.value(&mut cx);
553
+ let v = resp_vals.get::<JsString, _, _>(&mut cx, i)?.value(&mut cx);
554
+ response_headers.push((k, v));
555
+ }
480
556
 
481
557
  let poll = match mio::Poll::new() {
482
558
  Ok(p) => p,
@@ -501,6 +577,9 @@ fn server_listen(mut cx: FunctionContext) -> JsResult<JsBox<ServerHandle>> {
501
577
  cert_path,
502
578
  key_path,
503
579
  reuse_port,
580
+ supported_protocols,
581
+ allowed_origins,
582
+ response_headers,
504
583
  };
505
584
 
506
585
  let shared_for_thread = shared.clone();
@@ -620,6 +699,41 @@ fn server_close_session(mut cx: FunctionContext) -> JsResult<JsUndefined> {
620
699
  Ok(cx.undefined())
621
700
  }
622
701
 
702
+ fn server_drain(mut cx: FunctionContext) -> JsResult<JsUndefined> {
703
+ let handle = cx.argument::<JsBox<ServerHandle>>(0)?;
704
+ let session = to_stream_id(cx.argument::<JsNumber>(1)?.value(&mut cx));
705
+ handle.send(ServerCommand::Drain { session });
706
+ Ok(cx.undefined())
707
+ }
708
+
709
+ fn server_get_stats(mut cx: FunctionContext) -> JsResult<JsUndefined> {
710
+ let handle = cx.argument::<JsBox<ServerHandle>>(0)?;
711
+ let session = to_stream_id(cx.argument::<JsNumber>(1)?.value(&mut cx));
712
+ let request_id = to_request_id(cx.argument::<JsNumber>(2)?.value(&mut cx));
713
+ handle.send(ServerCommand::GetStats {
714
+ session,
715
+ request_id,
716
+ });
717
+ Ok(cx.undefined())
718
+ }
719
+
720
+ fn server_export_keying_material(mut cx: FunctionContext) -> JsResult<JsUndefined> {
721
+ let handle = cx.argument::<JsBox<ServerHandle>>(0)?;
722
+ let session = to_stream_id(cx.argument::<JsNumber>(1)?.value(&mut cx));
723
+ let request_id = to_request_id(cx.argument::<JsNumber>(2)?.value(&mut cx));
724
+ let label = cx.argument::<JsTypedArray<u8>>(3)?.as_slice(&cx).to_vec();
725
+ let context = cx.argument::<JsTypedArray<u8>>(4)?.as_slice(&cx).to_vec();
726
+ let length = cx.argument::<JsNumber>(5)?.value(&mut cx) as u32;
727
+ handle.send(ServerCommand::ExportKeyingMaterial {
728
+ session,
729
+ request_id,
730
+ label,
731
+ context,
732
+ length,
733
+ });
734
+ Ok(cx.undefined())
735
+ }
736
+
623
737
  fn server_shutdown(mut cx: FunctionContext) -> JsResult<JsUndefined> {
624
738
  let handle = cx.argument::<JsBox<ServerHandle>>(0)?;
625
739
  handle.send(ServerCommand::Shutdown);
@@ -656,14 +770,60 @@ fn server_msg_to_js<'a>(cx: &mut TaskContext<'a>, msg: &ServerMsg) -> JsResult<'
656
770
  fn ev_to_js<'a>(cx: &mut TaskContext<'a>, ev: &Ev) -> JsResult<'a, JsObject> {
657
771
  let obj = cx.empty_object();
658
772
  match ev {
659
- Ev::Ready => {
773
+ Ev::Ready { protocol, headers } => {
660
774
  set_str(cx, &obj, "type", "ready")?;
775
+ match protocol {
776
+ Some(p) => set_str(cx, &obj, "protocol", p)?,
777
+ None => {
778
+ let n = cx.null();
779
+ obj.set(cx, "protocol", n)?;
780
+ }
781
+ }
782
+ // Ordered [name, value] pairs so the TS layer can build a Headers
783
+ // without collapsing duplicate header names.
784
+ let arr = cx.empty_array();
785
+ for (i, (k, v)) in headers.iter().enumerate() {
786
+ let pair = cx.empty_array();
787
+ let kn = cx.string(k);
788
+ let vn = cx.string(v);
789
+ pair.set(cx, 0, kn)?;
790
+ pair.set(cx, 1, vn)?;
791
+ arr.set(cx, i as u32, pair)?;
792
+ }
793
+ obj.set(cx, "responseHeaders", arr)?;
794
+ }
795
+ Ev::Draining => {
796
+ set_str(cx, &obj, "type", "draining")?;
797
+ }
798
+ Ev::Stats {
799
+ request_id,
800
+ bytes_sent,
801
+ bytes_received,
802
+ packets_sent,
803
+ packets_received,
804
+ packets_lost,
805
+ smoothed_rtt_ms,
806
+ rtt_variation_ms,
807
+ min_rtt_ms,
808
+ } => {
809
+ set_str(cx, &obj, "type", "stats")?;
810
+ set_num(cx, &obj, "requestId", *request_id as f64)?;
811
+ set_num(cx, &obj, "bytesSent", *bytes_sent as f64)?;
812
+ set_num(cx, &obj, "bytesReceived", *bytes_received as f64)?;
813
+ set_num(cx, &obj, "packetsSent", *packets_sent as f64)?;
814
+ set_num(cx, &obj, "packetsReceived", *packets_received as f64)?;
815
+ set_num(cx, &obj, "packetsLost", *packets_lost as f64)?;
816
+ set_num(cx, &obj, "smoothedRtt", *smoothed_rtt_ms)?;
817
+ set_num(cx, &obj, "rttVariation", *rtt_variation_ms)?;
818
+ set_num(cx, &obj, "minRtt", *min_rtt_ms)?;
661
819
  }
662
820
  Ev::ServerReady {
663
821
  authority,
664
822
  path,
665
823
  origin,
666
824
  headers,
825
+ requested_protocols,
826
+ protocol,
667
827
  remote_addr,
668
828
  remote_port,
669
829
  } => {
@@ -682,6 +842,19 @@ fn ev_to_js<'a>(cx: &mut TaskContext<'a>, ev: &Ev) -> JsResult<'a, JsObject> {
682
842
  set_str(cx, &hobj, k, v)?;
683
843
  }
684
844
  obj.set(cx, "headers", hobj)?;
845
+ let parr = cx.empty_array();
846
+ for (i, p) in requested_protocols.iter().enumerate() {
847
+ let s = cx.string(p);
848
+ parr.set(cx, i as u32, s)?;
849
+ }
850
+ obj.set(cx, "requestedProtocols", parr)?;
851
+ match protocol {
852
+ Some(p) => set_str(cx, &obj, "protocol", p)?,
853
+ None => {
854
+ let n = cx.null();
855
+ obj.set(cx, "protocol", n)?;
856
+ }
857
+ }
685
858
  set_str(cx, &obj, "remoteAddress", remote_addr)?;
686
859
  set_num(cx, &obj, "remotePort", *remote_port as f64)?;
687
860
  }
@@ -741,6 +914,19 @@ fn ev_to_js<'a>(cx: &mut TaskContext<'a>, ev: &Ev) -> JsResult<'a, JsObject> {
741
914
  set_num(cx, &obj, "requestId", *request_id as f64)?;
742
915
  set_bool(cx, &obj, "sent", *sent)?;
743
916
  }
917
+ Ev::KeyingMaterial { request_id, data } => {
918
+ set_str(cx, &obj, "type", "keyingMaterial")?;
919
+ set_num(cx, &obj, "requestId", *request_id as f64)?;
920
+ match data {
921
+ Some(bytes) => {
922
+ set_bool(cx, &obj, "ok", true)?;
923
+ set_buf(cx, &obj, "data", bytes)?;
924
+ }
925
+ None => {
926
+ set_bool(cx, &obj, "ok", false)?;
927
+ }
928
+ }
929
+ }
744
930
  }
745
931
  Ok(obj)
746
932
  }
@@ -803,6 +989,9 @@ fn main(mut cx: ModuleContext) -> NeonResult<()> {
803
989
  cx.export_function("isReady", is_ready)?;
804
990
  cx.export_function("isClosed", is_closed)?;
805
991
  cx.export_function("closeSession", close_session)?;
992
+ cx.export_function("drain", drain)?;
993
+ cx.export_function("getStats", get_stats)?;
994
+ cx.export_function("exportKeyingMaterial", export_keying_material)?;
806
995
  cx.export_function("shutdown", shutdown)?;
807
996
 
808
997
  // Server surface.
@@ -816,6 +1005,9 @@ fn main(mut cx: ModuleContext) -> NeonResult<()> {
816
1005
  cx.export_function("serverSendDatagram", server_send_datagram)?;
817
1006
  cx.export_function("serverMaxDatagramSize", server_max_datagram_size)?;
818
1007
  cx.export_function("serverCloseSession", server_close_session)?;
1008
+ cx.export_function("serverDrain", server_drain)?;
1009
+ cx.export_function("serverGetStats", server_get_stats)?;
1010
+ cx.export_function("serverExportKeyingMaterial", server_export_keying_material)?;
819
1011
  cx.export_function("serverShutdown", server_shutdown)?;
820
1012
  Ok(())
821
1013
  }