h2lean 0.1.1 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/lib/server.js +180 -13
  2. package/package.json +2 -1
package/lib/server.js CHANGED
@@ -34,6 +34,24 @@
34
34
  // rounds on an idle machine, 26 of 40 and 29 of 30 in two loaded runs) while h2lean reports
35
35
  // the echo in every round of every run. test/event-order.test.js drops the echo outside its
36
36
  // 'goaway' scenario for that reason.
37
+ // * allowHTTP1 + http1Options (both createSecureServer options, per node's docs): when the
38
+ // fallback is live, node serves HTTP/1.1 from the SAME object -- _http_server's private
39
+ // storeHTTPOptions() writes the HTTP/1 options into private fields of the Http2SecureServer
40
+ // and http's _connectionListener is bound to it -- so one emitter and one listener list
41
+ // carry both protocols. Those symbols are not reachable from node:http, so the fallback
42
+ // here is an embedded http.Server that never listens, fed the sockets the ALPN verdict
43
+ // hands it, with a newListener/removeListener mirror (node's own setupCompat hook) carrying
44
+ // the application's request/upgrade/clientError/... listeners onto it and taking them
45
+ // back off. Two written-down consequences of that model: removeAllListeners fires neither
46
+ // hook, so listeners removed that way stay mirrored (node has no such seam at all, and
47
+ // there is no per-listener event to hook); the embedded server's own idle-connection
48
+ // bookkeeping never starts, because its
49
+ // 'listening' never fires, so the handed-off sockets are tracked here and close() shuts
50
+ // the idle keep-alive ones down while letting a response in flight finish (node waits
51
+ // through net.Server's own bookkeeping); and an unknownProtocol socket -- no ALPN, no
52
+ // allowHTTP1 -- is answered with node's 403 text instead of being destroyed silently,
53
+ // which is what node does (core.js connectionListener) and what this file used to claim
54
+ // wrong: no ALPN is not h2 prior knowledge, and it never became a session on node.
37
55
  'use strict';
38
56
 
39
57
  const net = require('node:net');
@@ -76,6 +94,21 @@ function initHttp2Server(server, options) {
76
94
  };
77
95
  server._sessions = new Set();
78
96
  server[kCompat] = null;
97
+ // node validates this as uint32 and defaults it to 10000 (initializeOptions, core.js);
98
+ // it bounds how long an unknown-protocol socket may sit after the 403 text.
99
+ if (opts.unknownProtocolTimeout !== undefined &&
100
+ (!Number.isInteger(opts.unknownProtocolTimeout) || opts.unknownProtocolTimeout < 0)) {
101
+ const err = new RangeError(`Invalid unknownProtocolTimeout: ${opts.unknownProtocolTimeout}`);
102
+ err.code = 'ERR_OUT_OF_RANGE';
103
+ throw err;
104
+ }
105
+ server._sessionOptions.unknownProtocolTimeout = opts.unknownProtocolTimeout ?? 10000;
106
+ // allowHTTP1 has nothing to negotiate over a plain socket (no ALPN, so the branch
107
+ // that would consume it is unreachable -- the same reason node's cleartext server
108
+ // ignores it), and http1Options is accepted here only so that the option bag a
109
+ // caller builds for node keeps working verbatim. The live HTTP/1 machinery is
110
+ // built, when allowHTTP1 is set, in initHttp1Fallback below.
111
+ server._http1 = null;
79
112
  }
80
113
 
81
114
  // Turns an accepted socket -- plain or already decrypted -- into a session.
