h2lean 0.19.7 → 0.19.9

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
@@ -33,7 +33,7 @@ Up to **8× less CPU per request** and **6.8× more requests per second** than `
33
33
  - [Monkey-patching for frameworks without injection](#monkey-patching-for-frameworks-without-injection)
34
34
  - 🛠️ [Advanced Tuning](#️-advanced-tuning)
35
35
  - 🔒 [Security](#-security)
36
- - ⚠️ [Not Implemented — Said Loudly](#️-not-implemented--said-loudly)
36
+ - ⚠️ [Known Divergences](#️-known-divergences)
37
37
  - 📚 [Documentation](#-documentation)
38
38
  - 🤝 [Contributing](#-contributing)
39
39
  - ⚖️ [License](#️-license)
@@ -93,7 +93,7 @@ Compatibility target is the **public surface** of `node:http2`: names, argument
93
93
 
94
94
  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.
95
95
 
96
- Where behavior deliberately differs from node, it is **documented, measured, and pinned by tests** — never silent. Known divergences: [CONTRIBUTING.md](./CONTRIBUTING.md) §5.
96
+ Where behavior deliberately differs from node, it is **documented, measured, and pinned by tests** — never silent. Known divergences: [DIVERGENCES.md](./DIVERGENCES.md).
97
97
 
98
98
  ## 📦 Installation
99
99
 
@@ -266,40 +266,30 @@ nodeHttp2.connect = h2lean.connect;
266
266
  h2lean 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)):
267
267
 
268
268
  - 🛡️ **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 h2lean: SETTINGS-entry cap (CVE-2020-11080), CONTINUATION cap (CVE-2024-28182), rapid-reset budget (CVE-2023-44487), outbound staging, parked-stream and history bounds.
269
- - 🚫 **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*. h2lean is stricter than node here, deliberately and measurably.
269
+ - 🚫 **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*. This is a deliberate, measured divergence from node in the strict direction ([DIVERGENCES.md](./DIVERGENCES.md), entry 19).
270
270
  - ✅ **Verified, not assumed:**
271
271
  - **300+ differential tests** — application scripts run against both `node:http2` and h2lean, transcripts compared;
272
272
  - **h2spec 146/146** — full RFC 9113/7541 conformance, same verdict as node's own HTTP/2 (`npm run spec`);
273
273
  - **mutation-tested guards** — every defensive limit is rewritten in place and proven to fail the suite ([tools/mutate-guards.js](./tools/mutate-guards.js)).
274
274
 
275
- ## ⚠️ Known Divergences From node:http2 — Said Loudly
275
+ ## ⚠️ Known Divergences
276
276
 
277
277
  The core surface is implemented: server (stream + compat), client (`connect`),
278
- `performServerHandshake`, and server push (`pushStream` / PUSH_PROMISE reception). The
279
- remaining gaps against the documented `node:http2` API are enumerated below — each was read
280
- out of node's docs and confirmed against the current tree (a `in`-probe over live objects).
281
- None silently returns a wrong answer: a missing method is `undefined`, so calling it throws
282
- `TypeError`, never a fabricated result.
278
+ `performServerHandshake`, and server push (`pushStream` / PUSH_PROMISE reception).
279
+ None of the remaining gaps silently returns a wrong answer: a missing method is
280
+ `undefined`, so calling it throws `TypeError`, never a fabricated result.
283
281
 
284
- **Missing methods / properties** (the compat `(req, res)` request side is complete):
285
-
286
- - 🌊 **`ServerHttp2Stream` is not a `stream.Duplex`** — its base is `stream.Stream`, but `pipe()`, `read()`, `cork()/uncork()`, `setEncoding()` and the `readable*`/`writable*` getters are carried as methods/getters over the hand-rolled core. Deliberate: a Duplex base costs ~1.4 µs/req of intrinsic machinery ([OPTIMIZATION.md](./OPTIMIZATION.md) item 41). `on('data'/'end')`, `pause/resume`, `write/end`, `setTimeout`, `priority`, `sendTrailers` all work.
287
- - ⏱️ **`server.timeout`** getter is absent (`setTimeout()` is present).
288
-
289
- **Events not emitted:**
290
-
291
- - 🪤 **`'ready'`** on a stream (node emits it when the stream id is assigned).
292
-
293
- **Behavioural differences** (full reasoning in the header comment of the affected file and [AGENTS.md](./AGENTS.md) §10):
294
-
295
- - 🎛️ **Options accepted but ignored:** `headerHintTimeout`/`headerHintSize` (no 1xx informational-flood guard). `paddingStrategy` (0/1/2, with node's 8-octet-aligned and 255-octet-pad wire shapes) and `maxSessionMemory` (per-stream and retained-header budget with node's ENHANCE_YOUR_CALM refusal and callback-failure teardown) are now implemented; see [SECURITY.md](./SECURITY.md).
296
- - 🚪 The **graceful-close predicate**, the **spurious `200` on `end()` with no body**, a **response queued in the same batch as a refusal**, the **`COMPRESSION_ERROR` vs `FRAME_SIZE_ERROR`** verdict, the **teardown event order**, and **`req.pause()/read()` not slowing the peer** (credit is window-bounded, not per-`read()`) differ from node — each pinned as a KNOWN DIVERGENCE in the test suite.
282
+ Every known divergence — its scenario, node's measured behaviour, h2lean's
283
+ behaviour and the reason it is not implemented — is recorded in
284
+ [DIVERGENCES.md](./DIVERGENCES.md). That file is the single home for this
285
+ material; it is a decision record, not a to-do list.
297
286
 
298
287
  ## 📚 Documentation
299
288
 
300
289
  | Document | What it holds |
301
290
  |---|---|
302
291
  | [PERFORMANCE.md](./PERFORMANCE.md) | 🏎️ Benchmarks: methodology, full tables, caveats, re-run commands |
292
+ | [DIVERGENCES.md](./DIVERGENCES.md) | 🔀 Every known divergence from node, measured and explained |
303
293
  | [SECURITY.md](./SECURITY.md) | 🔒 Threat model, every hardening limit, known gaps — stated plainly |
304
294
  | [OPTIMIZATION.md](./OPTIMIZATION.md) | 🔬 All 35 measured optimization techniques (and rejected ones) |
305
295
  | [CHANGELOG.md](./CHANGELOG.md) | 📋 Release history, Keep-a-Changelog format |
@@ -103,6 +103,12 @@ const hdr = require('./headers');
103
103
 
104
104
  const EMPTY = Buffer.alloc(0);
105
105
 
106
+ // The compat layer's cached req.socket/res.socket Proxy, one per stream. node
107
+ // reserves this slot in its Http2Stream constructor (core.js:1343,2166) so the
108
+ // first `.socket` read only fills the slot instead of adding a property and
109
+ // changing the stream's hidden class. Server streams initialise it to null.
110
+ const kCompatSocket = Symbol('compatSocket');
111
+
106
112
  // node's Http2Stream sets no highWaterMark (internal/http2/core.js constructor passes only
107
113
  // allowHalfOpen/decodeStrings/autoDestroy), so its writableHighWaterMark is the default
108
114
  // Writable one -- 16384 on node 20, 65536 from 22 on. Read it off node itself once rather
@@ -667,22 +673,30 @@ function specType(v) {
667
673
  // ("must be of type number"), a non-integer number is ERR_OUT_OF_RANGE ("It must be an
668
674
  // integer"), and a code outside [0, 2^32-1] is ERR_OUT_OF_RANGE ("It must be >= 0 &&
669
675
  // <= 4294967295"). The callback's own message names "callback" and follows the same
670
- // determineSpecificType shapes (measured: string, null, number).
676
+ // determineSpecificType shapes (measured: string, null, number). node builds the
677
+ // validators off TypeError (ERR_INVALID_ARG_TYPE) and RangeError (ERR_OUT_OF_RANGE)
678
+ // in internal/errors.js, not off plain Error -- the class is observable on a
679
+ // caught throw (test/upstream/client-rststream-before-connect.js).
680
+ function rstValidatorErr(code, msg) {
681
+ const err = code === 'ERR_INVALID_ARG_TYPE' ? new TypeError(msg) : new RangeError(msg);
682
+ err.code = code;
683
+ return err;
684
+ }
671
685
  function validateRstCode(code, callback) {
672
686
  if (typeof code !== 'number') {
673
- throw errorOf('ERR_INVALID_ARG_TYPE',
687
+ throw rstValidatorErr('ERR_INVALID_ARG_TYPE',
674
688
  `The "code" argument must be of type number. Received ${specType(code)}`);
675
689
  }
676
690
  if (!Number.isInteger(code)) {
677
- throw errorOf('ERR_OUT_OF_RANGE',
691
+ throw rstValidatorErr('ERR_OUT_OF_RANGE',
678
692
  `The value of "code" is out of range. It must be an integer. Received ${code}`);
679
693
  }
680
694
  if (code < 0 || code > 4294967295) {
681
- throw errorOf('ERR_OUT_OF_RANGE',
695
+ throw rstValidatorErr('ERR_OUT_OF_RANGE',
682
696
  `The value of "code" is out of range. It must be >= 0 && <= 4294967295. Received ${code}`);
683
697
  }
684
698
  if (callback !== undefined && typeof callback !== 'function') {
685
- throw errorOf('ERR_INVALID_ARG_TYPE',
699
+ throw rstValidatorErr('ERR_INVALID_ARG_TYPE',
686
700
  `The "callback" argument must be of type function. Received ${specType(callback)}`);
687
701
  }
688
702
  }
@@ -1325,4 +1339,4 @@ function streamErrorOf(code) {
1325
1339
  }
1326
1340
 
1327
1341
 
1328
- module.exports = { Http2Stream, fs, frames, hdr, EMPTY, WRITABLE_HWM, READABLE_HWM, emitNT, emitCloseNT, emitDrainNT, emitErrorCloseNT, emitErrorOnlyNT, emitEndNT, wantTrailersNT, finishNT, emitEndCloseNT, emitCloseDeliveredNT, autoCloseNT, noopClose, FILE_CHUNK, isFileHandle, receivedArgType, argTypeError, propertyValueError, fdOptions, prepareResponseHeadersObject, errorOf, specType, validateRstCode, kEmpty, kEof, ASYNC_ITERATOR_PROTO, noop, abortError, validateObjectArg, validateFunctionArg, validateSignalArg, validateOperatorOptions, toIntegerOrInfinity, createStreamIterator, opMap, opFilter, opFlatMap, opDrop, opTake, streamErrorOf };
1342
+ module.exports = { Http2Stream, fs, frames, hdr, EMPTY, kCompatSocket, WRITABLE_HWM, READABLE_HWM, emitNT, emitCloseNT, emitDrainNT, emitErrorCloseNT, emitErrorOnlyNT, emitEndNT, wantTrailersNT, finishNT, emitEndCloseNT, emitCloseDeliveredNT, autoCloseNT, noopClose, FILE_CHUNK, isFileHandle, receivedArgType, argTypeError, propertyValueError, fdOptions, prepareResponseHeadersObject, errorOf, specType, validateRstCode, kEmpty, kEof, ASYNC_ITERATOR_PROTO, noop, abortError, validateObjectArg, validateFunctionArg, validateSignalArg, validateOperatorOptions, toIntegerOrInfinity, createStreamIterator, opMap, opFilter, opFlatMap, opDrop, opTake, streamErrorOf };
@@ -129,6 +129,7 @@
129
129
  const { EventEmitter } = require('node:events');
130
130
  const net = require('node:net');
131
131
  const tls = require('node:tls');
132
+ const { deprecate } = require('node:util');
132
133
  const f = require('../frames');
133
134
  const { Decoder, Encoder, HPackError } = require('../hpack');
134
135
  const FlatList = require('../flat-list');
@@ -142,6 +143,7 @@ const FLAT = new FlatList(64);
142
143
  const { nullProto, isFieldName, lowerName, neverNames, CONNECTION_SPECIFIC, SINGLE_VALUE_FIELDS,
143
144
  KSensitiveHeaders } = require('../headers');
144
145
  const { Http2ClientStream, AbortError } = require('./Http2ClientStream');
146
+ const { streamErrorOf } = require('../Http2Stream');
145
147
  const { pieceByteAt, pieceSlice, pieceConcat, pieceEquals } = require('../pieces');
146
148
  // The settings tables, defaults and buffer-path constants are the server's, reused
147
149
  // verbatim so a client and a server in this one library never disagree about what a
@@ -150,7 +152,8 @@ const {
150
152
  OUR_DEFAULTS, PEER_DEFAULTS, SETTINGS_BY_ID, ID_BY_SETTING, BODY_MIN, MAX_OUT_BATCH,
151
153
  STAGE_MIN, MAX_SHAPES, MAX_SEND_BLOCK, PRIORITY_SPECLEN,
152
154
  strictSingleValueFields, hashBlock, hashPieces, kBoundSession,
153
- proxySocketHandler, urlOrigin, parseAltSvc, parseOrigins, received, extError, checkPing,
155
+ proxySocketHandler, urlOrigin, parseAltSvc, parseOrigins, received, outOfRangeValue,
156
+ extError, checkPing,
154
157
  pingCancelled, checkSettings, buildSubmission, submissionValues, accumulateCustom,
155
158
  customView, checkRemoteCustomEntries
156
159
  } = require('../server/Http2ServerSession');
@@ -190,11 +193,13 @@ const DEFAULT_WINDOW = 65535;
190
193
  // carries). Re-running an uncached regex here would be the same work the response
191
194
  // path has already learned to skip.
192
195
 
193
- // Methods RFC 9113 asks a client not to send a body with; node ends the stream by
194
- // default for these (`isPayloadMeaningless(method)` in core.js).
196
+ // node's kNoPayloadMethods (internal/http2/util.js) is exactly DELETE, GET and
197
+ // HEAD. CONNECT leaves the writable half open so the tunnel can carry bytes;
198
+ // trailing CONNECT on END_STREAM stopped the peer from emitting 'connect'
199
+ // (test/upstream/client-connection-tunnelling). OPTIONS and TRACE are not in
200
+ // node's set either -- a request body on them is legal and must stay open.
195
201
  function payloadMeaningless(method) {
196
- return method === 'GET' || method === 'HEAD' || method === 'DELETE' || method === 'CONNECT'
197
- || method === 'OPTIONS' || method === 'TRACE';
202
+ return method === 'GET' || method === 'HEAD' || method === 'DELETE';
198
203
  }
199
204
 
200
205
  // assertIsObject + validateSettings live in lib/server/Http2ServerSession.js as checkSettings, beside checkPing:
@@ -206,6 +211,13 @@ function payloadMeaningless(method) {
206
211
  // measured position is unchanged (OPTIMIZATION.md item 36).
207
212
  const DEFAULT_METHOD = 'GET';
208
213
 
214
+ // node's request() deprecates the priority `weight` option with DEP0194
215
+ // (internal/http2/core.js setAndValidatePriorityOptions). A module-level
216
+ // util.deprecate shares node's process-wide codesWarned, so the warning fires
217
+ // once no matter how many sessions pass the option.
218
+ const deprecateWeight = deprecate(() => {},
219
+ 'Priority signaling has been deprecated as of RFC 9113.', 'DEP0194');
220
+
209
221
  // The estimate _encodeRequest just computed, read by its caller immediately after --
210
222
  // the result-slot shape lib/frames.js and lib/headers.js use, for the same reason: no
211
223
  // allocation per block. Only _encodeRequest writes it.
@@ -381,6 +393,10 @@ class Http2ClientSession extends EventEmitter {
381
393
  // the only value we can promise it credit against -- see _creditRecv(). At the
382
394
  // default this is the same number the old `>= advertised >> 1` test produced.
383
395
  this._connRecvWin = Math.min(this.localSettings.initialWindowSize, DEFAULT_WINDOW);
396
+ // The window last advertised through SETTINGS. node keeps it apart from the
397
+ // connection's available window: setLocalWindowSize lowers only this one, while
398
+ // the connection window never shrinks (core.js:1457, measured on v26.12.1).
399
+ this._effectiveLocalWindowSize = this.localSettings.initialWindowSize;
384
400
  // Streams that took DATA since the last credit pass. _creditRecv() visits only
385
401
  // these instead of scanning every open stream: with the default 100 concurrent
386
402
  // streams a download that touches one of them used to pay ~100 property reads per
@@ -630,9 +646,10 @@ class Http2ClientSession extends EventEmitter {
630
646
  // const sess = lite.connect(url, { createConnection: () => alreadyOpenSocket });
631
647
  // sess.on('connect', handler); // attached after emit already ran synchronously
632
648
  this._tick(() => {
633
- if (this.destroyed || this._closeEmitted) {
634
- return;
635
- }
649
+ // node's setupHandle emits 'connect' on the next tick even when close() or
650
+ // destroy() already happened while the socket was connecting (core.js:1110).
651
+ // The queued requests below keep their own liveness checks, so a session
652
+ // that died in the meantime submits nothing.
636
653
  this.emit('connect');
637
654
  if (this._queuedReq !== null) {
638
655
  const q = this._queuedReq;
@@ -645,8 +662,13 @@ class Http2ClientSession extends EventEmitter {
645
662
  // connecting (req.destroy(), an aborted signal) submits nothing: the
646
663
  // server never sees a stream for it. A session closed in the meantime
647
664
  // refuses the request instead, with the same GOAWAY_SESSION error
648
- // request() itself would have produced.
649
- if (r.stream.destroyed) {
665
+ // request() itself would have produced. A close() parked before connect
666
+ // is the exception: it is not destroyed and still owes the peer its
667
+ // HEADERS and RST_STREAM (core.js:2113-2122).
668
+ if (this.destroyed) {
669
+ break;
670
+ }
671
+ if (r.stream.destroyed && r.stream._pendingCloseCode === undefined) {
650
672
  continue;
651
673
  }
652
674
  if (this.closed) {
@@ -891,7 +913,15 @@ class Http2ClientSession extends EventEmitter {
891
913
  } else if (this.closed) {
892
914
  requestError = httpErr('ERR_HTTP2_GOAWAY_SESSION',
893
915
  'New streams cannot be created after receiving a GOAWAY');
894
- }
916
+ } else if (this._nextSid > 0x7fffffff) {
917
+ // node's binding refuses the 2^31st client id with STREAM_ID_NOT_AVAILABLE,
918
+ // which requestOnConnect reports on the stream (internal/http2/core.js).
919
+ // The reserved id is not advanced by a refusal -- state.nextStreamID stays
920
+ // 2147483649 after setNextStreamID(0x7fffffff) and two requests.
921
+ requestError = httpErr('ERR_HTTP2_OUT_OF_STREAMS',
922
+ 'No stream ID is available because maximum stream ID has been reached');
923
+ }
924
+ checkRequestOptions(options);
895
925
  // No defensive copy of options: node spreads it because it validates and
896
926
  // then MUTATES the copy (setAndValidatePriorityOptions, options.endStream =
897
927
  // ... in internal/http2/core.js request()); h2lean has no priority options
@@ -948,6 +978,48 @@ class Http2ClientSession extends EventEmitter {
948
978
  // applies neverIndex.includes(key) to pseudo lines as well).
949
979
  list.push(':method', method, neverList !== null && neverList.has(':method'));
950
980
  }
981
+ // A plain CONNECT (no :protocol) gets no default :path/:scheme/:authority:
982
+ // node's prepareRequestHeadersObject/Array (internal/http2/util.js) requires
983
+ // the application to supply :authority and refuses a :scheme or :path. An
984
+ // extended CONNECT with :protocol keeps the ordinary pseudo-header fills.
985
+ let plainConnect = false;
986
+ if (method === 'CONNECT') {
987
+ let hasProtocol = false;
988
+ for (let i = 0; i < list.length; i += 3) {
989
+ if (list[i] === ':protocol') {
990
+ hasProtocol = true;
991
+ break;
992
+ }
993
+ }
994
+ plainConnect = !hasProtocol;
995
+ }
996
+ if (plainConnect) {
997
+ let hasAuthority = false;
998
+ let hasScheme = false;
999
+ let hasPath = false;
1000
+ for (let i = 0; i < list.length; i += 3) {
1001
+ const key = list[i];
1002
+ if (key === ':authority') {
1003
+ hasAuthority = true;
1004
+ } else if (key === ':scheme') {
1005
+ hasScheme = true;
1006
+ } else if (key === ':path') {
1007
+ hasPath = true;
1008
+ }
1009
+ }
1010
+ if (!hasAuthority) {
1011
+ throw httpErr('ERR_HTTP2_CONNECT_AUTHORITY',
1012
+ ':authority header is required for CONNECT requests');
1013
+ }
1014
+ if (hasScheme) {
1015
+ throw httpErr('ERR_HTTP2_CONNECT_SCHEME',
1016
+ 'The :scheme header is forbidden for CONNECT requests');
1017
+ }
1018
+ if (hasPath) {
1019
+ throw httpErr('ERR_HTTP2_CONNECT_PATH',
1020
+ 'The :path header is forbidden for CONNECT requests');
1021
+ }
1022
+ }
951
1023
 
952
1024
  let endStream = options === undefined ? undefined : options.endStream;
953
1025
  if (endStream === undefined) {
@@ -959,7 +1031,11 @@ class Http2ClientSession extends EventEmitter {
959
1031
  // internal/http2/core.js:1902-1904); the getter folds it into the request map on read.
960
1032
  stream._sentSrc = headersParam;
961
1033
  this._trackClose(stream);
962
- this._nextSid += 2; // the id is reserved now, HEADERS may wait
1034
+ // A refusal reserves no id: node's binding never submits the request, so a
1035
+ // later request sees the same nextStreamID (client-onconnect-errors).
1036
+ if (requestError === undefined) {
1037
+ this._nextSid += 2; // the id is reserved now, HEADERS may wait
1038
+ }
963
1039
  // RFC 8336: a 421 (Misdirected Request) answer removes the origin that request
964
1040
  // was sent to from `originSet`. node records the origin on the stream at
965
1041
  // request() time -- `stream[kOrigin] = ${scheme}://${authority}` (core.js), where
