h2lean 0.2.5 → 0.2.6

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
@@ -90,7 +90,7 @@ Compatibility target is the **public surface** of `node:http2`: names, argument
90
90
  server.listen(8080);
91
91
  ```
92
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.
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, and `performServerHandshake()` to run a server session over a socket you already hold.
94
94
 
95
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
96
 
@@ -236,10 +236,9 @@ h2lean terminates **untrusted bytes from the internet** and turns them into obje
236
236
 
237
237
  ## ⚠️ Not Implemented — Said Loudly
238
238
 
239
- Two APIs are absent, and both fail **loudly** with `ERR_H2LEAN_NOT_IMPLEMENTED` — never a silent wrong answer:
239
+ One API is absent, and it fails **loudly** with `ERR_H2LEAN_NOT_IMPLEMENTED` — never a silent wrong answer:
240
240
 
241
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
242
 
244
243
  ## 📚 Documentation
245
244
 
package/index.js CHANGED
@@ -10,8 +10,8 @@
10
10
  'use strict';
11
11
 
12
12
  const nodeHttp2 = require('node:http2');
13
- const { createServer, createSecureServer, Http2Server, Http2SecureServer,
14
- Http2ServerRequest, Http2ServerResponse, notImplemented } = require('./lib/server');
13
+ const { createServer, createSecureServer, performServerHandshake, Http2Server, Http2SecureServer,
14
+ Http2ServerRequest, Http2ServerResponse } = require('./lib/server');
15
15
  const { Http2Session, OUR_DEFAULTS, PEER_DEFAULTS, SETTINGS_BY_ID, ID_BY_SETTING } = require('./lib/session');
16
16
  const { DATA, HEADERS, PRIORITY, RST_STREAM, SETTINGS, PUSH_PROMISE, PING, GOAWAY,
17
17
  WINDOW_UPDATE, CONTINUATION } = require('./lib/frames');
@@ -54,7 +54,7 @@ module.exports = {
54
54
  createServer,
55
55
  createSecureServer,
56
56
  connect,
57
- performServerHandshake: () => { throw notImplemented('performServerHandshake'); },
57
+ performServerHandshake,
58
58
  getDefaultSettings: () => ({ ...OUR_DEFAULTS }),
59
59
  getPackedSettings,
60
60
  getUnpackedSettings,
@@ -81,7 +81,7 @@ const { pieceByteAt, pieceSlice, pieceConcat, pieceEquals } = require('./pieces'
81
81
  // SETTINGS id means, what node advertises, or where the copy/reference break-even sits.
82
82
  const {
83
83
  OUR_DEFAULTS, PEER_DEFAULTS, SETTINGS_BY_ID, ID_BY_SETTING, BODY_MIN, MAX_OUT_BATCH,
84
- STAGE_MIN, MAX_SHAPES, strictSingleValueFields, hashBlock, hashPieces
84
+ STAGE_MIN, MAX_SHAPES, strictSingleValueFields, hashBlock, hashPieces, kBoundSession
85
85
  } = require('./session');
86
86
 
87
87
  const {
@@ -124,6 +124,15 @@ class ClientHttp2Session extends EventEmitter {
124
124
  constructor(socket, options, scheme, authority) {
125
125
  super();
126
126
  const opts = options || {};
127
+ // The same ownership mark the server session takes (node's one Http2Session base
128
+ // constructor): a socket bound to any session -- client or server -- cannot be
129
+ // bound again, so performServerHandshake on a client's socket throws too.
130
+ if (socket[kBoundSession] !== undefined) {
131
+ const err = new Error('The socket is already bound to an Http2Session');
132
+ err.code = 'ERR_HTTP2_SOCKET_BOUND';
133
+ throw err;
134
+ }
135
+ socket[kBoundSession] = this;
127
136
  this.socket = socket;
128
137
  this.type = 1; // NGHTTP2_SESSION_CLIENT
129
138
  this.closed = false;
@@ -2023,6 +2032,7 @@ class ClientHttp2Session extends EventEmitter {
2023
2032
  }
2024
2033
 
2025
2034
  _onSocketClose() {
2035
+ this.socket[kBoundSession] = undefined;
2026
2036
  if (this._closeEmitted) {
2027
2037
  return;
2028
2038
  }
package/lib/compat.js CHANGED
@@ -846,4 +846,4 @@ function onServerStream(stream, headers, options, rawHeaders) {
846
846
  server.emit('request', request, response);
847
847
  }
848
848
 
849
- module.exports = { Http2ServerRequest, Http2ServerResponse, onServerStream };
849
+ module.exports = { Http2ServerRequest, Http2ServerResponse, onServerStream, describeType };
package/lib/server.js CHANGED
@@ -52,12 +52,20 @@
52
52
  // allowHTTP1 -- is answered with node's 403 text instead of being destroyed silently,
53
53
  // which is what node does (core.js connectionListener) and what this file used to claim
54
54
  // wrong: no ALPN is not h2 prior knowledge, and it never became a session on node.
55
+ // * performServerHandshake(socket, options) runs a server session over a socket the caller
56
+ // already holds, with no server object (node: initializeOptions + new ServerHttp2Session
57
+ // (options, socket, undefined)). One surface difference, measured on v26.12.1: node wraps
58
+ // a socket that is not a StreamBase (a generic Duplex, e.g. stream.duplexPair()) in a
59
+ // JSStreamSocket (core.js Http2Session constructor), so the second argument of 'connect'
60
+ // is that wrapper; h2lean is stream-based and hands over the socket itself. For a real
61
+ // net.Socket/TLSSocket -- the StreamBase case -- both pass the same object. The first
62
+ // argument (the session) and the argument count agree in every case.
55
63
  'use strict';
56
64
 
57
65
  const net = require('node:net');
58
66
  const tls = require('node:tls');
59
67
  const { Http2Session, OUR_DEFAULTS, strictSingleValueFields } = require('./session');
60
- const { onServerStream, Http2ServerRequest, Http2ServerResponse } = require('./compat');
68
+ const { onServerStream, Http2ServerRequest, Http2ServerResponse, describeType } = require('./compat');
61
69
 
62
70
  const kCompat = Symbol('h2lean.compatListener');
63
71
  // The transport's own close/on, captured before the shared API overrides them:
@@ -116,7 +124,6 @@ function initHttp2Server(server, options) {
116
124
 
117
125
  // Turns an accepted socket -- plain or already decrypted -- into a session.
118
126
  function attachSession(server, socket) {
119
- socket.setNoDelay(true);
120
127
  const session = new Http2Session(socket, server._sessionOptions);
121
128
  session.server = server;
122
129
  server._sessions.add(session);
@@ -436,7 +443,42 @@ function createSecureServer(options, onRequestHandler) {
436
443
  return server;
437
444
  }
438
445
 
446
+ // node's performServerHandshake (core.js): initializeOptions(options) then a
447
+ // ServerHttp2Session with NO server object. The socket is one the caller already
448
+ // holds -- typically a TLSSocket an https server negotiated 'h2' on, or a plain
449
+ // net.Socket for h2c. node does NOT check alpnProtocol here (the ALPN verdict is
450
+ // the caller's, not the handshake's), and neither do we; a still-connecting socket
451
+ // is waited for by the session constructor. The options h2lean implements are
452
+ // validated the way initializeOptions validates them; the rest (remoteCustomSettings,
453
+ // maxSessionInvalidFrames, connectionWindowSize, origins) concern features h2lean
454
+ // does not implement and are ignored here exactly as they are at createServer. The one
455
+ // surface difference (node's JSStreamSocket wrap of a generic Duplex, so 'connect's second
456
+ // argument differs there) is written up in this file's header.
457
+ function performServerHandshake(socket, options) {
458
+ if (options !== undefined &&
459
+ (options === null || typeof options !== 'object' || Array.isArray(options))) {
460
+ const err = new TypeError(
461
+ `The "options" argument must be of type object. Received ${describeType(options)}`);
462
+ err.code = 'ERR_INVALID_ARG_TYPE';
463
+ throw err;
464
+ }
465
+ const opts = { ...options };
466
+ if (opts.settings !== undefined &&
467
+ (opts.settings === null || typeof opts.settings !== 'object' || Array.isArray(opts.settings))) {
468
+ const err = new TypeError(
469
+ `The "options.settings" property must be of type object. Received ${describeType(opts.settings)}`);
470
+ err.code = 'ERR_INVALID_ARG_TYPE';
471
+ throw err;
472
+ }
473
+ strictSingleValueFields(opts);
474
+ // opts.settings carries only what the application asked for, and the session's
475
+ // _advertised defaults to Object.keys(opts.settings) -- so the first SETTINGS frame
476
+ // advertises exactly those, empty when nothing was asked, the way node's does.
477
+ // No server means no compat layer: the session emits 'stream', never 'request'.
478
+ return new Http2Session(socket, opts);
479
+ }
480
+
439
481
  module.exports = {
440
- Http2Server, Http2SecureServer, createServer, createSecureServer, notImplemented,
441
- Http2ServerRequest, Http2ServerResponse
482
+ Http2Server, Http2SecureServer, createServer, createSecureServer, performServerHandshake,
483
+ notImplemented, Http2ServerRequest, Http2ServerResponse
442
484
  };
package/lib/session.js CHANGED
@@ -19,6 +19,7 @@
19
19
  'use strict';
20
20
 
21
21
  const { EventEmitter } = require('node:events');
22
+ const tls = require('node:tls');
22
23
  const f = require('./frames');
23
24
  const { Decoder, Encoder, HPackError } = require('./hpack');
24
25
  const { Http2Stream, errorOf, emitNT } = require('./stream');
@@ -37,6 +38,12 @@ const FlatList = require('./flat-list');
37
38
  const FLAT = new FlatList(64);
38
39
  const { pieceCopyTo, pieceSlice, pieceConcat, pieceEquals } = require('./pieces');
39
40
  const { nullProto, hasBadValue, SINGLE_VALUE_FIELDS } = require('./headers');
41
+
42
+ // The socket's ownership mark, shared with the client session (node keeps it as
43
+ // socket[kBoundSession] in the one Http2Session base constructor both kinds run
44
+ // through). A socket binds to exactly one session; performServerHandshake on an
45
+ // already-bound socket throws ERR_HTTP2_SOCKET_BOUND.
46
+ const kBoundSession = Symbol('h2lean.boundSession');
40
47
  // One shared 499 ms clock for the long idle timeouts, instead of a libuv timer
41
48
  // handle per connection. Vendored verbatim; see lib/fast-timer.js.
42
49
  const { setTimeout: idleSetTimeout, clearTimeout: idleClearTimeout } =
@@ -319,17 +326,27 @@ class Http2Session extends EventEmitter {
319
326
  constructor(socket, options) {
320
327
  super();
321
328
  const opts = options || {};
329
+ if (socket[kBoundSession] !== undefined) {
330
+ const err = new Error('The socket is already bound to an Http2Session');
331
+ err.code = 'ERR_HTTP2_SOCKET_BOUND';
332
+ throw err;
333
+ }
334
+ socket[kBoundSession] = this;
322
335
  this.socket = socket;
323
- this.server = null; // set by the server on attach
336
+ // undefined until a server attaches itself; a performServerHandshake session has
337
+ // no server, and node's `session.server` getter reads undefined there (core.js).
338
+ this.server = undefined;
324
339
  this.type = 0; // NGHTTP2_SESSION_SERVER
325
340
  this.closed = false;
326
341
  this.destroyed = false;
327
342
  this.connecting = false;
328
- // node reads both of these off the socket. Over h2c there is no encryption and
329
- // no ALPN; over h2s a peer that negotiated nothing reports false rather than
330
- // a protocol name, which is h2 with prior knowledge on a TLS connection.
331
- this.encrypted = socket.encrypted === true;
332
- this.alpnProtocol = socket.alpnProtocol === undefined ? null : socket.alpnProtocol;
343
+ this._connectEmitted = false;
344
+ // Derived from the socket in _start, once it is connected -- node's setupHandle
345
+ // fills them then and its getters read undefined before that. Over h2c there is no
346
+ // encryption and the protocol is 'h2c'; over h2s a peer that negotiated nothing
347
+ // reports false rather than a name, which is h2 with prior knowledge on TLS.
348
+ this.encrypted = undefined;
349
+ this.alpnProtocol = undefined;
333
350
  // What the application sees. node keeps the received values in a private state object and
334
351
  // exposes them through getters that answer NO_ERROR / 0 when no GOAWAY has arrived
335
352
  // (`this[kState].goawayCode || NGHTTP2_NO_ERROR`), so `session.goawayCode` reads 0 on a live
@@ -523,7 +540,6 @@ class Http2Session extends EventEmitter {
523
540
  // costs no allocation per write
524
541
  this._onWrittenCb = () => this._onWritten();
525
542
 
526
- socket.on('data', (d) => this._onData(d));
527
543
  socket.on('error', (err) => this._onSocketError(err));
528
544
  socket.on('end', () => this.destroy(NO_ERROR));
529
545
  // 'finish' means everything we wrote reached the OS, so the GOAWAY of a close() is never
@@ -536,8 +552,77 @@ class Http2Session extends EventEmitter {
536
552
  }
537
553
  });
538
554
  socket.on('close', () => this._onSocketClose());
555
+ // node's constructor takes the socket's Nagle and renegotiation settings here
556
+ // (core.js), so a performServerHandshake socket gets them too -- attachSession
557
+ // used to be the only place setNoDelay was called.
558
+ if (typeof socket.setNoDelay === 'function') {
559
+ socket.setNoDelay();
560
+ }
561
+ if (typeof socket.disableRenegotiation === 'function') {
562
+ socket.disableRenegotiation();
563
+ }
564
+ // node defers setupHandle until the socket reports connected ("socket.connecting
565
+ // || socket.secureConnecting", core.js). An accepted server socket always is; a
566
+ // performServerHandshake socket may still be connecting, and under TLS the ALPN
567
+ // verdict is not known until 'secureConnect'.
568
+ if (socket.connecting || socket.secureConnecting) {
569
+ this.connecting = true;
570
+ const ev = socket instanceof tls.TLSSocket ? 'secureConnect' : 'connect';
571
+ socket.once(ev, () => this._start());
572
+ } else {
573
+ this._start();
574
+ }
575
+ if (socket.readableLength > 0) {
576
+ // A caller may hand performServerHandshake a paused socket with the peer's preface
577
+ // already buffered. node drains that buffer on the next tick (core.js constructor);
578
+ // do the same, then subscribe. 'connect' was queued by _start ahead of this drain, so
579
+ // it fires first. An accepted createServer socket has nothing buffered here and takes
580
+ // the synchronous subscription below, the read path this file always had.
581
+ process.nextTick(() => {
582
+ if (this.destroyed) {
583
+ return;
584
+ }
585
+ let buf;
586
+ while (socket.readableLength > 0 && (buf = socket.read()) !== null) {
587
+ this._onData(buf);
588
+ }
589
+ if (!this.destroyed) {
590
+ socket.on('data', (d) => this._onData(d));
591
+ }
592
+ });
593
+ } else {
594
+ socket.on('data', (d) => this._onData(d));
595
+ }
596
+ }
539
597
 
598
+ // The server session's setupHandle (node core.js): advertise our SETTINGS, fill the
599
+ // encryption/ALPN getters and tell the application the session is up. 'connect' carries
600
+ // (session, socket) and fires on the next tick so a listener attached after the
601
+ // constructor still catches it -- at setup, before any peer octet, NOT when the preface
602
+ // arrives (what this used to do, and what the old comment wrongly claimed node did).
603
+ // Measured on v26.12.1 (tools/probe-handshake.js CASE1/CASE6): node fires it at setup
604
+ // with both arguments, for createServer and performServerHandshake alike.
605
+ _start() {
606
+ if (this.destroyed) {
607
+ // node still emits 'connect' for a session destroyed before its socket connected
608
+ // (setupHandle's destroyed branch), so the handlers at least run and clear out.
609
+ if (!this._connectEmitted) {
610
+ this._connectEmitted = true;
611
+ process.nextTick(() => this.emit('connect', this, this.socket));
612
+ }
613
+ return;
614
+ }
615
+ this.connecting = false;
616
+ if (this.socket.encrypted) {
617
+ this.encrypted = true;
618
+ this.alpnProtocol = this.socket.alpnProtocol;
619
+ } else {
620
+ this.encrypted = false;
621
+ this.alpnProtocol = 'h2c';
622
+ }
540
623
  this._sendSettings();
624
+ this._connectEmitted = true;
625
+ process.nextTick(() => this.emit('connect', this, this.socket));
541
626
  }
542
627
 
543
628
  // ---- outbound queue --------------------------------------------------------
@@ -864,11 +949,6 @@ class Http2Session extends EventEmitter {
864
949
  return this._fatal(PROTOCOL_ERROR, 'connection preface malformed');
865
950
  }
866
951
  this._prefaceSeen += take;
867
- // node's server-side session fires 'connect' once the peer's preface is in,
868
- // before any SETTINGS have been decoded
869
- if (this._prefaceSeen === PREFACE_LEN) {
870
- this.emit('connect');
871
- }
872
952
  i = take;
873
953
  // the chunk stopped inside the preface: nothing was produced, but the
874
954
  // batch flag must not leak into whatever the peer sends next
@@ -2682,6 +2762,8 @@ class Http2Session extends EventEmitter {
2682
2762
  }
2683
2763
 
2684
2764
  _onSocketClose() {
2765
+ // release the ownership mark (node cleanupSession clears socket[kBoundSession])
2766
+ this.socket[kBoundSession] = undefined;
2685
2767
  this._open = false;
2686
2768
  if (!this.destroyed) {
2687
2769
  this.destroy(NO_ERROR);
@@ -2784,4 +2866,4 @@ class Http2Session extends EventEmitter {
2784
2866
 
2785
2867
  module.exports = { Http2Session, OUR_DEFAULTS, PEER_DEFAULTS, SETTINGS_BY_ID,
2786
2868
  ID_BY_SETTING, MAX_OUT_BATCH, MAX_SESSION_HOLD, STREAM_HOLD_CHARGE, BODY_MIN,
2787
- STAGE_MIN, MAX_SHAPES, strictSingleValueFields, hashBlock, hashPieces };
2869
+ STAGE_MIN, MAX_SHAPES, strictSingleValueFields, hashBlock, hashPieces, kBoundSession };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "h2lean",
3
- "version": "0.2.5",
3
+ "version": "0.2.6",
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": [
@@ -14,6 +14,8 @@
14
14
  "keywords": [
15
15
  "http2",
16
16
  "h2c",
17
+ "h2",
18
+ "request",
17
19
  "node:http2",
18
20
  "nghttp2",
19
21
  "server",