rwebtransport 0.1.0 → 0.1.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.
Files changed (113) hide show
  1. package/Cargo.lock +666 -666
  2. package/Cargo.toml +31 -31
  3. package/LICENSE +202 -202
  4. package/NOTICE +41 -41
  5. package/README.md +550 -550
  6. package/crates/echo-server/Cargo.toml +20 -20
  7. package/crates/echo-server/src/main.rs +666 -666
  8. package/crates/native/Cargo.toml +23 -23
  9. package/crates/native/src/config.rs +129 -129
  10. package/crates/native/src/driver.rs +463 -463
  11. package/crates/native/src/lib.rs +821 -821
  12. package/crates/native/src/server.rs +718 -718
  13. package/crates/native/src/session.rs +1191 -1191
  14. package/crates/native/src/tls.rs +96 -96
  15. package/crates/wtcore/Cargo.toml +15 -15
  16. package/crates/wtcore/src/h3.rs +226 -226
  17. package/crates/wtcore/src/lib.rs +9 -9
  18. package/dist/index.js.map +1 -1
  19. package/dist/index.mjs.map +1 -1
  20. package/package.json +80 -79
  21. package/prebuilds/darwin-arm64/rwebtransport.node +0 -0
  22. package/prebuilds/linux-arm64/rwebtransport.node +0 -0
  23. package/prebuilds/linux-x64/rwebtransport.node +0 -0
  24. package/prebuilds/win32-x64/rwebtransport.node +0 -0
  25. package/scripts/bench.mjs +180 -180
  26. package/scripts/build.js +67 -67
  27. package/scripts/postinstall.js +67 -67
  28. package/scripts/setup-unix.sh +129 -129
  29. package/scripts/setup-windows.ps1 +229 -229
  30. package/vendor/quiche/AGENTS.md +75 -75
  31. package/vendor/quiche/COPYING +23 -23
  32. package/vendor/quiche/Cargo.lock +1212 -1212
  33. package/vendor/quiche/Cargo.toml +215 -215
  34. package/vendor/quiche/README.md +466 -466
  35. package/vendor/quiche/examples/Makefile +46 -46
  36. package/vendor/quiche/examples/README.md +20 -20
  37. package/vendor/quiche/examples/cert-big.crt +90 -90
  38. package/vendor/quiche/examples/cert.crt +18 -18
  39. package/vendor/quiche/examples/cert.key +28 -28
  40. package/vendor/quiche/examples/client.c +343 -343
  41. package/vendor/quiche/examples/client.rs +281 -281
  42. package/vendor/quiche/examples/gen-certs.sh +15 -15
  43. package/vendor/quiche/examples/http3-client.c +473 -473
  44. package/vendor/quiche/examples/http3-client.rs +349 -349
  45. package/vendor/quiche/examples/http3-server.c +614 -614
  46. package/vendor/quiche/examples/http3-server.rs +680 -680
  47. package/vendor/quiche/examples/qpack-decode.rs +87 -87
  48. package/vendor/quiche/examples/qpack-encode.rs +88 -88
  49. package/vendor/quiche/examples/rootca.crt +21 -21
  50. package/vendor/quiche/examples/server.c +529 -529
  51. package/vendor/quiche/examples/server.rs +529 -529
  52. package/vendor/quiche/include/quiche.h +1282 -1282
  53. package/vendor/quiche/src/buffers.rs +105 -105
  54. package/vendor/quiche/src/build.rs +66 -66
  55. package/vendor/quiche/src/cid.rs +1079 -1079
  56. package/vendor/quiche/src/crypto/boringssl.rs +373 -373
  57. package/vendor/quiche/src/crypto/mod.rs +671 -671
  58. package/vendor/quiche/src/dgram.rs +118 -118
  59. package/vendor/quiche/src/error.rs +263 -263
  60. package/vendor/quiche/src/ffi.rs +2290 -2290
  61. package/vendor/quiche/src/flowcontrol.rs +246 -246
  62. package/vendor/quiche/src/frame.rs +2172 -2172
  63. package/vendor/quiche/src/h3/AGENTS.md +54 -54
  64. package/vendor/quiche/src/h3/ffi.rs +442 -442
  65. package/vendor/quiche/src/h3/frame.rs +1404 -1404
  66. package/vendor/quiche/src/h3/mod.rs +8223 -8223
  67. package/vendor/quiche/src/h3/qpack/decoder.rs +288 -288
  68. package/vendor/quiche/src/h3/qpack/encoder.rs +235 -235
  69. package/vendor/quiche/src/h3/qpack/mod.rs +202 -202
  70. package/vendor/quiche/src/h3/qpack/static_table.rs +323 -323
  71. package/vendor/quiche/src/h3/stream.rs +1595 -1595
  72. package/vendor/quiche/src/lib.rs +9556 -9556
  73. package/vendor/quiche/src/minmax.rs +446 -446
  74. package/vendor/quiche/src/packet.rs +2334 -2334
  75. package/vendor/quiche/src/path.rs +1374 -1374
  76. package/vendor/quiche/src/pmtud.rs +652 -652
  77. package/vendor/quiche/src/rand.rs +64 -64
  78. package/vendor/quiche/src/range_buf.rs +186 -186
  79. package/vendor/quiche/src/ranges.rs +755 -755
  80. package/vendor/quiche/src/recovery/AGENTS.md +80 -80
  81. package/vendor/quiche/src/recovery/bandwidth.rs +565 -565
  82. package/vendor/quiche/src/recovery/bytes_in_flight.rs +179 -179
  83. package/vendor/quiche/src/recovery/congestion/cubic.rs +1038 -1038
  84. package/vendor/quiche/src/recovery/congestion/delivery_rate.rs +514 -514
  85. package/vendor/quiche/src/recovery/congestion/hystart.rs +241 -241
  86. package/vendor/quiche/src/recovery/congestion/mod.rs +361 -361
  87. package/vendor/quiche/src/recovery/congestion/prr.rs +238 -238
  88. package/vendor/quiche/src/recovery/congestion/recovery.rs +1170 -1170
  89. package/vendor/quiche/src/recovery/congestion/reno.rs +291 -291
  90. package/vendor/quiche/src/recovery/congestion/test_sender.rs +201 -201
  91. package/vendor/quiche/src/recovery/gcongestion/bbr/bandwidth_sampler.rs +1947 -1947
  92. package/vendor/quiche/src/recovery/gcongestion/bbr/windowed_filter.rs +158 -158
  93. package/vendor/quiche/src/recovery/gcongestion/bbr.rs +37 -37
  94. package/vendor/quiche/src/recovery/gcongestion/bbr2/drain.rs +120 -120
  95. package/vendor/quiche/src/recovery/gcongestion/bbr2/mode.rs +318 -318
  96. package/vendor/quiche/src/recovery/gcongestion/bbr2/network_model.rs +784 -784
  97. package/vendor/quiche/src/recovery/gcongestion/bbr2/probe_bw.rs +729 -729
  98. package/vendor/quiche/src/recovery/gcongestion/bbr2/probe_rtt.rs +175 -175
  99. package/vendor/quiche/src/recovery/gcongestion/bbr2/startup.rs +190 -190
  100. package/vendor/quiche/src/recovery/gcongestion/bbr2.rs +855 -855
  101. package/vendor/quiche/src/recovery/gcongestion/mod.rs +275 -275
  102. package/vendor/quiche/src/recovery/gcongestion/pacer.rs +294 -294
  103. package/vendor/quiche/src/recovery/gcongestion/recovery.rs +1384 -1384
  104. package/vendor/quiche/src/recovery/mod.rs +3086 -3086
  105. package/vendor/quiche/src/recovery/rtt.rs +152 -152
  106. package/vendor/quiche/src/stream/mod.rs +2210 -2210
  107. package/vendor/quiche/src/stream/recv_buf.rs +1236 -1236
  108. package/vendor/quiche/src/stream/send_buf.rs +849 -849
  109. package/vendor/quiche/src/test_utils.rs +681 -681
  110. package/vendor/quiche/src/tests.rs +12922 -12922
  111. package/vendor/quiche/src/tls/boringssl.rs +375 -375
  112. package/vendor/quiche/src/tls/mod.rs +1245 -1245
  113. package/vendor/quiche/src/transport_params.rs +628 -628
