h2lean 0.19.8 → 0.19.13

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.
@@ -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:
@@ -205,6 +210,14 @@ function payloadMeaningless(method) {
205
210
  // supply one. Hoisted for reuse, not for speed: V8 interns string literals, so the
206
211
  // measured position is unchanged (OPTIMIZATION.md item 36).
207
212
  const DEFAULT_METHOD = 'GET';
213
+ const TOO_MANY_INVALID_FRAMES = 'Too many invalid HTTP/2 frames';
214
+
215
+ // node's request() deprecates the priority `weight` option with DEP0194
216
+ // (internal/http2/core.js setAndValidatePriorityOptions). A module-level
217
+ // util.deprecate shares node's process-wide codesWarned, so the warning fires
218
+ // once no matter how many sessions pass the option.
219
+ const deprecateWeight = deprecate(() => {},
220
+ 'Priority signaling has been deprecated as of RFC 9113.', 'DEP0194');
208
221
 
209
222
  // The estimate _encodeRequest just computed, read by its caller immediately after --
210
223
  // the result-slot shape lib/frames.js and lib/headers.js use, for the same reason: no
@@ -335,6 +348,14 @@ class Http2ClientSession extends EventEmitter {
335
348
  // counter in node, the count is rebuilt from the live streams here.
336
349
  this._maxReservedRemoteStreams = opts.maxReservedRemoteStreams === undefined
337
350
  ? 200 : opts.maxReservedRemoteStreams;
351
+ // nghttp2 keeps one session-lifetime invalid-frame budget on the client too
352
+ // (node_http2.cc: invalid_frame_count_, default 1000). The counted class on
353
+ // this path is zero-length DATA without END_STREAM; immediate protocol
354
+ // violations are fatal on their own. Measured on v26.12.1: the (limit+2)-th
355
+ // counted frame trips, valid frames never reset the count.
356
+ this._invalidFrames = 0;
357
+ this._maxInvalidFrames = typeof opts.maxSessionInvalidFrames === 'number'
358
+ ? opts.maxSessionInvalidFrames : 1000;
338
359
  this._streams = new Map();
339
360
  // Streams whose wire life is still open. A stream that took END_STREAM stops
340
361
  // counting against the peer's max_concurrent_streams as soon as nghttp2 closes
@@ -381,6 +402,24 @@ class Http2ClientSession extends EventEmitter {
381
402
  // the only value we can promise it credit against -- see _creditRecv(). At the
382
403
  // default this is the same number the old `>= advertised >> 1` test produced.
383
404
  this._connRecvWin = Math.min(this.localSettings.initialWindowSize, DEFAULT_WINDOW);
405
+ // The window last advertised through SETTINGS. node keeps it apart from the
406
+ // connection's available window: setLocalWindowSize lowers only this one, while
407
+ // the connection window never shrinks (core.js:1457, measured on v26.12.1).
408
+ this._effectiveLocalWindowSize = this.localSettings.initialWindowSize;
409
+ // node's connectionWindowSize option (IDX_OPTIONS_CONNECTION_WINDOW_SIZE in
410
+ // internal/http2/util.js) is the connection RECEIVE window, not the send window:
411
+ // it seeds the window we maintain and the size the state getter reports, and
412
+ // _start() grants the peer the delta above 65535 with one WINDOW_UPDATE(0).
413
+ // Node leaves the per-stream windows (SETTINGS_INITIAL_WINDOW_SIZE) and the
414
+ // connection SEND window at their defaults. connect() validates the option.
415
+ if (opts.connectionWindowSize !== undefined) {
416
+ // A WINDOW_UPDATE cannot shrink a live window, so the available connection
417
+ // credit starts at the default even when the option (and the size reported
418
+ // by effectiveLocalWindowSize) is smaller. Measured on v26.12.1: with 1024,
419
+ // localWindowSize stays 65535 while effectiveLocalWindowSize reports 1024.
420
+ this._connRecvWin = Math.max(DEFAULT_WINDOW, opts.connectionWindowSize);
421
+ this._effectiveLocalWindowSize = opts.connectionWindowSize;
422
+ }
384
423
  // Streams that took DATA since the last credit pass. _creditRecv() visits only
385
424
  // these instead of scanning every open stream: with the default 100 concurrent
386
425
  // streams a download that touches one of them used to pay ~100 property reads per
@@ -446,6 +485,9 @@ class Http2ClientSession extends EventEmitter {
446
485
  // the memcpy (BODY_MIN). See _frame/_need/_commit/_writePending, which mirror the
447
486
  // server's queue exactly.
448
487
  this._outQ = [];
488
+ // Bodies of requests whose HEADERS were staged in the current turn. Drained by
489
+ // _flush so every HEADERS of a burst precedes every DATA (see _flush).
490
+ this._bodyQ = null;
449
491
  this._stage = null;
450
492
  this._stageLen = 0; // bytes of _stage not yet queued
451
493
  this._stageCap = STAGE_MIN; // size of the next staging buffer
@@ -615,6 +657,17 @@ class Http2ClientSession extends EventEmitter {
615
657
  this._stageLen += PREFACE_LEN;
616
658
  this._outLen += PREFACE_LEN;
617
659
  this._sendSettings();
660
+ // node's connectionWindowSize raises the connection receive window above the
661
+ // 65535 default by granting the difference with one WINDOW_UPDATE(0) at setup
662
+ // (nghttp2_session_set_local_window_size on stream 0). A value at or below the
663
+ // default cannot shrink the live window: no update goes out (an increment must
664
+ // be positive), which is why the peer still reports 65535 on an upload.
665
+ const cws = this._opts.connectionWindowSize;
666
+ if (cws !== undefined && cws > DEFAULT_WINDOW) {
667
+ const wu = Buffer.allocUnsafe(4);
668
+ wu.writeUInt32BE(cws - DEFAULT_WINDOW, 0);
669
+ this._frame(WINDOW_UPDATE, 0, 0, wu, true);
670
+ }
618
671
  this._flush();
619
672
  if (preQueued.length !== 0) {
620
673
  this._outQ = preQueued;
@@ -630,9 +683,10 @@ class Http2ClientSession extends EventEmitter {
630
683
  // const sess = lite.connect(url, { createConnection: () => alreadyOpenSocket });
631
684
  // sess.on('connect', handler); // attached after emit already ran synchronously
632
685
  this._tick(() => {
633
- if (this.destroyed || this._closeEmitted) {
634
- return;
635
- }
686
+ // node's setupHandle emits 'connect' on the next tick even when close() or
687
+ // destroy() already happened while the socket was connecting (core.js:1110).
688
+ // The queued requests below keep their own liveness checks, so a session
689
+ // that died in the meantime submits nothing.
636
690
  this.emit('connect');
637
691
  if (this._queuedReq !== null) {
638
692
  const q = this._queuedReq;
@@ -645,8 +699,13 @@ class Http2ClientSession extends EventEmitter {
645
699
  // connecting (req.destroy(), an aborted signal) submits nothing: the
646
700
  // server never sees a stream for it. A session closed in the meantime
647
701
  // refuses the request instead, with the same GOAWAY_SESSION error
648
- // request() itself would have produced.
649
- if (r.stream.destroyed) {
702
+ // request() itself would have produced. A close() parked before connect
703
+ // is the exception: it is not destroyed and still owes the peer its
704
+ // HEADERS and RST_STREAM (core.js:2113-2122).
705
+ if (this.destroyed) {
706
+ break;
707
+ }
708
+ if (r.stream.destroyed && r.stream._pendingCloseCode === undefined) {
650
709
  continue;
651
710
  }
652
711
  if (this.closed) {
@@ -761,6 +820,25 @@ class Http2ClientSession extends EventEmitter {
761
820
  }
762
821
 
763
822
  _flush() {
823
+ // Bodies of requests framed in this turn wait until here. node's C++ submits every
824
+ // HEADERS produced by a run of request() calls before it pumps any queued body DATA
825
+ // (measured on v26.12.1 with two requests and end()/write()/end('x') bodies: HEADERS
826
+ // 1, HEADERS 3, then DATA 1 on the wire in all three shapes). Releasing the body in
827
+ // _afterRequestHeaders would instead put DATA 1 between the two HEADERS, so a peer
828
+ // with SETTINGS_MAX_CONCURRENT_STREAMS=1 frees the slot and dispatches a second
829
+ // 'stream' handler where node refuses the second stream (test/upstream/
830
+ // max-concurrent-streams.test.js).
831
+ if (this._bodyQ !== null) {
832
+ const q = this._bodyQ;
833
+ this._bodyQ = null;
834
+ // Frames produced by the pump belong to this flush: the write they schedule
835
+ // is the one just below, not a new microtask.
836
+ this._inBatch = true;
837
+ for (let i = 0; i < q.length; i++) {
838
+ q[i]._bodyDeferred = false;
839
+ this._pump(q[i]);
840
+ }
841
+ }
764
842
  // leaving a batch, whatever the reason: from here on frames are produced outside a
765
843
  // socket read and have to schedule their own write
766
844
  this._inBatch = false;
@@ -891,7 +969,15 @@ class Http2ClientSession extends EventEmitter {
891
969
  } else if (this.closed) {
892
970
  requestError = httpErr('ERR_HTTP2_GOAWAY_SESSION',
893
971
  'New streams cannot be created after receiving a GOAWAY');
894
- }
972
+ } else if (this._nextSid > 0x7fffffff) {
973
+ // node's binding refuses the 2^31st client id with STREAM_ID_NOT_AVAILABLE,
974
+ // which requestOnConnect reports on the stream (internal/http2/core.js).
975
+ // The reserved id is not advanced by a refusal -- state.nextStreamID stays
976
+ // 2147483649 after setNextStreamID(0x7fffffff) and two requests.
977
+ requestError = httpErr('ERR_HTTP2_OUT_OF_STREAMS',
978
+ 'No stream ID is available because maximum stream ID has been reached');
979
+ }
980
+ checkRequestOptions(options);
895
981
  // No defensive copy of options: node spreads it because it validates and
896
982
  // then MUTATES the copy (setAndValidatePriorityOptions, options.endStream =
897
983
  // ... in internal/http2/core.js request()); h2lean has no priority options
@@ -948,6 +1034,48 @@ class Http2ClientSession extends EventEmitter {
948
1034
  // applies neverIndex.includes(key) to pseudo lines as well).
949
1035
  list.push(':method', method, neverList !== null && neverList.has(':method'));
950
1036
  }
1037
+ // A plain CONNECT (no :protocol) gets no default :path/:scheme/:authority:
1038
+ // node's prepareRequestHeadersObject/Array (internal/http2/util.js) requires
1039
+ // the application to supply :authority and refuses a :scheme or :path. An
1040
+ // extended CONNECT with :protocol keeps the ordinary pseudo-header fills.
1041
+ let plainConnect = false;
1042
+ if (method === 'CONNECT') {
1043
+ let hasProtocol = false;
1044
+ for (let i = 0; i < list.length; i += 3) {
1045
+ if (list[i] === ':protocol') {
1046
+ hasProtocol = true;
1047
+ break;
1048
+ }
1049
+ }
1050
+ plainConnect = !hasProtocol;
1051
+ }
1052
+ if (plainConnect) {
1053
+ let hasAuthority = false;
1054
+ let hasScheme = false;
1055
+ let hasPath = false;
1056
+ for (let i = 0; i < list.length; i += 3) {
1057
+ const key = list[i];
1058
+ if (key === ':authority') {
1059
+ hasAuthority = true;
1060
+ } else if (key === ':scheme') {
1061
+ hasScheme = true;
1062
+ } else if (key === ':path') {
1063
+ hasPath = true;
1064
+ }
1065
+ }
1066
+ if (!hasAuthority) {
1067
+ throw httpErr('ERR_HTTP2_CONNECT_AUTHORITY',
1068
+ ':authority header is required for CONNECT requests');
1069
+ }
1070
+ if (hasScheme) {
1071
+ throw httpErr('ERR_HTTP2_CONNECT_SCHEME',
1072
+ 'The :scheme header is forbidden for CONNECT requests');
1073
+ }
1074
+ if (hasPath) {
1075
+ throw httpErr('ERR_HTTP2_CONNECT_PATH',
1076
+ 'The :path header is forbidden for CONNECT requests');
1077
+ }
1078
+ }
951
1079
 
952
1080
  let endStream = options === undefined ? undefined : options.endStream;
953
1081
  if (endStream === undefined) {
@@ -959,7 +1087,11 @@ class Http2ClientSession extends EventEmitter {
959
1087
  // internal/http2/core.js:1902-1904); the getter folds it into the request map on read.
960
1088
  stream._sentSrc = headersParam;
961
1089
  this._trackClose(stream);
962
- this._nextSid += 2; // the id is reserved now, HEADERS may wait
1090
+ // A refusal reserves no id: node's binding never submits the request, so a
1091
+ // later request sees the same nextStreamID (client-onconnect-errors).
1092
+ if (requestError === undefined) {
1093
+ this._nextSid += 2; // the id is reserved now, HEADERS may wait
1094
+ }
963
1095
  // RFC 8336: a 421 (Misdirected Request) answer removes the origin that request
964
1096
  // was sent to from `originSet`. node records the origin on the stream at
965
1097
  // request() time -- `stream[kOrigin] = ${scheme}://${authority}` (core.js), where
@@ -1035,11 +1167,12 @@ class Http2ClientSession extends EventEmitter {
1035
1167
  // object across requests, the HPACK encoder produces identical bytes every time
1036
1168
  // after the dynamic table stabilises, and _sendRequest can use _blocks to replay
1037
1169
  // the encoded block without re-encoding. (The server's shareHeaders equivalent.)
1038
- const req = { stream, list, nl: neverList, end: endStream, hp: headersParam };
1170
+ const req = { stream, list, nl: neverList, end: endStream, hp: headersParam, plainConnect };
1039
1171
  if (requestError !== undefined) {
1040
1172
  // 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.
1173
+ // next tick, and submit nothing. The id is never used here: a destroyed or
1174
+ // GOAWAYed session submits nothing, and at the ID ceiling no id was
1175
+ // reserved at all.
1043
1176
  this._tick(() => stream.destroy(requestError));
1044
1177
  } else if (this._started) {
1045
1178
  this._enqueue(req);
@@ -1088,7 +1221,25 @@ class Http2ClientSession extends EventEmitter {
1088
1221
  req.stream._opened = true;
1089
1222
  this._liveWire++;
1090
1223
  this._streams.set(req.stream.id, req.stream);
1091
- this._sendRequest(req.stream, req.list, req.nl, req.end, req.hp);
1224
+ this._sendRequest(req.stream, req.list, req.nl, req.end, req.hp, req.plainConnect);
1225
+ if (req.stream._pendingCloseCode !== undefined) {
1226
+ // node's finishCloseStream defers the reset to 'ready' for a stream closed
1227
+ // while pending (core.js:2113). _sendRequest has framed the HEADERS by now;
1228
+ // rstStream() would skip the stream because push(null) set _rEof and the
1229
+ // empty body set _endSent, so submit the frame here and retire the id the
1230
+ // same way rstStream does, before the stream's own teardown runs. The body is
1231
+ // still owed (close(NO_ERROR) after end()), so release it before the reset
1232
+ // retires the id.
1233
+ if (req.stream._bodyDeferred) {
1234
+ this._releaseBody(req.stream);
1235
+ }
1236
+ const code = req.stream._pendingCloseCode;
1237
+ const body = Buffer.allocUnsafe(4);
1238
+ body.writeUInt32BE(code >>> 0, 0);
1239
+ this._frame(RST_STREAM, 0, req.stream.id, body, true);
1240
+ this._dropStream(req.stream.id);
1241
+ req.stream.destroy(streamErrorOf(code));
1242
+ }
1092
1243
  }
1093
1244
 
1094
1245
  // A slot just freed (a stream closed): start queued requests while the peer's
@@ -1164,13 +1315,15 @@ class Http2ClientSession extends EventEmitter {
1164
1315
  if (key.charCodeAt(0) === 58 /* : */) {
1165
1316
  if (key !== ':method' && key !== ':path' && key !== ':scheme' && key !== ':authority'
1166
1317
  && key !== ':protocol') {
1167
- throw httpErr('ERR_HTTP2_PSEUDOHEADER_NOT_ALLOWED', `cannot send ${key}`);
1318
+ throw httpErr('ERR_HTTP2_INVALID_PSEUDOHEADER',
1319
+ `"${key}" is an invalid pseudoheader or is used incorrectly`, TypeError);
1168
1320
  }
1169
1321
  list.push(key, String(isArray ? rawValue[0] : rawValue), never);
1170
1322
  return;
1171
1323
  }
1172
1324
  if (!isFieldName(key)) {
1173
- throw httpErr('ERR_INVALID_HTTP_TOKEN', `${key} is an invalid header token`);
1325
+ throw httpErr('ERR_INVALID_HTTP_TOKEN',
1326
+ `Header name must be a valid HTTP token ["${key}"]`, TypeError);
1174
1327
  }
1175
1328
  if (CONNECTION_SPECIFIC.has(key)) {
1176
1329
  throw httpErr('ERR_HTTP2_INVALID_CONNECTION_HEADERS',
@@ -1197,7 +1350,7 @@ class Http2ClientSession extends EventEmitter {
1197
1350
  return bound;
1198
1351
  }
1199
1352
 
1200
- _sendRequest(stream, list, neverList, end, hp) {
1353
+ _sendRequest(stream, list, neverList, end, hp, plainConnect) {
1201
1354
  // Fill the pseudo-headers the application omitted, in the canonical order, then
1202
1355
  // hand the whole list to HPACK. node completes :path to '/', :scheme and
1203
1356
  // :authority from the session; we mirror that so `request({})` is a GET /.
@@ -1223,15 +1376,17 @@ class Http2ClientSession extends EventEmitter {
1223
1376
  block = cached.block;
1224
1377
  bound = cached.bound;
1225
1378
  } 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'));
1379
+ if (!plainConnect) {
1380
+ if (!list.includes(':path')) {
1381
+ list.push(':path', '/', neverList !== null && neverList.has(':path'));
1382
+ }
1383
+ if (!list.includes(':scheme')) {
1384
+ list.push(':scheme', this._scheme, neverList !== null && neverList.has(':scheme'));
1385
+ }
1386
+ if (!list.includes(':authority')) {
1387
+ list.push(':authority', this._authority,
1388
+ neverList !== null && neverList.has(':authority'));
1389
+ }
1235
1390
  }
1236
1391
  orderPseudo(list); // in place: `list` is built by _addField for this request only
1237
1392
  bound = this._boundOfList(list);
@@ -1260,15 +1415,39 @@ class Http2ClientSession extends EventEmitter {
1260
1415
  this._afterRequestHeaders(stream);
1261
1416
  }
1262
1417
 
1263
- // HEADERS is now queued; release any body the application wrote before the socket
1264
- // connected (or before this queued request was framed). The DATA frames land in _out
1265
- // behind the HEADERS, so the wire order stays HEADERS -> DATA.
1418
+ // Release a body parked for the flush ahead of a local stream close (NO_ERROR
1419
+ // after end()). The body is still owed to the peer; only the write() queue the
1420
+ // close drops is what this settles.
1421
+ _releaseBody(stream) {
1422
+ if (!stream._bodyDeferred) {
1423
+ return;
1424
+ }
1425
+ stream._bodyDeferred = false;
1426
+ if (this._bodyQ !== null) {
1427
+ const i = this._bodyQ.indexOf(stream);
1428
+ if (i !== -1) {
1429
+ this._bodyQ.splice(i, 1);
1430
+ }
1431
+ }
1432
+ const was = this._inBatch;
1433
+ this._inBatch = true;
1434
+ this._pump(stream);
1435
+ this._inBatch = was;
1436
+ }
1437
+
1438
+ // HEADERS is now queued. The application may still write to the stream later in
1439
+ // this same turn; node's C++ submits every HEADERS of such a burst before any body
1440
+ // DATA, so hold this stream's pump until _flush (which runs after the turn).
1266
1441
  _afterRequestHeaders(stream) {
1267
1442
  stream._headersSent = true;
1268
1443
  stream.headersSent = true;
1269
- if (stream._pending !== null || stream._finalCb !== null) {
1270
- this._pump(stream);
1444
+ if (this._bodyQ === null) {
1445
+ this._bodyQ = [stream];
1446
+ } else {
1447
+ this._bodyQ.push(stream);
1271
1448
  }
1449
+ stream._bodyDeferred = true;
1450
+ this._schedule();
1272
1451
  }
1273
1452
 
1274
1453
  _encodeRequest(list) {
@@ -1456,6 +1635,12 @@ class Http2ClientSession extends EventEmitter {
1456
1635
  // Flow-controlled send for the writable half of a stream. Called from the Duplex's
1457
1636
  // _write/_final and again from WINDOW_UPDATE / SETTINGS to resume a stalled body.
1458
1637
  _pump(stream) {
1638
+ // A body written in the same turn as the request's HEADERS waits for _flush,
1639
+ // which releases it behind every HEADERS of that turn (node's frame order).
1640
+ // Once released the flag is clear and later writes pump inline as before.
1641
+ if (stream._bodyDeferred) {
1642
+ return;
1643
+ }
1459
1644
  // The peer reset this stream. nghttp2 refuses DATA and HEADERS on a closed stream
1460
1645
  // ("After calling close ... no DATA and HEADERS frames may be sent",
1461
1646
  // internal/http2/core.js), but closeStream called end() anyway, so the Duplex still
@@ -1522,6 +1707,12 @@ class Http2ClientSession extends EventEmitter {
1522
1707
  break; // a further write may follow
1523
1708
  }
1524
1709
  }
1710
+ // The write callback asked _driveW for the next chunk. In the trampoline that
1711
+ // request is deferred to the active loop, so do not finalize END_STREAM here
1712
+ // while queued bytes are still owed -- the outer loop frames them first.
1713
+ if (stream._driveAgain) {
1714
+ return;
1715
+ }
1525
1716
  // Everything is framed and we are finalizing: close the message with END_STREAM,
1526
1717
  // unless the GET put it on HEADERS already.
1527
1718
  if (stream._pending === null && stream._finalCb !== null && stream._writeCb === null
@@ -1750,7 +1941,15 @@ class Http2ClientSession extends EventEmitter {
1750
1941
  // out: the release is due when EITHER the half-window step says so or the window the
1751
1942
  // peer may fill without hearing from us drops under the step.
1752
1943
  _creditRecv() {
1753
- const step = Math.min(this.localSettings.initialWindowSize, DEFAULT_WINDOW) >> 1;
1944
+ // The per-stream step stays the conservative half of the smaller of what we
1945
+ // advertise and the 65535 a peer runs with until it reads our SETTINGS:
1946
+ // connectionWindowSize grows the CONNECTION window only, never a stream's
1947
+ // (measured on node: with a 2^21 connection window a stream still releases at
1948
+ // 32767 octets). The connection step is half the window we actually maintain --
1949
+ // with the option that is half the option, node's measured cadence, because the
1950
+ // one setup WINDOW_UPDATE grants the peer that window without waiting for SETTINGS.
1951
+ const streamStep = Math.min(this.localSettings.initialWindowSize, DEFAULT_WINDOW) >> 1;
1952
+ const step = this._effectiveLocalWindowSize >> 1;
1754
1953
  const debt = this._debt;
1755
1954
  // Compacted in place: a stream whose bytes have not yet crossed the half-window
1756
1955
  // step STAYS in the list (and stays marked), because the credit it owes is only
@@ -1759,7 +1958,7 @@ class Http2ClientSession extends EventEmitter {
1759
1958
  let k = 0;
1760
1959
  for (let i = 0; i < debt.length; i++) {
1761
1960
  const stream = debt[i];
1762
- if (stream._recvUsed >= step) {
1961
+ if (stream._recvUsed >= streamStep) {
1763
1962
  const inc = stream._recvUsed;
1764
1963
  stream._recvUsed = 0;
1765
1964
  stream._debtMarked = false;
@@ -2068,6 +2267,19 @@ class Http2ClientSession extends EventEmitter {
2068
2267
  if (id === 0x2) {
2069
2268
  this._fatal(PROTOCOL_ERROR, 'SETTINGS_ENABLE_PUSH from server'); return;
2070
2269
  }
2270
+ // Extended CONNECT cannot be turned off once the peer advertised it. node's
2271
+ // client ends the session with ERR_HTTP2_ERROR "Protocol error" when a server
2272
+ // sends SETTINGS_ENABLE_CONNECT_PROTOCOL=0 after having sent 1 (measured,
2273
+ // test/upstream/connect-method-extended-cant-turn-off.test.js). The fatal is
2274
+ // deferred to an immediate: the SETTINGS frame must finish -- 'remoteSettings'
2275
+ // still reports the value it had when the request was submitted -- and a tick
2276
+ // would run before the request's promise microtasks and report
2277
+ // ERR_HTTP2_INVALID_SESSION instead of node's error. _fatal() supplies the
2278
+ // GOAWAY, the session error and the request error with rstCode 2.
2279
+ if (id === 0x8 && value === 0 && seen.enableConnectProtocol === true) {
2280
+ setImmediate(() => this._fatal(PROTOCOL_ERROR,
2281
+ 'SETTINGS: server attempted to disable SETTINGS_ENABLE_CONNECT_PROTOCOL'));
2282
+ }
2071
2283
  // The two boolean settings land in remoteSettings as booleans, the way node's
2072
2284
  // getSettings turns them (`enablePush: !!slot`, `enableConnectProtocol: !!slot`,
2073
2285
  // internal/http2/util.js): the wire is a uint32, and handing the raw 0/1 to the
@@ -2447,7 +2659,11 @@ class Http2ClientSession extends EventEmitter {
2447
2659
  ? hit.block.equals(block)
2448
2660
  : pieceEquals(hit.block, pieces, from, to))) {
2449
2661
  this._shapeHits++;
2450
- fields = hit.flat;
2662
+ // The cached flat array is shared by every response of this shape. The
2663
+ // stream hands it out as the third 'response' argument (rawHeaders), which
2664
+ // the application may mutate, so each response gets its own copy. On a
2665
+ // decode the field list is already a per-response slice and needs none.
2666
+ fields = hit.flat.slice();
2451
2667
  fcount = fields.length;
2452
2668
  blockFlags = hit.flags;
2453
2669
  } else {
@@ -2461,8 +2677,10 @@ class Http2ClientSession extends EventEmitter {
2461
2677
  blockFlags = this._decoder.neverCount > 0 ? this._decoder.neverFlags : null;
2462
2678
  // The field list the stream holds must outlive this decode: the
2463
2679
  // scratch's backing array is cleared in place by the next one. The copy
2464
- // that caches the shape serves the stream too; without a cache entry
2465
- // the copy is the stream's own.
2680
+ // that caches the shape is a separate snapshot -- handing the same array
2681
+ // to the stream would let a 'response'/'push' listener mutate the cache
2682
+ // entry and poison every later response of that shape. Without a cache
2683
+ // entry the copy is the stream's own.
2466
2684
  let copy = null;
2467
2685
  if (shapes !== null) {
2468
2686
  if (++this._shapeMisses > 64 && this._shapeHits * 4 < this._shapeMisses) {
@@ -2481,7 +2699,7 @@ class Http2ClientSession extends EventEmitter {
2481
2699
  });
2482
2700
  }
2483
2701
  }
2484
- fields = copy !== null ? copy : fields.slice(0, fcount);
2702
+ fields = copy !== null ? copy.slice() : fields.slice(0, fcount);
2485
2703
  }
2486
2704
  } catch (err) {
2487
2705
  if (err instanceof HPackError) {
@@ -2655,6 +2873,17 @@ class Http2ClientSession extends EventEmitter {
2655
2873
  if (stream === undefined) {
2656
2874
  return;
2657
2875
  }
2876
+ // A zero-length DATA without END_STREAM is one of the two frame classes nghttp2
2877
+ // counts against maxSessionInvalidFrames (node_http2.cc HandleDataFrame). On the
2878
+ // trip the stream and the session both report node's custom error code and the
2879
+ // session answers GOAWAY(INTERNAL_ERROR) with no debug data.
2880
+ if (l === 0 && (flags & F_END_STREAM) === 0 && this._recordInvalidFrame()) {
2881
+ const err = httpErr('ERR_HTTP2_TOO_MANY_INVALID_FRAMES', TOO_MANY_INVALID_FRAMES);
2882
+ stream.destroy(err);
2883
+ this._fatal(INTERNAL_ERROR, '', 'ERR_HTTP2_TOO_MANY_INVALID_FRAMES',
2884
+ TOO_MANY_INVALID_FRAMES);
2885
+ return this._open;
2886
+ }
2658
2887
  // Book the consumed bytes as credit owed to BOTH windows ahead of the hand-over:
2659
2888
  // a synchronous consumer inside the 'data' event must see the window already
2660
2889
  // shrunken, node's shape (16384 consumed reads 49151 from the state getter at
@@ -2985,7 +3214,7 @@ class Http2ClientSession extends EventEmitter {
2985
3214
  if (code === undefined) {
2986
3215
  code = NO_ERROR;
2987
3216
  }
2988
- if (lastStreamID === undefined || lastStreamID === null) {
3217
+ if (lastStreamID === undefined || lastStreamID === null || lastStreamID <= 0) {
2989
3218
  // node's goaway() defaults lastStreamID to 0 and the C layer substitutes
2990
3219
  // nghttp2_session_get_last_proc_stream_id (src/node_http2.cc Http2Session::Goaway:
2991
3220
  // `if (lastStreamID <= 0) lastStreamID = ...get_last_proc_stream_id`). For a
@@ -2996,14 +3225,24 @@ class Http2ClientSession extends EventEmitter {
2996
3225
  // graceful close() echo after the peer's GOAWAY then killed the peer's open
2997
3226
  // stream (measured on live node: its client sends last=0,
2998
3227
  // h2lean sent last=1 and the node server answered ERR_HTTP2_ERROR).
3228
+ // The C++ substitution also applies to an explicitly non-positive id
3229
+ // (node_http2.cc Http2Session::Goaway), so -1 is not sent as 0xffffffff.
2999
3230
  lastStreamID = this._maxPushSid;
3000
3231
  }
3001
- const tail = reason ? Buffer.byteLength(reason) : 0;
3002
- const body = Buffer.alloc(8 + tail);
3232
+ // node accepts Buffer and any TypedArray/DataView as opaqueData; keep the
3233
+ // older string form accepted here too (see the server's sendGoaway).
3234
+ let opaque;
3235
+ if (reason !== undefined && reason !== null) {
3236
+ opaque = ArrayBuffer.isView(reason)
3237
+ ? Buffer.from(reason.buffer, reason.byteOffset, reason.byteLength)
3238
+ : Buffer.from(String(reason), 'latin1');
3239
+ }
3240
+ const tail = opaque === undefined ? 0 : opaque.length;
3241
+ const body = Buffer.allocUnsafe(8 + tail);
3003
3242
  body.writeUInt32BE(lastStreamID >>> 0, 0);
3004
3243
  body.writeUInt32BE(code >>> 0, 4);
3005
3244
  if (tail) {
3006
- body.write(reason, 8);
3245
+ opaque.copy(body, 8);
3007
3246
  }
3008
3247
  this._frame(GOAWAY, 0, 0, body, true);
3009
3248
  // No closed marking here: node's goaway() (core.js:1602-1618) validates and submits
@@ -3058,11 +3297,10 @@ class Http2ClientSession extends EventEmitter {
3058
3297
  this.goaway(code === undefined ? NO_ERROR : code);
3059
3298
  this._maybeClose();
3060
3299
  if (typeof cb === 'function') {
3061
- if (this._streams.size === 0) {
3062
- this._tick(cb);
3063
- } else {
3064
- this.once('close', cb);
3065
- }
3300
+ // node's close() always subscribes with once('close', cb) (core.js:1652):
3301
+ // the callback follows the session's 'close' event, even when no stream
3302
+ // was ever opened (test/upstream/client-shutdown-before-connect.test.js).
3303
+ this.once('close', cb);
3066
3304
  }
3067
3305
  }
3068
3306
 
@@ -3294,18 +3532,51 @@ class Http2ClientSession extends EventEmitter {
3294
3532
  if (this.destroyed) {
3295
3533
  throw httpErr('ERR_HTTP2_INVALID_SESSION', 'The session has been destroyed');
3296
3534
  }
3297
- this._nextSid = id; return this;
3535
+ // node's Http2Session.setNextStreamID (core.js:1444) runs validateNumber and
3536
+ // then ERR_OUT_OF_RANGE before touching the binding. The destroyed guard is
3537
+ // first there too, so a destroyed session still reports INVALID_SESSION.
3538
+ if (typeof id !== 'number') {
3539
+ throw extError('ERR_INVALID_ARG_TYPE',
3540
+ `The "id" argument must be of type number. Received ${received(id)}`);
3541
+ }
3542
+ if (id <= 0 || id > 0xffffffff) {
3543
+ const err = new RangeError('The value of "id" is out of range. '
3544
+ + `It must be > 0 and <= 4294967295. Received ${outOfRangeValue(id)}`);
3545
+ err.code = 'ERR_OUT_OF_RANGE';
3546
+ throw err;
3547
+ }
3548
+ this._nextSid = id;
3298
3549
  }
3299
3550
  setLocalWindowSize(size) {
3300
3551
  if (this.destroyed) {
3301
3552
  throw httpErr('ERR_HTTP2_INVALID_SESSION', 'The session has been destroyed');
3302
3553
  }
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;
3554
+ // validateInt32(windowSize, 'windowSize', 0) in node's core.js:1457.
3555
+ if (typeof size !== 'number') {
3556
+ throw extError('ERR_INVALID_ARG_TYPE',
3557
+ `The "windowSize" argument must be of type number. Received ${received(size)}`);
3558
+ }
3559
+ if (!Number.isInteger(size)) {
3560
+ const err = new RangeError('The value of "windowSize" is out of range. '
3561
+ + `It must be an integer. Received ${outOfRangeValue(size)}`);
3562
+ err.code = 'ERR_OUT_OF_RANGE';
3563
+ throw err;
3564
+ }
3565
+ if (size < 0 || size > 0x7fffffff) {
3566
+ const err = new RangeError('The value of "windowSize" is out of range. '
3567
+ + `It must be >= 0 && <= 2147483647. Received ${outOfRangeValue(size)}`);
3568
+ err.code = 'ERR_OUT_OF_RANGE';
3569
+ throw err;
3570
+ }
3571
+ // core.js:1462 hands the size to nghttp2, which rescales the peer's send windows
3572
+ // retroactively (RFC 9113 6.9.2) but never reclaims the connection's available
3573
+ // credit: a decrease moves only the advertised window that _creditRecv()'s step
3574
+ // is derived from. Measured on v26.12.1: 2**20 then 20 reports 20/1048576/65535,
3575
+ // and a fresh session set to 20 reports 20/65535/65535.
3576
+ this._effectiveLocalWindowSize = size;
3577
+ if (size > this._connRecvWin) {
3578
+ this._connRecvWin = size;
3579
+ }
3309
3580
  }
3310
3581
 
3311
3582
  // ---- teardown ---------------------------------------------------------------
@@ -3407,7 +3678,11 @@ class Http2ClientSession extends EventEmitter {
3407
3678
  this._maybeClose();
3408
3679
  }
3409
3680
 
3410
- _fatal(code, reason) {
3681
+ _recordInvalidFrame() {
3682
+ return this._invalidFrames++ > this._maxInvalidFrames;
3683
+ }
3684
+
3685
+ _fatal(code, reason, errCode, errMessage) {
3411
3686
  if (!this._open) {
3412
3687
  return false;
3413
3688
  }
@@ -3438,7 +3713,13 @@ class Http2ClientSession extends EventEmitter {
3438
3713
  socket.uncork();
3439
3714
  }
3440
3715
  }
3441
- const err = httpErr('ERR_HTTP2_ERROR', reason);
3716
+ // node's C layer names the two fatal classes, not the frame that triggered
3717
+ // them: measured off v26.12.1, every fatal code reports 'Protocol error'
3718
+ // except FLOW_CONTROL_ERROR's 'Flow control error' (the GOAWAY debug string
3719
+ // still carries this frame's own reason).
3720
+ const err = httpErr(errCode !== undefined ? errCode : 'ERR_HTTP2_ERROR',
3721
+ errMessage !== undefined ? errMessage
3722
+ : (code === FLOW_CONTROL_ERROR ? 'Flow control error' : 'Protocol error'));
3442
3723
  err.http2Code = code;
3443
3724
  this.destroy(err);
3444
3725
  return false;
@@ -3537,10 +3818,10 @@ class Http2ClientSession extends EventEmitter {
3537
3818
  // are provided; the dynamic-table figures are reported live off the codecs.
3538
3819
  get state() {
3539
3820
  return {
3540
- effectiveLocalWindowSize: this.localSettings.initialWindowSize,
3821
+ effectiveLocalWindowSize: this._effectiveLocalWindowSize,
3541
3822
  effectiveRecvDataLength: 0,
3542
3823
  nextStreamID: this._nextSid,
3543
- localWindowSize: this.localSettings.initialWindowSize,
3824
+ localWindowSize: this._connRecvWin - this._connRecvUsed,
3544
3825
  lastProcStreamID: this._goawayLastStreamID === null ? 0 : this._goawayLastStreamID,
3545
3826
  remoteWindowSize: this._connSendWin,
3546
3827
  outboundQueueSize: this._outboundQueue.length,
@@ -3634,8 +3915,54 @@ function orderPseudo(list) {
3634
3915
  }
3635
3916
  }
3636
3917
 
3637
- function httpErr(code, msg) {
3638
- const err = new Error(msg);
3918
+ // node's ClientHttp2Session.request() validates the four request options before
3919
+ // it reserves a stream (internal/http2/core.js setAndValidatePriorityOptions and
3920
+ // validateBoolean(options.endStream, 'options.endStream')). h2lean ignores the
3921
+ // priority VALUES -- RFC 9113 removed priority signalling -- but the type checks
3922
+ // are public surface: a wrong type must throw node's error, not be accepted. The
3923
+ // checks are kept out of request() itself so the common no-options path pays for
3924
+ // one call with an immediate return.
3925
+ function checkRequestOptions(options) {
3926
+ if (options === undefined) {
3927
+ return;
3928
+ }
3929
+ if ('weight' in options) {
3930
+ deprecateWeight();
3931
+ }
3932
+ const parent = options.parent;
3933
+ if (parent !== undefined) {
3934
+ if (typeof parent !== 'number') {
3935
+ throw extError('ERR_INVALID_ARG_TYPE',
3936
+ `The "options.parent" property must be of type number. Received ${received(parent)}`);
3937
+ }
3938
+ if (parent < 0) {
3939
+ const err = new RangeError('The value of "options.parent" is out of range. '
3940
+ + `It must be >= 0. Received ${parent}`);
3941
+ err.code = 'ERR_OUT_OF_RANGE';
3942
+ throw err;
3943
+ }
3944
+ }
3945
+ const exclusive = options.exclusive;
3946
+ if (exclusive !== undefined && typeof exclusive !== 'boolean') {
3947
+ throw extError('ERR_INVALID_ARG_TYPE',
3948
+ `The "options.exclusive" property must be of type boolean. Received ${received(exclusive)}`);
3949
+ }
3950
+ const silent = options.silent;
3951
+ if (silent !== undefined && typeof silent !== 'boolean') {
3952
+ throw extError('ERR_INVALID_ARG_TYPE',
3953
+ `The "options.silent" property must be of type boolean. Received ${received(silent)}`);
3954
+ }
3955
+ const endStream = options.endStream;
3956
+ if (endStream !== undefined && typeof endStream !== 'boolean') {
3957
+ throw extError('ERR_INVALID_ARG_TYPE',
3958
+ `The "options.endStream" property must be of type boolean. Received ${received(endStream)}`);
3959
+ }
3960
+ }
3961
+
3962
+ // node's internal/errors.js gives these two codes fixed classes; the default stays
3963
+ // Error for the many other callers.
3964
+ function httpErr(code, msg, Ctor = Error) {
3965
+ const err = new Ctor(msg);
3639
3966
  err.code = code;
3640
3967
  return err;
3641
3968
  }