quico 0.3.0 → 0.7.0

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
@@ -7,82 +7,167 @@
7
7
  <em>Pure JavaScript implementation of QUIC, HTTP/3, QPACK &amp; WebTransport for Node.js</em>
8
8
  </p>
9
9
 
10
+ <p align="center">
11
+ <strong>The entire HTTP/3 stack — QUIC, TLS 1.3, QPACK, congestion control — in JavaScript you can read.</strong>
12
+ </p>
13
+
10
14
  <p align="center">
11
15
  <a href="https://www.npmjs.com/package/quico">
12
16
  <img src="https://img.shields.io/npm/v/quico?color=blue" alt="npm">
13
17
  </a>
14
- <img src="https://img.shields.io/badge/status-in%20development-yellow" alt="status">
18
+ <img src="https://img.shields.io/badge/status-beta-yellow" alt="status">
19
+ <img src="https://img.shields.io/badge/interop-6%2F6%20implementations-brightgreen" alt="interop">
15
20
  <img src="https://img.shields.io/github/license/colocohen/quico?color=brightgreen" alt="license">
16
21
  </p>
17
22
 
18
23
  ---
19
24
 
20
- > **⚠️ Project status: Active development.**
21
- > APIs may change before v1.0. Use at your own risk and please report issues!
25
+ > **⚠️ Project status: Beta — active development.**
26
+ > The core transport is verified against six independent QUIC implementations
27
+ > (see [Interoperability](#-interoperability)), but APIs may still change before
28
+ > v1.0. Please report issues!
22
29
 
23
30
  ---
24
31
 
25
-
26
32
  ## Table of Contents
33
+
27
34
  1. [What is QUIC / HTTP/3?](#-what-is-quic--http3)
28
35
  2. [Why QUICO?](#-why-quico)
29
- 3. [Quick Start](#-quick-start)
30
- 4. [Features](#-features)
31
- 5. [Node.js API Compatibility](#-nodejs-api-compatibility)
32
- 6. [WebTransport](#-webtransport)
33
- 7. [Testing](#-testing)
34
- 8. [Project Structure](#-project-structure)
35
- 9. [Roadmap](#-roadmap)
36
- 10. [Sponsors](#-sponsors)
37
- 11. [Contact](#-contact)
38
- 12. [License](#-license)
36
+ 3. [Requirements & Installation](#-requirements--installation)
37
+ 4. [Quick Start](#-quick-start)
38
+ 5. [Features](#-features)
39
+ 6. [Design Choices](#-design-choices)
40
+ - [The send model: range reconciliation](#the-send-model-range-reconciliation-not-retransmission)
41
+ - [Congestion control](#congestion-control-bbr-style-not-loss-based)
42
+ - [The first round trips](#the-first-round-trips)
43
+ - [A returning client: Careful Resume](#a-returning-client-careful-resume)
44
+ - [Stream scheduling](#stream-scheduling-byte-level-round-robin)
45
+ - [Loss detection](#loss-detection-timers-and-how-we-treat-late-acks)
46
+ - [The handshake](#the-handshake-coalesced-datagrams-its-own-loss-detection)
47
+ - [Flow control](#flow-control-consumption-based-windows)
48
+ 7. [Interoperability](#-interoperability)
49
+ 8. [API Reference](#-api-reference)
50
+ - [`createServer()`](#quicocreateserveroptions-requestlistener)
51
+ - [`request()` / `get()`](#quicorequesturloptions-options-callback)
52
+ - [`IncomingMessage`](#incomingmessage) · [`ServerResponse`](#serverresponse) · [`ClientRequest`](#clientrequest)
53
+ - [`Agent`](#agent) · [`createSecureContext()`](#quicocreatesecurecontextoptions)
54
+ - [0-RTT (early data)](#0-rtt-early-data)
55
+ - [Framework compatibility](#framework-compatibility)
56
+ - [WebTransport](#webtransport-1)
57
+ - [WebSocket](#websocket-1)
58
+ - [CONNECT-UDP (proxying UDP)](#connect-udp-proxying-udp)
59
+ - [Fingerprinting](#fingerprinting-1)
60
+ - [Protocol layers](#protocol-layers)
61
+ - [Low-level QUIC API](#low-level-quic-api)
62
+ 9. [Configuration & Tuning](#-configuration--tuning)
63
+ 10. [Debugging](#-debugging)
64
+ 11. [Testing](#-testing)
65
+ 12. [Project Structure](#-project-structure)
66
+ 13. [Security](#-security)
67
+ 14. [Known Limitations](#-known-limitations)
68
+ 15. [Roadmap](#-roadmap)
69
+ 16. [Contributing](#-contributing)
70
+ 17. [Sponsors](#-sponsors)
71
+ 18. [Contact](#-contact)
72
+ 19. [License](#-license)
39
73
 
74
+ ---
40
75
 
41
76
  ## ⚡ What is QUIC / HTTP/3?
42
77
 
43
- **QUIC** is the future of Internet transport protocols. Created at Google and standardized by the IETF, QUIC powers **HTTP/3** and is already deployed at scale by the world’s largest platforms. It was specifically designed to overcome the limitations of TCP and deliver a faster, smoother, and more resilient web.
78
+ **QUIC is the future of Internet transport protocols.** Created at Google,
79
+ standardized by the IETF as [RFC 9000](https://www.rfc-editor.org/rfc/rfc9000), QUIC
80
+ powers **HTTP/3** and is already deployed at scale by the world's largest platforms.
81
+ It was specifically designed to overcome the limitations of TCP and deliver a faster,
82
+ smoother, and more resilient web.
44
83
 
45
84
  Key advantages of QUIC include:
46
85
 
47
- - **Eliminating bottlenecks**: With TCP, data must arrive strictly in order. If a single packet is lost or delayed, all subsequent packets are blocked until it arrives — a phenomenon called **head-of-line blocking**. QUIC removes this bottleneck by running over UDP, so each package arrives on its own and avoids dependence on delayed pieces of data.
86
+ - **Eliminating bottlenecks** — With TCP, data must arrive strictly in order. If a
87
+ single packet is lost or delayed, *all* subsequent packets are blocked until it
88
+ arrives — a phenomenon called **head-of-line blocking**. QUIC removes this
89
+ bottleneck by running over UDP and multiplexing independent streams: each stream
90
+ makes progress on its own, and a loss on one never stalls the others.
48
91
 
49
- - **UDP efficiency**: By running over UDP, QUIC bypasses decades of kernel-level constraints, enabling lightning-fast performance even on constrained devices such as smartphones, IoT hardware, or edge gateways.
92
+ - **UDP efficiency** — By running over UDP, QUIC bypasses decades of kernel-level TCP
93
+ constraints, enabling fast connection handling even on constrained devices such as
94
+ smartphones, IoT hardware, or edge gateways.
50
95
 
51
- - **Security by default**: TLS 1.3 is built directly into the protocol. Every connection is encrypted — no exceptions, no downgrade paths.
96
+ - **Security by default** — TLS 1.3 is built directly into the protocol. Every
97
+ connection is encrypted — no exceptions, no downgrade paths. Even the packet
98
+ headers are cryptographically protected.
52
99
 
53
- - **Seamless mobility**: Connections remain stable as devices move across networks (e.g., Wi-Fi → 4G/5G) or switch IP addresses, without breaking the session.
100
+ - **Seamless mobility** — Connections are identified by connection IDs rather than
101
+ IP/port 4-tuples, so a session can survive a device moving across networks
102
+ (Wi-Fi → 4G/5G) or changing addresses.
54
103
 
55
- - **Lower latency**: QUIC merges the transport and TLS handshake into fewer round-trips, significantly reducing connection setup time.
104
+ - **Lower latency** — QUIC merges the transport and TLS handshakes into a single
105
+ exchange, significantly reducing connection setup time.
56
106
 
57
- - **Smarter congestion control**: Advanced congestion control algorithms (such as BBR) continuously measure bandwidth, round-trip time, and loss in real time. They dynamically adjust to real-world network conditions.
107
+ - **Smarter congestion control** — Modern algorithms such as BBR continuously measure
108
+ bandwidth and round-trip time instead of only reacting to loss, adapting to
109
+ real-world network conditions in real time.
58
110
 
111
+ QUIC combines **UDP speed, TCP reliability, mandatory TLS security, and adaptive
112
+ multiplexing** into one transport layer.
59
113
 
60
- QUIC combines **UDP speed, TCP reliability, mandatory TLS security, and adaptive multiplexing** into one powerful transport layer.
61
-
62
- **HTTP/3** (h3 in short) is the layer on top of QUIC. This is the evolution of the web’s application layer. Instead of riding over TCP, HTTP/3 maps HTTP requests and responses directly onto QUIC streams.
63
- HTTP/3 is also himself dramatically reduces overhead and improves efficiency - thats bring faster page loads and real-time applications that scale across the modern web.
64
-
114
+ **HTTP/3** ([RFC 9114](https://www.rfc-editor.org/rfc/rfc9114)) is the layer on top:
115
+ the evolution of the web's application protocol. Instead of riding over TCP, HTTP/3
116
+ maps requests and responses directly onto QUIC streams, with
117
+ [QPACK](https://www.rfc-editor.org/rfc/rfc9204) header compression designed to avoid
118
+ reintroducing head-of-line blocking. The result: faster page loads and real-time
119
+ applications that scale across the modern web.
65
120
 
121
+ ---
66
122
 
67
123
  ## 🧠 Why QUICO?
68
124
 
69
- Node.js is the backbone of countless modern web applications, but it currently lacks a native QUIC implementation. Supporting QUIC inside Node.js requires **deep access to TLS internals** that Node's existing TLS APIs don't expose. Beyond that, QUIC demands a **highly complex architecture** — intricate state machines, packet schedulers, and congestion control mechanisms.
70
-
71
- **QUICO** brings this missing capability directly into the **Node.js ecosystem**. It is a from-scratch JavaScript implementation of QUIC, HTTP/3 and WebTransport, built without relying on OpenSSL or native code. At its core, it uses [LemonTLS](https://github.com/colocohen/lemon-tls) — a pure JavaScript TLS 1.3 library built by the same author — to provide the cryptographic layer that QUIC requires. Together, QUICO and LemonTLS form a complete, fully auditable JavaScript networking stack from UDP to HTTP/3.
72
-
73
- **What this means for you:**
125
+ Node.js is the backbone of countless modern web applications — yet it has **no native
126
+ QUIC implementation**. The browser you're reading this in speaks HTTP/3. The CDN that
127
+ served this page speaks HTTP/3. Your Node server? Stuck on TCP.
128
+
129
+ Why? Supporting QUIC inside Node.js requires **deep access to TLS internals** that
130
+ Node's existing TLS APIs simply don't expose. TLS-over-TCP hands you an encrypted
131
+ *byte stream*; QUIC needs something entirely different — the raw **handshake secrets**
132
+ at each encryption level, so it can derive its own packet-protection keys and encrypt
133
+ each packet individually. `node:tls` was never built to hand those out. Beyond the
134
+ crypto, QUIC demands a genuinely complex architecture: interlocking state machines
135
+ across three packet-number spaces, a packet scheduler with pacing, loss detection
136
+ timers, and congestion control.
137
+
138
+ **QUICO brings this missing capability directly into the Node.js ecosystem.** It is a
139
+ from-scratch JavaScript implementation of QUIC, HTTP/3 and WebTransport, built without
140
+ OpenSSL and without a single line of native code. The cryptographic layer is
141
+ [LemonTLS](https://github.com/colocohen/lemon-tls) — a pure JavaScript TLS 1.3 library
142
+ built by the same author specifically to expose what QUIC needs. Together, QUICO and
143
+ LemonTLS form a complete, fully auditable JavaScript networking stack from the UDP
144
+ socket all the way up to HTTP/3.
145
+
146
+ No build tools. No platform-specific binaries. No node-gyp. It runs anywhere Node runs
147
+ — Linux, macOS, Windows, ARM, Docker, edge — and when something breaks at 3 AM, the
148
+ stack trace ends in code you can open, not in a `.node` binary.
74
149
 
75
- - **`npm install` and go** — no build tools, no platform-specific binaries, no gyp
76
- - **Works everywhere Node.js runs** — Linux, macOS, Windows, ARM, Docker, edge
77
- - **Debuggable top to bottom** — every packet, every frame, every byte is JavaScript you can step through
150
+ ---
78
151
 
152
+ ## 📋 Requirements & Installation
79
153
 
80
- ## 📦 Quick Start
154
+ | Requirement | Notes |
155
+ |---|---|
156
+ | **Node.js 18+** | ESM only (`import`). Tested on 18, 20 and 22. |
157
+ | **No compiler** | Pure JavaScript — no native addons. |
158
+ | **Dependencies** | [`lemon-tls`](https://github.com/colocohen/lemon-tls) (TLS 1.3) and [`flat-ranges`](https://www.npmjs.com/package/flat-ranges) (range arithmetic). Nothing else. |
81
159
 
82
160
  ```bash
83
161
  npm install quico
84
162
  ```
85
163
 
164
+ QUICO is an **ES module**. Use `import`, and make sure your `package.json` has
165
+ `"type": "module"` (or use the `.mjs` extension).
166
+
167
+ ---
168
+
169
+ ## 📦 Quick Start
170
+
86
171
  ### Server
87
172
 
88
173
  ```js
@@ -90,7 +175,7 @@ import quico from 'quico';
90
175
  import fs from 'node:fs';
91
176
 
92
177
  const server = quico.createServer({
93
- key: fs.readFileSync('server.key'),
178
+ key: fs.readFileSync('server.key'),
94
179
  cert: fs.readFileSync('server.crt')
95
180
  }, (req, res) => {
96
181
  res.writeHead(200, { 'content-type': 'text/plain' });
@@ -108,48 +193,1528 @@ server.listen(4433, () => {
108
193
  import quico from 'quico';
109
194
 
110
195
  quico.request('https://www.google.com/', (res) => {
111
- console.log('Status:', res.statusCode); // 200
112
- console.log('Protocol:', res.httpVersion); // "3.0"
196
+ console.log('Status:', res.statusCode); // 200
197
+ console.log('Protocol:', res.httpVersion); // "3.0"
113
198
  res.on('data', (chunk) => process.stdout.write(chunk));
114
- });
199
+ }).end();
115
200
  ```
116
201
 
117
- > 📂 For more examples, see [`examples/`](./examples)
202
+ > GET and HEAD requests are ended for you on the next tick. For any method with a
203
+ > body, call `.end()` — like `node:https`, the request isn't sent until you do.
204
+
205
+ > 📂 More examples in [`examples/`](./examples)
206
+
207
+ ---
118
208
 
119
209
 
120
210
  ## ✨ Features
121
211
 
122
- ### HTTP/3 Server & Client
123
- - Full request/response cycle over QUIC
124
- - QPACK header compression with static and dynamic tables
125
- - Standard Node.js API: `req.headers`, `res.writeHead()`, `res.end()`
126
- - Multiple requests per connection (stream multiplexing)
127
- - Automatic `Alt-Svc` header for HTTP/3 protocol discovery
128
- - H3 → H2 → H1 fallback when QUIC isn't available
129
- - Tested against Google, Cloudflare, Facebook, Microsoft and nginx QUIC servers
212
+ ### One HTTP stack, three versions
213
+ QUICO does not import `node:http`, `node:https`, `node:http2` or `node:tls`. HTTP/1.1,
214
+ HTTP/2 and HTTP/3 are all implemented here, and all three hand the application the
215
+ same `IncomingMessage` / `ServerResponse` — so a framework written against `node:http`
216
+ runs over any of them without knowing which. For the network and cryptography, all
217
+ QUICO takes from Node is `node:net` (TCP), `node:dgram` (UDP) and `node:crypto`
218
+ (primitives).
219
+
220
+ - **HTTP/3** (RFC 9114) with QPACK, static and dynamic tables (RFC 9204); up to 100
221
+ blocked streams — a field section that references an entry whose insertion has not
222
+ arrived yet waits for it (`SETTINGS_QPACK_BLOCKED_STREAMS`)
223
+ - **HTTP/2** (RFC 9113) with HPACK, including h2c by connection preface
224
+ - **HTTP/1.1** with keep-alive, chunked transfer and trailers
225
+ - One server listens on UDP and TCP and serves all three; `Alt-Svc` is advertised
226
+ on HTTPS HTTP/1.1 and HTTP/2 responses so browsers discover HTTP/3 (see `altSvc`)
227
+ - Client with automatic H3 → H2 → H1.1 fallback, connection pooling and
228
+ per-origin coalescing
229
+ - `103 Early Hints` (`res.writeEarlyHints()`) on all three versions
230
+ - Extra protocols on the same TCP port through ALPN or byte sniffing
231
+ (`server.addProtocol()`)
232
+
233
+ ### QUIC Transport
234
+ - QUIC v1 (RFC 9000) and **QUIC v2** (RFC 9369) — Initial, Handshake and 1-RTT packet
235
+ spaces; everything a version decides (salt, key labels, packet type bits, Retry key)
236
+ in one profile per version (`quic_version.js`), the rest shared
237
+ - Compatible version negotiation (RFC 9368): a client that starts in v1 and offers v2 is
238
+ moved to v2 without a round trip when the server prefers it (`quicVersions`); Version
239
+ Negotiation and a second attempt when there is no compatible version
240
+ - TLS 1.3 handshake via LemonTLS, no OpenSSL (RFC 9001)
241
+ - Version Negotiation (RFC 9000 §6)
242
+ - HelloRetryRequest — X25519, P-256, P-384
243
+ - AES-128-GCM and AES-256-GCM
244
+ - Key Update — bidirectional key phase rotation (RFC 9001 §6)
245
+ - Session resumption on the server, with ticket keys shared across connections
246
+ (`ticketKeys`)
247
+ - Retry and address validation, switchable at runtime (`validateAddress`)
248
+ - Handshakes under way counted for the application (`getPendingHandshakes()`,
249
+ `'handshakeLoad'`), and capped per client address (`maxHandshakesPerAddress`)
250
+ - Anti-amplification limit — 3× until the client's address is validated (RFC 9000 §8.1)
251
+ - Connection migration (RFC 9000 §9): a client may move to another network (Wi-Fi to
252
+ cellular) and go on in the same connection — each side issues spare connection IDs
253
+ (NEW_CONNECTION_ID, RETIRE_CONNECTION_ID, Retire Prior To) and the new path is
254
+ addressed by one of its own (§9.5); NAT rebinding is followed too. Each new address is
255
+ validated with PATH_CHALLENGE first, and congestion/RTT state starts over on a new IP
256
+ - NEW_TOKEN (RFC 9000 §8.1.3): a returning client's address needs no proof — no Retry,
257
+ no 3× limit; the agent keeps one token per server and uses it once
258
+ - ACK frequency (draft-ietf-quic-ack-frequency): a receiver follows ACK_FREQUENCY and
259
+ IMMEDIATE_ACK; a sender with many packets in flight asks for an ACK every ~10 packets —
260
+ an 8 MB download, ~340 ACK packets instead of ~3,400
261
+ - `grease_quic_bit` (RFC 9287): the fixed bit sent unpredictable to a peer that allows it
262
+ (not on a UDP port shared with other protocols)
263
+ - Certificate compression (RFC 8879, in LemonTLS): the server's chain compressed for a
264
+ client that offers it (Chrome: brotli), only when it comes out smaller, and once per chain
265
+ (cached). The client offers brotli, zstd and zlib on every version. A client certificate
266
+ goes compressed when the server's CertificateRequest asks. Decompressing stops at the
267
+ declared length and never goes past 128 KB. With an RSA-4096 chain, the server's
268
+ Handshake flight over QUIC went from 9.6 KB to 6.0 KB. The server's algorithms are
269
+ `createServer({ certificateCompression })`; what went on the wire, each way, is
270
+ `socket.getNegotiationResult().certificateCompression` on every version. The chain is
271
+ compressed when the server is made, in the background, not by the first client's
272
+ handshake (brotli at quality 11: ~4 ms for a small chain, ~18 ms for 9 KB)
273
+ - Encrypted Client Hello (RFC 9849, in LemonTLS) — HTTP/3, HTTP/2 and HTTP/1.1 alike: the
274
+ site name and ALPN travel encrypted, to a key published in DNS (`ech`; see
275
+ [Encrypted Client Hello](#encrypted-client-hello-ech))
276
+ - Stateless reset with HMAC-derived tokens (`resetTokenSecret`)
277
+ - Stream and connection-level flow control with sliding windows
278
+ - Stream limits enforced in both directions, and raised with `MAX_STREAMS` as
279
+ streams close (RFC 9000 §4.6)
280
+ - Loss detection with PTO and exponential backoff (RFC 9002)
281
+ - BBR-style congestion control with pacing
282
+ - Path MTU discovery (DPLPMTUD, RFC 8899)
283
+ - Unreliable datagrams (RFC 9221)
284
+ - Idle timeout, keep-alive, TLS keylog export for Wireshark
130
285
 
131
286
  ### WebTransport
132
- - Client and server implementation
133
- - Bidirectional and unidirectional streams (Node.js Duplex + WHATWG Streams API)
134
- - Unreliable datagrams (RFC 9297)
287
+ - Client and server (RFC 9297 + draft-ietf-webtrans-http3)
288
+ - Bidirectional and unidirectional streams (Node.js Duplex API)
289
+ - Unreliable datagrams
135
290
  - Natural API: `req.on('stream')`, `res.sendDatagram()`, `res.writeHead(200)` to accept
136
291
 
137
- ### QUIC Transport
138
- - Full TLS 1.3 handshake via LemonTLS (no OpenSSL)
139
- - Initial, Handshake, and 1-RTT packet handling
140
- - Connection ID management
141
- - ACK processing and flow control
142
- - Key updates (key phase bit rotation)
143
- - HelloRetryRequest support (P-256, P-384, X25519)
144
- - AES-128-GCM and AES-256-GCM cipher suites
145
- - Handshake timeout
292
+ ### WebSocket
293
+ - Server over all three versions: HTTP/1.1 Upgrade, HTTP/2 extended CONNECT
294
+ (RFC 8441) and HTTP/3 extended CONNECT (RFC 9220) — one `'upgrade'` event for all
295
+ - `WebSocketServer` in the shape of the `ws` package, and a WHATWG-style
296
+ `WebSocket` client (HTTP/1.1)
297
+
298
+ ### CONNECT-UDP
299
+ - A UDP proxy (RFC 9298, MASQUE) over HTTP/3 — QUIC datagrams — and HTTP/2 and
300
+ HTTP/1.1 — capsules: `server.on('connectUdp', (req, tunnel) => tunnel.accept())`
301
+ - Its client: `quico.connectUdp(proxy, { host, port })`, a `dgram.Socket` that goes
302
+ through the proxy
303
+
304
+ ### Fingerprinting
305
+ - JA4H (HTTP request), HTTP/2 and HTTP/3 protocol fingerprints, per request
306
+ - TLS fingerprints (JA4, JA4S, JA5) through LemonTLS
307
+ - `profileRequest()` — scores how well a request's protocol behaviour matches the
308
+ client it claims to be
309
+
310
+ ---
311
+
312
+ ## 🧬 Design Choices
313
+
314
+ Two QUIC implementations can both be fully conformant and still behave completely
315
+ differently on the wire. RFC 9000 defines *what* must happen; it deliberately leaves
316
+ *how* to the implementer. This section documents where QUICO made a choice — the
317
+ places where another implementation would reasonably do something else.
318
+
319
+ ### The send model: range reconciliation, not retransmission
320
+
321
+ This is the foundational choice, and the one that most distinguishes QUICO from other
322
+ implementations.
323
+
324
+ **How it's normally done.** RFC 9002 describes tracking each packet you send along
325
+ with the frames it contained. When loss detection fires, you look up that packet,
326
+ recover its frames, and put them back in a retransmission queue. The sender is
327
+ *procedural*: an event happens (loss), and you perform a corrective action
328
+ (re-enqueue). Almost every QUIC stack works this way.
329
+
330
+ **What QUICO does instead.** There is no `sent_packets` table, no stored frame copies,
331
+ and no retransmission queue — those concepts don't exist in the codebase. Each stream
332
+ keeps only this:
333
+
334
+ ```js
335
+ {
336
+ q: [Uint8Array, …], // the bytes the application wrote, as written
337
+ acked_ranges: [from, to, …], // byte ranges the peer has confirmed
338
+ in_flight_ranges: { 47: [from, to], 48: [from, to] }, // packet number → bytes it carries
339
+ missing_ranges: [from, to, …] // the answer to the question below, kept (see below)
340
+ }
341
+ ```
342
+
343
+ Every send opportunity asks one question, and it's a set operation:
344
+
345
+ ```js
346
+ missing = invert(acked_ranges ∪ in_flight_ranges, 0, total_size)
347
+ ```
348
+
349
+ Whatever's missing goes out. That's the whole algorithm. The sender doesn't remember
350
+ what it *did* — it asks what the peer *still needs*, every time. It's a declarative
351
+ model: continuously reconcile "what the peer has" against "what the peer should have",
352
+ and emit the difference.
353
+
354
+ **The answer is kept, not recomputed.** `acked_ranges ∪ in_flight_ranges` was computed
355
+ from every packet in flight, three or four times per send pass — with thousands of
356
+ packets in flight on a large transfer, that was a fifth of the CPU. Each stream now holds
357
+ the answer itself, as [flat-ranges](https://github.com/colocohen/flat-ranges)' three
358
+ states of what the peer has:
359
+
360
+ | flat-ranges | QUICO | the peer… |
361
+ |---|---|---|
362
+ | `have` | `acked_ranges` | has these bytes — acknowledged |
363
+ | `not_have` | `missing_ranges` | surely lacks them — never sent, or given up on |
364
+ | `unknown` | `in_flight_ranges` (by packet) | may have them — in flight |
365
+
366
+ `have` and `not_have` never overlap, and `missing_ranges` is what the sender sends from.
367
+ It changes at exactly five points ([`nothingMissing`](./src/quic_connection.js)
368
+ documents them):
369
+
370
+ | Event | `missing_ranges` |
371
+ |---|---|
372
+ | the application writes bytes | added |
373
+ | bytes yielded into a packet (`get_stream_chunks`) | removed |
374
+ | an ACK credits bytes — a late one included | removed |
375
+ | the expiry timer gives a packet up | its bytes added, except any acknowledged meanwhile (`add_not_have`) |
376
+ | a packet that never left (encryption failed) | its bytes added |
377
+
378
+ Adding a packet's bytes back is exact because each byte is in flight in one packet at
379
+ most: bytes are yielded only while missing, and become missing again only when the
380
+ packet that carried them expires. `sendstate_test` checks `missing_ranges` against the
381
+ complement of `acked_ranges ∪ in_flight_ranges`, rebuilt from scratch every few
382
+ milliseconds under loss, reordering and late ACKs, and that it never overlaps
383
+ `acked_ranges`.
384
+
385
+ Congestion control counts something else: **packets, by their size on the wire** — header,
386
+ frames, padding and AEAD tag, whatever they carry, as RFC 9002 counts bytes in flight.
387
+ Each packet the peer must acknowledge enters `pkt_in_flight` when it leaves and goes when
388
+ it is acknowledged or given up on; `app_bytes_in_flight` is their sum, kept as they come
389
+ and go, and an ACK delivers what its packets weighed. The window, the pacing rate and the
390
+ bandwidth BBR measures are one unit. (They used to be STREAM bytes, which left out the
391
+ packets' overhead, packets of control frames, and most of the handshake.)
392
+
393
+ **Loss detection, therefore, is still one step:**
394
+
395
+ ```js
396
+ delete st.in_flight_ranges[pn]; // not in flight any more
397
+ flat_ranges.add_not_have(acked, missing, lostRanges); // → missing again, unless acked
398
+ ```
399
+
400
+ Deleting the mapping is the entire recovery action. Nothing is queued, scheduled, or
401
+ flagged. The bytes simply reappear in the next `missing` computation and get sent
402
+ along with everything else.
403
+
404
+ **The consequence: a packet is a disposable container, not an identity.** The data
405
+ that was in lost packet #47 doesn't come back *as* packet #47's contents. It comes
406
+ back as *bytes that need sending*, and the next burst may:
407
+
408
+ - **re-slice them differently** — the chunk boundaries depend on that burst's byte
409
+ budget, so a lost 1200-byte range might go out as 400 bytes appended to one packet
410
+ and 800 in the next;
411
+ - **coalesce them with new data** from the same stream, in a single STREAM frame;
412
+ - **pack them alongside other streams'** data in the same packet, via the round-robin
413
+ scheduler below.
414
+
415
+ Packet numbers and stream byte-offsets are fully decoupled: PNs are transient
416
+ bookkeeping for the loss timer, while the byte range is the only durable identity of
417
+ data. This is possible because QUIC frames carry explicit offsets — the receiver
418
+ reassembles by offset and genuinely does not care how the bytes were packetized.
419
+
420
+ **Why this design:**
421
+
422
+ - **State can't drift.** A retransmission queue is mutable state maintained
423
+ incrementally, and every incremental structure can desynchronize from reality —
424
+ entries duplicated, entries dropped, a range acked while a stale copy still sits in
425
+ the queue. Range arithmetic derives the truth fresh each pass, so a byte range can
426
+ neither be forgotten nor sent twice by bookkeeping error.
427
+ - **Recovery is free.** No priority juggling between "retransmit queue" and "new data
428
+ queue"; repairs and new data are the same thing, drawn from one computation and
429
+ paced by the same congestion controller.
430
+ - **Late information is harmless.** An ACK arriving after the loss timer already fired
431
+ isn't a contradiction to reconcile — it just adds a range to `acked_ranges`, and the
432
+ next pass naturally stops sending those bytes.
433
+
434
+ **What it costs.** A send opportunity reads a stream's few `missing_ranges` — usually
435
+ one or two — and keeping them is a range insert or removal per write, and per packet
436
+ sent, acknowledged or expired. The expiry walk visits a
437
+ stream's packets oldest first and stops at the first one still within the timeout, so
438
+ it costs the packets that expired, not every packet in flight.
439
+
440
+ **The receive side is symmetric.** Incoming data is recorded in a `ranges` array, and
441
+ delivery walks the contiguous prefix. Same range algebra, mirrored — which is exactly
442
+ why the receiver must tolerate chunks whose boundaries don't line up with anything it
443
+ saw before: on the sending side, they never had to. It does so at insertion: only the
444
+ bytes not already held are stored, so stored pieces never overlap, tile `ranges`
445
+ exactly, and delivery is an exact-key walk. A peer cannot make reassembly expensive
446
+ either — the number of gaps per stream is capped (1000, as in quic-go), and pieces are
447
+ compacted into one buffer per contiguous run when they outnumber the gaps.
448
+
449
+ ### Congestion control: BBR-style, not loss-based
450
+
451
+ **The choice:** most QUIC stacks ship a loss-based controller — quic-go uses Reno with
452
+ HyStart++, others default to CUBIC. QUICO implements a **model-based controller in the
453
+ BBRv1 family** instead.
454
+
455
+ The difference is philosophical. Loss-based algorithms grow the window until packets
456
+ drop, which means they *require* queue overflow to find the limit — and they misread
457
+ random wireless loss as congestion. BBR builds an explicit model of the path and
458
+ steers by it:
459
+
460
+ ```
461
+ BDP = BtlBw × RTprop
462
+ ```
463
+
464
+ - **BtlBw** (bottleneck bandwidth) — a **windowed maximum** of per-round delivery rate
465
+ over the last 10 rounds. Sampling happens once per round-trip, not per ACK: under
466
+ ACK aggregation, per-ACK samples spike and a windowed-max latches onto the spike.
467
+ - **RTprop** (round-trip propagation) — a **windowed minimum** of RTT over 10 seconds,
468
+ so queue-induced inflation decays out of the model.
469
+
470
+ Three states drive the two output knobs:
471
+
472
+ | State | Pacing gain | Purpose |
473
+ |---|---|---|
474
+ | `startup` | 2.89 (≈ 2/ln 2) | Exponential ramp to discover BtlBw. Exits after 3 rounds without ≥25% growth — the pipe is full. |
475
+ | `drain` | 1/2.89 | One phase to drain the queue startup necessarily built. |
476
+ | `probe_bw` | `[1.25, 0.75, 1, 1, 1, 1, 1, 1]` | Steady state: probe for more bandwidth, then yield to drain what the probe queued. |
477
+
478
+ The **pacing rate** (`gain × BtlBw`) spreads packets smoothly rather than dumping
479
+ window-sized bursts into the bottleneck; the **congestion window** (`cwnd_gain × BDP`)
480
+ is the in-flight backstop. Both are clamped to floors and ceilings so a single bad
481
+ measurement can never wedge the connection.
482
+
483
+ Watch it live, one line per round-trip:
484
+
485
+ ```bash
486
+ QUICO_DEBUG_BBR=1 node yourserver.js
487
+ ```
488
+ ```
489
+ [bbr] round=5 startup BtlBw=8.96Mbps RTprop=16ms BDP=17920B → cwnd=51789B pace=25.89Mbps
490
+ [bbr] round=9 drain BtlBw=10.98Mbps RTprop=16ms BDP=21952B → cwnd=63441B pace=3.80Mbps
491
+ [bbr] round=15 probe_bw BtlBw=10.98Mbps RTprop=16ms BDP=21952B → cwnd=27440B pace=10.98Mbps
492
+ ```
493
+
494
+ That trace is a real run through a 10 Mbps bottleneck with a 25-packet queue: startup
495
+ finds the link in ~7 rounds, drain empties the queue, probe_bw settles within 5% of
496
+ line rate.
497
+
498
+ #### The first round trips
499
+
500
+ A page's first view is decided before any of this has measured anything: by the window
501
+ the connection starts with, and how fast it grows. QUICO starts at **20 packets (24 KB)**
502
+ — `initialCongestionWindow` — where RFC 9002 suggests 10. That is where TCP effectively
503
+ is when its response goes out: a 10-segment TCP window has grown on the acknowledged
504
+ handshake segments by then, and a QUIC connection at 10 left a 60 KB page a round trip
505
+ behind HTTP/2 on the same path. In `startup` the window then grows by every byte the
506
+ peer acknowledges — the handshake's packets as well as the application's (RFC 9002
507
+ §7.3.1, TCP's slow start). Through an emulated 450 ms, 9 Mbps link, Chromium loading a
508
+ 61 KB page that references a 61 KB script:
509
+
510
+ | | HTML after its first byte | the script | `load` |
511
+ |---|---|---|---|
512
+ | a 10-packet start | 934 ms (2 round trips) | 1384 ms | 2326 ms |
513
+ | 20 packets (default) | 490 ms (1) | 942 ms | 1890 ms |
514
+
515
+ The window's ceiling is **8 MB** — what a long fat path needs at the pacing ceiling
516
+ (14 MB/s × 450 ms ≈ 6.3 MB); a 4 MB download through the same link takes 5.4 s (it took
517
+ 8.7 s under the earlier 300 KB ceiling). The window reaches it only where BBR measured
518
+ that much: on a short path, the BDP keeps it small.
519
+
520
+ #### A returning client: Careful Resume
521
+
522
+ A client back within the hour has already shown this server its path. QUICO keeps what
523
+ BBR measured — the bottleneck bandwidth and the minimum RTT — in the client's session
524
+ ticket, and a connection that resumes with it starts from there, as **RFC 9959 (Careful
525
+ Resume)** lays out, with its BBR appendix — when turned on (`carefulResume: true`; off by
526
+ default, for reasons measured at the end of this section):
527
+
528
+ - **Saved** once BBR has a measurement worth keeping (a capacity of at least four initial
529
+ windows): during Startup at each round it grows by a quarter, then when it moves by a
530
+ quarter either way — in a NewSessionTicket sent after the handshake (lemon-tls
531
+ `sendTicket()`), inside the ticket's encryption: the client carries it, cannot read or
532
+ forge it, and the server keeps nothing. A resumed connection carries it forward.
533
+ - **Not used** past an hour, from another network (the client's IPv4 /24 or IPv6 /48
534
+ changed: a laptop moved from home to a café), or when the first flight shows another
535
+ RTT — at most half, or over ten times, the saved one.
536
+ - **Reconnaissance → jump → validation.** The first flight goes out at the initial window,
537
+ as on any connection. Once it is acknowledged without loss, the first time the sender
538
+ has more than its window allows, the window jumps to **half** the saved capacity, paced
539
+ over one round trip; slow start goes on from what that delivers.
540
+ - **Safe Retreat.** A loss while the jump is out is taken for congestion: the saved state is
541
+ deleted, the window drops to half of what was actually delivered and holds until the jump
542
+ is acknowledged, and BBR goes on in ProbeBW from there.
543
+
544
+ Chromium through the emulated link, the second download on a new connection resuming with
545
+ the first one's ticket:
546
+
547
+ | Path | File | First visit | Returning, Careful Resume | Returning, without |
548
+ |---|---|---|---|---|
549
+ | 450 ms, 9 Mbps | 512 KB | 2365 ms | **1736 ms** | 2384 ms |
550
+ | 450 ms, 9 Mbps | 2 MB | 4107 ms | **3353 ms** | 4152 ms |
551
+ | 100 ms, 50 Mbps | 4 MB | 1876 ms | **1428 ms** | 1634 ms |
552
+ | 450 ms, 9 Mbps, 2 % random loss on the return | 2 MB | 4026 ms | 5357 ms | **4608 ms** |
553
+
554
+ The last row is the RFC's price: a random loss during the jump looks like congestion, and
555
+ the retreat costs more than QUICO's BBR loses without it — it does not react to loss at all.
556
+ On a path that did get slower (the same RTT, a third of the rate), the jump is what the
557
+ retreat is for; measured there, the returning download was still faster with it (6.8 s
558
+ against 7.8 s), the queue having absorbed it.
559
+
560
+ **Off by default.** Those measurements were of one file, downloaded twice — so the first
561
+ visit had measured the path at full rate. A website's first visit is a page: a document and
562
+ its resources, which measure a lower rate, so the jump on the next visit is smaller. Measured
563
+ again that way (Chromium, the second visit on a new connection), and with the handshake
564
+ and loss recovery improved since, which made connections without it faster too:
565
+
566
+ | Path | Returning visit | With Careful Resume | Without |
567
+ |---|---|---|---|
568
+ | 100 ms, 50 Mbps | 4 MB download | 1314 ms | 1320 ms |
569
+ | 450 ms, 9 Mbps | 512 KB download | 2833 ms | 2918 ms |
570
+ | 100 ms, 50 Mbps | page (60 KB + 20 scripts) | 731 ms | **678 ms** |
571
+ | 250 ms, 20 Mbps | page | 1769 ms | **1660 ms** |
572
+ | 250 ms, 20 Mbps, 3 % random loss | page | 3583 ms | **2150 ms** |
573
+
574
+ Almost nothing on clean paths, and a lot lost on a lossy one: with a hundred packets in the
575
+ jump and a few percent of random loss, one is nearly always lost, Safe Retreat takes it for
576
+ congestion, and the connection goes on at a fraction of the link. `carefulResume: true`
577
+ turns it on — for an application whose returning clients download large files over clean
578
+ paths, as in the first table; `getStats().carefulResume` gives a connection's phase.
579
+
580
+ **Honest scope:** this is BBR-*style*, not a certified BBRv2. ProbeRTT — the periodic
581
+ cwnd collapse that re-measures RTprop on a permanently saturated path — is not
582
+ implemented, and there is no explicit loss response. The windowed filters bound the
583
+ damage of stale measurements in the meantime.
584
+
585
+ ### Stream scheduling: byte-level round-robin, by priority
586
+
587
+ **The choice:** when several streams have data ready and one packet is going out, who
588
+ gets the space? Implementations differ sharply — many drain streams in priority or
589
+ creation order, filling each one before moving on.
590
+
591
+ QUICO interleaves at the **byte level, inside a single packet**
592
+ ([`execute_quic_burst`](./src/quic_connection.js)). The scheduler cycles through the
593
+ active streams, taking a chunk from each until the packet is full, then cycles again —
594
+ so a 1200-byte packet can carry STREAM frames from three different streams:
595
+
596
+ ```
597
+ ┌─────────────────────────────── one QUIC packet ───────────────────────────────┐
598
+ │ ACK │ STREAM(id=0, 450B) │ STREAM(id=4, 450B) │ STREAM(id=8, 400B) │
599
+ └───────────────────────────────────────────────────────────────────────────────┘
600
+ ```
601
+
602
+ The loop repeats while any stream still yields data and space remains (`progress`
603
+ flag), so a stream that runs dry doesn't hold a slot — the remaining bandwidth
604
+ redistributes to the others within the same packet.
605
+
606
+ **Each packet starts where the last one left off.** A stream takes what it has, up to
607
+ the room left — so a stream with plenty to send fills a whole packet on its own. If
608
+ every packet started from the lowest stream number, that stream would fill every
609
+ packet and the others would wait for it to finish: three 6 MB downloads ran one after
610
+ another. The scheduler remembers who opened the previous packet (`rr_cursor`) and starts
611
+ the next round just after it, so with three busy streams the packets go 0, 4, 8, 0, 4,
612
+ 8… and the downloads progress at equal rates. The cost is fragmentation — more STREAM
613
+ frame headers per packet (~24 bytes each) than a drain-one-stream-at-a-time scheduler.
614
+ QUICO accepts that trade for fairness.
615
+
616
+ **Priorities decide who takes part in a round.** The streams with data are arranged in
617
+ tiers, and a packet takes from the first tier with something to send; only if that
618
+ runs dry does the next tier fill the rest of the same packet:
619
+
620
+ - by **urgency**, most urgent first — RFC 9218's `u=0..7`, default 3; urgency −1 is
621
+ HTTP/3's own control and QPACK streams, ahead of everything (a header block that
622
+ refers to a QPACK entry stuck behind response bytes would block);
623
+ - within an urgency, **non-incremental** streams go one at a time, by stream number,
624
+ each a tier of its own — a stylesheet whole before the next;
625
+ - then the **incremental** ones, taking turns as above;
626
+ - a **group** (any object, given to `setStreamPriority`) takes *one* turn in its round,
627
+ and passes it to its member with the highest `order` that has something to send;
628
+ equal orders take turns. This is WebTransport's `sendGroup` / `sendOrder`, mapped in
629
+ the WebTransport layer; QUIC only knows "streams that share one turn".
630
+
631
+ A stream nobody set a priority for takes turns at urgency 3 — as every stream did
632
+ before. The mechanism lives in QUIC (`setStreamPriority(id, { urgency, incremental,
633
+ group, order })`); the policy comes from above: HTTP/3 reads the client's `priority`
634
+ header and `PRIORITY_UPDATE` frames, the application can override them
635
+ (`res.setPriority`) — the client's later signals do not undo the application's decision
636
+ — and WebTransport maps its streams' `sendGroup` / `sendOrder`. A client asks for a
637
+ priority with the `priority` header on its request (`'u=1, i'`) — QUICO's client: the
638
+ `priority` option, `req.setPriority()`. HTTP/2 has the same
639
+ rules in its own scheduler (`h2.js`), for the DATA that waits for a window or for the
640
+ socket; what the socket already holds leaves in the order it was written. An HTTP/2
641
+ server sends `SETTINGS_NO_RFC7540_PRIORITIES = 1`: it reads RFC 9218's signals, not
642
+ RFC 7540's priority tree.
643
+
644
+ A scheduler can only order what is waiting. A stream fed in small writes with
645
+ backpressure has little queued at any moment, and while its queue is empty the next
646
+ tier sends — so an application that wants a stream strictly first should hand it its
647
+ data ahead of time, not a chunk per `'drain'`. Likewise a stream blocked by the peer's
648
+ flow control lets the next one go, rather than leaving the packet empty.
649
+
650
+ **The subtle part** falls straight out of the reconciliation model: the sender decides
651
+ what to send by asking which bytes aren't acked or in flight — but chunks selected
652
+ *earlier in the same burst* have no packet number yet, so they're in neither set, and
653
+ the next iteration would select them again. `get_stream_chunks` takes what it yields out
654
+ of `missing_ranges` at once, so the next iteration sees it as taken; the packet's number
655
+ records it in `in_flight_ranges` when it is sent. A packet that does not leave hands its
656
+ bytes back to `missing`. One packet can carry two pieces of one stream — new data and a
657
+ repaired gap — so a packet's entry in `in_flight_ranges` is a range list, read whole by
658
+ the ACK, the expiry timer and a stream reset.
659
+
660
+ **Many streams on one connection.** What the sender does per packet and per ACK does not
661
+ walk every stream: each packet in flight records the streams it carries, so an ACK (and
662
+ the expiry timer) visits those; the streams that hit flow control, and those whose FIN
663
+ is still to go, are kept apart the same way. Walked, those loops were most of the CPU of
664
+ a connection with many streams — a thousand concurrent responses on one connection ran
665
+ at 25 Mbps on loopback, two thousand at 10. Now 1000 run at ~60 and 2000 at ~55, against
666
+ ~70 with 200 (one core, client and server in one process). What remains per stream is
667
+ the scheduler's arrangement of the streams with data, once per burst.
668
+
669
+ **Writes go out once per tick.** A write to a stream does not send: it asks for one send
670
+ pass at the end of the current tick, and every write until then rides in it. A response
671
+ written as headers, ten small writes and an end is one datagram, not fourteen. A pass
672
+ for any other reason — an ACK, a timer — still runs at once and takes what is waiting.
673
+
674
+ **Datagrams** (RFC 9221) are never retransmitted, but they go under the same congestion
675
+ control: they wait in a queue, are taken into packets ahead of stream data, and the
676
+ packets that carry them count in flight (with nothing to resend). A datagram sent with
677
+ a priority (WebTransport's `sendOrder` / `sendGroup`) is not first: it takes its place
678
+ in its group, as a member at its order. While the path cannot
679
+ keep up the oldest are dropped — any that have waited 250 ms (configurable), and past
680
+ 1 MB queued — since a late datagram is worth nothing. The peer's
681
+ `max_datagram_frame_size` is honoured.
682
+
683
+ ### The send queue: the application's buffers, not copies
684
+
685
+ What a stream holds for sending is the list of buffers the application wrote, by
686
+ reference, each with the stream offset it starts at. A packet takes a view of one of
687
+ them, or — where it straddles two — a copy of its own ~1200 bytes. Writes of up to
688
+ 4 KB are the exception: they are gathered into a 16 KB buffer of the stream's own, so
689
+ ten thousand one-byte writes are a handful of pieces. A buffer leaves the queue the
690
+ moment the peer has acknowledged all of it.
691
+
692
+ The effect is on memory: `res.end(file)` holds the file once, not once per layer, and
693
+ any number of concurrent responses of the same `Buffer` share it. As with
694
+ `net.Socket`, **a buffer passed to `write()` / `end()` must not be modified afterwards**
695
+ — it is referenced until acknowledged, and a retransmission reads it again.
696
+
697
+ **Backpressure on the sending side** works as on a TCP socket. A write is complete —
698
+ its callback runs — once the stream has *sent* all but `writableHighWaterMark` of what
699
+ was written (bytes in flight are bounded by the congestion window, as the kernel
700
+ bounds them for TCP). So on HTTP/3 `res.write()` returns `false` and `'drain'` follows,
701
+ and `readable.pipe(res)` reads at the client's pace: a 30 MB file piped to a browser
702
+ holds ~5 MB of buffers on the server, not the file. The same applies to WebTransport
703
+ streams and to tunnels (WebSocket over HTTP/3, CONNECT).
704
+
705
+ ### Within a stream: new data leads, gaps follow
706
+
707
+ Given the `missing` set, in what order do you drain it? QUICO walks it in two passes:
708
+ forward from the send cursor first (new data), then backfilling the gaps below it
709
+ (bytes whose packets were lost).
710
+
711
+ New data leads because it keeps the pipe full and the ACK clock running — the receiver
712
+ buffers out-of-order bytes anyway, and the gap gets repaired within the same burst
713
+ rather than a round-trip later. Both passes read from the same `missing` computation,
714
+ so there's no ordering conflict to arbitrate: it's one set, drained in two sweeps.
715
+
716
+ **Flow control interacts here in a non-obvious way.** Send-side limits cap the
717
+ *highest offset* we may send, so they bind only **new** bytes. A repair re-sends
718
+ offsets that were already inside the allowance when first sent — it consumes no budget
719
+ and must never be blocked. Getting this wrong deadlocks the connection: at the edge of
720
+ an exhausted window, the missing range itself becomes unsendable, and the peer can't
721
+ rescue you, because the data it would open the window for is exactly the data that
722
+ never arrived.
723
+
724
+ ### Loss detection: timers, and how we treat late ACKs
725
+
726
+ Because recovery itself is just the reconciliation pass, loss "detection" here means
727
+ only one thing: deciding when to stop counting a packet's bytes as in flight. Two
728
+ decisions worth calling out:
729
+
730
+ - **Late ACKs are honoured, not discarded.** When the timer expires a packet, its
731
+ stream ranges are parked in a *limbo* table rather than forgotten. If the ACK then
732
+ arrives late — routine on a queued path — the bytes are credited to the delivery
733
+ rate model, the pending retransmission is cancelled, and the loss counter is
734
+ corrected. QUIC never reuses packet numbers, so unlike TCP there's no
735
+ retransmission ambiguity: a late ACK is *unambiguous evidence* the data arrived, and
736
+ discarding it distorts BtlBw exactly when the model needs accuracy most.
737
+ - **RTT samples are taken from those packets too** — same reasoning, plus a subtle
738
+ failure mode it prevents: a too-short timer expires packets before their ACKs land,
739
+ and if those ACKs are then barred from producing RTT samples, the timer never learns
740
+ that it's too short. The loop is self-sealing. Accepting the sample breaks it.
741
+
742
+ - **Optimistic ACKs are caught** (RFC 9000 §21.4). Every 256–1023 packets, at random,
743
+ one 1-RTT packet number is skipped; an ACK that covers it acknowledges a packet that
744
+ was never sent, and closes the connection (PROTOCOL_VIOLATION). A peer acknowledging
745
+ ahead of what arrived would otherwise inflate the congestion window at will. The send
746
+ history keeps a zero-length placeholder for the skipped number, so its index math
747
+ stays contiguous.
748
+
749
+ The PTO itself is `srtt + max(4·rttvar, 1ms) + max_ack_delay`. That last term is not
750
+ optional: peers may legitimately sit on an ACK for their full advertised delay (25 ms
751
+ is common), and a timer without it expires packets moments before their ACKs arrive.
752
+
753
+ The timer is the backstop, not the first word. On a new connection rttvar is half the
754
+ first RTT sample, so the timer comes ~3 RTTs after a packet left — and a lost packet in
755
+ a page's first response is exactly where those RTTs are paid. Two things come first:
756
+
757
+ - **Loss by ACK: the time threshold** (RFC 9002 §6.1.2). A packet is given up on once a
758
+ packet sent after it is acknowledged and `max(9/8·RTT, RTT + 5 ms)` has passed since
759
+ it was sent (RTT: the larger of srtt and the latest sample) — not the timer. Then
760
+ exactly the timer's path: resent, parked for a late ACK, counted lost. The RFC's
761
+ packet threshold (three later packets acknowledged) is left out on purpose: a packet
762
+ that arrives out of order is not resent for that, only for being later than the
763
+ threshold; the 5 ms floor keeps that so on short paths, where an eighth of the RTT is
764
+ less than Wi-Fi's own retransmissions reorder by. A 60 KB response through a 200 ms
765
+ path with one packet lost: ~10 ms longer than with none, where it was ~185 ms.
766
+ - **The tail loss probe** (RFC 8985). The last packet of a response — or a request in
767
+ one packet — has no later one to be acknowledged: after `2·srtt + max_ack_delay`
768
+ without an ACK, a copy of its data goes as a new packet. Nothing is given up on (the
769
+ original stays in flight; whichever arrives counts), one probe until an ACK comes,
770
+ only once the handshake is confirmed, and only while the timer is further off.
771
+
772
+ Chromium through 250 ms with 3 % loss (a 60 KB page and 20 scripts): page load p75
773
+ 2.41 s → 2.02 s; through 20 ms with 1 % loss and 5 ms jitter: median 474 → 419 ms.
774
+
775
+ **Our own ACKs are delayed and batched** (RFC 9000 §13.2). In the 1-RTT space an ACK
776
+ goes out once two ack-eliciting packets are owed — decided at the end of the
777
+ event-loop turn, so datagrams that arrived together get one ACK — at once for a
778
+ packet out of order (that is what lets the sender detect loss quickly), and
779
+ otherwise within `max_ack_delay`. Any packet we send anyway carries the ACK that is
780
+ owed, and the ACK Delay field reports how long it was held, so the peer can take it
781
+ out of its RTT. Initial and Handshake packets are acknowledged immediately, as the
782
+ RFC requires — in the handshake's flush, with whatever else those spaces send (see
783
+ [the handshake](#the-handshake-coalesced-datagrams-its-own-loss-detection)). Before this, every ack-eliciting packet got an ACK packet of its own:
784
+ a 20 MB download had the receiver send ~18,000 of them; now ~1,200.
785
+
786
+ The ACK timer runs at `max_ack_delay − 15 ms` (10 ms against the 25 ms we
787
+ advertise): timers fire late by up to their granularity, ~15.6 ms on Windows, and
788
+ the peer's loss timer counts on our ACK arriving within the advertised value.
789
+
790
+ **ACK ranges are capped at 32** (RFC 9000 §13.2.4 permits acking a subset). Under
791
+ loss, packet-number gaps never close — a lost PN is gone forever, its data returns
792
+ under a new PN — so an uncapped ACK frame grows with the cumulative loss count until
793
+ it no longer fits in a packet. We measured exactly that against a line-rate sender:
794
+ ACK packets inflating 325 B → 1017 B second by second, until they crossed the MTU and
795
+ stopped being sendable at all.
796
+
797
+
798
+ ### The handshake: coalesced datagrams, its own loss detection
799
+
800
+ The handshake is the one place where every datagram must arrive before anything can
801
+ go on — so it is built to send as few as it can (RFC 9000 §12.2):
802
+
803
+ - **One flush, coalesced datagrams.** Initial and Handshake packets are not sent as
804
+ TLS produces each message. What the two spaces have to send — CRYPTO data neither
805
+ acknowledged nor in flight, an ACK they owe — goes out at the end of the turn, in
806
+ packets as full as the datagram allows, the packets in as few datagrams as they fit.
807
+ The datagram is padded to 1200 bytes, not an Initial packet with zeros ahead of the
808
+ Handshake packets that could have filled it. A server's whole flight (ServerHello,
809
+ EncryptedExtensions, Certificate, CertificateVerify, Finished, and the ACK of the
810
+ ClientHello) is **one datagram** with a small chain, where it was seven; a client's
811
+ answer one, where it was up to eight.
812
+ - **RTT from the first round trip.** ACKs of Initial and Handshake packets give RTT
813
+ samples, as 1-RTT ones do (RFC 9002 §4.1: RTT measurement is "unified across packet
814
+ number spaces"); the client has one when its handshake completes, not only after its
815
+ first 1-RTT packet is acknowledged.
816
+ - **ACK-based loss detection, in these two spaces only.** A packet is lost once a later
817
+ one is acknowledged and three more are, or 9/8 of an RTT has passed (RFC 9002 §6.1);
818
+ its range is sent again at once. The retransmission timer stays as the backstop. The
819
+ 1-RTT space keeps the recovery described above.
820
+ - **The client's anti-deadlock probe** (RFC 9002 §6.2.2.1). Until one of its Handshake
821
+ packets is acknowledged, a client keeps its timer even with nothing in flight — and
822
+ sends a PING when it fires: a server held by its anti-amplification limit has no
823
+ timer of its own, and waits for any datagram from the client.
824
+ - **The first 1-RTT packet rides in the last handshake datagram.** When 1-RTT keys
825
+ exist, the flush's last datagram waits for the end of the turn, and the first 1-RTT
826
+ packet made in it goes in it, last (a short header has no length): the server's
827
+ SETTINGS with its flight, the client's request — with its control streams — with its
828
+ Finished, in room the Initial's padding took anyway. A connection with one request:
829
+ 8 datagrams where it was 13; before the response, one datagram each way after the
830
+ ClientHello. Not where it would cost the server a round trip: a datagram the
831
+ anti-amplification budget would have let through alone is not made too large for it.
832
+ - **The peer's retransmission is news** (RFC 9002 §6.2.3). Handshake data received
833
+ again means the peer has not heard from us: what we sent in answer and is still
834
+ unacknowledged goes again at once, with the ACK the packet is owed — a server seeing
835
+ the ClientHello again, a client seeing the server's flight again — not a
836
+ retransmission timeout (three RTTs on the first sample) later. Twice per connection
837
+ at most. A 1-RTT packet that rode in a datagram found lost this way, or by the
838
+ ACK-based detection above, is lost with it and sent again in the new datagram — the
839
+ request does not wait for the 1-RTT space's own timeout because it travelled with the
840
+ Finished. A late ACK for either still counts.
841
+
842
+ Chromium against a QUICO server through a 250 ms path with 3 % loss: time to first byte
843
+ went from a median of 1182 ms to 516 ms (two round trips — the floor), and the page from
844
+ 2.8 s to 2.0 s. QUICO's client through the same path (100 connections): the 90th
845
+ percentile of time to first byte from ~1150 ms to ~850 ms, mostly the lost
846
+ Finished-and-request datagram answered on the server's retransmission.
847
+
848
+
849
+ ### Path MTU discovery
850
+
851
+ Packets start at what every QUIC path carries — 1200 bytes of frames — and most paths
852
+ carry more: ~1450 on Ethernet. Every byte more in a packet is a packet less, and a packet
853
+ is an encryption, a system call and its bookkeeping — where a JavaScript sender spends its
854
+ time: a 4 MB download goes out in ~16 % fewer packets at 1452.
855
+
856
+ A round trip after the handshake is confirmed — the first responses go first; a probe is
857
+ 1.4 KB of padding a slow link would put ahead of them — the sender probes (DPLPMTUD,
858
+ RFC 8899 / RFC 9000 §14.3), in a send pass of its own if nothing else would run one (a
859
+ client that only downloads may have nothing to send), and after the data of the pass it
860
+ shares:
861
+ a PING padded to a size, sent in the paced flow of the connection, and acknowledged — by
862
+ its own packet number — only if that size crossed the path. Sizes are whole UDP datagrams.
863
+ The first probe is at **the largest datagram the peer has sent on this path** (the limit is
864
+ most often the peer's own link — a PPPoE line, a VPN — and the same both ways), then at the
865
+ ceiling (1452, and the peer's `max_udp_payload_size`), and past a failure a binary search
866
+ down to 16 bytes. A size fails after three unacknowledged probes; the search runs again ten
867
+ minutes after it ends. A probe carries no stream data: a lost one — and a probe too large is
868
+ lost by design — holds nothing back, and is no loss to congestion control (§14.4).
869
+
870
+ **Black holes.** The MTU can shrink mid-connection. Packets above the floor lost in a row,
871
+ with none acknowledged since, are a suspicion, not a verdict — congestion loses packets in
872
+ runs too (Startup's overshoot does, every connection). A probe of the current size settles
873
+ it: acknowledged, it was congestion; lost three times, packets go back to 1200 and the
874
+ search starts again later. A new path starts from 1200, as its congestion state does.
875
+
876
+ | Path (largest datagram) | Found | Probes dropped |
877
+ |---|---|---|
878
+ | Ethernet (1472) | 1452 — the ceiling | 0 |
879
+ | a VPN (1392) | 1387, within the search's 16 bytes | ~9 |
880
+ | 1452, cut to 1300 mid-download | back to 1200 after 3 confirming probes | — |
881
+
882
+ ### Flow control: consumption-based windows
883
+
884
+ **The choice:** when do you tell the peer it may send more? The naive trigger is
885
+ "bytes arrived"; QUICO slides its receive windows on **consumption** — a
886
+ `MAX_STREAM_DATA` / `MAX_DATA` update goes out once in-order data has been delivered
887
+ up the stack and half a window has been used, never for bytes still sitting out of
888
+ order in the reassembly buffer.
889
+
890
+ **Where "consumed" is measured.** For what the application reads — a request body on
891
+ the server, a response body on the client, a WebTransport stream on either side — it is
892
+ the application's read: the
893
+ bytes that have left the Node stream's buffer, counted after each `read()` (which
894
+ flowing mode, `pipe()` and async iteration all go through). A reader that reads
895
+ nothing holds the peer to one stream window; one that reads slowly sets the peer's
896
+ pace. Everything else — HTTP/3's own streams — is consumed at the hand-off from QUIC to the HTTP/3 layer, and bounded there by its
897
+ own limits (a HEADERS frame by the field-section size we advertise, control frames by
898
+ a fixed cap).
899
+
900
+ These bytes count in the connection's window too (`initial_max_data`, 1 MB by
901
+ default): a few streams that nobody reads can hold the whole connection. An
902
+ application with many parallel streams — MoQT's stream per group — reads or stops
903
+ (`stopSending`) each one, and sizes the windows for it with `transportParams`.
904
+
905
+ **Autotuning.** A window caps the peer at one window a round trip: 256 KB a stream is
906
+ 10 Mbit/s at 200 ms. So, as Chromium and quiche do, a window the application consumed
907
+ half of within two round trips of the last update — the window is what limits, not the
908
+ path — doubles, up to **16 MB** a stream and **24 MB** the connection (a larger
909
+ `transportParams` value is kept as given); the connection's grows with its streams, to
910
+ 1.5× the largest. It grows only with what is consumed, so a reader that falls behind
911
+ keeps the window it has. Measured through an emulated 20 Mbit/s, 200 ms link, a 4 MB
912
+ download by QUICO's client: 7.8 s before, 4.2 s now (Chromium: 3.1 s).
913
+
914
+ **HTTP/2, over TCP.** The client's stream window is **6 MB** (Chrome's), not
915
+ HTTP/2's 64 KB, and the connection's 16 MB. Credit still goes back as the
916
+ application reads, so a response nobody reads stops at 6 MB. The 64 KB default held a
917
+ response to 64 KB a round trip: 16 MB through a 100 ms round trip took 52 s, and takes
918
+ under 1 s now. An application that wants less sets `initialWindowSize` on the request.
919
+
920
+ ### Reading the source
921
+
922
+ Files map one-to-one onto protocol layers (see
923
+ [Project Structure](#-project-structure)), state lives in plain objects you can
924
+ `console.log`, and the dense parts carry comments explaining *why*, not just what.
925
+ Start at [`src/quic_connection.js`](./src/quic_connection.js) and follow a packet in
926
+ from `feedDatagram()` or out from `sendStream()`.
927
+
928
+ ---
929
+
930
+ ## 🔬 Interoperability
931
+
932
+ Everything above is a claim; this section is the receipt.
933
+
934
+ QUICO is tested with the [QUIC Interop Runner](https://github.com/quic-interop/quic-interop-runner),
935
+ the standard cross-implementation test harness. Every test runs both directions
936
+ (QUICO as server *and* as client) through a network simulator with configurable
937
+ delay, bandwidth limits and packet loss.
938
+
939
+ | Peer implementation | Language | `handshake` | `transfer` | `http3` |
940
+ |---|---|:---:|:---:|:---:|
941
+ | [quic-go](https://github.com/quic-go/quic-go) | Go | ✅ | ✅ | ✅ |
942
+ | [ngtcp2](https://github.com/ngtcp2/ngtcp2) | C | ✅ | ✅ | ✅ |
943
+ | [quiche](https://github.com/cloudflare/quiche) (Cloudflare) | Rust | ✅ | ✅ | ✅ |
944
+ | [picoquic](https://github.com/private-octopus/picoquic) | C | ✅ | ✅ | ✅ |
945
+ | [aioquic](https://github.com/aiortc/aioquic) | Python | ✅ | ✅ | ✅ |
946
+ | [neqo](https://github.com/mozilla/neqo) (Firefox) | Rust | ✅ | ✅ | ✅ |
947
+
948
+ - **handshake** — TLS 1.3 handshake over QUIC completes
949
+ - **transfer** — 10 MB across multiple concurrent streams, through a 10 Mbps
950
+ bottleneck with a shallow queue (i.e. with real packet loss)
951
+ - **http3** — three concurrent HTTP/3 requests, which must share **one** QUIC
952
+ connection
953
+
954
+ 0-RTT over TCP is verified with OpenSSL both ways (`s_client -early_data`, `s_server
955
+ -early_data`: taken, refused and sent again, and after a HelloRetryRequest). Over QUIC,
956
+ 0-RTT is verified with Chromium (its second visit's request in its first flight, and its
957
+ retry after a `425`), and with aioquic and quic-go in both directions.
958
+
959
+ Additionally verified against production servers: **Google**, **Cloudflare**,
960
+ **Facebook**, **Microsoft**, **LiteSpeed** and **nginx** — including a 12.7 MB
961
+ download from `cloudflaremirrors.com` byte-for-byte.
962
+
963
+ ---
964
+
965
+ ## 📚 API Reference
966
+
967
+ QUICO mirrors the `node:https` API wherever possible. If a method or property is not
968
+ documented here, it likely behaves exactly as its `node:https` counterpart.
969
+
970
+ This chapter covers the HTTP/3 API first, then framework compatibility, WebTransport,
971
+ and finally the low-level QUIC primitives for non-HTTP protocols.
972
+
973
+ ### `quico.createServer([options][, requestListener])`
974
+
975
+ Creates a server for HTTP/3, HTTP/2 and HTTP/1.1. Returns a server object with
976
+ `listen()`, `close()` and `on()`.
977
+
978
+ **Options**
979
+
980
+ | Option | Type | Default | Description |
981
+ |---|---|---|---|
982
+ | `key` | `Buffer \| string \| Array` | — | Private key in PEM format (a string without `-----` is read as a file path). Required unless `SNICallback` is used. An array — `node:tls`'s form, keys or `{ pem, passphrase }` — for several certificates of different kinds, each key paired with the chain in `cert` that carries its public key (see [Post-quantum TLS](#post-quantum-tls)). |
983
+ | `cert` | `Buffer \| string \| Array` | — | Certificate chain in PEM format (or a file path, as for `key`); an array, one chain per key. |
984
+ | `ca` | `Buffer \| string \| Array` | `null` | Additional trusted CAs. |
985
+ | `SNICallback` | `Function` | `null` | `(servername, cb, info) => cb(null, secureContext)` for multi-domain setups. `info.transport` is `'tcp'` or `'quic'`. |
986
+ | `http3` | `boolean` | `true` | Listen for HTTP/3 over UDP. |
987
+ | `http2` | `boolean` | `true` | Also listen for HTTP/2 over TCP (fallback for non-QUIC clients). |
988
+ | `http1` | `boolean` | `true` | Also listen for HTTP/1.1 over TCP. |
989
+ | `ALPNProtocols` | `string[]` | — | ALPN names to accept, in preference order, as in `node:tls`. Served HTTP versions missing from the list are put first; naming a version that is disabled throws. |
990
+ | `maxConnections` | `number` | `10000` | Maximum concurrent QUIC connections. |
991
+ | `ticketKeys` | `Buffer` (48 bytes) | random | Session-ticket key, shared by TCP and QUIC. Pass a stable one to keep resumption working across restarts. |
992
+ | `ech` | `{ keys }` | — | Encrypted Client Hello keys, TCP and QUIC alike: `{ keys: [{ config, privateKey, retry }] }`, from `quico.generateEchKey()`. A key that does not match its config throws here. See [Encrypted Client Hello](#encrypted-client-hello-ech). |
993
+ | `earlyData` | `boolean` | `false` | Accept 0-RTT — a returning client's request in its first flight, answered one round trip sooner: over HTTP/3, and over TLS 1.3 on TCP (HTTP/2, HTTP/1.1). Off by default: early data can be replayed. See [0-RTT](#0-rtt-early-data). |
994
+ | `earlyDataMaxAge` | `number` (ms) | `10000` | 0-RTT: how far the age a client states for its ticket may be from what the server measures (RFC 8446 §8.3) — a captured first flight is good for this long at most. 1–600000. |
995
+ | `earlyDataReplay` | `(id, ttl, cb) => void` | in memory | 0-RTT's anti-replay store: `cb(null, true)` if `id` is new (and keep it `ttl` ms), `cb(null, false)` if seen. Share one (Redis, memcached) between servers that share `ticketKeys`. No answer in 100 ms, or an error: no 0-RTT, the handshake goes on. |
996
+ | `earlyDataFilter` | `(req, cb) => void` | `GET`, `HEAD`, `OPTIONS` | 0-RTT: whether a request that came early may be handled before the handshake completes — `cb(null, true)`; otherwise the client gets `425 Too Early` and sends it again after the handshake (RFC 8470). No answer in 100 ms: `425`. |
997
+ | `sessionTimeout` | `number` | `7200` | Seconds a session ticket stays good, TCP and QUIC alike (`node:tls`'s option; its default is 300). `0`–`604800` (RFC 8446's 7 days); `0` issues tickets that never resume. |
998
+ | `requestCert`, `rejectUnauthorized` | `boolean` | `false`, `true` | Client certificates, as in `node:tls`, on every version — HTTP/3 included — verified against `ca`. With `rejectUnauthorized` (the default) a client without a valid one is refused; with `false` it gets in, and `req.socket.authorized` says which. `req.socket.getPeerCertificate()` / `authorizationError` as on a `TLSSocket`; on a resumed connection, the certificate it proved on its first. |
999
+ | `minVersion`, `maxVersion` | `string` | `'TLSv1.2'`, `'TLSv1.3'` | `'TLSv1.2'` or `'TLSv1.3'`. HTTP/3 is TLS 1.3 only: `maxVersion: 'TLSv1.2'` needs `http3: false`. |
1000
+ | `certificateCompression` | `string[]` \| `boolean` | `true` | The algorithms the server's certificate may go compressed in (RFC 8879), in order: `['brotli', 'zstd', 'zlib']` — the default, `true`, is all of them that Node has (zstd from 22.15). It goes compressed only to a client that offered one, and only when that comes out smaller. `false`: always plain. TCP and QUIC alike; a name unknown throws from `createServer`. |
1001
+ | `honorCipherOrder` | `boolean` | `false` | As `node:tls`: the cipher suite by the server's order (`ciphers`). By default the client's — a client that asks for AES-256 first gets it. |
1002
+ | `ciphers`, `ecdhCurve`, `sigalgs` | `string` | — | As `node:tls` takes them (OpenSSL's colon-separated names; `ecdhCurve: 'X25519:P-256'`). The server's default groups: every post-quantum one Node has, then X25519, P-256, P-384 (see [Post-quantum TLS](#post-quantum-tls)). HTTP/3 uses the TLS 1.3 suites of `ciphers` (AES-GCM and ChaCha20-Poly1305); a list without one needs `http3: false`. A value naming nothing usable throws from `createServer`. |
1003
+ | `handshakeTimeout` | `number` | TCP `120000`, QUIC `10000` | Milliseconds a TLS handshake may take. Over QUIC, counted from the connection's first packet, and on a server until the client's Finished is verified — not only until the server's own Finished has gone: a client that sends a ClientHello and nothing more holds the connection for this long, not for the idle timeout. |
1004
+ | `passphrase` | `string` | — | For an encrypted `key`. |
1005
+ | `validateAddress` | `boolean` | `false` | Validate client addresses with a QUIC Retry before any handshake work. |
1006
+ | `handshakeLoadThreshold` | `number` | `500` | HTTP/3 handshakes under way at which `'handshakeLoad'` fires (`high: true`), and again under half of it (`high: false`). `0`: off. |
1007
+ | `maxHandshakesPerAddress` | `number` | `64` | HTTP/3 handshakes under way from one client address; past it an Initial from there makes no connection. `0`: no cap. |
1008
+ | `resetTokenSecret` | `Buffer` (≥ 16 bytes) | random | Secret for QUIC stateless-reset tokens. Keep it stable across restarts so clients of a crashed instance get a reset instead of a timeout. |
1009
+ | `socket` | `dgram.Socket` | `null` | Use an externally-bound IPv4 UDP socket instead of creating one. Must already be bound. |
1010
+ | `socket6` | `dgram.Socket` | `null` | Same, for IPv6. |
1011
+ | `greaseQuicBit` | `boolean` | `true`; `false` with `socket` / `socket6` | QUIC: invite clients to send the fixed bit unpredictable (RFC 9287), so the bit stays free to change. Off by default on an external socket, whose port may be shared with STUN, TURN or DTLS — told apart from QUIC by that bit (RFC 9443). `true` when that port carries QUIC alone. |
1012
+ | `port` | `number` | `443` | The port advertised in `Alt-Svc` when `listen()` is not used (externally fed server). |
1013
+ | `altSvc` | `string \| false` | — | The `Alt-Svc` header on HTTPS HTTP/1.1 and HTTP/2 responses. By default `h3=":<port>"; ma=86400` when this server runs HTTP/3, and none with `http3: false`. A string is sent as is — for HTTP/3 served by something else (`'h3=":443"; ma=86400'`); `false` sends none. A response's own `alt-svc` header wins. |
1014
+ | `connectUdp` | `object` | — | CONNECT-UDP's policy: `{ template, allowPrivate, maxTunnelsPerConnection, idleTimeout, lookup, proxyName }` — see [CONNECT-UDP](#connect-udp-proxying-udp). |
1015
+ | `shouldUpgradeCallback` | `(req) => boolean` | listens for `'upgrade'`? | As in `node:http`: whether an upgrade request (HTTP/1.1 `Upgrade`, or extended CONNECT over HTTP/2 and HTTP/3) is taken up as `'upgrade'`, or handled as an ordinary `'request'`. |
1016
+ | `headersTimeout` | `number` | `60000` | How long a request's head may take to arrive. HTTP/1.1: `408` and close. HTTP/2: a header block left open (HEADERS without END_HEADERS) blocks the whole connection, so the connection goes (GOAWAY). HTTP/3: the request stream is reset, `H3_REQUEST_INCOMPLETE`. `0` disables it. |
1017
+ | `requestTimeout` | `number` | `300000` | As `node:http`: the whole request, body included, must arrive within it, counted from the end of its head. HTTP/1.1: `408` and close. HTTP/2 and HTTP/3: that request's stream is reset (`CANCEL` / `H3_REQUEST_INCOMPLETE`) and the request gets `'aborted'`; the connection serves on. Not applied to `CONNECT` (WebSocket, WebTransport), whose stream is meant to stay open. The response is not timed. `0` disables it. |
1018
+ | `keepAliveTimeout` | `number` | `5000` | HTTP/1.1 only: an idle connection between requests. |
1019
+ | `streamResetBurst`, `streamResetRate` | `number` | `1000`, `33` | Rapid Reset (CVE-2023-44487) protection, `node:http2`'s options and defaults: a client may cancel `streamResetBurst` requests at once, then `streamResetRate` a second. Past it the connection is closed — HTTP/2 `GOAWAY` `ENHANCE_YOUR_CALM` (a `'sessionError'`, `ERR_HTTP2_STREAM_RESET_RATE`), HTTP/3 `H3_EXCESSIVE_LOAD`. HTTP/3 counts cancelled request streams (`RESET_STREAM` or `STOP_SENDING`, once each), not a WebTransport session's own streams. `Infinity` for either: no limit. The `'stream_reset'` event remains for a policy of your own. |
1020
+ | `maxRequestsPerSocket` | `number` | `0` (no limit) | `node:http`'s: requests one connection may carry. HTTP/1.1: the Nth response says `Connection: close` and the connection ends (a request past it, pipelined, gets `503`). HTTP/2 and HTTP/3: `GOAWAY` after the Nth — requests in flight finish, the client takes the next to a new connection (nginx's `keepalive_requests`). |
1021
+ | `maxHeaderSize` | `number` | `16384` | HTTP/1.1: request line plus headers, in bytes (`node:http`'s option and default). Over it: `431`. |
1022
+ | `maxHeaderCount` | `number` | `2000` | HTTP/1.1: header lines. Over it: `431` (`node:http` drops the extra ones instead). |
1023
+ | `noDelay`, `keepAlive`, `keepAliveInitialDelay` | | `true`, `false`, `0` | TCP socket options. |
1024
+ | `transportParams` | `object` | — | QUIC's windows and stream limits, as sent to every client: `initialMaxData`, `initialMaxStreamDataBidiLocal`, `initialMaxStreamDataBidiRemote`, `initialMaxStreamDataUni`, `initialMaxStreamsBidi`, `initialMaxStreamsUni`, `maxIdleTimeout`. See [Transport parameters](#transport-parameters). |
1025
+ | `initialCongestionWindow` | `number` | `20` | QUIC: the congestion window a connection starts with, in full-size packets (1200 B), `2`–`100`. See [The first round trips](#the-first-round-trips). |
1026
+ | `carefulResume` | `boolean` | `false` | QUIC: a returning client's connection starts from what the server measured on its last one (RFC 9959). Off by default: for page loads it gains almost nothing and costs a lot with random loss. Worth it where returning clients download large files on clean paths. See [Careful Resume](#a-returning-client-careful-resume). |
1027
+ | `startupCap` | `'stall'` \| `'always'` \| `'off'` | `'stall'` | QUIC: Startup's cap on the congestion window, 2 × BDP plus ACK aggregation (BBR v3). `'stall'`: from the first round in which bandwidth stopped growing — fewer drops at a router's queue where the window used to overshoot, no cost to a page's ramp-up. `'always'`: the whole of Startup — fewest drops, a slower ramp on long lossy paths (for bulk transfers). `'off'`: none. Also per connection (`connectionOptions`, `conn.setOptions`), at runtime (`setOptions`), and a client's own option for what it sends. |
1028
+ | `pmtuDiscovery` | `boolean` | `true` (`false` on Windows) | QUIC: path MTU discovery. Off on Windows by default — Node cannot set the Don't Fragment bit there, so a probe may cross fragmented and be taken for a fit. Off, packets stay at 1200 bytes of frames (or what was found before it was turned off). |
1029
+ | `maxUdpPayloadSize` | `number` | `1452` | QUIC: the largest UDP payload sent (1200–65527): where path MTU discovery stops. Lower it for a VPN or a tunnel; raise it for jumbo frames on a LAN. |
1030
+ | `initialRtt` | `number` (ms) | `333` | QUIC: the RTT assumed before there is a sample (RFC 9002's kInitialRtt) — how soon a lost handshake packet is sent again. Lower for clients known to be near (one country, a CDN edge); too low against far clients, handshake packets are resent needlessly. 10–10000. |
1031
+ | `reorderWindow` | `number` (ms) | `5` | QUIC: the least a packet is allowed to arrive out of order before a later one's ACK gives it up (the floor of the time threshold, see [Loss detection](#loss-detection-timers-and-how-we-treat-late-acks)). Raise it on paths that reorder more (some mobile networks, per-packet load balancing) — `getStats().spuriousLosses` counting up says so. 0–1000. |
1032
+ | `quicVersions` | `Array` | `['v1', 'v2']` | QUIC versions accepted, in preference (`'v1'`, `'v2'`, or the numbers). A client that offers both through `version_information` gets the first of these it can be moved to without a round trip (RFC 9368) — v1 by default; `['v2', 'v1']` moves such clients to v2. A client whose version is not listed gets Version Negotiation. `req.socket.quicVersion` says which. |
1033
+ | `connectionOptions` | `(info, callback) => void` | — | QUIC: each connection's own `initialCongestionWindow`, `transportParams`, `carefulResume` and `startupCap`, decided when its ClientHello arrives. See [Per-connection settings](#per-connection-settings-connectionoptions). |
1034
+ | `maxWebTransportSessions` | `number` | no limit | WebTransport sessions a connection may have open at once — sent as `SETTINGS_WT_MAX_SESSIONS`; a CONNECT past it is refused with `H3_REQUEST_REJECTED` before the application hears of it. |
1035
+ | `maxConcurrentStreams`, `headerTableSize`, `initialWindowSize`, `maxFrameSize`, `maxHeaderListSize`, `connectionWindowSize`, `enableConnectProtocol` | | `100`, `4096`, `65535`, `16384`, `131072`, 16 MB, `true` | HTTP/2 settings. |
1036
+ | `maxSessionMemory` | `number` | `10` | HTTP/2: megabytes a connection may have queued for a peer that is not reading (`node:http2`'s option). DATA waits for the socket instead of queueing; past this, the connection is closed. |
1037
+
1038
+ #### Per-connection settings: `connectionOptions`
1039
+
1040
+ The server's settings are everyone's. `connectionOptions` decides them per QUIC connection —
1041
+ from the client's address, the name it asked for, and whether it has been here before:
1042
+
1043
+ ```js
1044
+ createServer({
1045
+ key, cert,
1046
+ connectionOptions(info, callback) {
1047
+ // info: { remoteAddress, remotePort, servername, resumed,
1048
+ // previous: { rtt, bandwidth, age } | null }
1049
+ lookupNetwork(info.remoteAddress, (err, net) => {
1050
+ if (err) return callback(err); // → the server's settings
1051
+ callback(null, {
1052
+ initialCongestionWindow: net.satellite ? 40 : 20, // packets
1053
+ transportParams: { initialMaxData: 32 * 1024 * 1024 },
1054
+ carefulResume: !net.shared,
1055
+ startupCap: net.bulk ? 'always' : 'stall',
1056
+ });
1057
+ });
1058
+ },
1059
+ }, handler);
1060
+ ```
1061
+
1062
+ It is asked once the ClientHello is in and before anything is answered: the handshake waits
1063
+ for it, as it waits for an asynchronous `SNICallback` (whose turn it takes first), and
1064
+ `transportParams` — merged over the server's — go out in that same handshake. `previous` is
1065
+ what the client's last connection from the same network measured, within the hour: what
1066
+ [Careful Resume](#a-returning-client-careful-resume) would start from (`rtt` in ms,
1067
+ `bandwidth` in bits/s, `age` in seconds); `null` on a first visit, from another network, or
1068
+ past its lifetime. Every field of the answer is optional: `transportParams`, and any of
1069
+ the connection options — `initialCongestionWindow`, `carefulResume`, `startupCap`,
1070
+ `pmtuDiscovery`, `maxUdpPayloadSize`, `initialRtt`, `reorderWindow`. What a connection
1071
+ has is the answer's, else what the server had when it was made (`createServer`, or
1072
+ `setOptions` since), else the default; `conn.setOptions` changes it afterwards.
1073
+
1074
+ It cannot hold a connection hostage: no answer within **1 s**, an error, a throw, or an
1075
+ answer that does not check out (checked whole — nothing of it is taken) leaves the
1076
+ connection on the server's settings, and `process.emitWarning` says why (code
1077
+ `QUICO_CONNECTION_OPTIONS`). It runs for every Initial that opens a connection — spoofed
1078
+ ones included — so anything it calls out to should be cached; `validateAddress` screens
1079
+ spoofed addresses before it is asked.
1080
+
1081
+ Setting `http2: false` and `http1: false` makes the server **HTTP/3 only** — no TCP
1082
+ listener is opened. Without `key`/`cert`/`SNICallback`, the TCP side serves cleartext
1083
+ HTTP/1.1 and h2c.
1084
+
1085
+ **Methods**
1086
+
1087
+ - `server.listen(port[, host][, callback])` — start listening. Binds UDP (unless
1088
+ `http3: false` or external sockets were given) and TCP (unless both fallbacks are
1089
+ disabled). Port `0` picks a free port.
1090
+ - `server.close([callback])` — stop listening and close all connections.
1091
+ - `server.address()`
1092
+ - `server.handleConnection(socket)` — serve a TCP socket accepted elsewhere.
1093
+ - `server.setTimeout([msecs][, callback])` / `server.timeout` — as in `node:http`:
1094
+ a connection idle for `msecs` emits `'timeout'` with its socket, and is destroyed
1095
+ if nothing listens. `0` (default) disables it; changes apply to new connections.
1096
+ TCP connections (HTTP/1.1, HTTP/2) — an HTTP/3 connection has QUIC's idle timeout.
1097
+ - `server.handlePacket(msg, rinfo)` / `server.hasConnection(rinfo)` — feed UDP
1098
+ datagrams yourself when sharing a port (external socket mode).
1099
+ - `server.addProtocol(name, handler, { sniff? })` — serve another protocol on the same
1100
+ TCP port: by ALPN `name`, or for TLS connections without ALPN, by
1101
+ `sniff(firstBytes) → true | false | null`. `handler(socket, protocol)`.
1102
+ - `server.getTicketKeys()` / `setTicketKeys(keys)`,
1103
+ `getEchKeys()` / `setEchKeys(ech)`,
1104
+ `getValidateAddress()` / `setValidateAddress(on)`,
1105
+ `getResetTokenSecret()` / `setResetTokenSecret(secret)` — change these at runtime.
1106
+ - `server.setOptions(options)` / `server.getOptions()` — every other option that can
1107
+ change while the server runs, in one call, by the names `createServer` takes. See
1108
+ [Changing options while running](#changing-options-while-running).
1109
+ - `server.getPendingHandshakes()` — HTTP/3 handshakes under way: connections made whose
1110
+ handshake is not complete (the client's Finished verified) and has not failed.
1111
+ What load is, and what to do about it, is the application's — see `'handshakeLoad'`:
1112
+
1113
+ ```js
1114
+ // Retry (one round trip more) for new clients only while handshakes pile up.
1115
+ server.on('handshakeLoad', ({ high }) => server.setOptions({ validateAddress: high }));
1116
+ ```
1117
+
1118
+ `maxHandshakesPerAddress` is a cap, not a judgement of load: an address with that
1119
+ many handshakes under way gets no more connections until some end. High enough for
1120
+ many clients behind one address (a carrier NAT); with Retry on, it counts only
1121
+ addresses that came back with a token.
1122
+ - `server.getStats()` — the server's counters since it was made (a copy). Counts only:
1123
+ no addresses, names, headers or payloads. Codes are the protocol's, as hex strings,
1124
+ each mapped to how many times it was seen:
1125
+
1126
+ | Field | Counts |
1127
+ |---|---|
1128
+ | `connections.quic` / `.tcp` | Connections taken: a QUIC Initial that began a handshake; a TCP socket accepted |
1129
+ | `handshakes.quic` / `.tcp` | `{ completed, failed }` — failed: an alert either way, a timeout, the client gone first |
1130
+ | `handshakes.resumed` | Completed with a session ticket |
1131
+ | `protocols` | `{ h3, h2, 'http/1.1', other }` — connections by the protocol they spoke |
1132
+ | `earlyData` | `{ accepted, rejected, tooEarly }` — 0-RTT the clients offered, and requests answered 425 |
1133
+ | `closes.quic` | `{ sent, received, silent }` — QUIC's CONNECTION_CLOSE by code (`'0x12f'`: a TLS alert, illegal_parameter); silent: ended with none (idle timeout, stateless reset) |
1134
+ | `closes.h3` | `{ sent, received }` — HTTP/3's CONNECTION_CLOSE by code (`'0x100'`: H3_NO_ERROR) |
1135
+ | `closes.h2` | `{ sent, received }` — HTTP/2 GOAWAY by code |
1136
+ | `closes.http1` | `{ sent }` — HTTP/1.1 requests refused before the application saw them, by status (`'400'`) |
1137
+ | `streamResets.h3` / `.h2` | `{ sent, received }` — RESET_STREAM / RST_STREAM by code |
1138
+ | `amplificationBlocked` | Datagrams held at the anti-amplification limit (RFC 9000 §8.1) until the client's address was validated |
1139
+ | `internalErrors` | Exceptions of ours caught in the QUIC and HTTP/3 layers — a bug, never the client's |
1140
+ | `since`, `uptime` | When counting began; milliseconds since |
1141
+
1142
+ ```js
1143
+ setInterval(() => {
1144
+ const s = server.getStats();
1145
+ metrics.gauge('tls_failed', s.handshakes.quic.failed + s.handshakes.tcp.failed);
1146
+ metrics.gauge('h3_errors', Object.entries(s.closes.h3.sent).filter(([c]) => c !== '0x100').reduce((n, [, k]) => n + k, 0));
1147
+ }, 10000);
1148
+ ```
1149
+
1150
+ #### Changing options while running
1151
+
1152
+ `server.setOptions(partial)` changes what can change, by `createServer`'s names;
1153
+ `server.getOptions()` returns all of them as they are now (a copy).
1154
+
1155
+ ```js
1156
+ const server = createServer({ key, cert, startupCap: 'stall', initialRtt: 100 }, app);
146
1157
 
1158
+ server.on('handshakeLoad', ({ high }) => {
1159
+ server.setOptions({ validateAddress: high, maxHandshakesPerAddress: high ? 16 : 64 });
1160
+ });
1161
+
1162
+ server.setOptions({ startupCap: 'always' }); // returns server: chainable
1163
+ const { startupCap, validateAddress } = server.getOptions();
1164
+
1165
+ try {
1166
+ server.setOptions({ startupCap: 'off', initialRtt: -5 });
1167
+ } catch (e) {
1168
+ e.code; // 'ERR_OUT_OF_RANGE' — "initialRtt must be between 10 and 10000 (ms), got -5"
1169
+ server.getOptions().startupCap; // unchanged: one bad value, and nothing changes
1170
+ }
1171
+ server.setOptions({ cert }); // TypeError: "cert cannot be changed with setOptions(): use setSecureContext()"
1172
+ ```
1173
+
1174
+ | Option | Applies |
1175
+ |---|---|
1176
+ | `validateAddress` | from the next new client |
1177
+ | `handshakeLoadThreshold` | at once (the count as it stands) |
1178
+ | `maxHandshakesPerAddress` | from the next Initial |
1179
+ | `earlyData`, `earlyDataMaxAge` | from the next handshake (`earlyData: false` refuses early data on tickets already given out too) |
1180
+ | `startupCap`, `initialCongestionWindow`, `carefulResume`, `pmtuDiscovery`, `maxUdpPayloadSize`, `initialRtt`, `reorderWindow` | to HTTP/3 connections made from then on — those open keep theirs |
1181
+
1182
+ **One connection's.** The same two calls on a connection — the handle of `'connection'`
1183
+ (its first packet) and `'secureConnection'`, and an HTTP/3 request's `req.socket`; on the
1184
+ client, an HTTP/3 response's `res.socket`. Every request on that connection shares it.
1185
+
1186
+ ```js
1187
+ server.on('connection', (conn) => {
1188
+ if (conn.setOptions) conn.setOptions({ initialRtt: 80 }); // QUIC: before the handshake
1189
+ });
1190
+
1191
+ app.get('/downloads/*', (req, res) => {
1192
+ if (req.socket.setOptions) req.socket.setOptions({ startupCap: 'always' }); // HTTP/3 only
1193
+ // …
1194
+ });
1195
+ ```
1196
+
1197
+ Over TCP (HTTP/1.1, HTTP/2) there is no `setOptions`: these options are QUIC's. Some are
1198
+ about how a connection begins, and past that point the call throws `ERR_INVALID_STATE`
1199
+ rather than take a value that would do nothing:
1200
+
1201
+ | Option | On a running connection |
1202
+ |---|---|
1203
+ | `reorderWindow`, `startupCap` | any time (`startupCap` matters only while in Startup) |
1204
+ | `pmtuDiscovery` | any time: off — probes stop, the size found stays; on — the search starts |
1205
+ | `maxUdpPayloadSize` | any time: lower — packets shrink at once; higher — the search may go there |
1206
+ | `initialRtt` | before the first RTT sample |
1207
+ | `initialCongestionWindow` | before the first 1-RTT packet |
1208
+ | `carefulResume` | before the handshake is confirmed |
1209
+ | `transportParams` | not: they went out in the handshake (`connectionOptions` decides them) |
1210
+ | `validateAddress`, `handshakeLoadThreshold`, `maxHandshakesPerAddress` | not: the server's |
1211
+
1212
+ A client sets them in its request options (`request`, `connect`, `WebTransport`,
1213
+ `connectUdp`) for what it sends: `startupCap`, `initialCongestionWindow`, `pmtuDiscovery`,
1214
+ `maxUdpPayloadSize`, `initialRtt`, `reorderWindow`.
1215
+
1216
+ **Events**
1217
+
1218
+ | Event | Arguments | |
1219
+ |---|---|---|
1220
+ | `'request'` | `(req, res)` | Same as the `requestListener` argument. |
1221
+ | `'upgrade'` | `(req, socket, head)` | WebSocket and other upgrades, on all three versions — see [WebSocket](#websocket-1). With no listener, an upgrade request arrives as an ordinary `'request'`, as in Node (see `shouldUpgradeCallback`). |
1222
+ | `'connectUdp'` | `(req, tunnel)` | A request to proxy UDP (RFC 9298), on all three versions — see [CONNECT-UDP](#connect-udp-proxying-udp). With no listener, such a request arrives as before (`'upgrade'` or `'request'`). |
1223
+ | `'timeout'` | `(socket)` | A TCP connection was idle for `server.timeout` ms. |
1224
+ | `'connection'` | TCP: the socket, before TLS. QUIC: a connection handle, on the first packet. | Destroy it here to refuse a peer before any crypto is done. |
1225
+ | `'secureConnection'` | TCP: the TLS socket. QUIC: the connection handle. | After the handshake. |
1226
+ | `'stream_open'` | `(conn, streamId)` | HTTP/2 and HTTP/3: a request stream announced itself, before its headers are decoded. |
1227
+ | `'handshakeLoad'` | `({ pending, high })` | HTTP/3 handshakes under way reached `handshakeLoadThreshold` (`high: true`), or are back under half of it (`high: false`). |
1228
+ | `'stream_reset'` | `(conn, streamId, code)` | HTTP/2 RST_STREAM; HTTP/3 RESET_STREAM or STOP_SENDING — once per stream. A default limit applies (`streamResetBurst`, `streamResetRate`); this is for a policy of your own on top, for both versions. |
1229
+ | `'OCSPRequest'` | `(certificate, issuer, callback)` | As `node:tls`: a client asked for the certificate's OCSP status, TCP or QUIC. `certificate` and `issuer` are DER `Buffer`s (`issuer` `null` when the chain has none); `callback(null, response)` staples a DER OCSP response, `callback(null, null)` none, `callback(err)` fails the handshake. The handshake waits for the answer — fetch and cache responses ahead of time. Without a listener nothing is stapled. (Chromium asks over TCP, not over QUIC.) |
1230
+ | `'tlsClientError'` | `(err, socket \| conn)` | A handshake failed, as in `node:tls`: over TCP the TLS socket, over QUIC the connection handle. Either side may have ended it — plain HTTP sent to the TLS port (`ERR_SSL_WRONG_VERSION_NUMBER`), no common ALPN, or a client refusing the certificate (`ERR_TLS_ALERT_RECEIVED`, `err.alert` = 42 for `bad_certificate`). |
1231
+ | `'clientError'` | `(err, socket)` | HTTP/1.1, once the connection is up (parse errors, the socket's errors). TLS handshake failures are `'tlsClientError'`. |
1232
+ | `'sessionError'` | `(err, session)` | HTTP/2: the connection failed (a protocol error — GOAWAY already sent —, the socket's error, a peer not reading past `maxSessionMemory`). `session` is the connection handle of `'stream_open'`. As `node:http2`. |
1233
+ | `'listening'` | | |
1234
+ | `'error'` | `(err)` | |
1235
+
1236
+ The `conn` handle given to the HTTP/2 and HTTP/3 stream events has `remoteAddress`,
1237
+ `remotePort`, `fingerprint()`, `sendRstStream(streamId, 'refused' | 'cancelled' | code)`,
1238
+ `goaway([code])` and `destroy([code])` — the same on both versions, so one rate limiter
1239
+ serves both:
1240
+
1241
+ - `goaway()` stops new requests; those already in flight finish. HTTP/2 sends GOAWAY;
1242
+ HTTP/3 sends GOAWAY too, refuses any later request with `H3_REQUEST_REJECTED` (safe for
1243
+ the client to retry elsewhere), and closes the connection once the last response has
1244
+ been delivered. `goaway('overloaded')` says why: `ENHANCE_YOUR_CALM` / `H3_EXCESSIVE_LOAD`.
1245
+ - `destroy()` cuts the connection now, in-flight requests included (`'overloaded'` or a
1246
+ number sets the HTTP/3 close code).
147
1247
 
148
- ## 🔗 Node.js API Compatibility
1248
+ ```js
1249
+ const server = quico.createServer({ key, cert, http2: false, http1: false });
149
1250
 
150
- One of the core design goals of QUICO is to provide a **familiar API**. If you already know `node:https`, working with QUICO should feel natural — `createServer`, `request`, `req`, `res` all work the same way.
1251
+ server.on('request', (req, res) => {
1252
+ res.writeHead(200, { 'content-type': 'application/json' });
1253
+ res.end(JSON.stringify({ url: req.url, version: req.httpVersion }));
1254
+ });
151
1255
 
152
- This means existing frameworks work out of the box:
1256
+ server.listen(4433, '0.0.0.0');
1257
+ ```
1258
+
1259
+ ---
1260
+
1261
+ ### `quico.request(url|options[, options], callback)`
1262
+
1263
+ Issues an HTTP request — HTTP/3 first, falling back to HTTP/2 and HTTP/1.1. Returns a
1264
+ [`ClientRequest`](#clientrequest). Accepts a URL string, an options object, or both
1265
+ (options override the URL). Requests are always made over TLS.
1266
+
1267
+ **Options**
1268
+
1269
+ | Option | Type | Default | Description |
1270
+ |---|---|---|---|
1271
+ | `hostname` / `host` | `string` | `'localhost'` | Target host. |
1272
+ | `port` | `number` | `443` | Target port. |
1273
+ | `path` | `string` | `'/'` | Request path including query string. |
1274
+ | `method` | `string` | `'GET'` | HTTP method. |
1275
+ | `headers` | `object` | `{}` | Request headers. |
1276
+ | `priority` | `object` | — | `{ urgency: 0..7, incremental }` — the request's priority (RFC 9218), as the `priority` header; `req.setPriority()` changes it later. |
1277
+ | `ech` | `Buffer \| string` | — | The server's ECH key list (an ECHConfigList; base64 — the `ech=` of its HTTPS record — or bytes): the ClientHello goes encrypted, on every version. See [ECH](#encrypted-client-hello-ech). |
1278
+ | `echGrease` | `boolean` | `true` | Without `ech`: send GREASE ECH, as browsers do. |
1279
+ | `ecdhCurve` | `string` | `'auto'` | The key-exchange groups to offer, in order — `node:tls`'s option, on every version. `'auto'` is what `node:tls` offers and the browsers do: the post-quantum hybrid X25519MLKEM768 first, with an X25519 share beside it (a server without it needs no retry), then X25519, P-256, P-384 — the hybrid where Node has ML-KEM (24.7+), the classical groups alone before that. `'X25519:P-256'` and the like for classical only; `'MLKEM1024'`, `'SecP384r1MLKEM1024'` and the other post-quantum groups by name (see [Post-quantum TLS](#post-quantum-tls)). A name not implemented, or the hybrid in a Node without ML-KEM (it needs 24.7+ on OpenSSL 3.5), throws from `request()`. A request shares only connections opened with the same groups. |
1280
+ | `startupCap` | `'stall'` \| `'always'` \| `'off'` | `'stall'` | HTTP/3: Startup's window cap on what the client sends (an upload) — as the server's option. |
1281
+ | `pmtuDiscovery`, `maxUdpPayloadSize`, `initialRtt`, `reorderWindow`, `initialCongestionWindow` | | | HTTP/3: this client's connection options — as the server's. `res.socket.setOptions()` changes them while it runs. |
1282
+ | `rejectUnauthorized` | `boolean` | `true` | Verify the server certificate. Set `false` for self-signed certs. |
1283
+ | `ca` | `Buffer \| string \| Array` | `null` | Trust these CAs instead of the platform roots (as in Node). |
1284
+ | `sigalgs` | `string` | lemon-tls's list | The signature schemes to offer, in order — `node:tls`'s option. `'mldsa65:mldsa87:ecdsa_secp256r1_sha256'` asks a server that holds an ML-DSA certificate for it; the default offers ML-DSA after the classical schemes. A request shares only connections opened with the same list. |
1285
+ | `key`, `cert`, `passphrase` | | — | A client certificate, for a server that asks for one — on HTTP/3, HTTP/2 and HTTP/1.1. A request with one shares only connections opened with the same certificate (see `Agent`). |
1286
+ | `earlyData` | `boolean` | `false` | With a session whose ticket allows it, send a `GET`, `HEAD` or `OPTIONS` in the first flight (0-RTT) — on every version. Refused or answered `425`, it is sent again after the handshake by itself; `res.earlyData` says what happened. See [0-RTT](#0-rtt-early-data). |
1287
+ | `session` | `Buffer` | the agent's | A TLS session to resume with, from an earlier `'session'` event (as `https.request`). Without it the agent offers its own (see `Agent`). |
1288
+ | `requestOCSP` | `boolean` | `false` | Ask the server for its stapled OCSP response (`tls.connect`'s option), on every version; it comes as the request's `'OCSPResponse'` (a DER `Buffer`). Only a full handshake carries one — a resumed session has no certificate. |
1289
+ | `quicVersions` | `Array` | `['v1', 'v2']` | HTTP/3: the QUIC version of the first flight, then the others it offers (RFC 9368) — a server that prefers v2 moves the connection there. `['v2']`: v2 from the first packet. |
1290
+ | `agent` | `Agent \| false` | `globalAgent` | Connection pool to use. `false`, as in Node: a connection of this request's own, closed when it is done (over HTTP/2 and HTTP/1.1 it went on a pool shared by every `agent: false` request), and no sessions kept — pass `session` to resume. |
1291
+ | `http2` | `boolean` | `true` | Allow HTTP/2 fallback. |
1292
+ | `http1` | `boolean` | `true` | Allow HTTP/1.1 fallback. |
1293
+ | `h3Timeout` | `number` | `3000` | Milliseconds to wait for QUIC before falling back. |
1294
+
1295
+ ```js
1296
+ const req = quico.request({
1297
+ hostname: 'localhost',
1298
+ port: 4433,
1299
+ path: '/api/items',
1300
+ method: 'POST',
1301
+ headers: { 'content-type': 'application/json' },
1302
+ rejectUnauthorized: false // self-signed cert in development
1303
+ }, (res) => {
1304
+ let body = '';
1305
+ res.on('data', (c) => body += c);
1306
+ res.on('end', () => console.log(res.statusCode, body));
1307
+ });
1308
+
1309
+ req.on('error', console.error);
1310
+ req.write(JSON.stringify({ name: 'test' }));
1311
+ req.end();
1312
+ ```
1313
+
1314
+ ### `quico.get(url|options[, options], callback)`
1315
+
1316
+ Same as `request()` with `method: 'GET'`. (`request()` itself ends GET and HEAD
1317
+ requests on the next tick.)
1318
+
1319
+ ---
1320
+
1321
+ ### `IncomingMessage`
1322
+
1323
+ A Node.js `Readable` stream. On the server it is the request; on the client, the
1324
+ response.
1325
+
1326
+ | Property | Description |
1327
+ |---|---|
1328
+ | `httpVersion` | `'3.0'`, `'2.0'` or `'1.1'` depending on the transport actually used |
1329
+ | `headers` | Lower-cased header object |
1330
+ | `method` | Request method (server side) |
1331
+ | `url` | Request path (server side) |
1332
+ | `statusCode` | Response status (client side) |
1333
+ | `earlyData` | Server: `true` if the request came in 0-RTT (it could be a replay). Client: `'accepted'` (sent early, taken), `'rejected'` (sent again after the handshake), `null` (not sent early). |
1334
+ | `socket` / `connection` | Compatibility shim for frameworks |
1335
+
1336
+ Standard `Readable` behaviour applies: `'data'`, `'end'`, `'error'`, `pipe()`,
1337
+ `for await (const chunk of req)`, and `setTimeout(ms, cb)`.
1338
+
1339
+ A body cut short — on the server, a request the client cancels or whose connection
1340
+ drops; on the client, a response the server resets or cuts off — gets `aborted = true`,
1341
+ an `'aborted'` event, an `'error'` (`ECONNRESET`, or the cause) only if something listens
1342
+ for one, and `'close'`; never `'end'`, which would say the body arrived whole, and never
1343
+ an unhandled `'error'`, because a browser cancelling a request is ordinary traffic. This
1344
+ is node:http's behaviour, on all three versions. HTTP/2 requests have
1345
+ `req.h2Fingerprint()`, HTTP/3 requests `req.h3Fingerprint()`; over HTTP/2 and HTTP/3,
1346
+ `req.headers` also keeps the pseudo-headers (`:method`, `:path`, `:authority`, …), as
1347
+ `node:http2` does, plus `host` taken from `:authority`.
1348
+
1349
+ A request handler that throws ends only its own exchange — HTTP/1.1 answers `500` and
1350
+ closes the connection, HTTP/2 and HTTP/3 reset that one stream (`INTERNAL_ERROR`,
1351
+ `H3_INTERNAL_ERROR`), and other requests on the connection go on — and the exception is
1352
+ then rethrown on the next tick, so it reaches `process.on('uncaughtException')` (or ends
1353
+ the process) exactly as in Node. A response already ended before the throw is delivered.
1354
+
1355
+ ---
1356
+
1357
+ ### `ServerResponse`
1358
+
1359
+ A Node.js `Writable` stream.
1360
+
1361
+ - `res.writeHead(statusCode[, statusMessage][, headers])`
1362
+ - `res.setHeader(name, value)` / `getHeader` / `getHeaders` / `getHeaderNames` /
1363
+ `hasHeader` / `removeHeader`
1364
+ - `res.flushHeaders()`
1365
+ - `res.write(chunk)` / `res.end([chunk])` — over HTTP/1.1, a body given whole to `end()`
1366
+ (nothing written before it) is sent with `Content-Length`, otherwise chunked, as
1367
+ `node:http` does
1368
+ - `res.statusCode`, `res.headersSent`
1369
+ - `res.writeEarlyHints(hints[, callback])` — `103 Early Hints`, on all three versions
1370
+ - `res.destroy([err])` / `req.destroy([err])` — give up on the exchange, as in Node: the
1371
+ stream is reset, the connection serves on. HTTP/3: RESET_STREAM and STOP_SENDING with
1372
+ `H3_REQUEST_CANCELLED` (`H3_INTERNAL_ERROR` with an `err`; RFC 9114 §4.1.1); after a
1373
+ finished response, only STOP_SENDING with `H3_NO_ERROR` for a request body still
1374
+ coming. HTTP/2: RST_STREAM `CANCEL` (`INTERNAL_ERROR` with an `err`). HTTP/1.1: the
1375
+ socket. Both went unsent: a destroyed exchange held its stream until the idle timeout.
1376
+ - `res.addTrailers({ … })` before `end()` — response trailers, on all three versions
1377
+ (HTTP/1.1 chunked; HTTP/2 and HTTP/3 a HEADERS frame after the body). What gRPC
1378
+ answers with: `grpc-status` / `grpc-message` go only there. A request's trailers are in
1379
+ `req.trailers` / `req.rawTrailers` by `'end'`; on the client, `res.trailers`
1380
+ - `res.setPriority({ urgency, incremental })` — HTTP/2 and HTTP/3 (over HTTP/1.1, one
1381
+ response at a time, it does nothing — the same handler runs on all three): the response's
1382
+ priority (RFC 9218: urgency 0..7, 0 first, default 3; incremental: shares the
1383
+ connection with others of its urgency rather than going whole, one at a time). Without
1384
+ it, the client's `priority` header and `PRIORITY_UPDATE` frames decide; set, it is the
1385
+ server's decision and later signals from the client do not override it. The client's
1386
+ header is in `req.headers.priority`. See
1387
+ [Stream scheduling](#stream-scheduling-byte-level-round-robin-by-priority).
1388
+
1389
+ For WebTransport sessions, `ServerResponse` additionally exposes
1390
+ `sendDatagram()`, `maxDatagramSize()`, `datagrams`, `getStats()`, `createBidirectionalStream()`,
1391
+ `createUnidirectionalStream()`, `canOpenStream()`, `createSendGroup()`, `setWebTransportProtocol()`,
1392
+ `closeSession()` and `drainSession()` — see
1393
+ [WebTransport](#webtransport-1).
1394
+
1395
+ ---
1396
+
1397
+ ### `ClientRequest`
1398
+
1399
+ A Node.js `Writable` stream.
1400
+
1401
+ - `req.write(chunk)` / `req.end([chunk])` — the body streams, as `node:http`'s does: written
1402
+ while the connection is being made it is held (past 64 KB `write()` returns `false`, then
1403
+ `'drain'`), and from then on it goes as it is written, with the transport's backpressure —
1404
+ the QUIC stream's, HTTP/2's window, the socket's. Over HTTP/1.1 a body not yet complete goes
1405
+ chunked, unless a `content-length` was set: the bytes must then add up to it (too many or too
1406
+ few fails the request with `ERR_HTTP_CONTENT_LENGTH_MISMATCH`; on a pooled connection the
1407
+ difference would be read as another request). The first protocol to be ready takes the
1408
+ request, and only it sends: a request whose answer takes HTTP/3 longer than `h3Timeout` is not
1409
+ sent over TCP as well. The first 64 KB of a body are kept, so that a request refused
1410
+ unprocessed (`REFUSED_STREAM`, `H3_REQUEST_REJECTED`, past a GOAWAY), or whose protocol failed
1411
+ before it was sent, goes again whole; a larger one that has started cannot, and fails.
1412
+ - `req.addTrailers({ … })` before `end()` — request trailers (`node:http`'s), on all three
1413
+ versions: a HEADERS frame after the body over HTTP/2 and HTTP/3, after the last chunk over
1414
+ HTTP/1.1 (so only chunked, as in `node:http`). Connection-specific and forbidden fields are
1415
+ dropped, as for responses.
1416
+ - `req.setPriority({ urgency, incremental })`, or the `priority` option of `request()` — the
1417
+ request's priority (RFC 9218: urgency 0..7, 0 first, default 3; incremental: its response
1418
+ may share the connection with others of its urgency). Before the request goes it is the
1419
+ `priority` header (`'u=1, i'`; the default sends none), on all three versions; after, a
1420
+ `PRIORITY_UPDATE` frame over HTTP/2 and HTTP/3 (HTTP/1.1 has none — nothing is sent). It
1421
+ is the client's signal: a server whose application set the response's priority
1422
+ (`res.setPriority`) keeps its own.
1423
+ - `req.abort()` / `req.destroy([err])` — stop the exchange where it is carried: the
1424
+ request's stream over HTTP/3 and HTTP/2 (a pooled connection serves on), the socket over
1425
+ HTTP/1.1. `res.destroy()` on an unfinished response does the same. A request the server
1426
+ reset after it was sent — a non-idempotent one (RFC 9110 §9.2.2) — fails with the reset,
1427
+ and is not sent again over another version; one it refused is. As in Node, the response then sees `'aborted'` and `'close'` (an `'error'` only
1428
+ if it listens for one), never `'end'`; `destroy()` before any response fails the request
1429
+ with `ECONNRESET` (`socket hang up`), `abort()` emits `'abort'` and no error.
1430
+ - `req.protocol` — which transport was actually used: `'h3'`, `'h2'` or `'https'`
1431
+ - Events: `'response'`, `'error'`, `'timeout'`, `'session'` (a `Buffer`: a TLS session the
1432
+ server sent, to resume with — as a `TLSSocket`'s, once per ticket, on the request that
1433
+ opened the connection), `'OCSPResponse'` (with `requestOCSP`: the server's stapled OCSP
1434
+ response, DER, on the request that opened the connection)
1435
+ - A request the server did not process — refused (HTTP/2 `REFUSED_STREAM`, HTTP/3
1436
+ `H3_REQUEST_REJECTED`) or past its `GOAWAY` (a server that closes its connections after
1437
+ `maxRequestsPerSocket` requests does that to the ones in flight) — is sent again once,
1438
+ on a new connection (RFC 9113 §8.7, RFC 9114 §4.1.1, §5.2). When every protocol fails,
1439
+ the `'error'` has the last one's reason as its `cause`.
1440
+
1441
+ ---
1442
+
1443
+ ### `Agent`
1444
+
1445
+ Connection pool and protocol cache, analogous to `https.Agent`.
1446
+
1447
+ ```js
1448
+ import { Agent } from 'quico';
1449
+
1450
+ const agent = new Agent({
1451
+ http2: true, // allow H2 in the fallback chain
1452
+ http1: true, // allow H1.1 in the fallback chain
1453
+ h3Timeout: 3000, // ms before falling back from H3
1454
+ maxSockets: 256, // HTTP/1.1 sockets per origin; more requests wait
1455
+ maxCachedSessions: 100, // TLS sessions kept to resume with
1456
+ ecdhCurve: 'X25519:P-256' // its requests' key exchange (default 'auto': post-quantum first), unless one names its own
1457
+ });
1458
+
1459
+ quico.request({ hostname: 'example.com', agent }, handler).end();
1460
+ ```
1461
+
1462
+ HTTP/2 and HTTP/3 multiplex every request to an origin over one connection, which
1463
+ the agent keeps and shares. HTTP/1.1 needs a socket per request, and for those the
1464
+ agent takes `node:http.Agent`'s options, with Node's meanings:
1465
+
1466
+ | Option | Default | |
1467
+ |---|---|---|
1468
+ | `keepAlive` | `true` | Keep a socket for the next request (Node's `globalAgent` default; a plain `new http.Agent()` defaults to `false`). |
1469
+ | `keepAliveMsecs` | `1000` | TCP keep-alive initial delay on kept sockets. |
1470
+ | `maxSockets` | `256` | Sockets per origin at once. Requests beyond it wait for a socket. |
1471
+ | `maxFreeSockets` | `256` | Idle sockets kept per origin. |
1472
+ | `timeout` | `5000` | How long an idle socket is kept. |
1473
+
1474
+ **Protocol discovery.** The agent remembers which protocol worked for each origin,
1475
+ and separately what each origin advertises in `Alt-Svc` (RFC 7838), for its `ma=`
1476
+ lifetime. When an origin advertises HTTP/3 — on its own port or another — the next
1477
+ request tries HTTP/3 there first, and falls back to the origin over TCP (or its own
1478
+ HTTP/3) if that fails; a failed alternative is left alone for five minutes, as
1479
+ browsers do. Concurrent requests to an origin share one connection.
1480
+
1481
+ **Which connections a request shares.** As `https.Agent` names its connections
1482
+ (`agent.getName(options)`), a pooled connection is keyed by its origin and its TLS
1483
+ identity — `ca`, `cert` / `key`, `rejectUnauthorized`, `servername` (hashed). A
1484
+ connection opened with `rejectUnauthorized: false` never carries a request that
1485
+ verifies, nor one verified against a private `ca` a request that trusts the public
1486
+ roots; before, any connection to the origin was reused. The same goes for the
1487
+ standalone `h1Request` / `h2Request` pools.
1488
+
1489
+ **Session resumption.** As `https.Agent`, the agent keeps the TLS sessions each
1490
+ origin's server sent — up to 4 per origin, newest last; `maxCachedSessions` (default
1491
+ `100`, the oldest dropped; `0` keeps none) bounds the origins — and a new connection
1492
+ resumes with one — no certificate exchange — over HTTP/3, HTTP/2 and HTTP/1.1, and for
1493
+ `WebSocket` (`wss://`) and `connectUdp` too. Each session is used **once** (RFC 8446
1494
+ §C.4): two connections opened at once take two, so they cannot be linked, and both can
1495
+ send 0-RTT — with one kept per origin, the second's early data was always refused as a
1496
+ replay. A QUICO server sends two tickets per full handshake (one per resumption), as
1497
+ OpenSSL and BoringSSL do. An expired session is not offered (lemon-tls `sessionInfo`).
1498
+ TCP sessions are kept per ALPN (`h2`, `http/1.1`): a ticket carries 0-RTT only for the
1499
+ protocol it was issued under. Before, every connection was a full handshake, and a QUICO server
1500
+ never saw its own ticket again: what it saves there about the path (Careful Resume,
1501
+ above) is only used by a client that resumes. A session is offered only where it was
1502
+ made: the same transport (a TCP session is not offered to QUIC), origin, server name and
1503
+ verification — one from a connection with `rejectUnauthorized: false`, or another `ca`, is
1504
+ not offered to one that verifies. A session the handshake fails with is dropped. A
1505
+ resumed connection reports the server's certificate and `authorized` from the session, as
1506
+ Node does. For QUIC it also keeps the server's NEW_TOKEN token (RFC 9000 §8.1.3) — used
1507
+ once, by the next connection, which then needs no proof of address.
1508
+
1509
+ `quico.globalAgent` is the default instance used when no `agent` option is given.
1510
+ Call `agent.destroy()` to close everything it pools.
1511
+
1512
+ ---
1513
+
1514
+ ### `quico.createSecureContext(options)`
1515
+
1516
+ Creates a TLS context for use with `SNICallback`. Accepts `key`, `cert` and `ca`.
1517
+ Re-exported from LemonTLS.
1518
+
1519
+ ---
1520
+
1521
+ ### 0-RTT (early data)
1522
+
1523
+ A returning visitor's request can go in its first flight, with the ClientHello, under a
1524
+ key from its last session — the answer comes one round trip sooner. On a phone at
1525
+ 150 ms RTT, that is 150 ms off the first byte of every page that opens a new connection.
1526
+ It works the same on every version: over HTTP/3 in QUIC's 0-RTT packets, and over TLS 1.3 on
1527
+ TCP (HTTP/2, HTTP/1.1) as TLS early data — with Encrypted Client Hello as well (the early
1528
+ data is the inner hello's, RFC 9849 §6.1). Chromium and Firefox send 0-RTT over HTTP/3.
1529
+
1530
+ The price: early data has no protection against replay. Someone who captured the first
1531
+ flight can send it again, and the server would run the request again. So it is **off by
1532
+ default**, and turned on it is held to four rules:
1533
+
1534
+ 1. **A ticket carries early data once.** The server remembers each ticket's early data
1535
+ (`earlyDataReplay`, in memory by default) for twice `earlyDataMaxAge`; the second time,
1536
+ the handshake goes on without it.
1537
+ 2. **Only for a short while.** The age the client states for its ticket must be within
1538
+ `earlyDataMaxAge` (10 s) of what the server measures — a captured flight goes stale.
1539
+ 3. **Only under the same settings.** A ticket from before a change of transport
1540
+ parameters or of the HTTP/3 SETTINGS this server sends (or a restart with other ones),
1541
+ or one a connection with lower limits (`connectionOptions`) would not honour, resumes
1542
+ the session without early data: a client sends its early data under what it remembered
1543
+ (RFC 9000 §7.4.1, RFC 9114 §7.2.4.2).
1544
+ 4. **Only safe requests.** `earlyDataFilter` decides which requests may run before the
1545
+ handshake completes — by default `GET`, `HEAD` and `OPTIONS`; the others get
1546
+ `425 Too Early` and the client sends them again once the handshake is done (RFC 8470),
1547
+ by itself — a browser does, and so does `quico.request`.
1548
+
1549
+ Refused early data costs nothing but the round trip saved: the request is served as it
1550
+ would have been without it.
1551
+
1552
+ ```js
1553
+ const server = quico.createServer({
1554
+ key, cert,
1555
+ ticketKeys, // stable keys, or tickets die with the process
1556
+ earlyData: true,
1557
+ earlyDataFilter(req, cb) { // asynchronous: a database, a rule engine
1558
+ if (req.url.startsWith('/api/')) return cb(null, false); // → 425, after the handshake
1559
+ cb(null, true);
1560
+ }
1561
+ }, (req, res) => {
1562
+ // req.earlyData: this request may be a replay — never act on it (a payment,
1563
+ // a login) without the handshake; the filter is where to say so.
1564
+ res.end('hello');
1565
+ });
1566
+ ```
1567
+
1568
+ **A restart.** The default store is in memory and starts empty: a ticket issued before a
1569
+ restart (with `ticketKeys` kept) gets no early data for twice `earlyDataMaxAge` after it —
1570
+ a flight captured just before the restart cannot be sent again just after it. One 1-RTT
1571
+ handshake for such a client, and its new ticket is fine.
1572
+
1573
+ **More than one server.** Each server remembers in its own memory, so a flight captured
1574
+ at one could be replayed at another that shares `ticketKeys`. Give them one store:
1575
+
1576
+ ```js
1577
+ const server = quico.createServer({
1578
+ key, cert, ticketKeys, earlyData: true,
1579
+ // id: the ticket (a SHA-256, hex); ttl: how long to remember it, ms.
1580
+ earlyDataReplay(id, ttl, cb) {
1581
+ redis.set('0rtt:' + id, '1', 'PX', ttl, 'NX', (err, ok) => cb(err, ok === 'OK'));
1582
+ }
1583
+ });
1584
+ ```
1585
+
1586
+ `server.setOptions({ earlyData: false })` turns it off at once — tickets already given out
1587
+ included.
1588
+
1589
+ **What the client remembers.** Each session keeps, with the ticket, the server's transport
1590
+ parameters and its HTTP/3 SETTINGS; early data goes within them (RFC 9000 §7.4.1, RFC 9114
1591
+ §7.2.4.2). A server that accepts the 0-RTT and then gives less — a transport parameter
1592
+ lower than remembered, a setting omitted or lower — breaks the connection it took the
1593
+ early data on: the client closes it, `PROTOCOL_VIOLATION` or `H3_SETTINGS_ERROR`, naming
1594
+ what changed.
1595
+
1596
+ **The client.** `earlyData: true` on a request with a session (its own, or the agent's):
1597
+
1598
+ ```js
1599
+ const req = quico.request('https://example.com/', { earlyData: true }, (res) => {
1600
+ console.log(res.earlyData); // 'accepted', 'rejected' or null
1601
+ });
1602
+ req.end();
1603
+ ```
1604
+
1605
+ Only `GET`, `HEAD` and `OPTIONS` are sent early; anything else waits for the
1606
+ handshake. Refused — by the server's TLS, or with a `425` — the request is sent again after
1607
+ the handshake, and the response is the one to that.
1608
+
1609
+ **Over TCP.** The same options, the same checks (one use per ticket, the age, the context —
1610
+ a ticket from the HTTP/3 side carries no early data here, nor the other way round), the same
1611
+ `earlyDataFilter` and `425`. A ticket allows up to 16 KB of early data — room for a request,
1612
+ not an upload; what does not fit goes after the handshake. The server reads the early
1613
+ request as it comes and may answer as soon as its own handshake flight is out, so the
1614
+ client has the answer one round trip after its first flight.
1615
+
1616
+ ---
1617
+
1618
+ ### Encrypted Client Hello (ECH)
1619
+
1620
+ Without ECH, the first message of every TLS connection — the ClientHello, with the
1621
+ site's name (SNI) and the ALPN list — crosses the network in the clear: anyone on the
1622
+ path sees which site is being visited, HTTPS or not. With ECH (RFC 9849) the browser
1623
+ sends the real ClientHello encrypted, inside an outer one that names only a shared
1624
+ *public name*, to a key the server publishes in its DNS HTTPS record. The server
1625
+ decrypts it and the handshake goes on as usual — `SNICallback` gets the real name.
1626
+
1627
+ ECH hides names that **share an address**: when many sites sit behind one IP and one
1628
+ public name (a CDN, a host with many domains), the network sees only which group. A
1629
+ single site on its own IP is still known by the IP.
1630
+
1631
+ **1. A key, kept across restarts** — like DNSSEC keys:
1632
+
1633
+ ```js
1634
+ import quico from 'quico';
1635
+ const k = quico.generateEchKey({ publicName: 'ech.example.com' });
1636
+ // save k.config and k.privateKey (bytes); publish k.configListBase64 in DNS
1637
+ ```
1638
+
1639
+ **2. The DNS record** — the `ech` key of the domain's HTTPS record (RFC 9460), e.g.
1640
+ with [dnssec-server](https://github.com/colocohen/dnssec-server):
1641
+
1642
+ ```
1643
+ www IN HTTPS 1 . alpn="h3,h2" ech="AEb+DQBC…"
1644
+ ```
1645
+
1646
+ **3. The server** — with a certificate for the public name as well, served when a
1647
+ client's key could not be used:
1648
+
1649
+ ```js
1650
+ const server = quico.createServer({
1651
+ SNICallback: (name, cb) => cb(null, contexts[name]), // incl. ech.example.com
1652
+ ech: { keys: [{ config: saved.config, privateKey: saved.privateKey }] },
1653
+ }, (req, res) => {
1654
+ res.end(req.socket.servername + ' ' + req.socket.echStatus);
1655
+ });
1656
+ ```
1657
+
1658
+ `req.socket.echStatus` is `'accepted'` (the hidden name was used), `'rejected'` (the
1659
+ client's key was not one of ours: the handshake ran as the public name, and the client
1660
+ was sent our current keys — `retry_configs` — to connect again with), or `null` (no ECH
1661
+ offered). `req.socket.echAccepted` is the boolean.
1662
+
1663
+ **Rotation** — new key in DNS first, then on the server, the old one kept with
1664
+ `retry: false` until the old record's TTL has passed:
1665
+
1666
+ ```js
1667
+ server.setEchKeys({ keys: [
1668
+ { config: next.config, privateKey: next.privateKey },
1669
+ { config: prev.config, privateKey: prev.privateKey, retry: false },
1670
+ ] });
1671
+ ```
1672
+
1673
+ The key itself is not certified by anyone: its trust comes from DNS (DNSSEC, and
1674
+ DNS-over-HTTPS on the client). A substituted key could reveal which name was asked
1675
+ for, never let anyone impersonate the site — the certificate is still checked against
1676
+ that name. Tested against Go's `crypto/tls` client (accept, retry, HelloRetryRequest,
1677
+ resumption); DTLS is not covered.
1678
+
1679
+ #### The client
1680
+
1681
+ `quico.request`, `WebTransport` and `connectUdp` take the server's key list as `ech` —
1682
+ the `ech=` value of its HTTPS record (base64), or the bytes. The real ClientHello goes
1683
+ encrypted, over HTTP/3, HTTP/2 and HTTP/1.1 alike:
1684
+
1685
+ ```js
1686
+ const req = quico.request({ hostname: 'www.example.com', path: '/', ech: 'AEb+DQBC…' }, (res) => {
1687
+ console.log(res.socket.echStatus); // 'accepted'
1688
+ });
1689
+ req.end();
1690
+ ```
1691
+
1692
+ `res.socket.echStatus` (and `echAccepted`) on every version: `'accepted'`, `'grease'`, or
1693
+ `null`. When the server cannot use the key (it rotated its keys, say), it proves itself
1694
+ for the public name and sends its current keys; the request is tried once more with
1695
+ them, automatically. The agent keeps those keys (RFC 9849 §6.1.8) and uses them first on
1696
+ the next requests given the same `ech` — `quico.request` and `connectUdp` — so a server
1697
+ that rotated its keys costs one retry, not one per connection until your DNS has the new
1698
+ ones. They are kept as TLS sessions are: per origin and TLS settings, a day at most, none
1699
+ with `agent: false` or `maxCachedSessions: 0`. Rejected in their turn, they are forgotten
1700
+ and your `ech` is tried again. If it sends none — its ECH is off — the request fails with
1701
+ `ERR_ECH_REJECTED` (`err.retryConfigs` null) instead of falling back to a ClientHello
1702
+ in the clear: going on without ECH is the caller's decision.
1703
+
1704
+ Without `ech`, the client sends **GREASE ECH** (RFC 9849 §6.2), as Chrome and Firefox
1705
+ do: an ECH extension no server can decrypt, so that clients that do use ECH do not stand
1706
+ out. `echGrease: false` turns it off. QUICO does not look up HTTPS records itself (no
1707
+ DNS-over-HTTPS here): the application passes the key list it resolved.
1708
+
1709
+ ECH is TLS 1.3 only. Tested against Go's `crypto/tls` server (accept, retry,
1710
+ HelloRetryRequest, GREASE) and QUICO's own server, over QUIC and TCP.
1711
+
1712
+ ---
1713
+
1714
+ ### Framework compatibility
1715
+
1716
+ A core design goal is a **familiar API**. If you know `node:https`, QUICO should feel
1717
+ natural — which means existing frameworks work unmodified:
153
1718
 
154
1719
  ```js
155
1720
  import express from 'express';
@@ -162,17 +1727,20 @@ quico.createServer({ key: KEY, cert: CERT }, app).listen(4433);
162
1727
  // → { "protocol": "3.0" }
163
1728
  ```
164
1729
 
165
- For multi-domain setups, QUICO supports `SNICallback` just like `node:https`:
1730
+ Express, Fastify and Koa are all supported this way.
1731
+
1732
+ Multi-domain setups use `SNICallback`, exactly as in `node:https`:
166
1733
 
167
1734
  ```js
168
1735
  import quico from 'quico';
169
1736
  import tls from 'lemon-tls';
1737
+ import fs from 'node:fs';
170
1738
 
171
1739
  const server = quico.createServer({
172
- SNICallback: function (servername, cb) {
1740
+ SNICallback: (servername, cb) => {
173
1741
  cb(null, tls.createSecureContext({
174
- key: fs.readFileSync('certs/' + servername + '.key'),
175
- cert: fs.readFileSync('certs/' + servername + '.crt')
1742
+ key: fs.readFileSync(`certs/${servername}.key`),
1743
+ cert: fs.readFileSync(`certs/${servername}.crt`)
176
1744
  }));
177
1745
  }
178
1746
  }, (req, res) => {
@@ -180,186 +1748,960 @@ const server = quico.createServer({
180
1748
  res.end('Hello World from HTTP/3 on Node.js!');
181
1749
  });
182
1750
 
183
- server.listen(4433, () => {
184
- console.log('🚀 QUIC server running on https://localhost:4433');
185
- });
1751
+ server.listen(4433);
186
1752
  ```
187
1753
 
1754
+ ---
188
1755
 
189
- ## 🚀 WebTransport
1756
+ ### WebTransport
190
1757
 
191
- ### Server
1758
+ #### Server
192
1759
 
193
1760
  ```js
194
1761
  import quico from 'quico';
195
1762
 
196
1763
  quico.createServer({ key: KEY, cert: CERT }, (req, res) => {
197
1764
  if (req.headers[':protocol'] === 'webtransport') {
198
- // Accept the WebTransport session
199
- res.writeHead(200);
1765
+ res.writeHead(200); // accept the session
200
1766
 
201
- // Bidirectional streams from the client
202
- req.on('stream', (stream) => {
203
- stream.on('data', (chunk) => {
204
- stream.write(chunk); // echo back
205
- });
1767
+ req.on('stream', (stream) => { // client-initiated streams
1768
+ stream.on('data', (chunk) => stream.write(chunk)); // echo
206
1769
  stream.on('end', () => stream.end());
207
1770
  });
208
1771
 
209
- // Unreliable datagrams
210
- req.on('datagram', (data) => {
211
- res.sendDatagram(data); // echo back
212
- });
1772
+ req.on('datagram', (data) => res.sendDatagram(data));
213
1773
 
214
- // Server can also create streams
215
- const push = res.createBidirectionalStream();
1774
+ const push = res.createBidirectionalStream(); // server-initiated
216
1775
  push.write('server says hello');
217
1776
  push.end();
218
1777
  } else {
219
- // Regular HTTP/3 request
220
1778
  res.end('Hello HTTP/3!');
221
1779
  }
222
1780
  }).listen(4433);
223
1781
  ```
224
1782
 
225
- ### Client (Node.js)
1783
+ **Datagrams** (`res.sendDatagram(data)`) are never retransmitted, but they are sent under
1784
+ the connection's congestion control (RFC 9221 §5.4): they wait for room in a packet and
1785
+ go ahead of stream data. While the path cannot keep up, the oldest are dropped — any that
1786
+ have waited 250 ms, and past 1 MB queued. `sendDatagram` returns `true` when the datagram
1787
+ is queued, `false` when it cannot be sent at all (larger than `res.maxDatagramSize()`, or
1788
+ the peer takes no datagrams). Datagrams sent right after accepting the session are held
1789
+ until the `200` has left: a browser drops datagrams for a session it does not know yet.
1790
+
1791
+ `res.datagrams` is the browser's datagrams object too — the client's `wt.datagrams`,
1792
+ the same code: `readable`, `writable`, `createWritable({ sendOrder, sendGroup })`,
1793
+ `maxDatagramSize`, `incomingMaxAge`, `outgoingMaxAge` and the high-water marks. Its
1794
+ `outgoingMaxAge` is the session's own: sessions on one connection share its queue, each
1795
+ with its own age limit and its own count of datagrams dropped.
1796
+
1797
+ **Statistics** — `res.getStats()`, as the client's `wt.getStats()` (the same function):
1798
+ a Promise of the browser's `WebTransportConnectionStats` — `bytesSent`, `packetsSent`,
1799
+ `packetsLost`, `bytesReceived`, `packetsReceived` (whole packets), `smoothedRtt`,
1800
+ `rttVariation`, `minRtt` (ms), `estimatedSendRate` (bits/s, the congestion control's
1801
+ bandwidth estimate; `null` until measured), `atSendCapacity` (the congestion window is
1802
+ full) — with QUICO's `congestionWindow` and `bytesInFlight` besides, and `datagrams`:
1803
+ `{ droppedIncoming, expiredIncoming, expiredOutgoing, lostOutgoing }`, this session's.
1804
+ The connection's figures are shared by every session on it, as in the browser. A sender
1805
+ that has to choose what to drop for a slow receiver reads `atSendCapacity`, or
1806
+ `bytesInFlight` against `congestionWindow`: the congestion is the connection's, not one
1807
+ stream's.
1808
+
1809
+ **Priorities** are the browser's: a stream's `sendOrder` and `sendGroup`
1810
+ (`stream.sendGroup = res.createSendGroup()`), and `res.sendDatagram(data, { sendOrder,
1811
+ sendGroup })` as the browser's `datagrams.createWritable({ sendOrder, sendGroup })`. The
1812
+ groups of a session share its sending equally; within a group the highest `sendOrder`
1813
+ with something to send goes first, equal orders taking turns; a stream in no group is in
1814
+ the session's own. Datagrams sent without them go ahead of every stream. The session's
1815
+ urgency — the CONNECT request's `priority`, or `res.setPriority()` — is its streams'.
1816
+
1817
+ **Streams** are Node streams: a `Duplex` for a bidirectional stream, a `Readable` for the
1818
+ client's unidirectional one (`'unidirectionalStream'`), a `Writable` for ours. What the
1819
+ client sends is credited back to it as the application reads, so a stream nobody reads
1820
+ holds one stream window (256 KB bidirectional, 128 KB unidirectional, or as set with
1821
+ `transportParams`), not the whole upload. Each direction can be given up with an
1822
+ application error code (32-bit, mapped onto HTTP/3's codes as draft-ietf-webtrans-http3
1823
+ §4.4 defines), on its own — as in the browser, the two directions of a bidirectional
1824
+ stream are independent:
1825
+
1826
+ | | |
1827
+ |---|---|
1828
+ | `stream.resetStream(code[, { reliableSize }])` | Stop sending: what was written and not yet sent is dropped. A browser's reader fails with `streamErrorCode`. With `reliableSize`, the first that many bytes written still arrive whole before the reset (RESET_STREAM_AT, draft-ietf-quic-reliable-stream-reset) — a MOQT subgroup's header, say; the stream's own WebTransport header always does (draft-ietf-webtrans-http3 §4.4), so the peer knows its session. Needs a peer that takes RESET_STREAM_AT (`stream.reliableResetSupported`; QUICO advertises it); otherwise a RESET_STREAM. Also after `end()`, until all of it is acknowledged (RFC 9000 §3.1) — a MOQT subgroup past its delivery timeout is dropped, not sent to the end. Returns `true` when a reset went, `false` when there was nothing left to reset. |
1829
+ | `stream.stopSending(code)` | Stop reading (STOP_SENDING): the peer stops. A browser's writer fails with `streamErrorCode`. |
1830
+ | `stream.destroy()` | Both, with code 0, for whatever direction is unfinished. |
1831
+ | `'peerReset'` (`code`) | The peer stopped sending (RESET_STREAM): our reading is over — what was read stands, the readable side ends, and its WHATWG `readable` fails with the code. Our writing goes on. |
1832
+ | `'peerStopSending'` (`code`) | The peer stopped reading (STOP_SENDING): our writing is over — writes from now on are dropped, the WHATWG `writable` fails. Our reading goes on. |
1833
+ | `stream.streamErrorCode` | The peer's code from either (`null` if it sent none). |
1834
+ | `'committed'` | Our sending part is "all data committed" (draft-ietf-webtrans-overview §4.3; "Data Recvd", RFC 9000 §3.1): every byte written and the FIN acknowledged by the peer. Once; never for a stream reset first. `'finish'` (and `end()`'s callback) only says the bytes were handed to QUIC — a delivery deadline (MOQT's SUBGROUP_DELIVERY_TIMEOUT) runs from the FIN to here, and `resetStream()` before it drops what is left. `sendState` is then `'committed'`. |
1835
+ | `stream.id`, `stream.sessionId` | Its QUIC stream ID, and its session's — read-only. |
1836
+ | `stream.sendState`, `stream.recvState` | Each direction, read-only: `'open'`, `'finished'` (the FIN sent / received), `'committed'` (ours: all of it and the FIN acknowledged), `'reset'` (we gave up sending / the peer did), `'stopped'` (the peer asked us to stop / we stopped reading); `null` for the direction a unidirectional stream does not have. A `'drain'` says the writer may write; `sendState` says whether what it writes still goes anywhere. |
1837
+ | `'close'` | Once both directions are over — by FIN, reset or stop, from either side, in any order. When the peer's reset or stop is what ends the last one, an `Error` (`ERR_WEBTRANSPORT_STREAM_RESET` / `ERR_WEBTRANSPORT_STOP_SENDING`) goes to an `'error'` listener — only if there is one. |
1838
+
1839
+ **Opening streams** is the browser's: `res.createBidirectionalStream(options[, callback])`
1840
+ and `res.createUnidirectionalStream(options[, callback])` take `{ sendOrder, sendGroup,
1841
+ waitUntilAvailable }` and return the stream at once, in Node's way (`net.connect`'s).
1842
+ Past the client's `MAX_STREAMS` without `waitUntilAvailable` they return `null`
1843
+ (`res.canOpenStream({ bidirectional })` says beforehand); with it, the stream is opened
1844
+ and its bytes wait for the client to allow more. Until then `stream.pending` is `true`;
1845
+ when it is open, `'ready'` and `callback(null, stream)` — or `callback(err)` (code
1846
+ `ERR_WEBTRANSPORT_STREAM_NOT_OPEN`) if it was given up first, its session closed.
226
1847
 
227
1848
  ```js
228
- import { WebTransport } from 'quico';
1849
+ const st = res.createUnidirectionalStream({ waitUntilAvailable: true, sendOrder: 5 }, (err) => {
1850
+ if (err) return; // never opened: the session went first
1851
+ // open: the client has allowed it
1852
+ });
1853
+ st.write(object); // may be written at once; it waits with the stream
1854
+ ```
1855
+
1856
+ **The subprotocol** — the browser's `new WebTransport(url, { protocols: [...] })`: the
1857
+ client's offer is `req.webTransportProtocols`, in its order of preference (parsed from
1858
+ WT-Available-Protocols), and `res.setWebTransportProtocol(name)` before `writeHead(200)`
1859
+ picks one — sent as WT-Protocol, what the client's `wt.protocol` then says. A name the
1860
+ client did not offer throws: the client would fail the session over it.
229
1861
 
230
- const wt = new WebTransport('https://localhost:4433/echo');
1862
+ ```js
1863
+ const chosen = req.webTransportProtocols.find(p => SUPPORTED.includes(p));
1864
+ if (chosen) res.setWebTransportProtocol(chosen);
1865
+ res.writeHead(200);
1866
+ ```
1867
+
1868
+ **Streams that arrive early** — opened by the client right after its CONNECT, before
1869
+ the application accepts the session, or even read before the CONNECT itself — are
1870
+ held (one stream window each, up to 64 per connection) and delivered as
1871
+ `'stream'` / `'unidirectionalStream'` once `res.writeHead(200)` accepts it. If the
1872
+ application answers otherwise, or the CONNECT never comes, they are reset with
1873
+ `WEBTRANSPORT_BUFFERED_STREAM_REJECTED`.
1874
+
1875
+ **The session** ends with `'close'` on `req`. `res.closeSession(code, reason)` closes it with
1876
+ CLOSE_WEBTRANSPORT_SESSION — a 32-bit code and a reason of up to 1024 bytes, what a
1877
+ browser's `wt.closed` resolves with — and resets its streams. A client's close arrives the
1878
+ same way: `req.closeInfo` is `{ closeCode, reason }` when it sent one. `res.drainSession()`
1879
+ sends DRAIN_WEBTRANSPORT_SESSION (finish up, start nothing new); a client's DRAIN is
1880
+ `'draining'` on `req`.
1881
+
1882
+ #### Client (Node.js)
1883
+
1884
+ QUICO's `WebTransport` is the browser's API — the same class, promises, streams and
1885
+ options — so a client written for the browser runs in Node unchanged:
1886
+
1887
+ ```js
1888
+ import { WebTransport, WebTransportError } from 'quico'; // in a browser: globals
1889
+
1890
+ const wt = new WebTransport('https://example.com:4433/live', {
1891
+ serverCertificateHashes: [{ algorithm: 'sha-256', value: certHash }], // or a CA-signed cert
1892
+ });
231
1893
  await wt.ready;
232
1894
 
233
- // Bidirectional stream
234
- const stream = await wt.createBidirectionalStream();
235
- stream.write('hello');
236
- stream.on('data', (chunk) => console.log('echo:', chunk.toString()));
237
- stream.end();
1895
+ const { readable, writable } = await wt.createBidirectionalStream();
1896
+ const writer = writable.getWriter();
1897
+ await writer.write(new TextEncoder().encode('hello'));
1898
+ await writer.close();
1899
+ for (const reader = readable.getReader();;) { const { value, done } = await reader.read(); if (done) break; /* … */ }
238
1900
 
239
- // Unidirectional stream
240
- const uni = await wt.createUnidirectionalStream();
241
- uni.write('fire and forget');
242
- uni.end();
1901
+ const uni = await wt.createUnidirectionalStream(); // a WritableStream
1902
+ await uni.getWriter().abort(new WebTransportError({ streamErrorCode: 7 })); // RESET_STREAM, code 7
243
1903
 
244
- // Datagrams (unreliable)
245
- wt.sendDatagram(Buffer.from('ping'));
246
- wt.on('datagram', (data) => console.log('pong:', data.toString()));
1904
+ const incoming = wt.incomingUnidirectionalStreams.getReader(); // ReadableStream of ReadableStreams
1905
+ const dgWriter = wt.datagrams.writable.getWriter(); // and wt.datagrams.readable
247
1906
 
248
- wt.close();
1907
+ wt.close({ closeCode: 0, reason: 'done' });
1908
+ const { closeCode, reason } = await wt.closed; // the server's, if it closed first
249
1909
  ```
250
1910
 
251
- ### Client (Browser)
1911
+ The whole browser API is there: `ready`, `closed` (resolving with `{ closeCode, reason }`),
1912
+ `draining`, `close()`, `createBidirectionalStream()` / `createUnidirectionalStream()` with
1913
+ `sendOrder`, `sendGroup` and `waitUntilAvailable`, `incomingBidirectionalStreams`,
1914
+ `incomingUnidirectionalStreams`, `datagrams` (`readable`, `writable`, `createWritable()`,
1915
+ `maxDatagramSize`, `incomingMaxAge`, `outgoingMaxAge`, `incomingHighWaterMark`,
1916
+ `outgoingHighWaterMark`), `createSendGroup()`, `getStats()`, `reliability`,
1917
+ `congestionControl`, `protocol`, and stream `getStats()`; the options
1918
+ `serverCertificateHashes` (the leaf's SHA-256, a certificate valid for at most 14 days, as
1919
+ the browser requires), `protocols`, `requireUnreliable`, `congestionControl`,
1920
+ `transportParams` (QUICO's own: the windows and stream limits, as the server's),
1921
+ `key` / `cert` / `passphrase` (a client certificate, as `https.request` takes it),
1922
+ `quicVersions` and `ecdhCurve` (as `quico.request`'s),
1923
+ `session` (a TLS session from an earlier `'session'` event, to resume — not with
1924
+ `serverCertificateHashes`: a resumed handshake has no certificate to pin),
1925
+ `initialCongestionWindow` (as the server's),
1926
+ `allowPooling` and the `anticipatedConcurrent…` hints. `WebTransportError` takes the browser's
1927
+ `{ streamErrorCode }` form as well as the spec's `(message, options)`. A test runs the same
1928
+ client function in Chromium and in Node against a QUICO server and checks both see the same.
1929
+ `sendOrder` and `sendGroup` order what the client sends, as on the server (see above).
1930
+
1931
+ The same object also has a Node-style API, for Node code:
1932
+
1933
+ | | |
1934
+ |---|---|
1935
+ | `wt.on('stream', duplex)`, `wt.on('unidirectionalStream', readable)` | The server's streams as Node streams. A stream goes to a Node listener if there is one, otherwise to `incoming…Streams` once that is read, and waits for either. |
1936
+ | `wt.on('datagram', buf)`, `wt.sendDatagram(buf[, { sendOrder, sendGroup }])` → `true`/`false`, `wt.maxDatagramSize()` | Datagrams; with a `sendOrder` / `sendGroup` one takes its place among the streams, as the server's `res.sendDatagram`. |
1937
+ | `'ready'`, `'draining'`, `'close'` | The session's events. |
1938
+ | `'session'` (`Buffer`) | A TLS session the server sent, to pass back as `session` next time and resume. |
1939
+ | `stream.write()`, `stream.on('data')`, `stream.pipe()` | Every stream is a Node stream too: `createBidirectionalStream()` gives a `Duplex` that has the browser's `readable` / `writable`; `createUnidirectionalStream()` gives the browser's `WritableStream` that is Node's `Writable` too — `write()` / `'drain'`, `end()`, `resetStream()`, its events, `writableLength` and the rest of its state, and `readable.pipe()` into it. |
1940
+ | `stream.resetStream(code)`, `stream.stopSending(code)`, `stream.streamErrorCode` | Give up on a direction with a code; the peer's code when it gave up. |
1941
+ | `stream.id`, `stream.sessionId`, `stream.sendState`, `stream.recvState`, `stream.pending` | As on the server. `create…Stream()`'s Promise is settled once the stream is open — at once, or with `waitUntilAvailable` when the server allows it — as the browser's is. |
1942
+ | `wt.canOpenStream({ bidirectional })`, `wt.getStats()` | As the server's `res.canOpenStream()` and `res.getStats()`. |
1943
+ | `'peerReset'` / `'peerStopSending'` (`code`), `'close'` | As on the server: the direction the peer gave up on ends, the other goes on; `'close'` once both are over. |
1944
+ | `stream.sendOrder`, `stream.sendGroup` | Its place among the session's streams (see [Priorities](#webtransport-1) on the server — the same rules). |
1945
+
1946
+ The client's streams are the server's kind: the server's are recognised by their
1947
+ WebTransport prefix, not guessed from stream numbers, and what the server sends is credited
1948
+ back as the application reads — a stream nobody reads holds one stream window.
1949
+
1950
+ Besides the browser's options, the second argument takes `ca` and `rejectUnauthorized`
1951
+ (default `true`), as in `https.request`: the server's certificate is verified against the
1952
+ platform roots unless `ca` is given or `serverCertificateHashes` pins it. If the session
1953
+ cannot be established, `ready` and `closed` reject with a `WebTransportError` (source
1954
+ `'session'`, keeping node:tls's `err.code`, e.g. `DEPTH_ZERO_SELF_SIGNED_CERT`, when TLS is
1955
+ the reason), `state` becomes `'failed'` and the connection is closed, as in the browser.
1956
+ `'error'` is emitted too, but only when a listener is attached.
1957
+
1958
+ #### Client (Browser)
1959
+
1960
+ A QUICO server works with the **native browser WebTransport API** — no client library
1961
+ needed:
252
1962
 
253
1963
  ```js
254
1964
  const wt = new WebTransport('https://yourserver.com:4433/live');
255
1965
  await wt.ready;
256
1966
 
257
- // Send via WHATWG Streams API
258
1967
  const writer = wt.datagrams.writable.getWriter();
259
1968
  await writer.write(new TextEncoder().encode('Hello QUIC'));
260
1969
 
261
- // Receive
262
1970
  const reader = wt.datagrams.readable.getReader();
263
1971
  const { value } = await reader.read();
264
1972
  console.log('Received:', new TextDecoder().decode(value));
265
1973
  ```
266
1974
 
1975
+ ---
1976
+
1977
+ ### WebSocket
1978
+
1979
+ #### Server
1980
+
1981
+ One handler serves WebSocket over HTTP/1.1, HTTP/2 (RFC 8441) and HTTP/3 (RFC 9220):
1982
+ all three arrive as the server's `'upgrade'` event.
1983
+
1984
+ ```js
1985
+ import quico, { WebSocketServer } from 'quico';
1986
+
1987
+ const server = quico.createServer({ key: KEY, cert: CERT });
1988
+ const wss = new WebSocketServer({ server, path: '/chat', pingInterval: 30000 });
1989
+
1990
+ wss.on('connection', (ws, req) => {
1991
+ ws.on('message', (data, isBinary) => ws.send(data, { binary: isBinary }));
1992
+ });
1993
+
1994
+ server.listen(4433);
1995
+ ```
1996
+
1997
+ `WebSocketServer(options)` takes `server` (or `noServer: true` and call
1998
+ `wss.handleUpgrade(req, socket, head, cb)` yourself), `path`, `pingInterval` (clients
1999
+ that miss a pong are dropped) and the options of `upgradeWebSocket`:
2000
+
2001
+ - `origin` — a string, an array, or `fn(origin, req)`; a mismatch is answered with 403
2002
+ - `verifyClient(req)` — return `false` (401) or `{ code, message, headers }`
2003
+ - `protocol` (string or `fn(offered, req)`) / `protocols` (preference list)
2004
+ - `headers` — extra response headers
2005
+ - `maxPayload` — default 100 MB
2006
+
2007
+ `wss.clients` is the set of open connections; `wss.close([code][, reason])` closes them.
2008
+ For a single upgrade without a server object, `upgradeWebSocket(req, socket, head,
2009
+ options)` returns the socket, or `null` after answering the client itself.
2010
+
2011
+ Sockets have both surfaces: WHATWG (`onmessage`, `addEventListener`, `binaryType`) and
2012
+ the `ws` package's (`on('message', (data, isBinary))`, `on('close', (code, reason))`,
2013
+ `ping()`, `on('pong')`). Pings are answered automatically.
2014
+
2015
+ #### Client
2016
+
2017
+ ```js
2018
+ import { WebSocket } from 'quico';
2019
+
2020
+ const ws = new WebSocket('wss://localhost:4433/chat', [], { rejectUnauthorized: false });
2021
+ ws.onopen = () => ws.send('hello');
2022
+ ws.onmessage = (e) => console.log(e.data);
2023
+ ```
2024
+
2025
+ The client connects over HTTP/1.1. Options beyond the WHATWG constructor: `origin`,
2026
+ `headers`, `ca`, `rejectUnauthorized`, `maxPayload`, `agent` (whose TLS sessions a
2027
+ `wss://` connection resumes with and keeps — `globalAgent` by default) and `session` (one
2028
+ to resume with, from an earlier `'session'`). `ws.on('session', buf)`: each one the server
2029
+ sends.
2030
+
2031
+ ---
2032
+
2033
+ ### CONNECT-UDP (proxying UDP)
2034
+
2035
+ A QUICO server can be a UDP proxy (RFC 9298, the MASQUE working group's): a client
2036
+ asks it for a UDP "socket" to one target, a host and a port, and from then on sends
2037
+ the target UDP payloads through it and receives the target's. This is what a browser's
2038
+ or an OS's privacy relay does for QUIC traffic.
2039
+
2040
+ ```js
2041
+ const server = quico.createServer({ key: KEY, cert: CERT });
2042
+
2043
+ server.on('connectUdp', (req, tunnel) => {
2044
+ if (req.headers.authorization !== 'Bearer ' + TOKEN) return tunnel.reject(407);
2045
+ tunnel.accept(); // to tunnel.target, from the request
2046
+ tunnel.on('close', (stats) => console.log(tunnel.target, stats.bytesToClient, tunnel.closeReason));
2047
+ });
2048
+
2049
+ server.listen(443);
2050
+ ```
2051
+
2052
+ **How it travels.** The request names the target in its path, by a URI template the
2053
+ clients are configured with: by default `/.well-known/masque/udp/{target_host}/{target_port}/`
2054
+ (an IPv6 address with its colons percent-encoded). Over HTTP/3 it is an extended CONNECT
2055
+ (`:protocol: connect-udp`), and each UDP payload is an HTTP Datagram (RFC 9297) in a QUIC
2056
+ DATAGRAM frame — unreliable, as UDP is. A client that did not negotiate datagrams,
2057
+ HTTP/2 (extended CONNECT) and HTTP/1.1 (`Upgrade: connect-udp`, answered 101) carry them
2058
+ as DATAGRAM capsules on the request stream. The proxy relays from a UDP socket of its own,
2059
+ connected to the target, so only the target's packets come back through it. A payload
2060
+ larger than a QUIC datagram can carry is dropped, not moved to the stream (§5: a
2061
+ reliable, ordered copy of a UDP packet is not one).
2062
+
2063
+ **What the application decides** — in `'connectUdp'`, now or later (the client may
2064
+ send before the answer; the first 32 payloads wait):
2065
+
2066
+ | | |
2067
+ |---|---|
2068
+ | `tunnel.accept()` | Relay to `tunnel.target`. The host is resolved (`lookup`), the socket connected, then the 2xx goes. |
2069
+ | `tunnel.accept({ target: { host, port } })` | Relay to another target. |
2070
+ | `tunnel.accept({ socket })` | Relay through the application's own `dgram` socket (bound where it wants, say). Packets from senders other than the target are not relayed; the socket is not closed with the tunnel. |
2071
+ | `tunnel.accept({ relay: false })` | No relay: the application gets each payload from the client as `'message'` (a `Buffer`) and answers with `tunnel.send(buf)`. |
2072
+ | `tunnel.accept({ headers, allowPrivate })` | Extra response fields; the private-address rule for this tunnel. |
2073
+ | `tunnel.reject(status[, headers])` | Refuse it. |
2074
+ | `tunnel.send(buf)` | A payload to the client, in any mode. `false`: not sent (too large, or the stream is full — dropped, as UDP drops). |
2075
+ | `tunnel.close()` | End it (the request stream is ended). |
2076
+
2077
+ `tunnel.req` is the request (an `IncomingMessage`), `tunnel.target` `{ host, port }`,
2078
+ `tunnel.state` `'pending'` / `'open'` / `'closed'`. Events: `'open'`, `'message'` (with
2079
+ `relay: false`), `'close'` (with the stats; `tunnel.closeReason` says why: `'client'`,
2080
+ `'local'`, `'idle'`, `'aborted'` — the stream was reset or the connection went —,
2081
+ `'socket'` — the target's socket failed, an ICMP unreachable, say — or `'rejected'`;
2082
+ `tunnel.error` holds the error when there was one).
2083
+
2084
+ **Figures.** `tunnel.stats`: `{ target, address, port, httpVersion, state, transport
2085
+ ('datagram' | 'capsule'), openedAt, closedAt, durationMs, packetsFromClient,
2086
+ bytesFromClient, packetsToClient, bytesToClient, droppedFromClient, droppedToClient }`.
2087
+ `server.getConnectUdpStats()`: `{ active, accepted, rejected, closed }` and the same
2088
+ counters summed over every tunnel, open ones included.
2089
+
2090
+ **Refused on its own** — before `'connectUdp'`, or at `accept()`:
2091
+
2092
+ | Case | Answer |
2093
+ |---|---|
2094
+ | A path that is not the template's | 404 |
2095
+ | An empty host, a port outside 1..65535 | 400 |
2096
+ | HTTP/1.1, not a GET | 400 |
2097
+ | More tunnels on one connection than `maxTunnelsPerConnection` | 429 |
2098
+ | The host does not resolve | 502, `Proxy-Status: quico; error=dns_error` |
2099
+ | The host resolves only to private addresses | 403, `Proxy-Status: quico; error=destination_ip_prohibited` |
2100
+ | No `'connectUdp'` listener | Not a tunnel: the request goes to `'upgrade'` or `'request'`, as before |
2101
+
2102
+ **Options** (`createServer({ connectUdp: { … } })`):
2103
+
2104
+ | Option | Default | |
2105
+ |---|---|---|
2106
+ | `template` | `/.well-known/masque/udp/{target_host}/{target_port}/` | The URI template — variables in the path, or a query (`/masque{?target_host,target_port}`). |
2107
+ | `allowPrivate` | `false` | Allow targets in private, loopback, link-local, CGNAT, multicast and reserved ranges (IPv4 and IPv6, IPv4-mapped included). Off, a proxy cannot be used to reach its own network (RFC 9298 §7). |
2108
+ | `maxTunnelsPerConnection` | `16` | |
2109
+ | `idleTimeout` | `120000` | ms with nothing either way before a tunnel is closed; never under two minutes (RFC 9298 §3.1), `0` for none. |
2110
+ | `lookup` | `dns.lookup` | `(host, { all: true }, cb)`, as `dns.lookup`. |
2111
+ | `proxyName` | `'quico'` | The name in `Proxy-Status`. |
2112
+
2113
+ RFC 9298 asks that a UDP proxy serve authenticated users only — the check is the
2114
+ application's, in `'connectUdp'`.
2115
+
2116
+ #### Client: `quico.connectUdp(proxy, target[, options][, callback])`
2117
+
2118
+ A UDP socket to `target` (`{ host, port }`) through a proxy. What it returns behaves as a
2119
+ connected `dgram.Socket`, so code written for `dgram` moves to a proxied path by changing
2120
+ the line that makes the socket:
2121
+
2122
+ ```js
2123
+ import { connectUdp } from 'quico';
2124
+
2125
+ const sock = connectUdp('https://proxy.example', { host: '1.1.1.1', port: 53 },
2126
+ { headers: { 'proxy-authorization': 'Bearer ' + TOKEN } });
2127
+ sock.on('connect', () => sock.send(dnsQuery));
2128
+ sock.on('message', (msg, rinfo) => { /* rinfo: the target, as dgram gives it */ });
2129
+ sock.on('error', console.error);
2130
+ ```
2131
+
2132
+ `proxy` is the proxy's URL — and, if it contains `{target_host}`, the URI template too
2133
+ (`'https://proxy.example/masque{?target_host,target_port}'`); without one, the default
2134
+ template's path — or `{ hostname, port, template }`.
2135
+
2136
+ HTTP/3 first, each payload a QUIC datagram. If QUIC has not connected within `h3Timeout`
2137
+ (UDP blocked on the way, a proxy without HTTP/3), TCP: HTTP/2 extended CONNECT or HTTP/1.1
2138
+ Upgrade, as ALPN decides, the payloads in capsules.
2139
+
2140
+ Over HTTP/3 the tunnels to one proxy share a connection (RFC 9298's tunnels are requests;
2141
+ their datagrams are told apart by Quarter Stream ID): a tunnel joins the connection opened
2142
+ with the same TLS settings, or waits for the one being made — no handshake of its own, one
2143
+ congestion controller, one UDP port — and the connection closes with its last tunnel. A
2144
+ tunnel the proxy refuses, or one closed, leaves the others as they are; a connection lost
2145
+ ends each tunnel on it with `ERR_CONNECT_UDP_CLOSED`. `shareConnection: false` gives a
2146
+ tunnel its own. Over TCP each tunnel has its own connection.
2147
+
2148
+ | | |
2149
+ |---|---|
2150
+ | `send(msg[, offset, length][, callback])` | A connected socket's forms: a `Buffer`, a typed array, a string, or an array of them (one payload). Before `'connect'`, up to 64 are held and go when the tunnel opens. Larger than `maxPayloadSize`: `EMSGSIZE`. When the stream already holds too much (capsules), dropped as UDP drops — no error. With a port and address: `ERR_SOCKET_DGRAM_IS_CONNECTED`. |
2151
+ | `close([callback])` | Ends the tunnel: the request stream's end, and the connection's when it was the last on it. |
2152
+ | `remoteAddress()` | The target `{ address, family, port }`. |
2153
+ | `address()` | The local end of the connection to the proxy. |
2154
+ | `maxPayloadSize` | The largest payload `send()` takes now: over HTTP/3, what a QUIC datagram carries on this path (~1195 bytes at the start; more after path MTU discovery); over capsules, 65527. |
2155
+ | `protocol` | `'h3'`, `'h2'` or `'http/1.1'`, once open. |
2156
+ | `statusCode`, `responseHeaders` | The proxy's answer. |
2157
+ | `closeReason` | `'local'`, `'proxy'` (it ended the tunnel) or `'error'`. |
2158
+ | `stats` | `{ protocol, transport ('datagram' \| 'capsule'), target, openedAt, closedAt, durationMs, packetsSent, bytesSent, packetsReceived, bytesReceived, dropped }` |
2159
+
2160
+ TLS sessions to the proxy are kept and resumed with as `quico.request`'s are: the
2161
+ `agent` option's (`globalAgent` by default; `false`: none), each used once, or `session`;
2162
+ each the proxy sends is the socket's `'session'` event.
2163
+
2164
+ Events: `'connect'`, `'message'` `(msg, rinfo)`, `'error'`, `'close'`, `'session'`. A refusal is an
2165
+ `'error'` with `code: 'ERR_CONNECT_UDP_REFUSED'`, `statusCode` and `proxyStatus` (the
2166
+ proxy's `Proxy-Status`), then `'close'`.
2167
+
2168
+ | Option | Default | |
2169
+ |---|---|---|
2170
+ | `protocol` | `'auto'` | `'h3'` (no fallback), `'h2'` or `'http/1.1'` to use only that. |
2171
+ | `h3Timeout` | `3000` | ms to wait for QUIC before TCP. |
2172
+ | `fallback` | `true` | `false`: HTTP/3 only, even with `'auto'`. |
2173
+ | `shareConnection` | `true` | `false`: an HTTP/3 connection of its own, not shared with the proxy's other tunnels. |
2174
+ | `headers` | — | Fields for the request (authorization). |
2175
+ | `ech`, `echGrease` | | Encrypted Client Hello to the proxy, as `quico.request`'s. |
2176
+ | `ecdhCurve` | | The key-exchange groups to offer the proxy, as `quico.request`'s. |
2177
+ | `template` | the default | When the proxy URL carries none. |
2178
+ | `rejectUnauthorized`, `ca`, `key`, `cert`, `passphrase`, `servername`, `quicVersions` | | As `quico.request`. |
2179
+
2180
+ Tested against quic-go's masque-go in both directions — its client through QUICO's proxy
2181
+ (an HTTP/3 request inside the tunnel: QUIC in QUIC), QUICO's client through its proxy.
2182
+
2183
+ ---
2184
+
2185
+ ### Fingerprinting
2186
+
2187
+ Who is really on the other end? A browser and a script sending the same User-Agent
2188
+ still differ in how they speak the protocols underneath. QUICO exposes those
2189
+ differences, on every layer it implements.
2190
+
2191
+ | Function | Input | Returns |
2192
+ |---|---|---|
2193
+ | `ja4h(req)` | a request | JA4H: `{ hash, raw, a, b, c, d }` — method, version, header names and order, cookie names (never values) |
2194
+ | `req.h2Fingerprint()` | HTTP/2 request | `{ hash, raw, … }` from the client's SETTINGS, WINDOW_UPDATE, PRIORITY and pseudo-header order |
2195
+ | `req.h3Fingerprint()` | HTTP/3 request | `{ hash, raw, … }` from the client's QUIC transport parameters, HTTP/3 SETTINGS and pseudo-header order |
2196
+ | `h2Fingerprint(observed)` / `h3Fingerprint(observed)` | raw observations | the same, computed from your own data |
2197
+ | `req.socket.getJA4()` / `getJA4S()` / `getJA5()` | TLS | TLS fingerprints, from LemonTLS — `null` when the installed LemonTLS does not provide them |
2198
+ | `req.socket.getNegotiationResult()` / `res.socket.getNegotiationResult()` | TLS | What the handshake settled, on every version: `{ versionName, cipherName, groupName, alpn, resumed, helloRetried, certificateCompression: { sent, received }, … }` — `sent` and `received` the algorithm each side's certificate went in (`'brotli'`, `'zlib'`, `'zstd'`), `null` where it went plain or not at all (a resumed connection) |
2199
+ | `profileRequest(req)` | a request | `{ claimed, protocol, fingerprints: { ja4, ja4s, h2, h2raw, h3, h3raw }, signals, suspicion }` — signals where the request's TLS and HTTP/2 behaviour contradicts the client it claims to be, and a 0–100 score. HTTP/3 fingerprints are reported, not yet checked against browsers. |
2200
+
2201
+ ```js
2202
+ server.on('request', (req, res) => {
2203
+ const p = quico.profileRequest(req);
2204
+ if (p.suspicion >= 60) { res.writeHead(403); return res.end(); }
2205
+ // …
2206
+ });
2207
+ ```
2208
+
2209
+ ---
2210
+
2211
+ ### Protocol layers
2212
+
2213
+ The unified server and client are built from layers you can use on their own — for a
2214
+ custom transport, a proxy, or protocols other than HTTP.
2215
+
2216
+ | Export | What it is |
2217
+ |---|---|
2218
+ | `createH1Server(options, handler)` | HTTP/1.1 server on its own |
2219
+ | `createH2Server(options, handler)` | HTTP/2 server on its own |
2220
+ | `createH3Server(options, handler)` | HTTP/3 + WebTransport server on its own (over `createQuicServer`) |
2221
+ | `h1Request(options, cb)` / `h2Request(options, cb)` / `h3Request(options, cb)` | Single-protocol clients, no fallback. Each takes `session` and emits `'session'`, as `https.request`. `h2Request` streams its body: `write()` sends as it is called and returns `false` while the stream's window or the socket is full, then `'drain'` — an upload is never held whole |
2222
+ | `createTcpListener(options)` | TCP accept + TLS + ALPN dispatch: `register(alpn, handler, { sniff })`, `listen()` |
2223
+ | `createQuicServer(options)` | QUIC transport server — see below |
2224
+ | `createQuicClientSocket(opts)` | A UDP socket driving one client `QUICConnection` (`remoteIp`, `remotePort`, `hostname`, `alpn`, `ecdhCurve`, `onConnect(quic)`, `onSocket(quic)` before the handshake — the place to attach `'keylog'`) |
2225
+
2226
+ ---
2227
+
2228
+ ### Low-level QUIC API
2229
+
2230
+ For non-HTTP protocols over QUIC, or full control of the connection.
2231
+
2232
+ #### `createQuicServer(options)`
2233
+
2234
+ | Option | Type | Default | Description |
2235
+ |---|---|---|---|
2236
+ | `key`, `cert`, `ca` | | — | TLS credentials |
2237
+ | `SNICallback` | `Function` | `null` | Per-hostname contexts |
2238
+ | `alpn` | `string[]` | `['h3']` | ALPN protocols to accept |
2239
+ | `maxConnections` | `number` | `10000` | Connection cap |
2240
+ | `ticketKeys` | `Buffer` | random | Session-ticket key |
2241
+ | `sessionTimeout` | `number` | `7200` | Seconds a session ticket stays good |
2242
+ | `requestCert`, `rejectUnauthorized`, `ciphers`, `ecdhCurve`, `sigalgs`, `handshakeTimeout`, `passphrase`, `certificateCompression` | | | As `createServer` (TLS 1.3) |
2243
+ | `initialCongestionWindow` | `number` | `20` | Initial congestion window, in packets |
2244
+ | `carefulResume` | `boolean` | `false` | Careful Resume (RFC 9959) for returning clients |
2245
+ | `startupCap` | `string` | `'stall'` | Startup's window cap: `'stall'`, `'always'`, `'off'` (as `createServer`) |
2246
+ | `quicVersions` | `Array` | `['v1', 'v2']` | QUIC versions accepted, in preference (RFC 9368, RFC 9369) |
2247
+ | `connectionOptions` | `Function` | — | Per-connection settings (see above) |
2248
+ | `validateAddress` | `boolean` | `false` | Address validation with Retry |
2249
+ | `earlyData`, `earlyDataMaxAge`, `earlyDataReplay` | | `false`, `10000`, in memory | 0-RTT, as `createServer` (`quic.isEarlyStream(id)`: whether a stream came early) |
2250
+ | `handshakeLoadThreshold`, `maxHandshakesPerAddress` | `number` | `500`, `64` | As `createServer`; `getPendingHandshakes()`, `setOptions()` / `getOptions()` too |
2251
+ | `pmtuDiscovery`, `maxUdpPayloadSize`, `initialRtt`, `reorderWindow` | | | As `createServer` |
2252
+ | `resetTokenSecret` | `Buffer` | random | Stateless-reset secret |
2253
+ | `socket` / `socket6` | `dgram.Socket` | `null` | External, already-bound UDP sockets |
2254
+
2255
+ Returns `{ listen, close, on, handlePacket, hasConnection }` plus the runtime getters and
2256
+ setters for ticket keys, address validation and the reset secret. The `'connection'`
2257
+ event fires with `(quicConnection, peer)`.
2258
+
2259
+ ```js
2260
+ import { createQuicServer } from 'quico';
2261
+
2262
+ const qs = createQuicServer({ key, cert, alpn: ['my-protocol'] });
2263
+
2264
+ qs.on('connection', (quic, peer) => {
2265
+ console.log('connection from', peer.address, peer.port);
2266
+
2267
+ quic.on('stream', (streamId, data, fin) => {
2268
+ if (fin) quic.sendStream(streamId, Buffer.from('bye'), true);
2269
+ });
2270
+
2271
+ quic.on('datagram', (data) => quic.sendDatagram(data));
2272
+ });
2273
+
2274
+ qs.listen(4433);
2275
+ ```
2276
+
2277
+ `handlePacket(msg, rinfo)` and `hasConnection(rinfo)` support **external socket
2278
+ mode**, where QUICO shares a UDP port with another protocol (STUN/TURN, for example)
2279
+ and you route datagrams yourself.
2280
+
2281
+ #### `QUICConnection`
2282
+
2283
+ | Member | Description |
2284
+ |---|---|
2285
+ | `quic.state` | `'idle'`, `'handshaking'`, `'connected'`, `'closing'`, `'draining'`, `'closed'` |
2286
+ | `quic.sendStream(id, data, fin)` | Write to a stream. A new stream beyond the peer's `MAX_STREAMS` waits until the peer raises the limit. |
2287
+ | `quic.whenStreamCommitted(id, cb)` | `cb()` once every byte and the FIN of the stream are acknowledged ("Data Recvd"); never if it is reset first |
2288
+ | `quic.resetStream(id, code[, reliableSize])` | Abandon the sending part of a stream (RESET_STREAM); with `reliableSize`, its first bytes still delivered (RESET_STREAM_AT, when the peer takes it: `quic.resetStreamAtSupported`) |
2289
+ | `quic.stopSending(id, code)` | Ask the peer to stop sending on a stream (STOP_SENDING) |
2290
+ | `quic.sendDatagram(data[, prio])` | Send an unreliable datagram; `false` if not connected or too large. With `prio` (`{ urgency, group, order }`) it is scheduled among the streams instead of ahead of them |
2291
+ | `quic.setStreamPriority(id, { urgency, incremental, group, order }[, fromPeer])` | A stream's place in the scheduler — see [Stream scheduling](#stream-scheduling-byte-level-round-robin-by-priority). `fromPeer`: the peer's signal, which does not replace what the application set |
2292
+ | `quic.getStreamPriority(id)` | What is set for a stream, or `null` |
2293
+ | `quic.canOpenStream(bidi)` | Whether a stream of ours could be opened now, within the peer's `MAX_STREAMS` |
2294
+ | `quic.isReceiving(id)` | Whether a stream's receiving part is open (opened, and neither finished nor reset) |
2295
+ | `quic.maxDatagramSize()` | Largest datagram payload that fits one packet (a local estimate) |
2296
+ | `quic.close(errorCode, reason[, application])` | Send CONNECTION_CLOSE; `application: true` for application error codes |
2297
+ | `quic.remoteAddress` / `remotePort` | The peer's current address — follows NAT rebinding |
2298
+ | `quic.earlyDataStatus` | 0-RTT: `null` (none), `'offered'` (a client's, undecided), `'accepted'`, `'rejected'` |
2299
+ | `quic.isEarlyStream(id)` | Server: whether the stream was opened by 0-RTT data |
2300
+ | `quic.whenConfirmed(cb)` | `cb()` once the handshake is confirmed (RFC 9001 §4.1.2), at once if it is |
2301
+ | `quic.alpnProtocol`, `servername`, `getCertificate()`, `getTicketInfo()`, `isSessionReused()` | What the handshake decided, with `TLSSocket`'s names |
2302
+ | `quic.on(event, fn)` / `off` | Event subscription |
2303
+
2304
+ **Events:** `'connect'`, `'stream'` (`id, data, fin`), `'stream_reset'` (`id, code,
2305
+ finalSize`), `'stop_sending'` (`id, code`), `'datagram'`, `'path'` (`address, port`),
2306
+ `'peer_transport_params'`, `'close'`, `'error'`, `'keylog'`; a client's 0-RTT: `'early'` (it may
2307
+ send application data now), `'early_accepted'`, `'early_rejected'` (what went early is forgotten — send it again).
2308
+
2309
+ **Connection options** (when constructing directly): `idleTimeout` (default `30000`),
2310
+ `handshakeTimeout` (default `10000`), `keepAlive` (`true` → half the idle timeout, or
2311
+ a number of ms), `alpn`, `hostname`, `rejectUnauthorized`, `ca`.
2312
+
2313
+
2314
+ ---
2315
+
2316
+ ## ⚙️ Configuration & Tuning
2317
+
2318
+ ### Transport parameters
2319
+
2320
+ These are the values QUICO advertises to peers. The windows, stream limits and idle timeout can be
2321
+ set — `createServer({ transportParams })`, `new WebTransport(url, { transportParams })`
2322
+ — by RFC 9000's names in camelCase; a value out of range throws when the server or
2323
+ client is made.
2324
+
2325
+ | Parameter | Option | Default | Meaning |
2326
+ |---|---|---|---|
2327
+ | `initial_max_data` | `initialMaxData` | 1 MB | Connection-level receive window |
2328
+ | `initial_max_stream_data_bidi_local` | `initialMaxStreamDataBidiLocal` | 256 KB | Receive window of a bidirectional stream we open |
2329
+ | `initial_max_stream_data_bidi_remote` | `initialMaxStreamDataBidiRemote` | 256 KB | Receive window of one the peer opens |
2330
+ | `initial_max_stream_data_uni` | `initialMaxStreamDataUni` | 128 KB | Receive window of a unidirectional stream the peer opens |
2331
+ | `initial_max_streams_bidi` | `initialMaxStreamsBidi` | 100 | Bidirectional streams the peer may have open at once |
2332
+ | `initial_max_streams_uni` | `initialMaxStreamsUni` | 100 | Unidirectional streams the peer may have open at once (HTTP/3 keeps three for itself; at least 3) |
2333
+ | `max_idle_timeout` | `maxIdleTimeout` | 30 s | Milliseconds without a packet from the peer before the connection is closed — silently, with no CONNECTION_CLOSE (RFC 9000 §10.1); `0`: no limit. The one in force is the **smaller** of the two sides' (RFC 9000 §10.1), and never under three PTOs; `keepAlive: true` pings at half of it |
2334
+ | `disable_active_migration` | `disableActiveMigration` | not sent | `true`: clients may not move to another address (connection migration, RFC 9000 §9). Unset, they may — a phone from Wi-Fi to cellular goes on in the same connection |
2335
+ | `max_ack_delay` | | 25 ms | Maximum ACK delay we advertise |
2336
+ | `max_datagram_frame_size` | | 65527 | Datagram support (RFC 9221) |
2337
+ | `active_connection_id_limit` | | 4 | Connection IDs we will track (and issue to the peer, up to its own) |
2338
+ | `version_information` | `quicVersions` | v1, v2 | The versions offered or chosen (RFC 9368) |
2339
+ | `grease_quic_bit` | | sent | The peer may send the fixed bit as 0 (RFC 9287); not on a shared UDP port |
2340
+ | `reset_stream_at` | | sent | RESET_STREAM_AT is taken (draft-ietf-quic-reliable-stream-reset): a peer's reset can keep its stream's first bytes delivered |
2341
+ | `min_ack_delay` | | 1 ms (16 ms on Windows) | ACK_FREQUENCY and IMMEDIATE_ACK are taken (draft-ietf-quic-ack-frequency) |
2342
+
2343
+ Receive windows slide automatically as data is consumed, and grow (autotuning) while
2344
+ the application keeps up, so large downloads are not limited by the initial values. Stream limits work the same way: as
2345
+ the peer's streams close, `MAX_STREAMS` gives them back, keeping the number open at
2346
+ once, so a long-lived connection is not capped at 100 requests.
2347
+
2348
+ ### Per-connection timers
2349
+
2350
+ ```js
2351
+ // via the low-level API
2352
+ new QUICConnection({
2353
+ idleTimeout: 60000, // default 30000 — what we advertise (transportParams.maxIdleTimeout)
2354
+ handshakeTimeout: 10000, // default 10000
2355
+ keepAlive: true // PING at half the idle timeout in force; or a number of ms
2356
+ });
2357
+ ```
2358
+
2359
+ The idle timeout in force is the smaller of ours and the peer's, as RFC 9000 §10.1 has
2360
+ it — the peer's arrives with its transport parameters; `createQuicClientSocket` takes
2361
+ `idleTimeout` and `keepAlive` too.
2362
+
2363
+ ---
2364
+
2365
+ ## 🐛 Debugging
2366
+
2367
+ ### Environment variables
2368
+
2369
+ | Variable | Effect |
2370
+ |---|---|
2371
+ | `QUICO_DEBUG=1` | Full per-packet trace: every datagram, packet, frame, stream write, and TLS transition. **Very verbose** — it can become the bottleneck it observes, so don't use it for throughput measurements. |
2372
+ | `QUICO_DEBUG_BBR=1` | One line per round-trip with congestion-control state: `BtlBw`, `RTprop`, `BDP`, `cwnd`, pacing rate. Cheap enough to leave on. |
2373
+ | `QUICO_TRACE_ACK=1` | One line per packet received and per ACK sent — enough to line up with a peer's log when it rejects an acknowledgement. |
2374
+
2375
+ ```bash
2376
+ QUICO_DEBUG_BBR=1 node server.js
2377
+ # [bbr] round=12 probe_bw BtlBw=9.84Mbps RTprop=16ms BDP=19671B → cwnd=24589B pace=9.84Mbps
2378
+ ```
2379
+
2380
+ ### Decrypting traffic in Wireshark
2381
+
2382
+ QUICO emits TLS secrets in NSS keylog format, so you can read your own encrypted
2383
+ QUIC traffic:
2384
+
2385
+ ```js
2386
+ import fs from 'node:fs';
2387
+
2388
+ const out = fs.createWriteStream('/tmp/keys.log', { flags: 'a' });
2389
+ quic.on('keylog', (line) => out.write(line)); // low-level QUICConnection
2390
+ ```
2391
+
2392
+ Then in Wireshark, set *Preferences → Protocols → TLS → (Pre)-Master-Secret log
2393
+ filename* to that file — or from the command line:
2394
+
2395
+ ```bash
2396
+ tshark -r capture.pcap -o tls.keylog_file:/tmp/keys.log -Y quic
2397
+ ```
2398
+
2399
+ ---
267
2400
 
268
2401
  ## 🧪 Testing
269
2402
 
270
- QUIC requires TLS 1.3. Self-signed RSA certificates usually fail with QUIC clients and browsers. For local development, [mkcert](https://github.com/FiloSottile/mkcert) is the easiest option — it generates locally-trusted ECDSA certificates automatically.
2403
+ QUIC requires TLS 1.3. Self-signed RSA certificates are often rejected by QUIC clients
2404
+ and browsers; [mkcert](https://github.com/FiloSottile/mkcert) is the easiest way to get
2405
+ locally-trusted ECDSA certificates.
271
2406
 
272
- This project supports ALPN `"h3"` only (not draft variants like `h3-29`). You must explicitly force h3 when testing with Chrome.
2407
+ QUICO supports ALPN `"h3"` only — not draft variants such as `h3-29`. Chrome must be
2408
+ told explicitly to use QUIC against a local server:
273
2409
 
274
- **Chrome:**
2410
+ **Chrome**
275
2411
  ```bash
276
- chrome --enable-quic --quic-version=h3 --ignore-certificate-errors --origin-to-force-quic-on=localhost:4433
2412
+ chrome --enable-quic --quic-version=h3 --ignore-certificate-errors \
2413
+ --origin-to-force-quic-on=localhost:4433
277
2414
  ```
278
2415
 
279
- **curl:**
2416
+ **curl** (needs an HTTP/3-enabled build)
280
2417
  ```bash
281
2418
  curl --http3 https://localhost:4433 --insecure
282
2419
  ```
283
2420
 
284
- **Integration tests:**
2421
+ **Test suites**
285
2422
  ```bash
286
- node examples/test_integration.js # HTTP/3 client + server — 19 tests
287
- node examples/test_wt_server.js # WebTransport server echo (QUICO ↔ QUICO)
288
- node examples/test_webtransport.js URL # WebTransport client against any server
2423
+ node examples/test_integration.js # HTTP/3 client + server — 19 tests
2424
+ node examples/test_wt_server.js # WebTransport echo (QUICO ↔ QUICO)
2425
+ node examples/test_webtransport.js URL # WebTransport client against any server
289
2426
  ```
290
2427
 
2428
+ **Interop runner** — see [`interop/`](./interop) for the Docker endpoint used with the
2429
+ [QUIC Interop Runner](https://github.com/quic-interop/quic-interop-runner).
2430
+
2431
+ ---
291
2432
 
292
2433
  ## 📁 Project Structure
293
2434
 
294
2435
  ```
295
2436
  quico/
296
2437
  ├── index.js — Public API exports
2438
+ ├── interop/ — QUIC Interop Runner endpoint (Dockerfile + shim)
2439
+ ├── examples/ — Runnable examples and test suites
297
2440
  └── src/
298
- ├── server.js — Unified server (drop-in for node:https)
2441
+ ├── server.js — Unified server: HTTP/3 + HTTP/2 + HTTP/1.1 (drop-in for node:https)
2442
+ ├── server_stats.js — The server's counters (server.getStats())
299
2443
  ├── client.js — Unified client with H3 → H2 → H1 fallback
300
- ├── agent.js — Connection pooling and Alt-Svc protocol cache
2444
+ ├── agent.js — Connection pooling, coalescing, Alt-Svc cache
301
2445
  ├── streams.js — IncomingMessage, ServerResponse, ClientRequest
2446
+ ├── http_common.js — Shared header and message helpers
2447
+ │
302
2448
  ├── h3.js — HTTP/3 framing, QPACK, WebTransport detection
303
2449
  ├── h3_server.js — HTTP/3 + WebTransport server
304
- ├── h3_client.js — HTTP/3 client (DNS, UDP, QUIC, H3 pipeline)
305
- ├── quic_connection.js — QUIC state machine, burst scheduler, flow control
2450
+ ├── h3_client.js — HTTP/3 client
2451
+ ├── qpack.js — QPACK encoder and decoder tables
2452
+ ├── quic_version.js — QUIC versions: v1 and v2 (RFC 9369), one profile each
2453
+ ├── webtransport.js — WebTransport client
2454
+ ├── wt_stream.js — WebTransport streams (both sides)
2455
+ ├── connect_udp.js — CONNECT-UDP proxy (RFC 9298): templates, capsules, the relay
2456
+ ├── connect_udp_client.js — quico.connectUdp(): CONNECT-UDP's client
2457
+ │
2458
+ ├── h2.js — HTTP/2 connection: frames, streams, flow control
2459
+ ├── h2_frames.js — HTTP/2 frame encoding/decoding
2460
+ ├── h2_server.js — HTTP/2 server
2461
+ ├── h2_client.js — HTTP/2 client and session pool
2462
+ ├── hpack.js — HPACK
2463
+ ├── hpack_primitives.js — Prefixed integers, string literals, Huffman (shared by HPACK and QPACK)
2464
+ │
2465
+ ├── h1.js — HTTP/1.1 parser and serializer
2466
+ ├── h1_server.js — HTTP/1.1 server
2467
+ ├── h1_client.js — HTTP/1.1 client and socket pool
2468
+ ├── tcp_listener.js — TCP accept, TLS, ALPN dispatch and sniffing
2469
+ │
2470
+ ├── ws.js — WebSocket framing, and the WHATWG and ws-style event surfaces
2471
+ ├── ws_server.js — WebSocketServer, upgradeWebSocket
2472
+ ├── ws_client.js — WebSocket client
2473
+ │
2474
+ ├── ja4h.js — JA4H request fingerprint
2475
+ ├── h2_fingerprint.js — HTTP/2 and HTTP/3 fingerprints
2476
+ ├── client_profile.js — profileRequest()
2477
+ │
2478
+ ├── quic_server.js — UDP listener, connection routing, Retry, stateless reset
2479
+ ├── quic_socket.js — Client-side UDP socket + connection bootstrap
2480
+ ├── quic_connection.js — QUIC state machine, loss detection, CC, flow control
306
2481
  ├── transport.js — Packet parsing, frame encoding/decoding
307
- ├── crypto.js — AEAD encryption, header protection, key derivation
2482
+ ├── crypto.js — AEAD, header protection, key derivation
308
2483
  ├── tls_bridge.js — LemonTLS integration, transport parameters
309
- └── webtransport.js — WebTransport client + stream classes
2484
+ └── utils.js — VarInt, binary helpers, debug flags
310
2485
  ```
311
2486
 
2487
+ ---
2488
+
2489
+ ## 🔐 Security
2490
+
2491
+ ### Post-quantum TLS
2492
+
2493
+ With Node 24.7+ (ML-KEM and ML-DSA in `node:crypto`, OpenSSL 3.5), on every version —
2494
+ HTTP/3, HTTP/2, HTTP/1.1 — and checked against OpenSSL 3.5 in both directions:
2495
+
2496
+ - **Key exchange** — the hybrids X25519MLKEM768, SecP256r1MLKEM768 and SecP384r1MLKEM1024
2497
+ (draft-ietf-tls-ecdhe-mlkem), and ML-KEM alone: MLKEM512, MLKEM768, MLKEM1024
2498
+ (draft-ietf-tls-mlkem; MLKEM1024 is CNSA 2.0's). A server takes any of them, post-quantum
2499
+ before classical: the client's first post-quantum group, by the client's order — a
2500
+ HelloRetryRequest for it when the client sent no key share for it (a browser sends one
2501
+ for X25519MLKEM768, its first: one round trip; a CNSA 2.0 client listing MLKEM1024 first
2502
+ gets MLKEM1024). The client
2503
+ offers X25519MLKEM768 by default, as `node:tls` and the browsers do; the others by
2504
+ `ecdhCurve`. Each costs 1–1.7 KB in a ClientHello, so they are not offered unasked.
2505
+ - **Authentication** — ML-DSA-44, -65 and -87 certificates (FIPS 204,
2506
+ draft-ietf-tls-mldsa), and chains signed with ML-DSA, verified and presented. A server
2507
+ can hold an ML-DSA and a classical certificate at once — `key` and `cert` arrays, as in
2508
+ `node:tls` — and presents the one the client's `signature_algorithms` ask for first:
2509
+ a client that puts ML-DSA first gets ML-DSA, a browser (which offers none) gets ECDSA or
2510
+ RSA. The client offers ML-DSA after the classical schemes (an ML-DSA chain is several
2511
+ KB more in every handshake); `sigalgs: 'mldsa65:…'` asks for it first.
2512
+
2513
+ ```js
2514
+ createServer({
2515
+ key: [fs.readFileSync('ecdsa.key'), fs.readFileSync('mldsa.key')],
2516
+ cert: [fs.readFileSync('ecdsa.pem'), fs.readFileSync('mldsa.pem')], // in any order
2517
+ minVersion: 'TLSv1.3', // TLS 1.2 has no post-quantum key exchange
2518
+ }, app);
2519
+ ```
2520
+ - **What was negotiated** — `socket.getNegotiationResult()`: `groupName`
2521
+ (`'MLKEM1024'`, …) and `signatureAlgorithmName` (`'mldsa65'`, …).
2522
+ - **TLS 1.2** has no post-quantum key exchange; a server that still accepts it is open to
2523
+ a client pushed onto it. `minVersion: 'TLSv1.3'` closes it (CNSA 2.0 admits TLS 1.3
2524
+ alone). The default stays `node:tls`'s, TLS 1.2 and up; TLS 1.3's downgrade sentinel
2525
+ (RFC 8446 §4.1.3) is sent and checked either way.
2526
+ - **The cipher suite** is the client's choice among ours, as in `node:tls` — AES-256 for a
2527
+ client that asks for it first; `honorCipherOrder: true` for the server's.
2528
+ - An **empty `key_share`** (RFC 8446 §4.2.8 — the client asks the server to choose; how
2529
+ scanners enumerate a server's groups) is answered with a HelloRetryRequest.
2530
+
2531
+ QUICO parses everything a peer sends, so every buffer a peer can make it hold has a
2532
+ bound — and when a peer breaks the rules, the connection (or the stream) is closed
2533
+ with the error the RFC names, not left to grow.
2534
+
2535
+ - **Stream limits are enforced** before any state is allocated: a stream ID beyond the
2536
+ advertised `MAX_STREAMS` is `STREAM_LIMIT_ERROR`; a frame for a stream that cannot
2537
+ exist is `STREAM_STATE_ERROR`; a closed stream cannot be reopened.
2538
+ - **Every way a stream ends** — FIN, RESET_STREAM, STOP_SENDING, a WebTransport
2539
+ session closing, the connection closing — goes through one release path per layer,
2540
+ so nothing a stream allocated outlives it.
2541
+ - **Reassembly is bounded**: gaps per stream are capped, and out-of-order data costs
2542
+ linear, not quadratic, work.
2543
+ - **The handshake's CRYPTO data** is held to 64 KB past what was read and 128 pieces
2544
+ ahead of a gap (`CRYPTO_BUFFER_EXCEEDED`, RFC 9000 §7.5), each byte copied once; pieces
2545
+ sent again in other boundaries, overlapping, join as they should. A ClientHello split
2546
+ over several Initial packets — a post-quantum one is — is joined the same way. Over TCP,
2547
+ a handshake message declaring more than 128 KB is refused on sight (`illegal_parameter`),
2548
+ before its bytes are kept.
2549
+ - **Transport parameters are checked** before any is used (RFC 9000 §7.4, §18.2): out of
2550
+ range (`ack_delay_exponent` above 20, `max_ack_delay` of 2^14 or more,
2551
+ `active_connection_id_limit` below 2, `max_udp_payload_size` below 1200, a stream
2552
+ count above 2^60), malformed (truncated, an integer that does not fill its value, a
2553
+ connection ID over 20 bytes, a reset token not 16 bytes), sent twice, or — from a client
2554
+ — one only a server sends: `TRANSPORT_PARAMETER_ERROR`, on both sides.
2555
+ - **QUIC frames**: an unknown frame type, or a frame cut short, is
2556
+ `FRAME_ENCODING_ERROR`; a packet with no frames, a frame its packet type may not
2557
+ carry, or a DATAGRAM larger than we allowed, `PROTOCOL_VIOLATION` (§12.4, RFC 9221 §3).
2558
+ - **Connection IDs are bounded**: a peer's retired IDs are not kept, the
2559
+ `RETIRE_CONNECTION_ID`s it has not acknowledged are capped at twice our
2560
+ `active_connection_id_limit` (`CONNECTION_ID_LIMIT_ERROR`, §5.1.2), as are its active IDs; a
2561
+ server issues at most 32 IDs per connection, and every route to a connection goes with it.
2562
+ - **HTTP/3 and QPACK buffers are bounded**: a HEADERS frame larger than the field
2563
+ section size we advertise is refused before it is buffered; unknown frames are
2564
+ skipped as they arrive; a QPACK capacity or literal larger than we advertised is
2565
+ `QPACK_ENCODER_STREAM_ERROR`; bytes already parsed are dropped, not re-scanned.
2566
+ - **0-RTT is off by default**, and on, held to one use per ticket, a freshness window,
2567
+ the same transport parameters, and safe requests only — see [0-RTT](#0-rtt-early-data).
2568
+ - **HTTP/3 framing rules** are enforced: DATA before HEADERS is
2569
+ `H3_FRAME_UNEXPECTED`, a request stream without HEADERS is `H3_REQUEST_INCOMPLETE`;
2570
+ a control-stream frame on a request stream, or one of HTTP/2's reserved frame types
2571
+ anywhere, is `H3_FRAME_UNEXPECTED`; a payload that is not exactly its fields,
2572
+ `H3_FRAME_ERROR`.
2573
+ - **HTTP/3's direction rules** (RFC 9114 §4.6, §5.2, §7.2): neither side takes part in
2574
+ server push, and each holds the other to that — at the server, `PUSH_PROMISE` is
2575
+ `H3_FRAME_UNEXPECTED`, a push stream `H3_STREAM_CREATION_ERROR`, `CANCEL_PUSH`
2576
+ `H3_ID_ERROR`; at the client, `MAX_PUSH_ID` is `H3_FRAME_UNEXPECTED`, a push stream,
2577
+ `PUSH_PROMISE` or `CANCEL_PUSH` `H3_ID_ERROR`. `MAX_PUSH_ID` that goes down, `GOAWAY`
2578
+ that goes up, or a server's `GOAWAY` naming anything but a request stream:
2579
+ `H3_ID_ERROR`. `SETTINGS` with one of HTTP/2's identifiers, one twice, or
2580
+ `SETTINGS_H3_DATAGRAM` / `SETTINGS_ENABLE_CONNECT_PROTOCOL` other than 0 or 1:
2581
+ `H3_SETTINGS_ERROR`.
2582
+ - **HTTP/1.1 line endings**: a request must end its lines with CRLF — a bare LF is `400`,
2583
+ since a server that took one where a hop in front did not would read another message
2584
+ (request smuggling). A response may end them with LF alone, as RFC 9112 §2.2 allows and
2585
+ browsers and curl accept: the client is its last reader, with no one behind it to
2586
+ disagree. A bare CR is refused either way.
2587
+ - **Key shares** (RFC 8446 §4.2.8): one of the wrong length, an ML-KEM key that is not
2588
+ one, a share for a group the client did not list, two for one group, or `key_share`
2589
+ without `supported_groups` — a fatal alert, never a handshake in a group the client did
2590
+ not agree to.
2591
+ - **Our own failures are ours**: an exception inside the HTTP/3 code closes with
2592
+ `H3_INTERNAL_ERROR`, not a code that blames the peer; one inside the QUIC packet path
2593
+ drops that packet and is counted (`quic.context.internal_errors`).
2594
+ - **Fuzzed**: every parser in front of a peer's bytes — QUIC frames, transport
2595
+ parameters, packet headers, HTTP/1.1, WebSocket, HPACK and HTTP/2 connections, QPACK,
2596
+ capsules — and HTTP/3 and QUIC frames on live connections, with mutated valid input and
2597
+ noise; none ends in an exception of its own, a hang, or an internal-error close.
2598
+ - **Closing says so**: `server.close()` sends every connection its `CONNECTION_CLOSE`
2599
+ and closes the socket only once those have left, so clients learn at once rather than
2600
+ by their idle timeout.
2601
+
2602
+ To report a vulnerability, please see [SECURITY.md](./SECURITY.md) — or write to
2603
+ **support@quicojs.dev** — rather than opening a public issue.
2604
+
2605
+ ---
2606
+
2607
+ ## ⚠️ Known Limitations
2608
+
2609
+ Being explicit about what is **not** implemented yet:
2610
+
2611
+ | Area | Status |
2612
+ |---|---|
2613
+ | **0-RTT** | HTTP/3, HTTP/2 and HTTP/1.1 (TLS 1.3); not DTLS. The client sends early only `GET`, `HEAD` and `OPTIONS` requests. Over HTTP/3, what it sends early assumes the default SETTINGS (no QPACK dynamic table), not the ones it was given last time — the safe choice, at the cost of a few header bytes. |
2614
+ | **ECH** | Server and client (see [Encrypted Client Hello](#encrypted-client-hello-ech)). The client takes the key list from the application — it does not resolve HTTPS records itself. TLS only, not DTLS. |
2615
+ | **Client-initiated migration** | The server takes a client that moves; the QUICO client itself has no API to move to another local address. |
2616
+ | **ECN** | Not implemented — Node's `dgram` does not expose the required socket options. |
2617
+ | **Path MTU discovery** | DPLPMTUD up to 1452-byte datagrams (see [Path MTU discovery](#path-mtu-discovery)). Its probes rely on the Don't Fragment bit, which Node's `dgram` cannot set: Linux sets it on UDP by default, Windows does not — there a probe can cross fragmented and be taken for a fit. |
2618
+ | **Request bodies (`quico.request`)** | Streamed; only the first 64 KB are kept for sending again, so a larger body that started over one protocol cannot move to another. |
2619
+ | **Server push** | Not implemented, on either side: the server sends no `PUSH_PROMISE`, the client allows none (it sends no `MAX_PUSH_ID`). Browsers have dropped it too. |
2620
+ | **Post-quantum TLS** | Needs ML-KEM and ML-DSA in `node:crypto` (Node 24.7+, OpenSSL 3.5). Before that, classical only — `node:tls` there offers the hybrid through OpenSSL, which lemon-tls cannot reach. The hybrid ClientHello is ~1.4 KB: two QUIC Initial packets rather than one. Public CAs do not issue ML-DSA certificates yet. |
2621
+ | **WebSocket** | No permessage-deflate. The client connects over HTTP/1.1 only. |
2622
+ | **CONNECT-UDP** | Context ID 0 only (UDP payloads) — no CONNECT-IP, no extensions that register contexts. The client opens a connection per socket (no pooling of tunnels on one connection). |
2623
+ | **Other transport parameters** | `max_ack_delay` and the rest are compiled in (see [Configuration](#-configuration--tuning)); the windows, stream limits, idle timeout and `disableActiveMigration` can be set. |
2624
+
2625
+ Performance has not been formally benchmarked. QUICO is pure JavaScript; expect it to
2626
+ be slower than native implementations, especially for bulk transfer.
2627
+
2628
+ ---
312
2629
 
313
2630
  ## 🛣 Roadmap
314
2631
 
315
2632
  ### ✅ Done
316
2633
  - QUIC v1 transport (RFC 9000) — Initial, Handshake, 1-RTT
317
2634
  - TLS 1.3 via LemonTLS — X25519, P-256, P-384, AES-128/256-GCM
2635
+ - Version Negotiation, HelloRetryRequest
2636
+ - Key Update — bidirectional key phase rotation (RFC 9001 §6)
2637
+ - Loss detection, PTO with exponential backoff (RFC 9002)
2638
+ - BBR-style congestion control with pacing
2639
+ - Bidirectional flow control with sliding windows
2640
+ - Stream limits enforced in both directions, raised with `MAX_STREAMS`
2641
+ - Delayed and batched ACKs, piggybacked on outgoing packets (RFC 9000 §13.2)
2642
+ - Retry / address validation and the anti-amplification limit
2643
+ - NAT rebinding with path validation
2644
+ - Stateless reset
2645
+ - Session resumption, server and client
2646
+ - 0-RTT, server and client, over QUIC (RFC 9001 §4.6) and TLS 1.3 on TCP (RFC 8446 §4.2.10), with RFC 8470's 425; off by default
318
2647
  - HTTP/3 server and client (RFC 9114)
319
- - QPACK header compression with static and dynamic tables (RFC 9204)
320
- - WebTransport client and server — bidi/uni streams + datagrams (RFC 9297)
321
- - Node.js `https`-style API compatibility — `createServer`, `request`, `get`
322
- - Express / Fastify / Koa middleware support
323
- - Connection reuse and multiplexing
324
- - HelloRetryRequest — client and server
325
- - Key updates (key phase rotation)
326
- - Interop with Google, Cloudflare, Facebook, Microsoft, nginx
327
- - Handshake timeout
328
-
329
- ### 🔄 In Progress
330
- - Loss detection and PTO timers (RFC 9002)
331
- - Congestion control (BBR / CUBIC)
332
- - 0-RTT and session resumption
333
- - Debug log cleanup (`QUICO_DEBUG` environment flag)
2648
+ - QPACK with static and dynamic tables (RFC 9204)
2649
+ - HTTP/2 and HTTP/1.1, implemented in QUICO — one stack for all three versions
2650
+ - WebTransport client and server — streams + datagrams (RFC 9297)
2651
+ - WebSocket over HTTP/1.1, HTTP/2 (RFC 8441) and HTTP/3 (RFC 9220)
2652
+ - Unreliable datagrams (RFC 9221)
2653
+ - CONNECT-UDP proxy and client (RFC 9298)
2654
+ - Stream priorities (RFC 9218) for HTTP/2 and HTTP/3, and WebTransport's `sendOrder` / `sendGroup`
2655
+ - GOAWAY, 103 Early Hints
2656
+ - JA4H, HTTP/2 and HTTP/3 fingerprints, `profileRequest()`
2657
+ - `node:https`-style API — `createServer`, `request`, `get`, `Agent`
2658
+ - Express / Fastify / Koa support
2659
+ - Connection pooling, coalescing and multiplexing
2660
+ - TLS keylog export
2661
+ - **Interop: 6/6 implementations green** (handshake, transfer, http3, both directions)
334
2662
 
335
2663
  ### ⏳ Planned
336
- - Connection migration (PATH_CHALLENGE / PATH_RESPONSE)
337
- - ChaCha20-Poly1305 cipher suite (0x1303)
338
- - GOAWAY and graceful shutdown
339
- - Stream priority (RFC 9218)
340
- - TypeScript type definitions
2664
+ - ChaCha20-Poly1305 (0x1303)
2665
+ - Backpressure from a slow application reader into QUIC flow control
2666
+ - TypeScript type definitions, kept in step with the API
341
2667
  - Performance benchmarks
342
2668
  - Fuzz testing
343
2669
 
344
2670
  _Community contributions are welcome! Please ⭐ star the repo to follow progress._
345
2671
 
2672
+ ---
346
2673
 
347
- ## 🙏 Sponsors
2674
+ ## 🤝 Contributing
348
2675
 
349
- QUICO is an evenings-and-weekends project.
350
- Support development via **GitHub Sponsors** or simply share the project.
2676
+ Contributions are very welcome — bug reports, reproductions, and PRs alike.
351
2677
 
2678
+ Useful things to know before you start:
352
2679
 
2680
+ - Run `node examples/test_integration.js` before and after your change (19 tests).
2681
+ - `QUICO_DEBUG=1` gives a full packet trace; `QUICO_DEBUG_BBR=1` gives a congestion
2682
+ control timeline. Include the relevant excerpt in bug reports.
2683
+ - If you can capture a `.pcap` plus a keylog file, that makes protocol bugs enormously
2684
+ easier to diagnose — see [Debugging](#-debugging).
2685
+ - For interop-level changes, the [`interop/`](./interop) directory contains the Docker
2686
+ endpoint used with the QUIC Interop Runner.
2687
+
2688
+ ---
2689
+
2690
+ ## 🙏 Sponsors
2691
+
2692
+ QUICO is an evenings-and-weekends project.
2693
+ Support development via **GitHub Sponsors** — or simply share the project.
2694
+
2695
+ ---
353
2696
 
354
2697
  ## 💬 Contact
355
2698
 
356
- For feedback, ideas, or contributions,
357
- contact directly at:
2699
+ For feedback, ideas, or contributions:
358
2700
  📧 **support@quicojs.dev**
359
2701
 
360
2702
  For security-related issues, please see [SECURITY.md](./SECURITY.md).
361
2703
 
362
-
2704
+ ---
363
2705
 
364
2706
  ## 📜 License
365
2707
 
@@ -379,4 +2721,4 @@ distributed under the License is distributed on an "AS IS" BASIS,
379
2721
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
380
2722
  See the License for the specific language governing permissions and
381
2723
  limitations under the License.
382
- ```
2724
+ ```