package/README.md CHANGED
@@ -1,550 +1,550 @@
1
- <div align="center">
2
-
3
- # rwebtransport
4
-
5
- ### WebTransport for Node.js. The real thing.
6
-
7
- #### A fully-compatible [WebTransport](https://developer.mozilla.org/en-US/docs/Web/API/WebTransport) client **and** server for Node.js: the browser API, backed by Cloudflare **quiche** and **BoringSSL**, bound to Node through **neon**.
8
-
9
- <br/>
10
-
11
- **⚡ Native QUIC/HTTP-3.** Cloudflare's `quiche` transport, the engine that serves a large slice of the internet, linked straight into your Node process.
12
-
13
- **⚡ The standard API.** The same `WebTransport` class you use in Chrome: bidirectional and unidirectional streams as WHATWG streams, plus unreliable datagrams, over one multiplexed QUIC connection. And a matching server.
14
-
15
- <br/>
16
-
17
- [![npm](https://img.shields.io/npm/v/rwebtransport.svg?color=2563ff&label=npm&labelColor=0e1520)](https://www.npmjs.com/package/rwebtransport)
18
- [![ci](https://github.com/dacely-cloud/rwebtransport/actions/workflows/ci.yml/badge.svg)](https://github.com/dacely-cloud/rwebtransport/actions/workflows/ci.yml)
19
- [![node](https://img.shields.io/badge/node-24%20%7C%2026-22e3ab.svg?labelColor=0e1520)](#requirements)
20
- [![types](https://img.shields.io/badge/types-included-2563ff.svg?labelColor=0e1520)](https://www.typescriptlang.org/)
21
- [![quic](https://img.shields.io/badge/QUIC-quiche%200.29-7c3aed.svg?labelColor=0e1520)](https://github.com/cloudflare/quiche)
22
- [![tls](https://img.shields.io/badge/TLS-BoringSSL-654ff0.svg?labelColor=0e1520)](https://boringssl.googlesource.com/boringssl/)
23
- [![license](https://img.shields.io/badge/license-Apache--2.0-8b9ab4.svg?labelColor=0e1520)](./LICENSE)
24
-
25
- <br/>
26
-
27
- <img src="https://img.shields.io/badge/Rust-000000?style=for-the-badge&logo=rust&logoColor=white" alt="Rust" />
28
- <img src="https://img.shields.io/badge/TypeScript-3178c6?style=for-the-badge&logo=typescript&logoColor=white" alt="TypeScript" />
29
- <img src="https://img.shields.io/badge/HTTP%2F3-00589B?style=for-the-badge&logo=http3&logoColor=white" alt="HTTP/3" />
30
- <img src="https://img.shields.io/badge/QUIC-654ff0?style=for-the-badge&logoColor=white" alt="QUIC" />
31
- <img src="https://img.shields.io/badge/Node.js-5FA04E?style=for-the-badge&logo=nodedotjs&logoColor=white" alt="Node.js" />
32
-
33
- </div>
34
-
35
- ---
36
-
37
- <details>
38
- <summary><b>Table of contents</b></summary>
39
- <br/>
40
-
41
- 1. [Why](#why)
42
- 2. [Install](#install)
43
- 3. [Quick start](#quick-start)
44
- 4. [Reliable streams and unreliable datagrams](#reliable-streams-and-unreliable-datagrams)
45
- 5. [The client API](#the-client-api)
46
- - [Connecting](#connecting)
47
- - [Bidirectional streams](#bidirectional-streams)
48
- - [Unidirectional streams](#unidirectional-streams)
49
- - [Datagrams](#datagrams)
50
- - [Closing](#closing)
51
- 6. [The server API](#the-server-api)
52
- 7. [Threading, workers, and cluster](#threading-workers-and-cluster)
53
- 8. [Docs and examples](#docs-and-examples)
54
- 9. [Requirements](#requirements)
55
- 10. [How it works](#how-it-works)
56
- 11. [Building from source](#building-from-source)
57
- 12. [Testing](#testing)
58
- 13. [Robustness](#robustness)
59
- 14. [Security and the TLS profile](#security-and-the-tls-profile)
60
- 15. [License](#license)
61
-
62
- </details>
63
-
64
- ---
65
-
66
- **WebTransport is the modern transport for realtime apps:** lower latency than WebSocket, multiple independent streams over one connection with no head-of-line blocking, and unreliable datagrams for the data you would rather drop than delay. Browsers have shipped it for years. Node.js has not.
67
-
68
- `rwebtransport` closes that gap. It is not an emulation over HTTP/2 or a WebSocket shim. It is a genuine HTTP/3 endpoint speaking QUIC over UDP, built on the same [Cloudflare quiche](https://github.com/cloudflare/quiche) engine that powers WebTransport at scale, exposed through the exact `WebTransport` API you already know from the browser, plus a matching `WebTransportServer`.
69
-
70
- QUIC + HTTP/3 + WebTransport, implemented natively in Rust. It ships with prebuilt binaries. No round-trips through a browser, no polyfills, no HTTP/2 emulation, just an actual HTTP/3 datagram on the wire. And it provides the full standard surface: `WebTransport`, `WebTransportBidirectionalStream`, `WebTransportSendStream` and `WebTransportReceiveStream` as WHATWG streams, and `WebTransportDatagramDuplexStream`, all matching the [W3C spec](https://w3c.github.io/webtransport/).
71
-
72
- By default the client also puts **Chrome on the wire**: the TLS profile advertises Google Chrome's cipher suites, curve preferences, and signature algorithms, so your handshake looks like a browser's. See [Security and the TLS profile](#security-and-the-tls-profile).
73
-
74
- ```bash
75
- npm install rwebtransport
76
- ```
77
-
78
- ```ts
79
- import { WebTransport } from 'rwebtransport';
80
-
81
- const wt = new WebTransport('https://example.com:4433/echo');
82
- await wt.ready;
83
-
84
- const stream = await wt.createBidirectionalStream();
85
- const writer = stream.writable.getWriter();
86
- await writer.write(new TextEncoder().encode('hello over QUIC'));
87
- await writer.close();
88
-
89
- const { value } = await stream.readable.getReader().read();
90
- console.log(new TextDecoder().decode(value)); // "hello over QUIC"
91
- ```
92
-
93
- ---
94
-
95
- ## Why
96
-
97
- | | WebSocket | `rwebtransport` |
98
- | --------------------- | ------------------ | --------------------------- |
99
- | Transport | TCP + TLS | **QUIC** (UDP + TLS 1.3) |
100
- | Head-of-line blocking | Yes, one stream | **No**, independent streams |
101
- | Multiple streams | One per connection | **Many**, multiplexed |
102
- | Unreliable messages | ✗ | **Datagrams** ✓ |
103
- | Client and server | ✗ (server only) | **Both**, one package |
104
- | Browser-identical API | ✗ | **✓ WHATWG `WebTransport`** |
105
-
106
- If you are building game netcode, live media, collaborative editing, financial tick feeds, or anything where a stalled TCP segment must not freeze every other message, this is the transport you want, and now you can share client code between the browser and Node.
107
-
108
- ---
109
-
110
- ## Install
111
-
112
- ```bash
113
- npm install rwebtransport
114
- # or
115
- pnpm add rwebtransport
116
- # or
117
- yarn add rwebtransport
118
- ```
119
-
120
- Prebuilt native binaries are shipped for **Node 24 and Node 26** on **Linux, macOS, and Windows** (x64 and arm64). If a matching prebuilt binary is not found for your platform, the package **compiles the Rust core automatically** at install time. That needs a [Rust toolchain](https://rustup.rs), `cmake`, and a C/C++ compiler (BoringSSL is built from source). See [Building from source](#building-from-source).
121
-
122
- ---
123
-
124
- ## Quick start
125
-
126
- ```ts
127
- import { WebTransport } from 'rwebtransport';
128
-
129
- // 1. Open a session (QUIC handshake plus HTTP/3 Extended CONNECT).
130
- const wt = new WebTransport('https://localhost:4433/chat', {
131
- // Trust a specific self-signed cert by its SHA-256, exactly like the browser API:
132
- serverCertificateHashes: [{ algorithm: 'sha-256', value: certHashBytes }],
133
- });
134
- await wt.ready;
135
-
136
- // 2. Send an unreliable datagram.
137
- const dgramWriter = wt.datagrams.writable.getWriter();
138
- await dgramWriter.write(new Uint8Array([1, 2, 3]));
139
-
140
- // 3. Accept streams the server opens.
141
- const reader = wt.incomingUnidirectionalStreams.getReader();
142
- const { value: receive } = await reader.read();
143
- if (receive) {
144
- const { value: bytes } = await receive.getReader().read();
145
- console.log('server pushed', bytes?.length ?? 0, 'bytes');
146
- }
147
-
148
- // 4. Close.
149
- wt.close({ closeCode: 0, reason: 'bye' });
150
- ```
151
-
152
- Runnable versions of these live in [`examples/`](./examples).
153
-
154
- ---
155
-
156
- ## Reliable streams and unreliable datagrams
157
-
158
- Yes, both, over the one QUIC connection, and this library implements each:
159
-
160
- - **Streams are reliable and ordered.** A bidirectional stream (or a one-way send / receive stream) is a WHATWG `ReadableStream` / `WritableStream` of bytes. Everything you write is delivered, in order, with end-to-end backpressure onto QUIC flow control. Open as many as you want; they are independently multiplexed, so a stall on one never blocks another (no head-of-line blocking).
161
- - **Datagrams are unreliable and unordered.** `session.datagrams` is a duplex of `Uint8Array` messages. Each datagram is sent best-effort in a single QUIC packet: it may be dropped, reordered, or never arrive, and it is never retransmitted. Reach for them when you would rather drop data than delay it: position updates, audio frames, heartbeats.
162
-
163
- The complete TypeScript program below starts a server, connects a client, and exercises both. It is the runnable [`examples/echo.ts`](./examples/echo.ts) (the in-repo copy imports the built output; in your own project the import is `from 'rwebtransport'`). On Node 24+ you can run it directly with `node examples/echo.ts`.
164
-
165
- ```ts
166
- import { X509Certificate, createHash } from 'node:crypto';
167
- import { readFileSync } from 'node:fs';
168
- import { dirname, join } from 'node:path';
169
- import { fileURLToPath } from 'node:url';
170
-
171
- import { WebTransport, WebTransportServer, type WebTransportServerSession } from 'rwebtransport';
172
-
173
- const HERE = dirname(fileURLToPath(import.meta.url));
174
- const CERT = join(HERE, 'cert.pem');
175
- const KEY = join(HERE, 'key.pem');
176
-
177
- const encoder = new TextEncoder();
178
- const decoder = new TextDecoder();
179
- const sleep = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms));
180
-
181
- // SHA-256 of the certificate's DER encoding: exactly what serverCertificateHashes wants.
182
- function certHash(path: string): Uint8Array {
183
- const der = new X509Certificate(readFileSync(path)).raw;
184
- return new Uint8Array(createHash('sha256').update(der).digest());
185
- }
186
-
187
- // Echo an accepted session: pipe every reliable stream and every datagram back.
188
- function echo(session: WebTransportServerSession): void {
189
- void (async () => {
190
- const reader = session.incomingBidirectionalStreams.getReader();
191
- for (;;) {
192
- const { value: stream, done } = await reader.read();
193
- if (done) break;
194
- if (stream) void stream.readable.pipeTo(stream.writable).catch(() => {});
195
- }
196
- })();
197
- void session.datagrams.readable.pipeTo(session.datagrams.writable).catch(() => {});
198
- }
199
-
200
- // Read a reliable readable stream to end-of-stream and return all its bytes.
201
- async function readAll(readable: ReadableStream<Uint8Array>): Promise<Uint8Array> {
202
- const reader = readable.getReader();
203
- const chunks: Uint8Array[] = [];
204
- let total = 0;
205
- for (;;) {
206
- const { value, done } = await reader.read();
207
- if (done) break;
208
- if (value) {
209
- chunks.push(value);
210
- total += value.length;
211
- }
212
- }
213
- const out = new Uint8Array(total);
214
- let offset = 0;
215
- for (const chunk of chunks) {
216
- out.set(chunk, offset);
217
- offset += chunk.length;
218
- }
219
- return out;
220
- }
221
-
222
- async function main(): Promise<void> {
223
- // Server: bind an OS-assigned loopback port and echo everything.
224
- const server = new WebTransportServer({ host: '127.0.0.1', port: 0, cert: CERT, key: KEY });
225
- await server.ready;
226
- void (async () => {
227
- const reader = server.incomingSessions.getReader();
228
- for (;;) {
229
- const { value: session, done } = await reader.read();
230
- if (done) break;
231
- if (session) echo(session);
232
- }
233
- })();
234
-
235
- const url = `https://127.0.0.1:${server.port}/echo`;
236
- console.log(`server listening at ${url}`);
237
-
238
- // Client: connect, trusting the server's pinned certificate.
239
- const client = new WebTransport(url, {
240
- serverCertificateHashes: [{ algorithm: 'sha-256', value: certHash(CERT) }],
241
- });
242
- await client.ready;
243
- console.log('client connected');
244
-
245
- // RELIABLE: a bidirectional stream. Delivery is guaranteed and ordered.
246
- const stream = await client.createBidirectionalStream();
247
- const writer = stream.writable.getWriter();
248
- await writer.write(encoder.encode('hello over a reliable stream'));
249
- await writer.close(); // ends our send side so the echo's read side sees `done`
250
- const reply = decoder.decode(await readAll(stream.readable));
251
- console.log(`reliable stream echo: ${JSON.stringify(reply)}`);
252
-
253
- // UNRELIABLE: a datagram. Best-effort: it may be dropped, so we retry.
254
- const dgWriter = client.datagrams.writable.getWriter();
255
- const dgReader = client.datagrams.readable.getReader();
256
- const payload = encoder.encode('hello over an unreliable datagram');
257
- const inbound = dgReader.read().then((r) => r.value);
258
- let echoed: Uint8Array | undefined;
259
- for (let attempt = 0; attempt < 40 && !echoed; attempt++) {
260
- await dgWriter.write(payload);
261
- echoed = await Promise.race([inbound, sleep(25).then(() => undefined)]);
262
- }
263
- if (echoed) {
264
- console.log(`unreliable datagram echo: ${JSON.stringify(decoder.decode(echoed))}`);
265
- } else {
266
- console.log('unreliable datagram echo: none (datagrams are lossy by design)');
267
- }
268
-
269
- // Clean shutdown of both ends.
270
- client.close({ closeCode: 0, reason: 'done' });
271
- server.close();
272
- process.exit(0);
273
- }
274
-
275
- main().catch((err: unknown) => {
276
- console.error('echo failed:', err);
277
- process.exit(1);
278
- });
279
- ```
280
-
281
- Running it prints:
282
-
283
- ```text
284
- server listening at https://127.0.0.1:53348/echo
285
- client connected
286
- reliable stream echo: "hello over a reliable stream"
287
- unreliable datagram echo: "hello over an unreliable datagram"
288
- ```
289
-
290
- ---
291
-
292
- ## The client API
293
-
294
- `rwebtransport` implements the [W3C WebTransport](https://w3c.github.io/webtransport/) interface. If you have used it in a browser, you already know this library.
295
-
296
- ### Connecting
297
-
298
- ```ts
299
- const wt = new WebTransport(url, options?);
300
- await wt.ready; // resolves when the session is established, rejects if it fails
301
- await wt.closed; // resolves when the session ends cleanly, rejects on abnormal close
302
- ```
303
-
304
- | Option | Type | Meaning |
305
- | -------------------------------------------------------- | ------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- |
306
- | `serverCertificateHashes` | `{ algorithm: 'sha-256', value: BufferSource }[]` | Accept a server cert by its SHA-256 fingerprint (self-signed or pinned). Bypasses CA and hostname checks for the matching cert, exactly like the browser. |
307
- | `insecure` | `boolean` | Node extension. Disable **all** certificate verification. Development only. |
308
- | `headers` | `Record<string, string>` | Node extension. Extra request headers on the Extended CONNECT. |
309
- | `origin` | `string` | Node extension. Value for the `Origin` request header. |
310
- | `allowPooling`, `requireUnreliable`, `congestionControl` | | Accepted for spec parity; currently informational. |
311
-
312
- When neither `serverCertificateHashes` nor `insecure` is set, the client performs full PKI validation against the system trust store with hostname checking.
313
-
314
- ### Bidirectional streams
315
-
316
- ```ts
317
- const stream = await wt.createBidirectionalStream();
318
- // stream.readable : WebTransportReceiveStream (a ReadableStream<Uint8Array>)
319
- // stream.writable : WebTransportSendStream (a WritableStream<Uint8Array>)
320
-
321
- // Streams the peer opens:
322
- const reader = wt.incomingBidirectionalStreams.getReader();
323
- const { value: peerStream } = await reader.read();
324
- ```
325
-
326
- ### Unidirectional streams
327
-
328
- ```ts
329
- const send = await wt.createUnidirectionalStream(); // a WritableStream<Uint8Array>
330
- const writer = send.getWriter();
331
- await writer.write(payload);
332
- await writer.close();
333
- ```
334
-
335
- ### Datagrams
336
-
337
- ```ts
338
- const writer = wt.datagrams.writable.getWriter();
339
- await writer.write(new Uint8Array([0xde, 0xad]));
340
-
341
- const reader = wt.datagrams.readable.getReader();
342
- const { value } = await reader.read(); // Uint8Array or undefined
343
-
344
- wt.datagrams.maxDatagramSize; // largest payload that fits in one packet
345
- ```
346
-
347
- ### Closing
348
-
349
- ```ts
350
- wt.close({ closeCode: 0, reason: 'done' });
351
- await wt.closed;
352
- ```
353
-
354
- ---
355
-
356
- ## The server API
357
-
358
- The same package ships a **WebTransport server**. Bind a UDP port with a certificate, then consume `incomingSessions`. Each is a `WebTransportServerSession` with the exact same stream and datagram surface as the client `WebTransport`.
359
-
360
- ```ts
361
- import { WebTransportServer } from 'rwebtransport';
362
-
363
- const server = new WebTransportServer({
364
- port: 4433,
365
- host: '0.0.0.0',
366
- cert: '/path/to/cert.pem', // PEM certificate chain (file path)
367
- key: '/path/to/key.pem', // PEM private key (file path)
368
- });
369
- await server.ready;
370
- console.log('listening on', server.port);
371
-
372
- const reader = server.incomingSessions.getReader();
373
- for (;;) {
374
- const { value: session, done } = await reader.read();
375
- if (done) break;
376
-
377
- console.log('new session:', session.path, session.authority);
378
-
379
- // Echo every bidirectional stream straight back:
380
- const streams = session.incomingBidirectionalStreams.getReader();
381
- void (async () => {
382
- for (;;) {
383
- const { value: stream, done } = await streams.read();
384
- if (done) break;
385
- void stream.readable.pipeTo(stream.writable);
386
- }
387
- })();
388
-
389
- // Open a stream or send a datagram from the server side:
390
- const outbound = await session.createUnidirectionalStream();
391
- await outbound.getWriter().write(new TextEncoder().encode('welcome'));
392
- }
393
- ```
394
-
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.
396
-
397
- ---
398
-
399
- ## Threading, workers, and cluster
400
-
401
- - **Threading.** Each session runs its QUIC/HTTP-3 work on its own background thread and talks to the JS event loop through neon's `Channel`. Every hand-off is non-blocking (an unbounded command channel, a non-blocking event channel, atomics), so the library never deadlocks internally; it only ever applies backpressure. The one way to wedge a stream is the universal one: writing a large bidirectional stream without concurrently reading it. Read while you write.
402
- - **`worker_threads`.** Fully supported. The addon is context-aware, so a client or server can be created inside any Worker and each Worker gets its own instance bound to its own event loop. Multiple Workers run concurrently.
403
- - **`cluster`.** Clients work as-is (each process is independent). A server can share one listening port across cluster workers with `reusePort: true` (`SO_REUSEPORT`, Unix only); the kernel load-balances connections across the workers. On Windows, run one server per port or put a UDP load balancer in front.
404
-
405
- ---
406
-
407
- ## Docs and examples
408
-
409
- - **[`docs/`](./docs)** is the full guide: getting started, the client and server APIs in depth, streams and backpressure, datagrams, certificates and TLS, error handling, threading, building, and troubleshooting.
410
- - **[`examples/`](./examples)** has runnable client and server programs and a one-file end-to-end demo.
411
-
412
- ---
413
-
414
- ## Requirements
415
-
416
- - **Node.js 24.x or 26.x.** No other versions are supported; the native ABI is built and tested against exactly these.
417
- - **Linux, macOS, or Windows** (x64 or arm64).
418
- - To build from source: **Rust** (stable), **cmake**, and a **C/C++ toolchain** (plus **NASM** on Windows) for BoringSSL.
419
-
420
- ---
421
-
422
- ## How it works
423
-
424
- ```mermaid
425
- flowchart TB
426
- classDef js fill:#0e1520,stroke:#2563ff,stroke-width:2px,color:#cfe0ff;
427
- classDef rust fill:#160f1f,stroke:#7c3aed,stroke-width:2px,color:#ead7ff;
428
- classDef net fill:#0c1a14,stroke:#10b981,stroke-width:2px,color:#c8f5e2;
429
-
430
- subgraph APP["your code"]
431
- YOU["import { WebTransport, WebTransportServer } from 'rwebtransport'"]
432
- end
433
-
434
- subgraph TS["TypeScript layer, the WHATWG surface"]
435
- direction TB
436
- WTAPI["WebTransport / WebTransportServer / streams / datagrams<br/>ReadableStream + WritableStream + backpressure<br/>ready / closed promises"]
437
- LOADER["loader: pick prebuilt .node<br/>else compile via cargo"]
438
- end
439
-
440
- subgraph NATIVE["native addon in Rust (neon / N-API)"]
441
- direction TB
442
- BIND["neon bindings<br/>commands in, events out (Channel)"]
443
- DRIVER["driver thread<br/>UDP socket + quiche recv/send/timeout loop"]
444
- H3WT["H3 + WebTransport (dual-role)<br/>control streams, SETTINGS, Extended CONNECT<br/>QPACK, 0x54/0x41 stream signals, datagram quarter-id"]
445
- TLS["TLS config<br/>Chrome cipher suites, X25519/P-256/P-384, TLS 1.3"]
446
- end
447
-
448
- subgraph ENGINE["vendored engine"]
449
- QUICHE["Cloudflare quiche 0.29, QUIC transport and HTTP/3"]
450
- BSSL["BoringSSL for the TLS 1.3 handshake"]
451
- end
452
-
453
- WIRE["UDP, QUIC, HTTP/3, WebTransport"]
454
-
455
- YOU --> WTAPI
456
- WTAPI --> LOADER
457
- LOADER --> BIND
458
- BIND <--> DRIVER
459
- DRIVER --> H3WT
460
- H3WT --> QUICHE
461
- TLS --> BSSL
462
- QUICHE --> BSSL
463
- QUICHE --> WIRE
464
-
465
- class YOU,WTAPI,LOADER js;
466
- class BIND,DRIVER,H3WT,TLS rust;
467
- class QUICHE,BSSL,WIRE net;
468
- ```
469
-
470
- 1. **The TypeScript layer** presents the browser `WebTransport` API (and `WebTransportServer`) and maps it onto WHATWG `ReadableStream`/`WritableStream`, wiring up backpressure both ways.
471
- 2. **The neon binding** turns JS calls into commands for a dedicated **driver thread** and delivers asynchronous events (stream data, datagrams, session state) back to the event loop.
472
- 3. **The driver thread** owns a UDP socket and runs the **quiche** connection: reading packets, writing packets, arming timers.
473
- 4. **The H3/WebTransport layer**, since quiche does not itself speak WebTransport, implements the HTTP/3 control streams, the `SETTINGS` exchange, QPACK-encoded **Extended CONNECT** (sent by the client, answered by the server), the `0x54`/`0x41` stream signals, and the RFC 9297 quarter-stream-id datagram framing, all on top of quiche's raw QUIC streams. The state machine is dual-role, so client and server share one hardened implementation.
474
- 5. **BoringSSL**, configured with a Chrome-like TLS profile, performs the TLS 1.3 handshake inside QUIC.
475
-
476
- ---
477
-
478
- ## Building from source
479
-
480
- ```bash
481
- git clone https://github.com/dacely-cloud/rwebtransport
482
- cd rwebtransport
483
- npm install
484
- npm run build # cargo build, copy .node, bundle TS
485
- ```
486
-
487
- The native crates live in `crates/`, the QUIC engine is vendored under `vendor/quiche`, and the compiled addon is written to `prebuilds/<platform>-<arch>/rwebtransport.node`.
488
-
489
- ```bash
490
- npm run build:rust # release build of the native addon
491
- npm run build:rust:debug # faster debug build
492
- npm run build:ts # bundle the TypeScript layer
493
- ```
494
-
495
- Building from source needs a Rust toolchain, cmake, a C/C++ compiler, and Go (BoringSSL is compiled from source). Helper scripts install the toolchain for you, one per platform family:
496
-
497
- ```bash
498
- npm run setup:unix # Linux/macOS: compiler, cmake, ninja, Go, Rust via your package manager
499
- ```
500
-
501
- ```powershell
502
- npm run setup:windows # Windows: Rust, CMake, Go, NASM via winget, and sets ASM_NASM
503
- ```
504
-
505
- On **Windows** you also need NASM (BoringSSL's assembler) and the MSVC C++ Build Tools. `setup:windows` installs Rust, CMake, Go, and NASM and sets `ASM_NASM`; it checks for the MSVC C++ Build Tools and Node and points you to any that are missing, but it does not auto-install the multi-gigabyte Visual Studio C++ workload. If a `cargo build` there fails with `Could not find the compiler specified in the environment variable ASM_NASM`, that is the missing NASM; run the script above (or see [`docs/building.md`](./docs/building.md#windows-setup)) and rebuild in a fresh terminal.
506
-
507
- ---
508
-
509
- ## Testing
510
-
511
- End-to-end tests run the real client and the real server against each other and against a dedicated quiche echo-server fixture. No mocks.
512
-
513
- ```bash
514
- npm test
515
- ```
516
-
517
- The suite covers the QUIC handshake, Extended CONNECT, bidirectional and unidirectional streams, datagrams, backpressure, and graceful and error close paths. It also includes:
518
-
519
- - an **adversarial suite** that points a real client at a deliberately hostile server (rejected CONNECT, malformed QPACK, garbage frames, stream resets, mid-session close) and a careless caller (operations after close, oversized datagrams);
520
- - **server** tests where our own client drives our own server (bidi echo, large payloads, unidirectional echo, datagrams, concurrent sessions);
521
- - **`worker_threads`** tests (a client running inside a Worker, multiple Workers concurrently) and a **deadlock-freedom** test (a payload larger than every flow-control window echoed with concurrent read and write).
522
-
523
- ---
524
-
525
- ## Robustness
526
-
527
- The native core treats the peer and the caller as untrusted, on both the client and the server:
528
-
529
- - **A panic can never crash Node.** The entire driver thread runs inside a panic boundary; a panic (or a fatal setup error) is surfaced as an `error` event that rejects `ready`/`closed`. It never aborts the process and never silently hangs the session.
530
- - **Bounded memory under flood.** A hostile peer cannot grow memory without limit: event delivery to the JS loop is backpressured (unread stream data stays flow-controlled in QUIC, excess datagrams are dropped), the datagram queue is bounded, HTTP/3 frame buffers are capped, and finished streams are pruned.
531
- - **No blocking on the event loop.** DNS resolution, the socket bind, and the QUIC handshake all run on the driver thread, so the constructor never blocks Node.
532
- - **Hostile input is fail-closed.** Malformed HTTP/3, bad QPACK, oversized frames, unexpected resets, and out-of-range numbers from JS are handled by rejecting or closing cleanly rather than panicking.
533
-
534
- ---
535
-
536
- ## Security and the TLS profile
537
-
538
- By default the client advertises the **Google Chrome** TLS profile: Chrome's cipher-suite order, the `X25519 / P-256 / P-384` group preference, and Chrome's signature-algorithm list, negotiated as **TLS 1.3 only** (as QUIC requires). This makes the handshake indistinguishable from a browser's and maximizes compatibility with servers (including Cloudflare) that key behavior off the TLS ClientHello.
539
-
540
- Certificate verification follows the WebTransport model: full PKI validation by default, or explicit trust of a server certificate by its `sha-256` hash via `serverCertificateHashes`, exactly like the browser API. The `insecure` option disables verification entirely and is intended for development only.
541
-
542
- ---
543
-
544
- ## License
545
-
546
- [Apache-2.0](./LICENSE). Vendored components (Cloudflare quiche, BoringSSL, neon) remain under their own licenses. See [NOTICE](./NOTICE).
547
-
548
- <div align="center">
549
- <sub>Built by <a href="https://github.com/dacely-cloud">Dacely Cloud</a>.</sub>
550
- </div>
1
+ <div align="center">
2
+
3
+ # rwebtransport
4
+
5
+ ### WebTransport for Node.js. The real thing.
6
+
7
+ #### A fully-compatible [WebTransport](https://developer.mozilla.org/en-US/docs/Web/API/WebTransport) client **and** server for Node.js: the browser API, backed by Cloudflare **quiche** and **BoringSSL**, bound to Node through **neon**.
8
+
9
+ <br/>
10
+
11
+ **⚡ Native QUIC/HTTP-3.** Cloudflare's `quiche` transport, the engine that serves a large slice of the internet, linked straight into your Node process.
12
+
13
+ **⚡ The standard API.** The same `WebTransport` class you use in Chrome: bidirectional and unidirectional streams as WHATWG streams, plus unreliable datagrams, over one multiplexed QUIC connection. And a matching server.
14
+
15
+ <br/>
16
+
17
+ [![npm](https://img.shields.io/npm/v/rwebtransport.svg?color=2563ff&label=npm&labelColor=0e1520)](https://www.npmjs.com/package/rwebtransport)
18
+ [![ci](https://github.com/dacely-cloud/rwebtransport/actions/workflows/ci.yml/badge.svg)](https://github.com/dacely-cloud/rwebtransport/actions/workflows/ci.yml)
19
+ [![node](https://img.shields.io/badge/node-24%20%7C%2026-22e3ab.svg?labelColor=0e1520)](#requirements)
20
+ [![types](https://img.shields.io/badge/types-included-2563ff.svg?labelColor=0e1520)](https://www.typescriptlang.org/)
21
+ [![quic](https://img.shields.io/badge/QUIC-quiche%200.29-7c3aed.svg?labelColor=0e1520)](https://github.com/cloudflare/quiche)
22
+ [![tls](https://img.shields.io/badge/TLS-BoringSSL-654ff0.svg?labelColor=0e1520)](https://boringssl.googlesource.com/boringssl/)
23
+ [![license](https://img.shields.io/badge/license-Apache--2.0-8b9ab4.svg?labelColor=0e1520)](./LICENSE)
24
+
25
+ <br/>
26
+
27
+ <img src="https://img.shields.io/badge/Rust-000000?style=for-the-badge&logo=rust&logoColor=white" alt="Rust" />
28
+ <img src="https://img.shields.io/badge/TypeScript-3178c6?style=for-the-badge&logo=typescript&logoColor=white" alt="TypeScript" />
29
+ <img src="https://img.shields.io/badge/HTTP%2F3-00589B?style=for-the-badge&logo=http3&logoColor=white" alt="HTTP/3" />
30
+ <img src="https://img.shields.io/badge/QUIC-654ff0?style=for-the-badge&logoColor=white" alt="QUIC" />
31
+ <img src="https://img.shields.io/badge/Node.js-5FA04E?style=for-the-badge&logo=nodedotjs&logoColor=white" alt="Node.js" />
32
+
33
+ </div>
34
+
35
+ ---
36
+
37
+ <details>
38
+ <summary><b>Table of contents</b></summary>
39
+ <br/>
40
+
41
+ 1. [Why](#why)
42
+ 2. [Install](#install)
43
+ 3. [Quick start](#quick-start)
44
+ 4. [Reliable streams and unreliable datagrams](#reliable-streams-and-unreliable-datagrams)
45
+ 5. [The client API](#the-client-api)
46
+ - [Connecting](#connecting)
47
+ - [Bidirectional streams](#bidirectional-streams)
48
+ - [Unidirectional streams](#unidirectional-streams)
49
+ - [Datagrams](#datagrams)
50
+ - [Closing](#closing)
51
+ 6. [The server API](#the-server-api)
52
+ 7. [Threading, workers, and cluster](#threading-workers-and-cluster)
53
+ 8. [Docs and examples](#docs-and-examples)
54
+ 9. [Requirements](#requirements)
55
+ 10. [How it works](#how-it-works)
56
+ 11. [Building from source](#building-from-source)
57
+ 12. [Testing](#testing)
58
+ 13. [Robustness](#robustness)
59
+ 14. [Security and the TLS profile](#security-and-the-tls-profile)
60
+ 15. [License](#license)
61
+
62
+ </details>
63
+
64
+ ---
65
+
66
+ **WebTransport is the modern transport for realtime apps:** lower latency than WebSocket, multiple independent streams over one connection with no head-of-line blocking, and unreliable datagrams for the data you would rather drop than delay. Browsers have shipped it for years. Node.js has not.
67
+
68
+ `rwebtransport` closes that gap. It is not an emulation over HTTP/2 or a WebSocket shim. It is a genuine HTTP/3 endpoint speaking QUIC over UDP, built on the same [Cloudflare quiche](https://github.com/cloudflare/quiche) engine that powers WebTransport at scale, exposed through the exact `WebTransport` API you already know from the browser, plus a matching `WebTransportServer`.
69
+
70
+ QUIC + HTTP/3 + WebTransport, implemented natively in Rust. It ships with prebuilt binaries. No round-trips through a browser, no polyfills, no HTTP/2 emulation, just an actual HTTP/3 datagram on the wire. And it provides the full standard surface: `WebTransport`, `WebTransportBidirectionalStream`, `WebTransportSendStream` and `WebTransportReceiveStream` as WHATWG streams, and `WebTransportDatagramDuplexStream`, all matching the [W3C spec](https://w3c.github.io/webtransport/).
71
+
72
+ By default the client also puts **Chrome on the wire**: the TLS profile advertises Google Chrome's cipher suites, curve preferences, and signature algorithms, so your handshake looks like a browser's. See [Security and the TLS profile](#security-and-the-tls-profile).
73
+
74
+ ```bash
75
+ npm install rwebtransport
76
+ ```
77
+
78
+ ```ts
79
+ import { WebTransport } from 'rwebtransport';
80
+
81
+ const wt = new WebTransport('https://example.com:4433/echo');
82
+ await wt.ready;
83
+
84
+ const stream = await wt.createBidirectionalStream();
85
+ const writer = stream.writable.getWriter();
86
+ await writer.write(new TextEncoder().encode('hello over QUIC'));
87
+ await writer.close();
88
+
89
+ const { value } = await stream.readable.getReader().read();
90
+ console.log(new TextDecoder().decode(value)); // "hello over QUIC"
91
+ ```
92
+
93
+ ---
94
+
95
+ ## Why
96
+
97
+ | | WebSocket | `rwebtransport` |
98
+ | --------------------- | ------------------ | --------------------------- |
99
+ | Transport | TCP + TLS | **QUIC** (UDP + TLS 1.3) |
100
+ | Head-of-line blocking | Yes, one stream | **No**, independent streams |
101
+ | Multiple streams | One per connection | **Many**, multiplexed |
102
+ | Unreliable messages | ✗ | **Datagrams** ✓ |
103
+ | Client and server | ✗ (server only) | **Both**, one package |
104
+ | Browser-identical API | ✗ | **✓ WHATWG `WebTransport`** |
105
+
106
+ If you are building game netcode, live media, collaborative editing, financial tick feeds, or anything where a stalled TCP segment must not freeze every other message, this is the transport you want, and now you can share client code between the browser and Node.
107
+
108
+ ---
109
+
110
+ ## Install
111
+
112
+ ```bash
113
+ npm install rwebtransport
114
+ # or
115
+ pnpm add rwebtransport
116
+ # or
117
+ yarn add rwebtransport
118
+ ```
119
+
120
+ Prebuilt native binaries are shipped for **Node 24 and Node 26** on **Linux** (x64 and arm64), **macOS** (Apple Silicon), and **Windows** (x64). If a matching prebuilt binary is not found for your platform (for example an Intel Mac), the package **compiles the Rust core automatically** at install time. That needs a [Rust toolchain](https://rustup.rs), `cmake`, and a C/C++ compiler (BoringSSL is built from source). See [Building from source](#building-from-source).
121
+
122
+ ---
123
+
124
+ ## Quick start
125
+
126
+ ```ts
127
+ import { WebTransport } from 'rwebtransport';
128
+
129
+ // 1. Open a session (QUIC handshake plus HTTP/3 Extended CONNECT).
130
+ const wt = new WebTransport('https://localhost:4433/chat', {
131
+ // Trust a specific self-signed cert by its SHA-256, exactly like the browser API:
132
+ serverCertificateHashes: [{ algorithm: 'sha-256', value: certHashBytes }],
133
+ });
134
+ await wt.ready;
135
+
136
+ // 2. Send an unreliable datagram.
137
+ const dgramWriter = wt.datagrams.writable.getWriter();
138
+ await dgramWriter.write(new Uint8Array([1, 2, 3]));
139
+
140
+ // 3. Accept streams the server opens.
141
+ const reader = wt.incomingUnidirectionalStreams.getReader();
142
+ const { value: receive } = await reader.read();
143
+ if (receive) {
144
+ const { value: bytes } = await receive.getReader().read();
145
+ console.log('server pushed', bytes?.length ?? 0, 'bytes');
146
+ }
147
+
148
+ // 4. Close.
149
+ wt.close({ closeCode: 0, reason: 'bye' });
150
+ ```
151
+
152
+ Runnable versions of these live in [`examples/`](./examples).
153
+
154
+ ---
155
+
156
+ ## Reliable streams and unreliable datagrams
157
+
158
+ Yes, both, over the one QUIC connection, and this library implements each:
159
+
160
+ - **Streams are reliable and ordered.** A bidirectional stream (or a one-way send / receive stream) is a WHATWG `ReadableStream` / `WritableStream` of bytes. Everything you write is delivered, in order, with end-to-end backpressure onto QUIC flow control. Open as many as you want; they are independently multiplexed, so a stall on one never blocks another (no head-of-line blocking).
161
+ - **Datagrams are unreliable and unordered.** `session.datagrams` is a duplex of `Uint8Array` messages. Each datagram is sent best-effort in a single QUIC packet: it may be dropped, reordered, or never arrive, and it is never retransmitted. Reach for them when you would rather drop data than delay it: position updates, audio frames, heartbeats.
162
+
163
+ The complete TypeScript program below starts a server, connects a client, and exercises both. It is the runnable [`examples/echo.ts`](./examples/echo.ts) (the in-repo copy imports the built output; in your own project the import is `from 'rwebtransport'`). On Node 24+ you can run it directly with `node examples/echo.ts`.
164
+
165
+ ```ts
166
+ import { X509Certificate, createHash } from 'node:crypto';
167
+ import { readFileSync } from 'node:fs';
168
+ import { dirname, join } from 'node:path';
169
+ import { fileURLToPath } from 'node:url';
170
+
171
+ import { WebTransport, WebTransportServer, type WebTransportServerSession } from 'rwebtransport';
172
+
173
+ const HERE = dirname(fileURLToPath(import.meta.url));
174
+ const CERT = join(HERE, 'cert.pem');
175
+ const KEY = join(HERE, 'key.pem');
176
+
177
+ const encoder = new TextEncoder();
178
+ const decoder = new TextDecoder();
179
+ const sleep = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms));
180
+
181
+ // SHA-256 of the certificate's DER encoding: exactly what serverCertificateHashes wants.
182
+ function certHash(path: string): Uint8Array {
183
+ const der = new X509Certificate(readFileSync(path)).raw;
184
+ return new Uint8Array(createHash('sha256').update(der).digest());
185
+ }
186
+
187
+ // Echo an accepted session: pipe every reliable stream and every datagram back.
188
+ function echo(session: WebTransportServerSession): void {
189
+ void (async () => {
190
+ const reader = session.incomingBidirectionalStreams.getReader();
191
+ for (;;) {
192
+ const { value: stream, done } = await reader.read();
193
+ if (done) break;
194
+ if (stream) void stream.readable.pipeTo(stream.writable).catch(() => {});
195
+ }
196
+ })();
197
+ void session.datagrams.readable.pipeTo(session.datagrams.writable).catch(() => {});
198
+ }
199
+
200
+ // Read a reliable readable stream to end-of-stream and return all its bytes.
201
+ async function readAll(readable: ReadableStream<Uint8Array>): Promise<Uint8Array> {
202
+ const reader = readable.getReader();
203
+ const chunks: Uint8Array[] = [];
204
+ let total = 0;
205
+ for (;;) {
206
+ const { value, done } = await reader.read();
207
+ if (done) break;
208
+ if (value) {
209
+ chunks.push(value);
210
+ total += value.length;
211
+ }
212
+ }
213
+ const out = new Uint8Array(total);
214
+ let offset = 0;
215
+ for (const chunk of chunks) {
216
+ out.set(chunk, offset);
217
+ offset += chunk.length;
218
+ }
219
+ return out;
220
+ }
221
+
222
+ async function main(): Promise<void> {
223
+ // Server: bind an OS-assigned loopback port and echo everything.
224
+ const server = new WebTransportServer({ host: '127.0.0.1', port: 0, cert: CERT, key: KEY });
225
+ await server.ready;
226
+ void (async () => {
227
+ const reader = server.incomingSessions.getReader();
228
+ for (;;) {
229
+ const { value: session, done } = await reader.read();
230
+ if (done) break;
231
+ if (session) echo(session);
232
+ }
233
+ })();
234
+
235
+ const url = `https://127.0.0.1:${server.port}/echo`;
236
+ console.log(`server listening at ${url}`);
237
+
238
+ // Client: connect, trusting the server's pinned certificate.
239
+ const client = new WebTransport(url, {
240
+ serverCertificateHashes: [{ algorithm: 'sha-256', value: certHash(CERT) }],
241
+ });
242
+ await client.ready;
243
+ console.log('client connected');
244
+
245
+ // RELIABLE: a bidirectional stream. Delivery is guaranteed and ordered.
246
+ const stream = await client.createBidirectionalStream();
247
+ const writer = stream.writable.getWriter();
248
+ await writer.write(encoder.encode('hello over a reliable stream'));
249
+ await writer.close(); // ends our send side so the echo's read side sees `done`
250
+ const reply = decoder.decode(await readAll(stream.readable));
251
+ console.log(`reliable stream echo: ${JSON.stringify(reply)}`);
252
+
253
+ // UNRELIABLE: a datagram. Best-effort: it may be dropped, so we retry.
254
+ const dgWriter = client.datagrams.writable.getWriter();
255
+ const dgReader = client.datagrams.readable.getReader();
256
+ const payload = encoder.encode('hello over an unreliable datagram');
257
+ const inbound = dgReader.read().then((r) => r.value);
258
+ let echoed: Uint8Array | undefined;
259
+ for (let attempt = 0; attempt < 40 && !echoed; attempt++) {
260
+ await dgWriter.write(payload);
261
+ echoed = await Promise.race([inbound, sleep(25).then(() => undefined)]);
262
+ }
263
+ if (echoed) {
264
+ console.log(`unreliable datagram echo: ${JSON.stringify(decoder.decode(echoed))}`);
265
+ } else {
266
+ console.log('unreliable datagram echo: none (datagrams are lossy by design)');
267
+ }
268
+
269
+ // Clean shutdown of both ends.
270
+ client.close({ closeCode: 0, reason: 'done' });
271
+ server.close();
272
+ process.exit(0);
273
+ }
274
+
275
+ main().catch((err: unknown) => {
276
+ console.error('echo failed:', err);
277
+ process.exit(1);
278
+ });
279
+ ```
280
+
281
+ Running it prints:
282
+
283
+ ```text
284
+ server listening at https://127.0.0.1:53348/echo
285
+ client connected
286
+ reliable stream echo: "hello over a reliable stream"
287
+ unreliable datagram echo: "hello over an unreliable datagram"
288
+ ```
289
+
290
+ ---
291
+
292
+ ## The client API
293
+
294
+ `rwebtransport` implements the [W3C WebTransport](https://w3c.github.io/webtransport/) interface. If you have used it in a browser, you already know this library.
295
+
296
+ ### Connecting
297
+
298
+ ```ts
299
+ const wt = new WebTransport(url, options?);
300
+ await wt.ready; // resolves when the session is established, rejects if it fails
301
+ await wt.closed; // resolves when the session ends cleanly, rejects on abnormal close
302
+ ```
303
+
304
+ | Option | Type | Meaning |
305
+ | -------------------------------------------------------- | ------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- |
306
+ | `serverCertificateHashes` | `{ algorithm: 'sha-256', value: BufferSource }[]` | Accept a server cert by its SHA-256 fingerprint (self-signed or pinned). Bypasses CA and hostname checks for the matching cert, exactly like the browser. |
307
+ | `insecure` | `boolean` | Node extension. Disable **all** certificate verification. Development only. |
308
+ | `headers` | `Record<string, string>` | Node extension. Extra request headers on the Extended CONNECT. |
309
+ | `origin` | `string` | Node extension. Value for the `Origin` request header. |
310
+ | `allowPooling`, `requireUnreliable`, `congestionControl` | | Accepted for spec parity; currently informational. |
311
+
312
+ When neither `serverCertificateHashes` nor `insecure` is set, the client performs full PKI validation against the system trust store with hostname checking.
313
+
314
+ ### Bidirectional streams
315
+
316
+ ```ts
317
+ const stream = await wt.createBidirectionalStream();
318
+ // stream.readable : WebTransportReceiveStream (a ReadableStream<Uint8Array>)
319
+ // stream.writable : WebTransportSendStream (a WritableStream<Uint8Array>)
320
+
321
+ // Streams the peer opens:
322
+ const reader = wt.incomingBidirectionalStreams.getReader();
323
+ const { value: peerStream } = await reader.read();
324
+ ```
325
+
326
+ ### Unidirectional streams
327
+
328
+ ```ts
329
+ const send = await wt.createUnidirectionalStream(); // a WritableStream<Uint8Array>
330
+ const writer = send.getWriter();
331
+ await writer.write(payload);
332
+ await writer.close();
333
+ ```
334
+
335
+ ### Datagrams
336
+
337
+ ```ts
338
+ const writer = wt.datagrams.writable.getWriter();
339
+ await writer.write(new Uint8Array([0xde, 0xad]));
340
+
341
+ const reader = wt.datagrams.readable.getReader();
342
+ const { value } = await reader.read(); // Uint8Array or undefined
343
+
344
+ wt.datagrams.maxDatagramSize; // largest payload that fits in one packet
345
+ ```
346
+
347
+ ### Closing
348
+
349
+ ```ts
350
+ wt.close({ closeCode: 0, reason: 'done' });
351
+ await wt.closed;
352
+ ```
353
+
354
+ ---
355
+
356
+ ## The server API
357
+
358
+ The same package ships a **WebTransport server**. Bind a UDP port with a certificate, then consume `incomingSessions`. Each is a `WebTransportServerSession` with the exact same stream and datagram surface as the client `WebTransport`.
359
+
360
+ ```ts
361
+ import { WebTransportServer } from 'rwebtransport';
362
+
363
+ const server = new WebTransportServer({
364
+ port: 4433,
365
+ host: '0.0.0.0',
366
+ cert: '/path/to/cert.pem', // PEM certificate chain (file path)
367
+ key: '/path/to/key.pem', // PEM private key (file path)
368
+ });
369
+ await server.ready;
370
+ console.log('listening on', server.port);
371
+
372
+ const reader = server.incomingSessions.getReader();
373
+ for (;;) {
374
+ const { value: session, done } = await reader.read();
375
+ if (done) break;
376
+
377
+ console.log('new session:', session.path, session.authority);
378
+
379
+ // Echo every bidirectional stream straight back:
380
+ const streams = session.incomingBidirectionalStreams.getReader();
381
+ void (async () => {
382
+ for (;;) {
383
+ const { value: stream, done } = await streams.read();
384
+ if (done) break;
385
+ void stream.readable.pipeTo(stream.writable);
386
+ }
387
+ })();
388
+
389
+ // Open a stream or send a datagram from the server side:
390
+ const outbound = await session.createUnidirectionalStream();
391
+ await outbound.getWriter().write(new TextEncoder().encode('welcome'));
392
+ }
393
+ ```
394
+
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.
396
+
397
+ ---
398
+
399
+ ## Threading, workers, and cluster
400
+
401
+ - **Threading.** Each session runs its QUIC/HTTP-3 work on its own background thread and talks to the JS event loop through neon's `Channel`. Every hand-off is non-blocking (an unbounded command channel, a non-blocking event channel, atomics), so the library never deadlocks internally; it only ever applies backpressure. The one way to wedge a stream is the universal one: writing a large bidirectional stream without concurrently reading it. Read while you write.
402
+ - **`worker_threads`.** Fully supported. The addon is context-aware, so a client or server can be created inside any Worker and each Worker gets its own instance bound to its own event loop. Multiple Workers run concurrently.
403
+ - **`cluster`.** Clients work as-is (each process is independent). A server can share one listening port across cluster workers with `reusePort: true` (`SO_REUSEPORT`, Unix only); the kernel load-balances connections across the workers. On Windows, run one server per port or put a UDP load balancer in front.
404
+
405
+ ---
406
+
407
+ ## Docs and examples
408
+
409
+ - **[`docs/`](./docs)** is the full guide: getting started, the client and server APIs in depth, streams and backpressure, datagrams, certificates and TLS, error handling, threading, building, and troubleshooting.
410
+ - **[`examples/`](./examples)** has runnable client and server programs and a one-file end-to-end demo.
411
+
412
+ ---
413
+
414
+ ## Requirements
415
+
416
+ - **Node.js 24.x or 26.x.** No other versions are supported; the native ABI is built and tested against exactly these.
417
+ - **Linux, macOS, or Windows** (x64 or arm64).
418
+ - To build from source: **Rust** (stable), **cmake**, and a **C/C++ toolchain** (plus **NASM** on Windows) for BoringSSL.
419
+
420
+ ---
421
+
422
+ ## How it works
423
+
424
+ ```mermaid
425
+ flowchart TB
426
+ classDef js fill:#0e1520,stroke:#2563ff,stroke-width:2px,color:#cfe0ff;
427
+ classDef rust fill:#160f1f,stroke:#7c3aed,stroke-width:2px,color:#ead7ff;
428
+ classDef net fill:#0c1a14,stroke:#10b981,stroke-width:2px,color:#c8f5e2;
429
+
430
+ subgraph APP["your code"]
431
+ YOU["import { WebTransport, WebTransportServer } from 'rwebtransport'"]
432
+ end
433
+
434
+ subgraph TS["TypeScript layer, the WHATWG surface"]
435
+ direction TB
436
+ WTAPI["WebTransport / WebTransportServer / streams / datagrams<br/>ReadableStream + WritableStream + backpressure<br/>ready / closed promises"]
437
+ LOADER["loader: pick prebuilt .node<br/>else compile via cargo"]
438
+ end
439
+
440
+ subgraph NATIVE["native addon in Rust (neon / N-API)"]
441
+ direction TB
442
+ BIND["neon bindings<br/>commands in, events out (Channel)"]
443
+ DRIVER["driver thread<br/>UDP socket + quiche recv/send/timeout loop"]
444
+ H3WT["H3 + WebTransport (dual-role)<br/>control streams, SETTINGS, Extended CONNECT<br/>QPACK, 0x54/0x41 stream signals, datagram quarter-id"]
445
+ TLS["TLS config<br/>Chrome cipher suites, X25519/P-256/P-384, TLS 1.3"]
446
+ end
447
+
448
+ subgraph ENGINE["vendored engine"]
449
+ QUICHE["Cloudflare quiche 0.29, QUIC transport and HTTP/3"]
450
+ BSSL["BoringSSL for the TLS 1.3 handshake"]
451
+ end
452
+
453
+ WIRE["UDP, QUIC, HTTP/3, WebTransport"]
454
+
455
+ YOU --> WTAPI
456
+ WTAPI --> LOADER
457
+ LOADER --> BIND
458
+ BIND <--> DRIVER
459
+ DRIVER --> H3WT
460
+ H3WT --> QUICHE
461
+ TLS --> BSSL
462
+ QUICHE --> BSSL
463
+ QUICHE --> WIRE
464
+
465
+ class YOU,WTAPI,LOADER js;
466
+ class BIND,DRIVER,H3WT,TLS rust;
467
+ class QUICHE,BSSL,WIRE net;
468
+ ```
469
+
470
+ 1. **The TypeScript layer** presents the browser `WebTransport` API (and `WebTransportServer`) and maps it onto WHATWG `ReadableStream`/`WritableStream`, wiring up backpressure both ways.
471
+ 2. **The neon binding** turns JS calls into commands for a dedicated **driver thread** and delivers asynchronous events (stream data, datagrams, session state) back to the event loop.
472
+ 3. **The driver thread** owns a UDP socket and runs the **quiche** connection: reading packets, writing packets, arming timers.
473
+ 4. **The H3/WebTransport layer**, since quiche does not itself speak WebTransport, implements the HTTP/3 control streams, the `SETTINGS` exchange, QPACK-encoded **Extended CONNECT** (sent by the client, answered by the server), the `0x54`/`0x41` stream signals, and the RFC 9297 quarter-stream-id datagram framing, all on top of quiche's raw QUIC streams. The state machine is dual-role, so client and server share one hardened implementation.
474
+ 5. **BoringSSL**, configured with a Chrome-like TLS profile, performs the TLS 1.3 handshake inside QUIC.
475
+
476
+ ---
477
+
478
+ ## Building from source
479
+
480
+ ```bash
481
+ git clone https://github.com/dacely-cloud/rwebtransport
482
+ cd rwebtransport
483
+ npm install
484
+ npm run build # cargo build, copy .node, bundle TS
485
+ ```
486
+
487
+ The native crates live in `crates/`, the QUIC engine is vendored under `vendor/quiche`, and the compiled addon is written to `prebuilds/<platform>-<arch>/rwebtransport.node`.
488
+
489
+ ```bash
490
+ npm run build:rust # release build of the native addon
491
+ npm run build:rust:debug # faster debug build
492
+ npm run build:ts # bundle the TypeScript layer
493
+ ```
494
+
495
+ Building from source needs a Rust toolchain, cmake, a C/C++ compiler, and Go (BoringSSL is compiled from source). Helper scripts install the toolchain for you, one per platform family:
496
+
497
+ ```bash
498
+ npm run setup:unix # Linux/macOS: compiler, cmake, ninja, Go, Rust via your package manager
499
+ ```
500
+
501
+ ```powershell
502
+ npm run setup:windows # Windows: Rust, CMake, Go, NASM via winget, and sets ASM_NASM
503
+ ```
504
+
505
+ On **Windows** you also need NASM (BoringSSL's assembler) and the MSVC C++ Build Tools. `setup:windows` installs Rust, CMake, Go, and NASM and sets `ASM_NASM`; it checks for the MSVC C++ Build Tools and Node and points you to any that are missing, but it does not auto-install the multi-gigabyte Visual Studio C++ workload. If a `cargo build` there fails with `Could not find the compiler specified in the environment variable ASM_NASM`, that is the missing NASM; run the script above (or see [`docs/building.md`](./docs/building.md#windows-setup)) and rebuild in a fresh terminal.
506
+
507
+ ---
508
+
509
+ ## Testing
510
+
511
+ End-to-end tests run the real client and the real server against each other and against a dedicated quiche echo-server fixture. No mocks.
512
+
513
+ ```bash
514
+ npm test
515
+ ```
516
+
517
+ The suite covers the QUIC handshake, Extended CONNECT, bidirectional and unidirectional streams, datagrams, backpressure, and graceful and error close paths. It also includes:
518
+
519
+ - an **adversarial suite** that points a real client at a deliberately hostile server (rejected CONNECT, malformed QPACK, garbage frames, stream resets, mid-session close) and a careless caller (operations after close, oversized datagrams);
520
+ - **server** tests where our own client drives our own server (bidi echo, large payloads, unidirectional echo, datagrams, concurrent sessions);
521
+ - **`worker_threads`** tests (a client running inside a Worker, multiple Workers concurrently) and a **deadlock-freedom** test (a payload larger than every flow-control window echoed with concurrent read and write).
522
+
523
+ ---
524
+
525
+ ## Robustness
526
+
527
+ The native core treats the peer and the caller as untrusted, on both the client and the server:
528
+
529
+ - **A panic can never crash Node.** The entire driver thread runs inside a panic boundary; a panic (or a fatal setup error) is surfaced as an `error` event that rejects `ready`/`closed`. It never aborts the process and never silently hangs the session.
530
+ - **Bounded memory under flood.** A hostile peer cannot grow memory without limit: event delivery to the JS loop is backpressured (unread stream data stays flow-controlled in QUIC, excess datagrams are dropped), the datagram queue is bounded, HTTP/3 frame buffers are capped, and finished streams are pruned.
531
+ - **No blocking on the event loop.** DNS resolution, the socket bind, and the QUIC handshake all run on the driver thread, so the constructor never blocks Node.
532
+ - **Hostile input is fail-closed.** Malformed HTTP/3, bad QPACK, oversized frames, unexpected resets, and out-of-range numbers from JS are handled by rejecting or closing cleanly rather than panicking.
533
+
534
+ ---
535
+
536
+ ## Security and the TLS profile
537
+
538
+ By default the client advertises the **Google Chrome** TLS profile: Chrome's cipher-suite order, the `X25519 / P-256 / P-384` group preference, and Chrome's signature-algorithm list, negotiated as **TLS 1.3 only** (as QUIC requires). This makes the handshake indistinguishable from a browser's and maximizes compatibility with servers (including Cloudflare) that key behavior off the TLS ClientHello.
539
+
540
+ Certificate verification follows the WebTransport model: full PKI validation by default, or explicit trust of a server certificate by its `sha-256` hash via `serverCertificateHashes`, exactly like the browser API. The `insecure` option disables verification entirely and is intended for development only.
541
+
542
+ ---
543
+
544
+ ## License
545
+
546
+ [Apache-2.0](./LICENSE). Vendored components (Cloudflare quiche, BoringSSL, neon) remain under their own licenses. See [NOTICE](./NOTICE).
547
+
548
+ <div align="center">
549
+ <sub>Built by <a href="https://github.com/dacely-cloud">Dacely Cloud</a>.</sub>
550
+ </div>