h2lean 0.2.5 → 0.3.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
@@ -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/headers.js CHANGED
@@ -282,7 +282,7 @@ function refreshDate() {
282
282
  // `info` marks the informational (1xx) block that additionalHeaders() sends: node applies
283
283
  // a different status rule and different error codes there, and it generates no date for it.
284
284
  function parse(headers, sensitive,
285
- { trailer = false, sendDate = false, info = false, strict = true } = {}) {
285
+ { trailer = false, sendDate = false, info = false, strict = true, request = false } = {}) {
286
286
  if (headers === null || typeof headers !== 'object') {
287
287
  throw httpError('ERR_HTTP2_INVALID_HEADER_VALUE', 'headers must be an object');
288
288
  }
@@ -361,6 +361,27 @@ function parse(headers, sensitive,
361
361
  if (trailer) {
362
362
  throw httpError('ERR_HTTP2_PSEUDOHEADER_NOT_ALLOWED', 'cannot send trailers with pseudo-headers');
363
363
  }
364
+ if (request) {
365
+ // Request pseudo-headers for PUSH_PROMISE (node: assertValidPseudoHeader,
366
+ // internal/http2/util.js). :status is response-only; the five request
367
+ // pseudo-headers are the ones RFC 9113 8.3.1 defines.
368
+ if (key !== ':method' && key !== ':path' && key !== ':scheme'
369
+ && key !== ':authority' && key !== ':protocol') {
370
+ throw httpError('ERR_HTTP2_PSEUDOHEADER_NOT_ALLOWED', `cannot send ${key} in a request`);
371
+ }
372
+ const val = String(Array.isArray(raw) ? raw[0] : raw);
373
+ if (key === ':method' && !isToken.test(val)) {
374
+ throw httpError('ERR_INVALID_HTTP_TOKEN', `${val} is an invalid method`);
375
+ }
376
+ if (key === ':path' && val === '') {
377
+ throw httpError('ERR_HTTP2_INVALID_HEADER_VALUE', ':path must not be empty');
378
+ }
379
+ if (key === ':scheme' && !isToken.test(val)) {
380
+ throw httpError('ERR_INVALID_HTTP_TOKEN', `${val} is an invalid scheme`);
381
+ }
382
+ pseudo.push(key, val);
383
+ continue;
384
+ }
364
385
  if (key !== ':status') {
365
386
  throw httpError('ERR_HTTP2_PSEUDOHEADER_NOT_ALLOWED', `cannot send ${key} in a response`);
366
387
  }
@@ -421,7 +442,8 @@ function parse(headers, sensitive,
421
442
  // answers 200. Measured: respond({'x-a': 1}) arrives as :status 200 with a date, where
422
443
  // this used to throw. An informational block has no such default -- node validates a
423
444
  // :status only if the application put one there -- and trailers have no status at all.
424
- if (!trailer) {
445
+ // A request block (PUSH_PROMISE) has no status and no date.
446
+ if (!trailer && !request) {
425
447
  if (info) {
426
448
  if (sawStatus) {
427
449
  pseudo.push(':status', String(status));
@@ -553,5 +575,22 @@ function encodeAt(parsed, enc, at) {
553
575
  return off;
554
576
  }
555
577
 
556
- module.exports = { block, encode, parse, nullProto, isFieldName, trimName, lowerName,
578
+ // The HPACK block for a PUSH_PROMISE payload: request-style pseudo-headers, no date,
579
+ // no status default, no cache (a promise is one-shot). The encoder is the session's,
580
+ // so the block shares the connection's dynamic table with every other outbound block.
581
+ // Returns a view into the shared scratch, valid until the next encode call -- the
582
+ // caller (session.sendPushPromise) copies it into the frame immediately.
583
+ function pushBlock(headers, sensitive, session) {
584
+ const enc = session._encoder;
585
+ const update = enc.takeSizeUpdate();
586
+ const parsed = parse(headers, sensitive, { request: true, strict: session._strictSingle });
587
+ const at = update === null ? 0 : update.length;
588
+ const end = encodeAt(parsed, enc, at);
589
+ if (at !== 0) {
590
+ update.copy(scratch, 0);
591
+ }
592
+ return scratch.subarray(0, end);
593
+ }
594
+
595
+ module.exports = { block, pushBlock, encode, parse, nullProto, isFieldName, trimName, lowerName,
557
596
  nameCacheSize, hasBadValue, CONNECTION_SPECIFIC, KSensitiveHeaders, SINGLE_VALUE_FIELDS };
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
@@ -481,6 +498,10 @@ class Http2Session extends EventEmitter {
481
498
  this._rstSec = (Date.now() / 1000) | 0;
482
499
 
483
500
  this._maxInboundSid = 0;
501
+ // The next even stream id to reserve for a PUSH_PROMISE (RFC 9113 5.1.1: server-initiated
502
+ // streams are even). Starts at 2; _allocPushSid increments by 2 and throws
503
+ // ERR_HTTP2_OUT_OF_STREAMS when the 31-bit space is exhausted.
504
+ this._nextPushSid = 2;
484
505
  // The highest id of a HEADERS frame this side has accepted -- nghttp2 opens the
485
506
  // stream in prep_frame, after the length, padding and priority checks but BEFORE
486
507
  // the block is decoded or any verdict on it is given, and its last-proc-stream-id
@@ -523,7 +544,6 @@ class Http2Session extends EventEmitter {
523
544
  // costs no allocation per write
524
545
  this._onWrittenCb = () => this._onWritten();
525
546
 
526
- socket.on('data', (d) => this._onData(d));
527
547
  socket.on('error', (err) => this._onSocketError(err));
528
548
  socket.on('end', () => this.destroy(NO_ERROR));
529
549
  // 'finish' means everything we wrote reached the OS, so the GOAWAY of a close() is never
@@ -536,8 +556,77 @@ class Http2Session extends EventEmitter {
536
556
  }
537
557
  });
538
558
  socket.on('close', () => this._onSocketClose());
559
+ // node's constructor takes the socket's Nagle and renegotiation settings here
560
+ // (core.js), so a performServerHandshake socket gets them too -- attachSession
561
+ // used to be the only place setNoDelay was called.
562
+ if (typeof socket.setNoDelay === 'function') {
563
+ socket.setNoDelay();
564
+ }
565
+ if (typeof socket.disableRenegotiation === 'function') {
566
+ socket.disableRenegotiation();
567
+ }
568
+ // node defers setupHandle until the socket reports connected ("socket.connecting
569
+ // || socket.secureConnecting", core.js). An accepted server socket always is; a
570
+ // performServerHandshake socket may still be connecting, and under TLS the ALPN
571
+ // verdict is not known until 'secureConnect'.
572
+ if (socket.connecting || socket.secureConnecting) {
573
+ this.connecting = true;
574
+ const ev = socket instanceof tls.TLSSocket ? 'secureConnect' : 'connect';
575
+ socket.once(ev, () => this._start());
576
+ } else {
577
+ this._start();
578
+ }
579
+ if (socket.readableLength > 0) {
580
+ // A caller may hand performServerHandshake a paused socket with the peer's preface
581
+ // already buffered. node drains that buffer on the next tick (core.js constructor);
582
+ // do the same, then subscribe. 'connect' was queued by _start ahead of this drain, so
583
+ // it fires first. An accepted createServer socket has nothing buffered here and takes
584
+ // the synchronous subscription below, the read path this file always had.
585
+ process.nextTick(() => {
586
+ if (this.destroyed) {
587
+ return;
588
+ }
589
+ let buf;
590
+ while (socket.readableLength > 0 && (buf = socket.read()) !== null) {
591
+ this._onData(buf);
592
+ }
593
+ if (!this.destroyed) {
594
+ socket.on('data', (d) => this._onData(d));
595
+ }
596
+ });
597
+ } else {
598
+ socket.on('data', (d) => this._onData(d));
599
+ }
600
+ }
539
601
 
602
+ // The server session's setupHandle (node core.js): advertise our SETTINGS, fill the
603
+ // encryption/ALPN getters and tell the application the session is up. 'connect' carries
604
+ // (session, socket) and fires on the next tick so a listener attached after the
605
+ // constructor still catches it -- at setup, before any peer octet, NOT when the preface
606
+ // arrives (what this used to do, and what the old comment wrongly claimed node did).
607
+ // Measured on v26.12.1 (tools/probe-handshake.js CASE1/CASE6): node fires it at setup
608
+ // with both arguments, for createServer and performServerHandshake alike.
609
+ _start() {
610
+ if (this.destroyed) {
611
+ // node still emits 'connect' for a session destroyed before its socket connected
612
+ // (setupHandle's destroyed branch), so the handlers at least run and clear out.
613
+ if (!this._connectEmitted) {
614
+ this._connectEmitted = true;
615
+ process.nextTick(() => this.emit('connect', this, this.socket));
616
+ }
617
+ return;
618
+ }
619
+ this.connecting = false;
620
+ if (this.socket.encrypted) {
621
+ this.encrypted = true;
622
+ this.alpnProtocol = this.socket.alpnProtocol;
623
+ } else {
624
+ this.encrypted = false;
625
+ this.alpnProtocol = 'h2c';
626
+ }
540
627
  this._sendSettings();
628
+ this._connectEmitted = true;
629
+ process.nextTick(() => this.emit('connect', this, this.socket));
541
630
  }
542
631
 
543
632
  // ---- outbound queue --------------------------------------------------------
@@ -740,6 +829,53 @@ class Http2Session extends EventEmitter {
740
829
  }
741
830
  }
742
831
 
832
+ // Reserve the next even stream id for a PUSH_PROMISE. RFC 9113 5.1.1: server-initiated
833
+ // streams use even ids; the 31-bit space is exhausted at 2^31-1 (the R bit is not an id).
834
+ // node: nghttp2_session_get_next_stream_id returns NGHTTP2_ERR_STREAM_ID_NOT_AVAILABLE,
835
+ // which core.js maps to ERR_HTTP2_OUT_OF_STREAMS.
836
+ _allocPushSid() {
837
+ const sid = this._nextPushSid;
838
+ if (sid > 0x7fffffff) {
839
+ throw errorOf('ERR_HTTP2_OUT_OF_STREAMS', 'No stream ID is available');
840
+ }
841
+ this._nextPushSid += 2;
842
+ return sid;
843
+ }
844
+
845
+ // PUSH_PROMISE frame (RFC 9113 6.6): the payload is a 4-octet promised stream id (R=0)
846
+ // followed by the header block fragment. The frame rides on the PARENT stream id (odd);
847
+ // the promised id inside the payload is even. CONTINUATION split mirrors sendHeaders,
848
+ // with the first frame carrying the 4-octet prefix and the block fragment that fits.
849
+ sendPushPromise(parentSid, promisedSid, block) {
850
+ this.state.deflateDynamicTableSize = this._encoder.size;
851
+ const max = this.remoteSettings.maxFrameSize;
852
+ // The payload is the 4-byte promised id + the block. The first frame can carry
853
+ // max - 4 bytes of block; the rest goes into CONTINUATION frames.
854
+ const firstCap = max - 4;
855
+ if (block.length <= firstCap) {
856
+ const payload = Buffer.allocUnsafe(4 + block.length);
857
+ payload.writeUInt32BE(promisedSid, 0);
858
+ block.copy(payload, 4);
859
+ this._frame(PUSH_PROMISE, F_END_HEADERS, parentSid, payload);
860
+ return;
861
+ }
862
+ const first = Buffer.allocUnsafe(4 + firstCap);
863
+ first.writeUInt32BE(promisedSid, 0);
864
+ block.copy(first, 4, 0, firstCap);
865
+ this._frame(PUSH_PROMISE, 0, parentSid, first);
866
+ let off = firstCap;
867
+ for (;;) {
868
+ const n = Math.min(block.length - off, max);
869
+ const last = off + n >= block.length;
870
+ this._frame(CONTINUATION, last ? F_END_HEADERS : 0, parentSid,
871
+ block.subarray(off, off + n));
872
+ off += n;
873
+ if (last) {
874
+ return;
875
+ }
876
+ }
877
+ }
878
+
743
879
  // Writes DATA within the stream and connection windows. Returns true when
744
880
  // everything went out; false means the caller should wait for WINDOW_UPDATE.
745
881
  sendData(stream, buf, end) {
@@ -864,11 +1000,6 @@ class Http2Session extends EventEmitter {
864
1000
  return this._fatal(PROTOCOL_ERROR, 'connection preface malformed');
865
1001
  }
866
1002
  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
1003
  i = take;
873
1004
  // the chunk stopped inside the preface: nothing was produced, but the
874
1005
  // batch flag must not leak into whatever the peer sends next
@@ -1926,6 +2057,7 @@ class Http2Session extends EventEmitter {
1926
2057
  return;
1927
2058
  }
1928
2059
  const stream = new Http2Stream(this, sid);
2060
+ stream._requestHeaders = headers;
1929
2061
  this._streams.set(sid, stream);
1930
2062
  this._liveStreams++;
1931
2063
  // content-length is a promise about the body, and the two checks that hold the peer to it
@@ -2022,7 +2154,11 @@ class Http2Session extends EventEmitter {
2022
2154
  // the 'idle' state of 5.1, and DATA is allowed in 'open' and 'half-closed (local)' only.
2023
2155
  // Measured on node (probe cases U5, U13, U14): GOAWAY(PROTOCOL_ERROR) -- including for the
2024
2156
  // connection-level sid 0 and for an even id, neither of which a client may ever open.
2025
- if (sid === 0 || (sid & 1) === 0 || sid > this._maxInboundSid) {
2157
+ // Even ids this side pushed are known (reserved-local): a late DATA for one that already
2158
+ // closed is the discard of 5.1, not the idle error. Only even ids above the highest push
2159
+ // id ever allocated are truly unknown.
2160
+ if (sid === 0 || ((sid & 1) === 0 && sid > this._nextPushSid - 2)
2161
+ || ((sid & 1) !== 0 && sid > this._maxInboundSid)) {
2026
2162
  this._fatal(PROTOCOL_ERROR, 'DATA on a stream in the idle state');
2027
2163
  return undefined;
2028
2164
  }
@@ -2156,7 +2292,8 @@ class Http2Session extends EventEmitter {
2156
2292
  // is GOAWAY(PROTOCOL_ERROR). For an id at or below the highest one opened the stream has
2157
2293
  // been answered, refused or reset -- a credit note that arrived late -- and node drops it,
2158
2294
  // so this does too rather than turning the peer's own in-flight frame into an error.
2159
- if (sid > this._maxInboundSid) {
2295
+ // Even push ids are compared against the highest push id allocated, not the inbound line.
2296
+ if (sid > ((sid & 1) !== 0 ? this._maxInboundSid : this._nextPushSid - 2)) {
2160
2297
  this._fatal(PROTOCOL_ERROR, 'WINDOW_UPDATE on an idle stream');
2161
2298
  }
2162
2299
  return;
@@ -2286,7 +2423,8 @@ class Http2Session extends EventEmitter {
2286
2423
  // allows RST_STREAM in 'open' and 'half-closed (local)' only. Measured on node (h2spec
2287
2424
  // http2/5.1 and 6.4): GOAWAY(PROTOCOL_ERROR). A reset for a stream that has already been
2288
2425
  // answered or refused is the peer's own late frame and is dropped.
2289
- if (sid > this._maxInboundSid) {
2426
+ // Even push ids are compared against the highest push id allocated, not the inbound line.
2427
+ if (sid > ((sid & 1) !== 0 ? this._maxInboundSid : this._nextPushSid - 2)) {
2290
2428
  this._fatal(PROTOCOL_ERROR, 'RST_STREAM on an idle stream');
2291
2429
  return;
2292
2430
  }
@@ -2682,6 +2820,8 @@ class Http2Session extends EventEmitter {
2682
2820
  }
2683
2821
 
2684
2822
  _onSocketClose() {
2823
+ // release the ownership mark (node cleanupSession clears socket[kBoundSession])
2824
+ this.socket[kBoundSession] = undefined;
2685
2825
  this._open = false;
2686
2826
  if (!this.destroyed) {
2687
2827
  this.destroy(NO_ERROR);
@@ -2784,4 +2924,4 @@ class Http2Session extends EventEmitter {
2784
2924
 
2785
2925
  module.exports = { Http2Session, OUR_DEFAULTS, PEER_DEFAULTS, SETTINGS_BY_ID,
2786
2926
  ID_BY_SETTING, MAX_OUT_BATCH, MAX_SESSION_HOLD, STREAM_HOLD_CHARGE, BODY_MIN,
2787
- STAGE_MIN, MAX_SHAPES, strictSingleValueFields, hashBlock, hashPieces };
2927
+ STAGE_MIN, MAX_SHAPES, strictSingleValueFields, hashBlock, hashPieces, kBoundSession };
package/lib/stream.js CHANGED
@@ -270,6 +270,101 @@ class Http2Stream extends EventEmitter {
270
270
  return true;
271
271
  }
272
272
 
273
+ // node: ServerHttp2Stream.pushAllowed (internal/http2/core.js:2961).
274
+ // Truthiness of remoteSettings.enablePush: the CLIENT's advertisement decides whether
275
+ // the server may push. Measured on v26.12.1: a client with settings:{enablePush:false}
276
+ // makes pushAllowed false and pushStream throw ERR_HTTP2_PUSH_DISABLED synchronously.
277
+ get pushAllowed() {
278
+ return !this._destroyed && !this.closed && !this.session.closed
279
+ && !this.session.destroyed && !!this.session.remoteSettings.enablePush;
280
+ }
281
+
282
+ // node: ServerHttp2Stream.pushStream (internal/http2/core.js:2971).
283
+ // Synchronous throws: ERR_HTTP2_PUSH_DISABLED, ERR_HTTP2_NESTED_PUSH.
284
+ // Asynchronous errors (allocation, closed stream) go to callback via nextTick.
285
+ // The pushed stream's readable side is pre-ended (a push has no request body);
286
+ // the application answers it through the normal respond()/write()/end() path.
287
+ pushStream(headers, options, callback) {
288
+ if (!this.pushAllowed) {
289
+ throw errorOf('ERR_HTTP2_PUSH_DISABLED', 'Push is disabled');
290
+ }
291
+ if ((this.id & 1) === 0) {
292
+ throw errorOf('ERR_HTTP2_NESTED_PUSH', 'Nested push is not allowed');
293
+ }
294
+ if (typeof options === 'function') {
295
+ callback = options;
296
+ options = undefined;
297
+ }
298
+ if (options === undefined || options === null) {
299
+ options = {};
300
+ }
301
+ if (typeof options !== 'object' || Array.isArray(options)) {
302
+ const err = new TypeError('The "options" argument must be of type object');
303
+ err.code = 'ERR_INVALID_ARG_TYPE';
304
+ throw err;
305
+ }
306
+ if (callback !== undefined && typeof callback !== 'function') {
307
+ const err = new TypeError('The "callback" argument must be of type function');
308
+ err.code = 'ERR_INVALID_ARG_TYPE';
309
+ throw err;
310
+ }
311
+ const endStream = !!options.endStream;
312
+
313
+ // Defaults from the parent request (node: core.js pushStream fills :method GET,
314
+ // :authority and :scheme from the request, :path '/'). The headers object is copied
315
+ // into a null-proto map so the application's object is not mutated.
316
+ const req = this._requestHeaders || {};
317
+ const h = Object.assign(Object.create(null), headers);
318
+ if (h[':method'] === undefined) {
319
+ h[':method'] = 'GET';
320
+ }
321
+ if (h[':authority'] === undefined && req[':authority'] !== undefined) {
322
+ h[':authority'] = req[':authority'];
323
+ }
324
+ if (h[':scheme'] === undefined && req[':scheme'] !== undefined) {
325
+ h[':scheme'] = req[':scheme'];
326
+ }
327
+ if (h[':path'] === undefined) {
328
+ h[':path'] = '/';
329
+ }
330
+ const isHead = h[':method'] === 'HEAD';
331
+
332
+ // Allocate the promised id. Errors here are asynchronous (callback via nextTick),
333
+ // matching node's nghttp2_submit_push_promise error path.
334
+ let promisedId;
335
+ try {
336
+ promisedId = this.session._allocPushSid();
337
+ } catch (err) {
338
+ if (callback) {
339
+ process.nextTick(callback, err);
340
+ return;
341
+ }
342
+ throw err;
343
+ }
344
+
345
+ // Validation errors are synchronous in node (buildNgHeaderString throws before
346
+ // the frame is submitted). The id was already reserved; it stays consumed.
347
+ const block = hdr.pushBlock(h, options.sensitiveHeaders, this.session);
348
+ this.session.sendPushPromise(this.id, promisedId, block);
349
+
350
+ // Create the pushed stream and register it. The readable side is pre-ended:
351
+ // remoteClose=1 means _endLocalSide() takes the graceful close path (no RST),
352
+ // and no inbound credit is ever charged for a request body that does not exist.
353
+ const stream = new Http2Stream(this.session, promisedId);
354
+ stream.sentHeaders = h;
355
+ stream._requestHeaders = h;
356
+ this.session._streams.set(promisedId, stream);
357
+ this.session._liveStreams++;
358
+ stream._remoteEnded();
359
+
360
+ if (endStream || isHead) {
361
+ stream.end();
362
+ }
363
+ if (callback) {
364
+ process.nextTick(callback, null, stream, h, 0);
365
+ }
366
+ }
367
+
273
368
  // Readable-side control, node's contract: while paused no credit is released,
274
369
  // so the sender is the one that waits, and whatever arrives in the meantime is
275
370
  // buffered and replayed on resume(). Returns this, like the Duplex does.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "h2lean",
3
- "version": "0.2.5",
3
+ "version": "0.3.0",
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",