h2lean 0.0.0-stage → 0.1.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/LICENSE +201 -0
- package/README.md +265 -2
- package/index.js +72 -0
- package/lib/client-session.js +2068 -0
- package/lib/client-stream.js +166 -0
- package/lib/client.js +85 -0
- package/lib/compat.js +849 -0
- package/lib/fast-timer.js +436 -0
- package/lib/frames.js +127 -0
- package/lib/headers.js +463 -0
- package/lib/hpack-data.js +333 -0
- package/lib/hpack.js +1288 -0
- package/lib/pieces.js +134 -0
- package/lib/server.js +272 -0
- package/lib/session.js +2698 -0
- package/lib/stream.js +519 -0
- package/package.json +49 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,3 +1,266 @@
|
|
|
1
|
-
|
|
1
|
+
<div align="center">
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
<img src="assets/banner.svg" alt="h2lite banner" width="720">
|
|
4
|
+
|
|
5
|
+
### The pure-JavaScript HTTP/2 stack for Node.js
|
|
6
|
+
|
|
7
|
+
**Drop-in replacement for `node:http2` — without the nghttp2 C layer.**
|
|
8
|
+
|
|
9
|
+
[](https://www.npmjs.com/package/h2lite)
|
|
10
|
+
[](https://nodejs.org)
|
|
11
|
+
[](package.json)
|
|
12
|
+
[](LICENSE)
|
|
13
|
+
|
|
14
|
+
Up to **8× less CPU per request** and **6.8× more requests per second** than `node:http2` — measured, paired, and reproducible. Outperforms even uWebSockets (C++) at header-bound HTTP/2 workloads.
|
|
15
|
+
|
|
16
|
+
</div>
|
|
17
|
+
|
|
18
|
+
---
|
|
19
|
+
|
|
20
|
+
## 📑 Table of Contents
|
|
21
|
+
|
|
22
|
+
- ⚡ [Why h2lite?](#-why-h2lite)
|
|
23
|
+
- 🏎️ [Performance](#️-performance)
|
|
24
|
+
- 🔌 [Compatibility — Drop-in Replacement](#-compatibility--drop-in-replacement)
|
|
25
|
+
- 📦 [Installation](#-installation)
|
|
26
|
+
- 🚀 [Getting Started](#-getting-started)
|
|
27
|
+
- [Server — the `(req, res)` API](#server--the-req-res-api)
|
|
28
|
+
- [Server — the raw `Http2Stream` API](#server--the-raw-http2stream-api)
|
|
29
|
+
- [Secure server (h2s / TLS)](#secure-server-h2s--tls)
|
|
30
|
+
- [Client — `connect()`](#client--connect)
|
|
31
|
+
- [Fastify and other frameworks](#fastify-and-other-frameworks)
|
|
32
|
+
- [Monkey-patching for frameworks without injection](#monkey-patching-for-frameworks-without-injection)
|
|
33
|
+
- 🛠️ [Advanced Tuning](#️-advanced-tuning)
|
|
34
|
+
- 🔒 [Security](#-security)
|
|
35
|
+
- ⚠️ [Not Implemented — Said Loudly](#️-not-implemented--said-loudly)
|
|
36
|
+
- 📚 [Documentation](#-documentation)
|
|
37
|
+
- 🤝 [Contributing](#-contributing)
|
|
38
|
+
- ⚖️ [License](#️-license)
|
|
39
|
+
|
|
40
|
+
## ⚡ Why h2lite?
|
|
41
|
+
|
|
42
|
+
Node's native `node:http2` (stable since v10.10.0) has a fundamental architectural constraint: every HTTP/2 frame crosses the JS ↔ C++ boundary between V8 and bundled nghttp2. Frame dispatch, HPACK encoding/decoding, and flow-control bookkeeping all pay for that crossing — on every single frame of every single request.
|
|
43
|
+
|
|
44
|
+
**h2lite removes the crossing entirely.** The entire protocol — frame parsing, HPACK (RFC 7541), flow control, connection state machines — lives in pure JavaScript, tuned item by item against measured data ([OPTIMIZATION.md](./OPTIMIZATION.md), 35 numbered techniques). Zero native code, zero runtime dependencies.
|
|
45
|
+
|
|
46
|
+
The result is a library that keeps `node:http2`'s exact public surface while spending dramatically less CPU per request. Perfect for:
|
|
47
|
+
|
|
48
|
+
- 🧩 **Microservices** — header-heavy service-to-service traffic is where the gap is widest
|
|
49
|
+
- 📡 **gRPC servers** — many small streams, all header-bound
|
|
50
|
+
- 🤖 **AI backends** — long-lived streams, high connection counts, every CPU cycle matters
|
|
51
|
+
- 🔁 **Behind a reverse proxy** — pair h2lite with an HTTP/2-terminating edge and stop paying for HTTP/1.1
|
|
52
|
+
|
|
53
|
+
## 🏎️ Performance
|
|
54
|
+
|
|
55
|
+
Every number below is `node`'s own per-request CPU time (μs/req, read inside the process — the metric that travels) or requests per second, measured with [h2load](https://nghttp2.org/documentation/h2load.1.html) against six honest responder arms on the same machine in the same session. Full methodology, caveats and re-run instructions: **[PERFORMANCE.md](./PERFORMANCE.md)**.
|
|
56
|
+
|
|
57
|
+
**Server, headers-only workload** (the workload HTTP/2 exists for):
|
|
58
|
+
|
|
59
|
+
| Server | μs/req | req/s | CPU vs `node:http2` |
|
|
60
|
+
|---|--:|--:|--:|
|
|
61
|
+
| node:http (HTTP/1.1) | 9.11 | 111,816 | 1.21× |
|
|
62
|
+
| uWebSockets C++ (HTTP/1.1) | 4.87 | 203,283 | 2.27× |
|
|
63
|
+
| node:http2 (stream API) | 7.30 | 171,835 | 1.52× |
|
|
64
|
+
| **h2lite (stream API)** | **1.38** | **765,149** | **8.01×** |
|
|
65
|
+
| **h2lite (compat API)** | **2.85** | **367,275** | **3.88×** |
|
|
66
|
+
|
|
67
|
+
**Server, with response body:** 16 kB — **2.50× less CPU** than `node:http2` ([PERFORMANCE.md](./PERFORMANCE.md)). 256 kB — parity, as expected: the work is body-bound, and h2lite does not win by cutting corners.
|
|
68
|
+
|
|
69
|
+
**Client, same-server paired measurement** (`h2lite.connect()` vs `node:http2.connect()`, driven against nghttpd):
|
|
70
|
+
|
|
71
|
+
| Workload | node client μs/req | h2lite client μs/req | Advantage |
|
|
72
|
+
|---|--:|--:|---|
|
|
73
|
+
| Headers only | 12.08 | **3.61** | 3.35× |
|
|
74
|
+
| 16 kB | 19.66 | **11.73** | 1.68× |
|
|
75
|
+
| 256 kB | 148.70 | 134.24 | within noise |
|
|
76
|
+
|
|
77
|
+
> 💡 **Re-measure before quoting.** The project's own rule: an unpaired before/after run cannot separate a change from noise. Both benchmark matrices re-run with one command (`npm run bench:showcase`, `npm run bench:client`) — [bench/](./bench) has the arms, [CONTRIBUTING.md](./CONTRIBUTING.md) §3 has the method.
|
|
78
|
+
|
|
79
|
+
## 🔌 Compatibility — Drop-in Replacement
|
|
80
|
+
|
|
81
|
+
Compatibility target is the **public surface** of `node:http2`: names, argument shapes, event orders, wire-visible frame sequences, `rstCode`/`goawayCode` numbers — verified differentially. The test suite runs the **same application scripts** against both `node:http2` and h2lite and compares the transcripts ([test/diff-harness.js](./test/diff-harness.js)); [h2spec](https://github.com/summerwind/h2spec) conformance is 146/146 — the same verdict node's own HTTP/2 receives.
|
|
82
|
+
|
|
83
|
+
```diff
|
|
84
|
+
- const http2 = require('node:http2');
|
|
85
|
+
+ const http2 = require('h2lite');
|
|
86
|
+
|
|
87
|
+
const server = http2.createServer((req, res) => {
|
|
88
|
+
res.end('hello world');
|
|
89
|
+
});
|
|
90
|
+
server.listen(8080);
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
Same class names (`Http2Session`, `Http2Stream`, `Http2ServerRequest`, `Http2ServerResponse`), same event names, same `Http2Session` and settings semantics, all 240 protocol constants re-exported from `node:http2` itself — user code that compares `error.code !== http2.constants.NGHTTP2_ENHANCE_YOUR_CALM` keeps working unchanged. Both transports on both sides: `createServer` (h2c), `createSecureServer` (h2s), `connect()` over cleartext and TLS with node's ALPN rules.
|
|
94
|
+
|
|
95
|
+
Where behavior deliberately differs from node, it is **documented, measured, and pinned by tests** — never silent. Known divergences: [CONTRIBUTING.md](./CONTRIBUTING.md) §5.
|
|
96
|
+
|
|
97
|
+
## 📦 Installation
|
|
98
|
+
|
|
99
|
+
```bash
|
|
100
|
+
npm install h2lite
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
Requires Node.js **≥ 20** (verified against v26.12.1). Zero runtime dependencies — `lib/` imports nothing but `node:` builtins.
|
|
104
|
+
|
|
105
|
+
## 🚀 Getting Started
|
|
106
|
+
|
|
107
|
+
### Server — the `(req, res)` API
|
|
108
|
+
|
|
109
|
+
The compat API feels like HTTP/1.1 but speaks HTTP/2 — this is what replaces `node:http2` in an existing application:
|
|
110
|
+
|
|
111
|
+
```javascript
|
|
112
|
+
const http2 = require('h2lite');
|
|
113
|
+
|
|
114
|
+
const server = http2.createServer((req, res) => {
|
|
115
|
+
// req is an Http2ServerRequest, res is an Http2ServerResponse
|
|
116
|
+
res.writeHead(200, { 'content-type': 'text/plain' });
|
|
117
|
+
res.end('hello from h2lite');
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
server.listen(8080);
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
### Server — the raw `Http2Stream` API
|
|
124
|
+
|
|
125
|
+
Maximum throughput: skip the compat objects entirely and work with streams and header maps:
|
|
126
|
+
|
|
127
|
+
```javascript
|
|
128
|
+
const http2 = require('h2lite');
|
|
129
|
+
|
|
130
|
+
const server = http2.createServer();
|
|
131
|
+
|
|
132
|
+
server.on('stream', (stream, headers) => {
|
|
133
|
+
stream.respond({ ':status': 200, 'content-type': 'text/plain' });
|
|
134
|
+
stream.end('hello from the stream API');
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
server.listen(8081);
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
### Secure server (h2s / TLS)
|
|
141
|
+
|
|
142
|
+
```javascript
|
|
143
|
+
const http2 = require('h2lite');
|
|
144
|
+
|
|
145
|
+
const server = http2.createSecureServer({
|
|
146
|
+
key: require('fs').readFileSync('key.pem'),
|
|
147
|
+
cert: require('fs').readFileSync('cert.pem')
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
server.on('stream', (stream, headers) => {
|
|
151
|
+
stream.respond({ ':status': 200 });
|
|
152
|
+
stream.end('secure h2');
|
|
153
|
+
});
|
|
154
|
+
|
|
155
|
+
server.listen(8443);
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
TLS decisions stay delegated to `node:tls` — ALPN is pinned to `h2` exactly the way node does it, and certificate handling is node's, not ours.
|
|
159
|
+
|
|
160
|
+
### Client — `connect()`
|
|
161
|
+
|
|
162
|
+
```javascript
|
|
163
|
+
const http2 = require('h2lite');
|
|
164
|
+
|
|
165
|
+
const session = http2.connect('http://localhost:8080');
|
|
166
|
+
|
|
167
|
+
const req = session.request({ ':path': '/', ':method': 'GET' });
|
|
168
|
+
req.on('response', (headers) => {
|
|
169
|
+
console.log('status:', headers[':status']);
|
|
170
|
+
});
|
|
171
|
+
req.setEncoding('utf8');
|
|
172
|
+
req.on('data', (chunk) => console.log(chunk));
|
|
173
|
+
req.on('end', () => session.close());
|
|
174
|
+
|
|
175
|
+
req.end();
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
Works over `https://…` too — the client speaks both h2c and h2s.
|
|
179
|
+
|
|
180
|
+
### Fastify and other frameworks
|
|
181
|
+
|
|
182
|
+
Any framework that lets you hand it a server instance takes h2lite in two lines. Fastify's [`serverFactory`](https://fastify.dev/docs/latest/Reference/Server/#serverfactory):
|
|
183
|
+
|
|
184
|
+
```javascript
|
|
185
|
+
const Fastify = require('fastify');
|
|
186
|
+
const h2lite = require('h2lite');
|
|
187
|
+
|
|
188
|
+
const fastify = Fastify({
|
|
189
|
+
http2: true,
|
|
190
|
+
serverFactory: (handler) => {
|
|
191
|
+
return h2lite.createServer((req, res) => handler(req, res));
|
|
192
|
+
}
|
|
193
|
+
});
|
|
194
|
+
|
|
195
|
+
fastify.get('/', async () => ({ hello: 'from h2lite under Fastify' }));
|
|
196
|
+
fastify.listen({ port: 8080 });
|
|
197
|
+
```
|
|
198
|
+
|
|
199
|
+
### Monkey-patching for frameworks without injection
|
|
200
|
+
|
|
201
|
+
If a framework requires `node:http2` internally and offers no injection point, patch the builtin's exports **before anything else loads** — every later `require('node:http2')` receives the same (mutated) module object:
|
|
202
|
+
|
|
203
|
+
```javascript
|
|
204
|
+
// patch.js — require this first: node -r ./patch.js app.js
|
|
205
|
+
const nodeHttp2 = require('node:http2');
|
|
206
|
+
const h2lite = require('h2lite');
|
|
207
|
+
|
|
208
|
+
nodeHttp2.createServer = h2lite.createServer;
|
|
209
|
+
nodeHttp2.createSecureServer = h2lite.createSecureServer;
|
|
210
|
+
nodeHttp2.connect = h2lite.connect;
|
|
211
|
+
```
|
|
212
|
+
|
|
213
|
+
## 🛠️ Advanced Tuning
|
|
214
|
+
|
|
215
|
+
- ♻️ **Freeze reusable header objects.** `Object.freeze()` on a header set enables h2lite's per-connection response-block cache — the HPACK bytes are encoded once and copied afterwards. Measured **~25% CPU saved** on a headers-only workload ([PERFORMANCE.md](./PERFORMANCE.md)):
|
|
216
|
+
|
|
217
|
+
```javascript
|
|
218
|
+
const HEADERS = Object.freeze({ ':status': 200, 'content-type': 'application/json' });
|
|
219
|
+
server.on('stream', (stream) => stream.respond(HEADERS));
|
|
220
|
+
```
|
|
221
|
+
|
|
222
|
+
- 📏 **Raise `initialWindowSize`** for high-throughput downloads (see the [settings object reference](https://nodejs.org/api/http2.html#settings-object)) — default flow-control windows are conservative and will throttle bulk transfer.
|
|
223
|
+
- 🌊 **Prefer more streams per connection over more connections.** HPACK state, one staging buffer and one dynamic table are per-connection: amortize them by multiplexing, not by fanning out sockets.
|
|
224
|
+
- 🔍 **Read the playbook.** [OPTIMIZATION.md](./OPTIMIZATION.md) documents 35 measured techniques — and the ones that were tried and rejected, so you don't re-invent them.
|
|
225
|
+
|
|
226
|
+
## 🔒 Security
|
|
227
|
+
|
|
228
|
+
h2lite terminates **untrusted bytes from the internet** and turns them into objects your application trusts — the threat model is treated as the primary design constraint ([SECURITY.md](./SECURITY.md)):
|
|
229
|
+
|
|
230
|
+
- 🛡️ **Every denial-of-service limit matches nghttp2** (the engine inside node) or was measured against a live node server — a peer's budget against node is its budget against h2lite: SETTINGS-entry cap (CVE-2020-11080), CONTINUATION cap (CVE-2024-28182), rapid-reset budget (CVE-2023-44487), outbound staging, parked-stream and history bounds.
|
|
231
|
+
- 🚫 **Request-smuggling defense by construction** (RFC 9113 §10.3): field names must be lower-case tokens, values may not carry NUL/CR/LF, connection-specific fields are refused in both directions — all refused at encode time, *before a single octet reaches the wire*. h2lite is stricter than node here, deliberately and measurably.
|
|
232
|
+
- ✅ **Verified, not assumed:**
|
|
233
|
+
- **300+ differential tests** — application scripts run against both `node:http2` and h2lite, transcripts compared;
|
|
234
|
+
- **h2spec 146/146** — full RFC 9113/7541 conformance, same verdict as node's own HTTP/2 (`npm run spec`);
|
|
235
|
+
- **mutation-tested guards** — every defensive limit is rewritten in place and proven to fail the suite ([tools/mutate-guards.js](./tools/mutate-guards.js)).
|
|
236
|
+
|
|
237
|
+
## ⚠️ Not Implemented — Said Loudly
|
|
238
|
+
|
|
239
|
+
Two APIs are absent, and both fail **loudly** with `ERR_H2LITE_NOT_IMPLEMENTED` — never a silent wrong answer:
|
|
240
|
+
|
|
241
|
+
- **Server push** — removed from browsers in 2022 and considered obsolete; the safer replacement is [Early Hints (103)](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/103).
|
|
242
|
+
- **`performServerHandshake`** — no known use case outside node's own tests.
|
|
243
|
+
|
|
244
|
+
## 📚 Documentation
|
|
245
|
+
|
|
246
|
+
| Document | What it holds |
|
|
247
|
+
|---|---|
|
|
248
|
+
| [PERFORMANCE.md](./PERFORMANCE.md) | 🏎️ Benchmarks: methodology, full tables, caveats, re-run commands |
|
|
249
|
+
| [SECURITY.md](./SECURITY.md) | 🔒 Threat model, every hardening limit, known gaps — stated plainly |
|
|
250
|
+
| [OPTIMIZATION.md](./OPTIMIZATION.md) | 🔬 All 35 measured optimization techniques (and rejected ones) |
|
|
251
|
+
| [CHANGELOG.md](./CHANGELOG.md) | 📋 Release history, Keep-a-Changelog format |
|
|
252
|
+
| [CONTRIBUTING.md](./CONTRIBUTING.md) | 🧪 Testing, benchmarking and commit rules for contributors |
|
|
253
|
+
|
|
254
|
+
## 🤝 Contributing
|
|
255
|
+
|
|
256
|
+
Contributions are welcome! The project holds itself to an unusual standard and expects the same from patches:
|
|
257
|
+
|
|
258
|
+
- **"node behaves this way" needs proof** — read from node's bundled source or measured off a live server, not recalled ([CONTRIBUTING.md](./CONTRIBUTING.md) §3).
|
|
259
|
+
- **"it's faster" needs a paired benchmark** — same session, same shape, ABBA-interleaved.
|
|
260
|
+
- `npm test` (300+ differential tests) and `npm run lint` must be green before a commit lands.
|
|
261
|
+
|
|
262
|
+
Good first contributions: fuzzing harness (start from [tools/probe-wire.js](./tools/probe-wire.js)), more differential scenarios in [test/](./test), documentation.
|
|
263
|
+
|
|
264
|
+
## ⚖️ License
|
|
265
|
+
|
|
266
|
+
[Apache-2.0](./LICENSE)
|
package/index.js
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
// h2lite -- a pure-JS HTTP/2 library with a node:http2-shaped API.
|
|
2
|
+
//
|
|
3
|
+
// Servers: h2c and h2s (prior-knowledge, ALPN 'h2'), the `stream` and compat
|
|
4
|
+
// (`request`) APIs. Client: `connect()` + `session.request()` over h2c and h2s
|
|
5
|
+
// (see lib/client.js); server push on the client stays notImplemented.
|
|
6
|
+
// Deliberately reused from node:http2, because re-typing them would only create
|
|
7
|
+
// drift: the 240 protocol constants and the `sensitiveHeaders` symbol. A peer
|
|
8
|
+
// must see the same rstCode/goawayCode numbers as with node, and user code
|
|
9
|
+
// compares against those names.
|
|
10
|
+
'use strict';
|
|
11
|
+
|
|
12
|
+
const nodeHttp2 = require('node:http2');
|
|
13
|
+
const { createServer, createSecureServer, Http2Server, Http2SecureServer,
|
|
14
|
+
Http2ServerRequest, Http2ServerResponse, notImplemented } = require('./lib/server');
|
|
15
|
+
const { Http2Session, OUR_DEFAULTS, PEER_DEFAULTS, SETTINGS_BY_ID, ID_BY_SETTING } = require('./lib/session');
|
|
16
|
+
const { DATA, HEADERS, PRIORITY, RST_STREAM, SETTINGS, PUSH_PROMISE, PING, GOAWAY,
|
|
17
|
+
WINDOW_UPDATE, CONTINUATION } = require('./lib/frames');
|
|
18
|
+
const { Decoder, Encoder, HPackError } = require('./lib/hpack');
|
|
19
|
+
const { connect } = require('./lib/client');
|
|
20
|
+
|
|
21
|
+
// The packed SETTINGS blob node's getPackedSettings produces: id/value pairs.
|
|
22
|
+
function getPackedSettings(settings) {
|
|
23
|
+
const names = Object.keys(settings).filter((k) => ID_BY_SETTING[k] !== undefined);
|
|
24
|
+
const body = Buffer.alloc(names.length * 6);
|
|
25
|
+
let n = 0;
|
|
26
|
+
for (const name of names) {
|
|
27
|
+
const value = typeof settings[name] === 'boolean' ? (settings[name] ? 1 : 0) : settings[name];
|
|
28
|
+
body.writeUInt16BE(ID_BY_SETTING[name], n);
|
|
29
|
+
body.writeUInt32BE(value >>> 0, n + 2);
|
|
30
|
+
n += 6;
|
|
31
|
+
}
|
|
32
|
+
return body;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function getUnpackedSettings(buf) {
|
|
36
|
+
const out = {};
|
|
37
|
+
if (!Buffer.isBuffer(buf)) throw new TypeError('a Buffer is required');
|
|
38
|
+
if (buf.length % 6 !== 0) {
|
|
39
|
+
const err = new Error('buffer length must be a multiple of 6');
|
|
40
|
+
err.code = 'ERR_HTTP2_INVALID_PACKED_SETTINGS_LENGTH';
|
|
41
|
+
throw err;
|
|
42
|
+
}
|
|
43
|
+
for (let i = 0; i + 6 <= buf.length; i += 6) {
|
|
44
|
+
const name = SETTINGS_BY_ID[buf.readUInt16BE(i)];
|
|
45
|
+
if (name === undefined) continue;
|
|
46
|
+
out[name] = buf.readUInt32BE(i + 2);
|
|
47
|
+
}
|
|
48
|
+
return out;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
module.exports = {
|
|
52
|
+
constants: nodeHttp2.constants,
|
|
53
|
+
sensitiveHeaders: nodeHttp2.sensitiveHeaders,
|
|
54
|
+
createServer,
|
|
55
|
+
createSecureServer,
|
|
56
|
+
connect,
|
|
57
|
+
performServerHandshake: () => { throw notImplemented('performServerHandshake'); },
|
|
58
|
+
getDefaultSettings: () => ({ ...OUR_DEFAULTS }),
|
|
59
|
+
getPackedSettings,
|
|
60
|
+
getUnpackedSettings,
|
|
61
|
+
Http2Server,
|
|
62
|
+
Http2SecureServer,
|
|
63
|
+
Http2Session,
|
|
64
|
+
// node exports exactly these two compat classes at the top level
|
|
65
|
+
Http2ServerRequest,
|
|
66
|
+
Http2ServerResponse,
|
|
67
|
+
// internal pieces, exported because tests and benchmarks reach for them
|
|
68
|
+
HPack: { Decoder, Encoder, HPackError },
|
|
69
|
+
FrameType: { DATA, HEADERS, PRIORITY, RST_STREAM, SETTINGS, PUSH_PROMISE, PING,
|
|
70
|
+
GOAWAY, WINDOW_UPDATE, CONTINUATION },
|
|
71
|
+
PeerDefaults: PEER_DEFAULTS,
|
|
72
|
+
};
|