@@ -132,7 +165,13 @@ function applyHttp2ServerApi(proto) {
132
165
  // followed by closeAllSessions(this) (internal/http2/core): the listening socket goes away
133
166
  // right away and its callback is net.Server's own. Waiting for the session set to empty first
134
167
  // was ours, and it made close(cb) a promise that a session which cannot drain never keeps --
135
- // 'close' then depended on every connection finishing.
168
+ // 'close' then depended on every connection finishing. When the HTTP/1 fallback is live,
169
+ // node also runs httpServerPreClose() (closeIdleConnections + the checker interval); the
170
+ // public-API equivalent here shuts the idle keep-alive sockets down and lets the active
171
+ // responses finish, see closeHttp1().
172
+ if (this._http1) {
173
+ closeHttp1(this);
174
+ }
136
175
  proto[kTransportClose].call(this, cb);
137
176
  for (const session of [...this._sessions]) {
138
177
  session.close();
@@ -204,28 +243,156 @@ class Http2Server extends net.Server {
204
243
  }
205
244
  }
206
245
 
207
- // node's h2s server insists on h2 and overwrites whatever ALPNProtocols the
208
- // application passed: a peer offering only http/1.1 is refused by the handshake
209
- // itself, with the TLS alert no_application_protocol, rather than after it. The
210
- // list is therefore fixed here too, and the ALPN check in secureConnection below
211
- // stays as the guard for contexts installed later through setSecureContext().
246
+ // node's h2s server fixes the ALPN list the way initializeTLSOptions (core.js) does:
247
+ // ['h2'] -- with 'http/1.1' added when allowHTTP1 asks for the fallback -- and an
248
+ // options.ALPNCallback keeps the application's list out of reach. A peer offering only
249
+ // http/1.1 without allowHTTP1 is therefore still refused by the handshake itself, with
250
+ // the TLS alert no_application_protocol, rather than after it. The ALPN check in
251
+ // secureConnection below stays as the guard for contexts installed later through
252
+ // setSecureContext().
212
253
  function alpnOptions(options) {
213
254
  const opts = { ...(options || {}) };
214
- opts.ALPNProtocols = ['h2'];
255
+ if (!opts.ALPNCallback) {
256
+ opts.ALPNProtocols = ['h2'];
257
+ if (opts.allowHTTP1 === true) {
258
+ opts.ALPNProtocols.push('http/1.1');
259
+ }
260
+ }
215
261
  return opts;
216
262
  }
217
263
 
264
+ // The events an HTTP/1 connection produces that an application registers on the h2
265
+ // server. node serves both protocols from ONE emitter (http's _connectionListener is
266
+ // bound to the Http2SecureServer itself), so a listener sees both kinds of request;
267
+ // the mirror below is what makes one 'request' handler keep working here, where the
268
+ // fallback lives on an embedded server instead.
269
+ const HTTP1_MIRROR = new Set([
270
+ 'request', 'checkContinue', 'checkExpectation', 'upgrade', 'connect', 'clientError'
271
+ ]);
272
+
273
+ // node's fallback is a mixin: _http_server's private storeHTTPOptions() writes the
274
+ // HTTP/1 options into private fields of the Http2SecureServer itself, so there is no
275
+ // second server object and no second listener list. Those symbols are not reachable
276
+ // from node:http, so the fallback here is a real http.Server that never listens and
277
+ // receives the sockets the ALPN verdict hands it. The mirror tracks removals too (the
278
+ // handler below); removeAllListeners fires neither hook and is the one seam the mirror
279
+ // cannot follow -- recorded in the header comment. The embedded server's own connection
280
+ // bookkeeping never starts because 'listening' never fires -- the handed-off sockets are
281
+ // tracked here instead.
282
+ function initHttp1Fallback(server, opts) {
283
+ const http = require('node:http');
284
+ // DEP0202 (doc/api/deprecations.md): the top-level Http1IncomingMessage and
285
+ // Http1ServerResponse names migrate into http1Options.
286
+ const http1Options = { ...(opts.http1Options || {}) };
287
+ if (opts.Http1IncomingMessage !== undefined && http1Options.IncomingMessage === undefined) {
288
+ http1Options.IncomingMessage = opts.Http1IncomingMessage;
289
+ }
290
+ if (opts.Http1ServerResponse !== undefined && http1Options.ServerResponse === undefined) {
291
+ http1Options.ServerResponse = opts.Http1ServerResponse;
292
+ }
293
+ server._http1 = new http.Server(http1Options);
294
+ server._http1Sockets = new Set();
295
+ server._http1Active = 0;
296
+ server._http1Closing = false;
297
+ server.on('newListener', (event, listener) => {
298
+ if (HTTP1_MIRROR.has(event)) {
299
+ server._http1.on(event, listener);
300
+ }
301
+ });
302
+ server.on('removeListener', (event, listener) => {
303
+ // the other half of the mirror: node serves both protocols from ONE listener list,
304
+ // so taking a listener off the server takes it off the HTTP/1 side too. A once
305
+ // listener's self-removal after its single fire passes through here as well and
306
+ // drops the (now inert) wrapper from _http1. removeAllListeners fires neither
307
+ // hook -- the one seam the mirror cannot follow, header comment.
308
+ if (HTTP1_MIRROR.has(event)) {
309
+ server._http1.removeListener(event, listener);
310
+ }
311
+ });
312
+ // Per-socket activity, so close() can tell an idle keep-alive socket (destroy it,
313
+ // the way closeIdleConnections does on node) from one with a response in flight.
314
+ server._http1.on('request', (req, res) => {
315
+ server._http1Active++;
316
+ req.socket._h2leanActive = true;
317
+ res.once('finish', () => {
318
+ server._http1Active--;
319
+ req.socket._h2leanActive = false;
320
+ if (server._http1Closing && server._http1Active === 0) {
321
+ for (const socket of server._http1Sockets) {
322
+ socket.destroy();
323
+ }
324
+ }
325
+ });
326
+ });
327
+ }
328
+
329
+ function handOffHttp1(server, socket) {
330
+ server._http1Sockets.add(socket);
331
+ socket.once('close', () => server._http1Sockets.delete(socket));
332
+ server._http1.emit('connection', socket);
333
+ }
334
+
335
+ // The public-API equivalent of node's httpServerPreClose(): the idle keep-alive
336
+ // sockets go away right away, a response in flight is allowed to finish, and when the
337
+ // last one finishes the sockets it was talking on go too. node's mixin waits through
338
+ // net.Server's own connection bookkeeping instead; that bookkeeping is exactly what
339
+ // the embedded-server model cannot reach.
340
+ function closeHttp1(server) {
341
+ server._http1Closing = true;
342
+ for (const socket of [...server._http1Sockets]) {
343
+ if (!socket._h2leanActive) {
344
+ socket.destroy();
345
+ }
346
+ }
347
+ }
348
+
349
+ function unknownProtocol(server, socket) {
350
+ if (server.emit('unknownProtocol', socket)) {
351
+ return;
352
+ }
353
+ // core.js connectionListener: with no listener, the socket is told in a format it
354
+ // might understand why it got nothing, and an unref'd timer bounds how long a peer
355
+ // that never closes can hold it.
356
+ socket.end('HTTP/1.0 403 Forbidden\r\n' +
357
+ 'Content-Type: text/plain\r\n\r\n' +
358
+ 'Missing ALPN Protocol, expected `h2` to be available.\n' +
359
+ 'If this is a HTTP request: The server was not ' +
360
+ 'configured with the `allowHTTP1` option or a ' +
361
+ 'listener for the `unknownProtocol` event.\n');
362
+ const timer = setTimeout(() => {
363
+ if (!socket.destroyed) {
364
+ socket.destroy();
365
+ }
366
+ }, server._sessionOptions.unknownProtocolTimeout);
367
+ timer.unref();
368
+ socket.once('close', () => clearTimeout(timer));
369
+ }
370
+
218
371
  class Http2SecureServer extends tls.Server {
219
372
  constructor(options) {
220
- super(alpnOptions(options));
221
- initHttp2Server(this, options);
373
+ const opts = options || {};
374
+ super(alpnOptions(opts));
375
+ initHttp2Server(this, opts);
376
+ if (opts.allowHTTP1 === true) {
377
+ initHttp1Fallback(this, opts);
378
+ }
222
379
  this.on('secureConnection', (socket) => {
223
- // node's rule: 'h2' negotiated, or no ALPN at all -- which is h2 with prior
224
- // knowledge carried over a TLS connection. Anything else is dropped without
225
- // ever becoming a session.
380
+ // node's connectionListener (core.js): 'h2' negotiated becomes a session;
381
+ // 'http/1.1' -- or no ALPN at all, which is NOT h2 prior knowledge, whatever an
382
+ // older comment here claimed -- goes to the HTTP/1 fallback when allowHTTP1 is
383
+ // set, and otherwise to 'unknownProtocol', with the 403 text when nobody
384
+ // listens. Measured on node 26 in this session: a no-ALPN client speaking
385
+ // HTTP/1.1 is served by the fallback under allowHTTP1 and receives the 403
386
+ // without it.
226
387
  const alpn = socket.alpnProtocol;
227
- if (alpn === 'h2' || alpn === false) {
388
+ if (alpn === 'h2') {
228
389
  attachSession(this, socket);
390
+ } else if (alpn === 'http/1.1' || alpn === false) {
391
+ if (this._http1) {
392
+ handOffHttp1(this, socket);
393
+ } else {
394
+ unknownProtocol(this, socket);
395
+ }
229
396
  } else {
230
397
  socket.destroy();
231
398
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "h2lean",
3
- "version": "0.1.1",
3
+ "version": "0.2.1",
4
4
  "description": "Pure-JavaScript HTTP/2 for Node.js — a drop-in node:http2 replacement (server and client, h2c and TLS) with zero dependencies",
5
5
  "main": "index.js",
6
6
  "files": [
@@ -45,6 +45,7 @@
45
45
  "devDependencies": {
46
46
  "@eslint/js": "^10.0.1",
47
47
  "eslint": "^10.14.0",
48
+ "fastify": "^5.12.8",
48
49
  "fast-xml-parser": "^5.12.0",
49
50
  "uWebSockets.js": "github:uNetworking/UWebSockets.js#v20.70.0"
50
51
  }