@@ -1035,11 +1111,12 @@ class Http2ClientSession extends EventEmitter {
1035
1111
  // object across requests, the HPACK encoder produces identical bytes every time
1036
1112
  // after the dynamic table stabilises, and _sendRequest can use _blocks to replay
1037
1113
  // the encoded block without re-encoding. (The server's shareHeaders equivalent.)
1038
- const req = { stream, list, nl: neverList, end: endStream, hp: headersParam };
1114
+ const req = { stream, list, nl: neverList, end: endStream, hp: headersParam, plainConnect };
1039
1115
  if (requestError !== undefined) {
1040
1116
  // node's requestOnError: destroy the stream with the captured error on the
1041
- // next tick, and submit nothing. The id reserved above is never used -- the
1042
- // session is destroyed or past its GOAWAY mark, so no later request takes it.
1117
+ // next tick, and submit nothing. The id is never used here: a destroyed or
1118
+ // GOAWAYed session submits nothing, and at the ID ceiling no id was
1119
+ // reserved at all.
1043
1120
  this._tick(() => stream.destroy(requestError));
1044
1121
  } else if (this._started) {
1045
1122
  this._enqueue(req);
@@ -1088,7 +1165,20 @@ class Http2ClientSession extends EventEmitter {
1088
1165
  req.stream._opened = true;
1089
1166
  this._liveWire++;
1090
1167
  this._streams.set(req.stream.id, req.stream);
1091
- this._sendRequest(req.stream, req.list, req.nl, req.end, req.hp);
1168
+ this._sendRequest(req.stream, req.list, req.nl, req.end, req.hp, req.plainConnect);
1169
+ if (req.stream._pendingCloseCode !== undefined) {
1170
+ // node's finishCloseStream defers the reset to 'ready' for a stream closed
1171
+ // while pending (core.js:2113). _sendRequest has framed the HEADERS by now;
1172
+ // rstStream() would skip the stream because push(null) set _rEof and the
1173
+ // empty body set _endSent, so submit the frame here and retire the id the
1174
+ // same way rstStream does, before the stream's own teardown runs.
1175
+ const code = req.stream._pendingCloseCode;
1176
+ const body = Buffer.allocUnsafe(4);
1177
+ body.writeUInt32BE(code >>> 0, 0);
1178
+ this._frame(RST_STREAM, 0, req.stream.id, body, true);
1179
+ this._dropStream(req.stream.id);
1180
+ req.stream.destroy(streamErrorOf(code));
1181
+ }
1092
1182
  }
1093
1183
 
1094
1184
  // A slot just freed (a stream closed): start queued requests while the peer's
@@ -1197,7 +1287,7 @@ class Http2ClientSession extends EventEmitter {
1197
1287
  return bound;
1198
1288
  }
1199
1289
 
1200
- _sendRequest(stream, list, neverList, end, hp) {
1290
+ _sendRequest(stream, list, neverList, end, hp, plainConnect) {
1201
1291
  // Fill the pseudo-headers the application omitted, in the canonical order, then
1202
1292
  // hand the whole list to HPACK. node completes :path to '/', :scheme and
1203
1293
  // :authority from the session; we mirror that so `request({})` is a GET /.
@@ -1223,15 +1313,17 @@ class Http2ClientSession extends EventEmitter {
1223
1313
  block = cached.block;
1224
1314
  bound = cached.bound;
1225
1315
  } else {
1226
- if (!list.includes(':path')) {
1227
- list.push(':path', '/', neverList !== null && neverList.has(':path'));
1228
- }
1229
- if (!list.includes(':scheme')) {
1230
- list.push(':scheme', this._scheme, neverList !== null && neverList.has(':scheme'));
1231
- }
1232
- if (!list.includes(':authority')) {
1233
- list.push(':authority', this._authority,
1234
- neverList !== null && neverList.has(':authority'));
1316
+ if (!plainConnect) {
1317
+ if (!list.includes(':path')) {
1318
+ list.push(':path', '/', neverList !== null && neverList.has(':path'));
1319
+ }
1320
+ if (!list.includes(':scheme')) {
1321
+ list.push(':scheme', this._scheme, neverList !== null && neverList.has(':scheme'));
1322
+ }
1323
+ if (!list.includes(':authority')) {
1324
+ list.push(':authority', this._authority,
1325
+ neverList !== null && neverList.has(':authority'));
1326
+ }
1235
1327
  }
1236
1328
  orderPseudo(list); // in place: `list` is built by _addField for this request only
1237
1329
  bound = this._boundOfList(list);
@@ -1750,7 +1842,7 @@ class Http2ClientSession extends EventEmitter {
1750
1842
  // out: the release is due when EITHER the half-window step says so or the window the
1751
1843
  // peer may fill without hearing from us drops under the step.
1752
1844
  _creditRecv() {
1753
- const step = Math.min(this.localSettings.initialWindowSize, DEFAULT_WINDOW) >> 1;
1845
+ const step = Math.min(this._effectiveLocalWindowSize, DEFAULT_WINDOW) >> 1;
1754
1846
  const debt = this._debt;
1755
1847
  // Compacted in place: a stream whose bytes have not yet crossed the half-window
1756
1848
  // step STAYS in the list (and stays marked), because the credit it owes is only
@@ -3058,11 +3150,10 @@ class Http2ClientSession extends EventEmitter {
3058
3150
  this.goaway(code === undefined ? NO_ERROR : code);
3059
3151
  this._maybeClose();
3060
3152
  if (typeof cb === 'function') {
3061
- if (this._streams.size === 0) {
3062
- this._tick(cb);
3063
- } else {
3064
- this.once('close', cb);
3065
- }
3153
+ // node's close() always subscribes with once('close', cb) (core.js:1652):
3154
+ // the callback follows the session's 'close' event, even when no stream
3155
+ // was ever opened (test/upstream/client-shutdown-before-connect.test.js).
3156
+ this.once('close', cb);
3066
3157
  }
3067
3158
  }
3068
3159
 
@@ -3294,18 +3385,51 @@ class Http2ClientSession extends EventEmitter {
3294
3385
  if (this.destroyed) {
3295
3386
  throw httpErr('ERR_HTTP2_INVALID_SESSION', 'The session has been destroyed');
3296
3387
  }
3297
- this._nextSid = id; return this;
3388
+ // node's Http2Session.setNextStreamID (core.js:1444) runs validateNumber and
3389
+ // then ERR_OUT_OF_RANGE before touching the binding. The destroyed guard is
3390
+ // first there too, so a destroyed session still reports INVALID_SESSION.
3391
+ if (typeof id !== 'number') {
3392
+ throw extError('ERR_INVALID_ARG_TYPE',
3393
+ `The "id" argument must be of type number. Received ${received(id)}`);
3394
+ }
3395
+ if (id <= 0 || id > 0xffffffff) {
3396
+ const err = new RangeError('The value of "id" is out of range. '
3397
+ + `It must be > 0 and <= 4294967295. Received ${outOfRangeValue(id)}`);
3398
+ err.code = 'ERR_OUT_OF_RANGE';
3399
+ throw err;
3400
+ }
3401
+ this._nextSid = id;
3298
3402
  }
3299
3403
  setLocalWindowSize(size) {
3300
3404
  if (this.destroyed) {
3301
3405
  throw httpErr('ERR_HTTP2_INVALID_SESSION', 'The session has been destroyed');
3302
3406
  }
3303
- // RFC 9113 6.9.2: the change rescales the peer's send windows retroactively, so the
3304
- // window we maintain moves by the same delta rather than only applying to streams
3305
- // opened from here on -- and _creditRecv()'s threshold is derived from it per call.
3306
- this._connRecvWin += size - this.localSettings.initialWindowSize;
3307
- this.localSettings.initialWindowSize = size;
3308
- return this;
3407
+ // validateInt32(windowSize, 'windowSize', 0) in node's core.js:1457.
3408
+ if (typeof size !== 'number') {
3409
+ throw extError('ERR_INVALID_ARG_TYPE',
3410
+ `The "windowSize" argument must be of type number. Received ${received(size)}`);
3411
+ }
3412
+ if (!Number.isInteger(size)) {
3413
+ const err = new RangeError('The value of "windowSize" is out of range. '
3414
+ + `It must be an integer. Received ${outOfRangeValue(size)}`);
3415
+ err.code = 'ERR_OUT_OF_RANGE';
3416
+ throw err;
3417
+ }
3418
+ if (size < 0 || size > 0x7fffffff) {
3419
+ const err = new RangeError('The value of "windowSize" is out of range. '
3420
+ + `It must be >= 0 && <= 2147483647. Received ${outOfRangeValue(size)}`);
3421
+ err.code = 'ERR_OUT_OF_RANGE';
3422
+ throw err;
3423
+ }
3424
+ // core.js:1462 hands the size to nghttp2, which rescales the peer's send windows
3425
+ // retroactively (RFC 9113 6.9.2) but never reclaims the connection's available
3426
+ // credit: a decrease moves only the advertised window that _creditRecv()'s step
3427
+ // is derived from. Measured on v26.12.1: 2**20 then 20 reports 20/1048576/65535,
3428
+ // and a fresh session set to 20 reports 20/65535/65535.
3429
+ this._effectiveLocalWindowSize = size;
3430
+ if (size > this._connRecvWin) {
3431
+ this._connRecvWin = size;
3432
+ }
3309
3433
  }
3310
3434
 
3311
3435
  // ---- teardown ---------------------------------------------------------------
@@ -3438,7 +3562,12 @@ class Http2ClientSession extends EventEmitter {
3438
3562
  socket.uncork();
3439
3563
  }
3440
3564
  }
3441
- const err = httpErr('ERR_HTTP2_ERROR', reason);
3565
+ // node's C layer names the two fatal classes, not the frame that triggered
3566
+ // them: measured off v26.12.1, every fatal code reports 'Protocol error'
3567
+ // except FLOW_CONTROL_ERROR's 'Flow control error' (the GOAWAY debug string
3568
+ // still carries this frame's own reason).
3569
+ const err = httpErr('ERR_HTTP2_ERROR',
3570
+ code === FLOW_CONTROL_ERROR ? 'Flow control error' : 'Protocol error');
3442
3571
  err.http2Code = code;
3443
3572
  this.destroy(err);
3444
3573
  return false;
@@ -3537,10 +3666,10 @@ class Http2ClientSession extends EventEmitter {
3537
3666
  // are provided; the dynamic-table figures are reported live off the codecs.
3538
3667
  get state() {
3539
3668
  return {
3540
- effectiveLocalWindowSize: this.localSettings.initialWindowSize,
3669
+ effectiveLocalWindowSize: this._effectiveLocalWindowSize,
3541
3670
  effectiveRecvDataLength: 0,
3542
3671
  nextStreamID: this._nextSid,
3543
- localWindowSize: this.localSettings.initialWindowSize,
3672
+ localWindowSize: this._connRecvWin - this._connRecvUsed,
3544
3673
  lastProcStreamID: this._goawayLastStreamID === null ? 0 : this._goawayLastStreamID,
3545
3674
  remoteWindowSize: this._connSendWin,
3546
3675
  outboundQueueSize: this._outboundQueue.length,
@@ -3634,6 +3763,50 @@ function orderPseudo(list) {
3634
3763
  }
3635
3764
  }
3636
3765
 
3766
+ // node's ClientHttp2Session.request() validates the four request options before
3767
+ // it reserves a stream (internal/http2/core.js setAndValidatePriorityOptions and
3768
+ // validateBoolean(options.endStream, 'options.endStream')). h2lean ignores the
3769
+ // priority VALUES -- RFC 9113 removed priority signalling -- but the type checks
3770
+ // are public surface: a wrong type must throw node's error, not be accepted. The
3771
+ // checks are kept out of request() itself so the common no-options path pays for
3772
+ // one call with an immediate return.
3773
+ function checkRequestOptions(options) {
3774
+ if (options === undefined) {
3775
+ return;
3776
+ }
3777
+ if ('weight' in options) {
3778
+ deprecateWeight();
3779
+ }
3780
+ const parent = options.parent;
3781
+ if (parent !== undefined) {
3782
+ if (typeof parent !== 'number') {
3783
+ throw extError('ERR_INVALID_ARG_TYPE',
3784
+ `The "options.parent" property must be of type number. Received ${received(parent)}`);
3785
+ }
3786
+ if (parent < 0) {
3787
+ const err = new RangeError('The value of "options.parent" is out of range. '
3788
+ + `It must be >= 0. Received ${parent}`);
3789
+ err.code = 'ERR_OUT_OF_RANGE';
3790
+ throw err;
3791
+ }
3792
+ }
3793
+ const exclusive = options.exclusive;
3794
+ if (exclusive !== undefined && typeof exclusive !== 'boolean') {
3795
+ throw extError('ERR_INVALID_ARG_TYPE',
3796
+ `The "options.exclusive" property must be of type boolean. Received ${received(exclusive)}`);
3797
+ }
3798
+ const silent = options.silent;
3799
+ if (silent !== undefined && typeof silent !== 'boolean') {
3800
+ throw extError('ERR_INVALID_ARG_TYPE',
3801
+ `The "options.silent" property must be of type boolean. Received ${received(silent)}`);
3802
+ }
3803
+ const endStream = options.endStream;
3804
+ if (endStream !== undefined && typeof endStream !== 'boolean') {
3805
+ throw extError('ERR_INVALID_ARG_TYPE',
3806
+ `The "options.endStream" property must be of type boolean. Received ${received(endStream)}`);
3807
+ }
3808
+ }
3809
+
3637
3810
  function httpErr(code, msg) {
3638
3811
  const err = new Error(msg);
3639
3812
  err.code = code;