h2lean 0.19.9 → 0.19.14

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/index.js CHANGED
@@ -82,15 +82,15 @@ function getUnpackedSettings(buf, options) {
82
82
  err.code = 'ERR_HTTP2_INVALID_PACKED_SETTINGS_LENGTH';
83
83
  throw err;
84
84
  }
85
- // The octets are read through a Buffer over the same memory: a Uint8Array is the same
86
- // bytes, and nothing is copied either way.
87
- const src = Buffer.isBuffer(buf)
88
- ? buf
89
- : Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
85
+ // node passes the view straight to internal/buffer's readUInt16BE/readUInt32BE, which
86
+ // index the view by element. For a Buffer (a Uint8Array) element and octet coincide; for
87
+ // a wider typed array node reads word-sized values. Match that instead of wrapping the
88
+ // view in a Buffer, which would change a Uint16Array's meaning (getpackedsettings.test.js).
90
89
  const out = {};
91
90
  for (let i = 0; i + 6 <= buf.length; i += 6) {
92
- const id = src.readUInt16BE(i);
93
- const value = src.readUInt32BE(i + 2);
91
+ const id = buf[i] * 2 ** 8 + buf[i + 1];
92
+ const value = buf[i + 2] * 2 ** 24 + buf[i + 3] * 2 ** 16 +
93
+ buf[i + 4] * 2 ** 8 + buf[i + 5];
94
94
  switch (id) {
95
95
  case 1: out.headerTableSize = value; break;
96
96
  case 2: out.enablePush = value !== 0; break;
@@ -163,11 +163,15 @@ const {
163
163
  WINDOW_UPDATE, CONTINUATION, ALTSVC, ORIGIN,
164
164
  F_END_STREAM, F_ACK, F_END_HEADERS, F_PADDED, F_PRIORITY,
165
165
  NO_ERROR, PROTOCOL_ERROR, INTERNAL_ERROR, FLOW_CONTROL_ERROR, FRAME_SIZE_ERROR, COMPRESSION_ERROR, CANCEL, REFUSED_STREAM,
166
+ ENHANCE_YOUR_CALM,
166
167
  HEADER_LEN, PREFACE, PREFACE_LEN, readHeader, writeHeader, trimPadding
167
168
  } = f;
168
169
 
169
170
  const MAX_SETTINGS_ENTRIES = 32; // CVE-2020-11080; same bound as the server
170
171
  const MAX_CONTINUATIONS = 8; // CVE-2024-28182; same bound as the server
172
+ // node's default outstanding-ping cap (initializeOptions, internal/http2/util.js),
173
+ // mirrored from the server (lib/server/Http2ServerSession.js).
174
+ const DEFAULT_MAX_OUTSTANDING_PINGS = 10;
171
175
  // Cap on the pool of completed staging buffers, so what one client retains for reuse is
172
176
  // bounded independently of how many batches it sends. Same number as the server's.
173
177
  const MAX_STAGE_POOL = 32;
@@ -210,6 +214,7 @@ function payloadMeaningless(method) {
210
214
  // supply one. Hoisted for reuse, not for speed: V8 interns string literals, so the
211
215
  // measured position is unchanged (OPTIMIZATION.md item 36).
212
216
  const DEFAULT_METHOD = 'GET';
217
+ const TOO_MANY_INVALID_FRAMES = 'Too many invalid HTTP/2 frames';
213
218
 
214
219
  // node's request() deprecates the priority `weight` option with DEP0194
215
220
  // (internal/http2/core.js setAndValidatePriorityOptions). A module-level
@@ -347,6 +352,14 @@ class Http2ClientSession extends EventEmitter {
347
352
  // counter in node, the count is rebuilt from the live streams here.
348
353
  this._maxReservedRemoteStreams = opts.maxReservedRemoteStreams === undefined
349
354
  ? 200 : opts.maxReservedRemoteStreams;
355
+ // nghttp2 keeps one session-lifetime invalid-frame budget on the client too
356
+ // (node_http2.cc: invalid_frame_count_, default 1000). The counted class on
357
+ // this path is zero-length DATA without END_STREAM; immediate protocol
358
+ // violations are fatal on their own. Measured on v26.12.1: the (limit+2)-th
359
+ // counted frame trips, valid frames never reset the count.
360
+ this._invalidFrames = 0;
361
+ this._maxInvalidFrames = typeof opts.maxSessionInvalidFrames === 'number'
362
+ ? opts.maxSessionInvalidFrames : 1000;
350
363
  this._streams = new Map();
351
364
  // Streams whose wire life is still open. A stream that took END_STREAM stops
352
365
  // counting against the peer's max_concurrent_streams as soon as nghttp2 closes
@@ -397,6 +410,20 @@ class Http2ClientSession extends EventEmitter {
397
410
  // connection's available window: setLocalWindowSize lowers only this one, while
398
411
  // the connection window never shrinks (core.js:1457, measured on v26.12.1).
399
412
  this._effectiveLocalWindowSize = this.localSettings.initialWindowSize;
413
+ // node's connectionWindowSize option (IDX_OPTIONS_CONNECTION_WINDOW_SIZE in
414
+ // internal/http2/util.js) is the connection RECEIVE window, not the send window:
415
+ // it seeds the window we maintain and the size the state getter reports, and
416
+ // _start() grants the peer the delta above 65535 with one WINDOW_UPDATE(0).
417
+ // Node leaves the per-stream windows (SETTINGS_INITIAL_WINDOW_SIZE) and the
418
+ // connection SEND window at their defaults. connect() validates the option.
419
+ if (opts.connectionWindowSize !== undefined) {
420
+ // A WINDOW_UPDATE cannot shrink a live window, so the available connection
421
+ // credit starts at the default even when the option (and the size reported
422
+ // by effectiveLocalWindowSize) is smaller. Measured on v26.12.1: with 1024,
423
+ // localWindowSize stays 65535 while effectiveLocalWindowSize reports 1024.
424
+ this._connRecvWin = Math.max(DEFAULT_WINDOW, opts.connectionWindowSize);
425
+ this._effectiveLocalWindowSize = opts.connectionWindowSize;
426
+ }
400
427
  // Streams that took DATA since the last credit pass. _creditRecv() visits only
401
428
  // these instead of scanning every open stream: with the default 100 concurrent
402
429
  // streams a download that touches one of them used to pay ~100 property reads per
@@ -462,6 +489,9 @@ class Http2ClientSession extends EventEmitter {
462
489
  // the memcpy (BODY_MIN). See _frame/_need/_commit/_writePending, which mirror the
463
490
  // server's queue exactly.
464
491
  this._outQ = [];
492
+ // Bodies of requests whose HEADERS were staged in the current turn. Drained by
493
+ // _flush so every HEADERS of a burst precedes every DATA (see _flush).
494
+ this._bodyQ = null;
465
495
  this._stage = null;
466
496
  this._stageLen = 0; // bytes of _stage not yet queued
467
497
  this._stageCap = STAGE_MIN; // size of the next staging buffer
@@ -513,6 +543,19 @@ class Http2ClientSession extends EventEmitter {
513
543
  // octets as its pong). Matching by payload would hand those octets to the wrong callback
514
544
  // and, for two identical payloads, lose one of them outright.
515
545
  this._pingQ = [];
546
+ // Unbounded-work-per-peer guard (SECURITY §8B): node caps the unanswered-ping
547
+ // queue at maxOutstandingPings (default 10). A full queue is not an error: node
548
+ // calls the callback synchronously with ERR_HTTP2_PING_CANCEL and ping() returns
549
+ // false, and the refused ping never reaches the wire (measured on v26.12.1).
550
+ this._maxPingQ = typeof opts.maxOutstandingPings === 'number'
551
+ ? opts.maxOutstandingPings : DEFAULT_MAX_OUTSTANDING_PINGS;
552
+ // node's inbound header-pair cap (initializeOptions, internal/http2/util.js):
553
+ // default 128, counting every decoded field (pseudo-headers included) per
554
+ // block. A block over the cap is refused per stream with
555
+ // RST_STREAM(ENHANCE_YOUR_CALM) and ERR_HTTP2_STREAM_ERROR (measured on
556
+ // v26.12.1: default boundary at 128 fields, 5 fields refused with cap 4).
557
+ this._maxHeaderListPairs = typeof opts.maxHeaderListPairs === 'number'
558
+ ? opts.maxHeaderListPairs : 128;
516
559
  // Response header shapes seen before: the cached object for a block whose bytes
517
560
  // we have already decoded under this dynamic-table state (the server's cache).
518
561
  this._shapes = opts.shapeCache === false ? null : new Map();
@@ -631,6 +674,17 @@ class Http2ClientSession extends EventEmitter {
631
674
  this._stageLen += PREFACE_LEN;
632
675
  this._outLen += PREFACE_LEN;
633
676
  this._sendSettings();
677
+ // node's connectionWindowSize raises the connection receive window above the
678
+ // 65535 default by granting the difference with one WINDOW_UPDATE(0) at setup
679
+ // (nghttp2_session_set_local_window_size on stream 0). A value at or below the
680
+ // default cannot shrink the live window: no update goes out (an increment must
681
+ // be positive), which is why the peer still reports 65535 on an upload.
682
+ const cws = this._opts.connectionWindowSize;
683
+ if (cws !== undefined && cws > DEFAULT_WINDOW) {
684
+ const wu = Buffer.allocUnsafe(4);
685
+ wu.writeUInt32BE(cws - DEFAULT_WINDOW, 0);
686
+ this._frame(WINDOW_UPDATE, 0, 0, wu, true);
687
+ }
634
688
  this._flush();
635
689
  if (preQueued.length !== 0) {
636
690
  this._outQ = preQueued;
@@ -783,6 +837,25 @@ class Http2ClientSession extends EventEmitter {
783
837
  }
784
838
 
785
839
  _flush() {
840
+ // Bodies of requests framed in this turn wait until here. node's C++ submits every
841
+ // HEADERS produced by a run of request() calls before it pumps any queued body DATA
842
+ // (measured on v26.12.1 with two requests and end()/write()/end('x') bodies: HEADERS
843
+ // 1, HEADERS 3, then DATA 1 on the wire in all three shapes). Releasing the body in
844
+ // _afterRequestHeaders would instead put DATA 1 between the two HEADERS, so a peer
845
+ // with SETTINGS_MAX_CONCURRENT_STREAMS=1 frees the slot and dispatches a second
846
+ // 'stream' handler where node refuses the second stream (test/upstream/
847
+ // max-concurrent-streams.test.js).
848
+ if (this._bodyQ !== null) {
849
+ const q = this._bodyQ;
850
+ this._bodyQ = null;
851
+ // Frames produced by the pump belong to this flush: the write they schedule
852
+ // is the one just below, not a new microtask.
853
+ this._inBatch = true;
854
+ for (let i = 0; i < q.length; i++) {
855
+ q[i]._bodyDeferred = false;
856
+ this._pump(q[i]);
857
+ }
858
+ }
786
859
  // leaving a batch, whatever the reason: from here on frames are produced outside a
787
860
  // socket read and have to schedule their own write
788
861
  this._inBatch = false;
@@ -1026,7 +1099,12 @@ class Http2ClientSession extends EventEmitter {
1026
1099
  endStream = payloadMeaningless(method);
1027
1100
  }
1028
1101
 
1029
- const stream = new Http2ClientStream(this, this._nextSid, {});
1102
+ // node's refused stream has no id at all: nghttp2 never reserved one, so the
1103
+ // binding leaves stream.id undefined even though the session's nextStreamID has
1104
+ // advanced past the ceiling (measured on v26.12.1). The id is only assigned to
1105
+ // the returned object, never used for wire bookkeeping on a refused request --
1106
+ // rstStream and _trackClose find nothing under undefined and are no-ops.
1107
+ const stream = new Http2ClientStream(this, requestError === undefined ? this._nextSid : undefined, {});
1030
1108
  // node records what the application passed at this point (kSentHeaders / kRawHeaders,
1031
1109
  // internal/http2/core.js:1902-1904); the getter folds it into the request map on read.
1032
1110
  stream._sentSrc = headersParam;
@@ -1171,7 +1249,12 @@ class Http2ClientSession extends EventEmitter {
1171
1249
  // while pending (core.js:2113). _sendRequest has framed the HEADERS by now;
1172
1250
  // rstStream() would skip the stream because push(null) set _rEof and the
1173
1251
  // 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.
1252
+ // same way rstStream does, before the stream's own teardown runs. The body is
1253
+ // still owed (close(NO_ERROR) after end()), so release it before the reset
1254
+ // retires the id.
1255
+ if (req.stream._bodyDeferred) {
1256
+ this._releaseBody(req.stream);
1257
+ }
1175
1258
  const code = req.stream._pendingCloseCode;
1176
1259
  const body = Buffer.allocUnsafe(4);
1177
1260
  body.writeUInt32BE(code >>> 0, 0);
@@ -1225,7 +1308,7 @@ class Http2ClientSession extends EventEmitter {
1225
1308
  // at, which is why the check stands above the pseudo branch; an empty array is
1226
1309
  // skipped before any bookkeeping (node's `case 0: return`), so it neither pushes
1227
1310
  // a value nor spends a slot in _singlesSeen.
1228
- _addField(list, neverList, rawKey, rawValue) {
1311
+ _addField(list, neverList, rawKey, rawValue, isTrailer) {
1229
1312
  if (rawValue === undefined) {
1230
1313
  return;
1231
1314
  }
@@ -1252,15 +1335,26 @@ class Http2ClientSession extends EventEmitter {
1252
1335
  // one-char string, and charCodeAt is the cheaper spelling on every input --
1253
1336
  // the fall-through case and the match case alike (OPTIMIZATION.md item 33).
1254
1337
  if (key.charCodeAt(0) === 58 /* : */) {
1338
+ // assertValidPseudoHeaderTrailer (internal/http2/util.js) throws for EVERY
1339
+ // colon key, including the request pseudo-headers. A trailer block carries
1340
+ // no pseudo-header at all (measured on v26.12.1 with all five request
1341
+ // pseudo-keys and with an unknown one: TypeError ERR_HTTP2_INVALID_PSEUDOHEADER
1342
+ // and the same message shape, lowercased from the key the caller passed).
1343
+ if (isTrailer) {
1344
+ throw httpErr('ERR_HTTP2_INVALID_PSEUDOHEADER',
1345
+ `"${key}" is an invalid pseudoheader or is used incorrectly`, TypeError);
1346
+ }
1255
1347
  if (key !== ':method' && key !== ':path' && key !== ':scheme' && key !== ':authority'
1256
1348
  && key !== ':protocol') {
1257
- throw httpErr('ERR_HTTP2_PSEUDOHEADER_NOT_ALLOWED', `cannot send ${key}`);
1349
+ throw httpErr('ERR_HTTP2_INVALID_PSEUDOHEADER',
1350
+ `"${key}" is an invalid pseudoheader or is used incorrectly`, TypeError);
1258
1351
  }
1259
1352
  list.push(key, String(isArray ? rawValue[0] : rawValue), never);
1260
1353
  return;
1261
1354
  }
1262
1355
  if (!isFieldName(key)) {
1263
- throw httpErr('ERR_INVALID_HTTP_TOKEN', `${key} is an invalid header token`);
1356
+ throw httpErr('ERR_INVALID_HTTP_TOKEN',
1357
+ `Header name must be a valid HTTP token ["${key}"]`, TypeError);
1264
1358
  }
1265
1359
  if (CONNECTION_SPECIFIC.has(key)) {
1266
1360
  throw httpErr('ERR_HTTP2_INVALID_CONNECTION_HEADERS',
@@ -1352,15 +1446,39 @@ class Http2ClientSession extends EventEmitter {
1352
1446
  this._afterRequestHeaders(stream);
1353
1447
  }
1354
1448
 
1355
- // HEADERS is now queued; release any body the application wrote before the socket
1356
- // connected (or before this queued request was framed). The DATA frames land in _out
1357
- // behind the HEADERS, so the wire order stays HEADERS -> DATA.
1449
+ // Release a body parked for the flush ahead of a local stream close (NO_ERROR
1450
+ // after end()). The body is still owed to the peer; only the write() queue the
1451
+ // close drops is what this settles.
1452
+ _releaseBody(stream) {
1453
+ if (!stream._bodyDeferred) {
1454
+ return;
1455
+ }
1456
+ stream._bodyDeferred = false;
1457
+ if (this._bodyQ !== null) {
1458
+ const i = this._bodyQ.indexOf(stream);
1459
+ if (i !== -1) {
1460
+ this._bodyQ.splice(i, 1);
1461
+ }
1462
+ }
1463
+ const was = this._inBatch;
1464
+ this._inBatch = true;
1465
+ this._pump(stream);
1466
+ this._inBatch = was;
1467
+ }
1468
+
1469
+ // HEADERS is now queued. The application may still write to the stream later in
1470
+ // this same turn; node's C++ submits every HEADERS of such a burst before any body
1471
+ // DATA, so hold this stream's pump until _flush (which runs after the turn).
1358
1472
  _afterRequestHeaders(stream) {
1359
1473
  stream._headersSent = true;
1360
1474
  stream.headersSent = true;
1361
- if (stream._pending !== null || stream._finalCb !== null) {
1362
- this._pump(stream);
1475
+ if (this._bodyQ === null) {
1476
+ this._bodyQ = [stream];
1477
+ } else {
1478
+ this._bodyQ.push(stream);
1363
1479
  }
1480
+ stream._bodyDeferred = true;
1481
+ this._schedule();
1364
1482
  }
1365
1483
 
1366
1484
  _encodeRequest(list) {
@@ -1548,6 +1666,12 @@ class Http2ClientSession extends EventEmitter {
1548
1666
  // Flow-controlled send for the writable half of a stream. Called from the Duplex's
1549
1667
  // _write/_final and again from WINDOW_UPDATE / SETTINGS to resume a stalled body.
1550
1668
  _pump(stream) {
1669
+ // A body written in the same turn as the request's HEADERS waits for _flush,
1670
+ // which releases it behind every HEADERS of that turn (node's frame order).
1671
+ // Once released the flag is clear and later writes pump inline as before.
1672
+ if (stream._bodyDeferred) {
1673
+ return;
1674
+ }
1551
1675
  // The peer reset this stream. nghttp2 refuses DATA and HEADERS on a closed stream
1552
1676
  // ("After calling close ... no DATA and HEADERS frames may be sent",
1553
1677
  // internal/http2/core.js), but closeStream called end() anyway, so the Duplex still
@@ -1614,6 +1738,12 @@ class Http2ClientSession extends EventEmitter {
1614
1738
  break; // a further write may follow
1615
1739
  }
1616
1740
  }
1741
+ // The write callback asked _driveW for the next chunk. In the trampoline that
1742
+ // request is deferred to the active loop, so do not finalize END_STREAM here
1743
+ // while queued bytes are still owed -- the outer loop frames them first.
1744
+ if (stream._driveAgain) {
1745
+ return;
1746
+ }
1617
1747
  // Everything is framed and we are finalizing: close the message with END_STREAM,
1618
1748
  // unless the GET put it on HEADERS already.
1619
1749
  if (stream._pending === null && stream._finalCb !== null && stream._writeCb === null
@@ -1655,12 +1785,12 @@ class Http2ClientSession extends EventEmitter {
1655
1785
  }
1656
1786
  if (Array.isArray(src)) {
1657
1787
  for (let i = 0; i + 1 < src.length; i += 2) {
1658
- this._addField(list, neverList, src[i], src[i + 1]);
1788
+ this._addField(list, neverList, src[i], src[i + 1], true);
1659
1789
  }
1660
1790
  } else {
1661
1791
  const keys = Object.keys(src);
1662
1792
  for (let i = 0; i < keys.length; i++) {
1663
- this._addField(list, neverList, keys[i], src[keys[i]]);
1793
+ this._addField(list, neverList, keys[i], src[keys[i]], true);
1664
1794
  }
1665
1795
  }
1666
1796
  // RFC 9113 8.1: a trailer block carries no pseudo-header. _addField throws
@@ -1842,7 +1972,15 @@ class Http2ClientSession extends EventEmitter {
1842
1972
  // out: the release is due when EITHER the half-window step says so or the window the
1843
1973
  // peer may fill without hearing from us drops under the step.
1844
1974
  _creditRecv() {
1845
- const step = Math.min(this._effectiveLocalWindowSize, DEFAULT_WINDOW) >> 1;
1975
+ // The per-stream step stays the conservative half of the smaller of what we
1976
+ // advertise and the 65535 a peer runs with until it reads our SETTINGS:
1977
+ // connectionWindowSize grows the CONNECTION window only, never a stream's
1978
+ // (measured on node: with a 2^21 connection window a stream still releases at
1979
+ // 32767 octets). The connection step is half the window we actually maintain --
1980
+ // with the option that is half the option, node's measured cadence, because the
1981
+ // one setup WINDOW_UPDATE grants the peer that window without waiting for SETTINGS.
1982
+ const streamStep = Math.min(this.localSettings.initialWindowSize, DEFAULT_WINDOW) >> 1;
1983
+ const step = this._effectiveLocalWindowSize >> 1;
1846
1984
  const debt = this._debt;
1847
1985
  // Compacted in place: a stream whose bytes have not yet crossed the half-window
1848
1986
  // step STAYS in the list (and stays marked), because the credit it owes is only
@@ -1851,7 +1989,7 @@ class Http2ClientSession extends EventEmitter {
1851
1989
  let k = 0;
1852
1990
  for (let i = 0; i < debt.length; i++) {
1853
1991
  const stream = debt[i];
1854
- if (stream._recvUsed >= step) {
1992
+ if (stream._recvUsed >= streamStep) {
1855
1993
  const inc = stream._recvUsed;
1856
1994
  stream._recvUsed = 0;
1857
1995
  stream._debtMarked = false;
@@ -2160,6 +2298,19 @@ class Http2ClientSession extends EventEmitter {
2160
2298
  if (id === 0x2) {
2161
2299
  this._fatal(PROTOCOL_ERROR, 'SETTINGS_ENABLE_PUSH from server'); return;
2162
2300
  }
2301
+ // Extended CONNECT cannot be turned off once the peer advertised it. node's
2302
+ // client ends the session with ERR_HTTP2_ERROR "Protocol error" when a server
2303
+ // sends SETTINGS_ENABLE_CONNECT_PROTOCOL=0 after having sent 1 (measured,
2304
+ // test/upstream/connect-method-extended-cant-turn-off.test.js). The fatal is
2305
+ // deferred to an immediate: the SETTINGS frame must finish -- 'remoteSettings'
2306
+ // still reports the value it had when the request was submitted -- and a tick
2307
+ // would run before the request's promise microtasks and report
2308
+ // ERR_HTTP2_INVALID_SESSION instead of node's error. _fatal() supplies the
2309
+ // GOAWAY, the session error and the request error with rstCode 2.
2310
+ if (id === 0x8 && value === 0 && seen.enableConnectProtocol === true) {
2311
+ setImmediate(() => this._fatal(PROTOCOL_ERROR,
2312
+ 'SETTINGS: server attempted to disable SETTINGS_ENABLE_CONNECT_PROTOCOL'));
2313
+ }
2163
2314
  // The two boolean settings land in remoteSettings as booleans, the way node's
2164
2315
  // getSettings turns them (`enablePush: !!slot`, `enableConnectProtocol: !!slot`,
2165
2316
  // internal/http2/util.js): the wire is a uint32, and handing the raw 0/1 to the
@@ -2539,7 +2690,11 @@ class Http2ClientSession extends EventEmitter {
2539
2690
  ? hit.block.equals(block)
2540
2691
  : pieceEquals(hit.block, pieces, from, to))) {
2541
2692
  this._shapeHits++;
2542
- fields = hit.flat;
2693
+ // The cached flat array is shared by every response of this shape. The
2694
+ // stream hands it out as the third 'response' argument (rawHeaders), which
2695
+ // the application may mutate, so each response gets its own copy. On a
2696
+ // decode the field list is already a per-response slice and needs none.
2697
+ fields = hit.flat.slice();
2543
2698
  fcount = fields.length;
2544
2699
  blockFlags = hit.flags;
2545
2700
  } else {
@@ -2553,8 +2708,10 @@ class Http2ClientSession extends EventEmitter {
2553
2708
  blockFlags = this._decoder.neverCount > 0 ? this._decoder.neverFlags : null;
2554
2709
  // The field list the stream holds must outlive this decode: the
2555
2710
  // scratch's backing array is cleared in place by the next one. The copy
2556
- // that caches the shape serves the stream too; without a cache entry
2557
- // the copy is the stream's own.
2711
+ // that caches the shape is a separate snapshot -- handing the same array
2712
+ // to the stream would let a 'response'/'push' listener mutate the cache
2713
+ // entry and poison every later response of that shape. Without a cache
2714
+ // entry the copy is the stream's own.
2558
2715
  let copy = null;
2559
2716
  if (shapes !== null) {
2560
2717
  if (++this._shapeMisses > 64 && this._shapeHits * 4 < this._shapeMisses) {
@@ -2573,7 +2730,7 @@ class Http2ClientSession extends EventEmitter {
2573
2730
  });
2574
2731
  }
2575
2732
  }
2576
- fields = copy !== null ? copy : fields.slice(0, fcount);
2733
+ fields = copy !== null ? copy.slice() : fields.slice(0, fcount);
2577
2734
  }
2578
2735
  } catch (err) {
2579
2736
  if (err instanceof HPackError) {
@@ -2657,6 +2814,15 @@ class Http2ClientSession extends EventEmitter {
2657
2814
  // the block was refused, so the caller does not build or hand over the
2658
2815
  // header object.
2659
2816
  _refuseHeaders(sid, stream, fields, count) {
2817
+ // maxHeaderListPairs counts every field in this block, :status among them.
2818
+ // Each block is checked on its own -- a 1xx block and the later response do
2819
+ // not accumulate -- and a refusal is per stream: RST_STREAM(ENHANCE_YOUR_CALM),
2820
+ // ERR_HTTP2_STREAM_ERROR on the stream, session still up (measured v26.12.1).
2821
+ if (count / 2 > this._maxHeaderListPairs) {
2822
+ this.rstStream(sid, ENHANCE_YOUR_CALM);
2823
+ stream._onRst(ENHANCE_YOUR_CALM);
2824
+ return true;
2825
+ }
2660
2826
  let status = 0;
2661
2827
  let bad = null;
2662
2828
  for (let i = 0; i < count; i += 2) {
@@ -2747,6 +2913,17 @@ class Http2ClientSession extends EventEmitter {
2747
2913
  if (stream === undefined) {
2748
2914
  return;
2749
2915
  }
2916
+ // A zero-length DATA without END_STREAM is one of the two frame classes nghttp2
2917
+ // counts against maxSessionInvalidFrames (node_http2.cc HandleDataFrame). On the
2918
+ // trip the stream and the session both report node's custom error code and the
2919
+ // session answers GOAWAY(INTERNAL_ERROR) with no debug data.
2920
+ if (l === 0 && (flags & F_END_STREAM) === 0 && this._recordInvalidFrame()) {
2921
+ const err = httpErr('ERR_HTTP2_TOO_MANY_INVALID_FRAMES', TOO_MANY_INVALID_FRAMES);
2922
+ stream.destroy(err);
2923
+ this._fatal(INTERNAL_ERROR, '', 'ERR_HTTP2_TOO_MANY_INVALID_FRAMES',
2924
+ TOO_MANY_INVALID_FRAMES);
2925
+ return this._open;
2926
+ }
2750
2927
  // Book the consumed bytes as credit owed to BOTH windows ahead of the hand-over:
2751
2928
  // a synchronous consumer inside the 'data' event must see the window already
2752
2929
  // shrunken, node's shape (16384 consumed reads 49151 from the state getter at
@@ -3004,6 +3181,13 @@ class Http2ClientSession extends EventEmitter {
3004
3181
  : Buffer.from(payload.buffer, payload.byteOffset, 8);
3005
3182
  f.copyInto(body, 0, src, 0, 8);
3006
3183
  }
3184
+ // maxOutstandingPings: a full queue refuses the submit. node invokes the callback
3185
+ // SYNCHRONOUSLY with ERR_HTTP2_PING_CANCEL before ping() returns false, and the
3186
+ // callback is never registered in the queue (measured on v26.12.1, both halves).
3187
+ if (this._pingQ.length >= this._maxPingQ) {
3188
+ cb(pingCancelled());
3189
+ return false;
3190
+ }
3007
3191
  this._pingQ.push({ cb, at: process.hrtime.bigint() });
3008
3192
  this._frame(PING, 0, 0, body, true);
3009
3193
  // node hands back what nghttp2's submit returned (measured: a live node session answers
@@ -3077,7 +3261,7 @@ class Http2ClientSession extends EventEmitter {
3077
3261
  if (code === undefined) {
3078
3262
  code = NO_ERROR;
3079
3263
  }
3080
- if (lastStreamID === undefined || lastStreamID === null) {
3264
+ if (lastStreamID === undefined || lastStreamID === null || lastStreamID <= 0) {
3081
3265
  // node's goaway() defaults lastStreamID to 0 and the C layer substitutes
3082
3266
  // nghttp2_session_get_last_proc_stream_id (src/node_http2.cc Http2Session::Goaway:
3083
3267
  // `if (lastStreamID <= 0) lastStreamID = ...get_last_proc_stream_id`). For a
@@ -3088,14 +3272,24 @@ class Http2ClientSession extends EventEmitter {
3088
3272
  // graceful close() echo after the peer's GOAWAY then killed the peer's open
3089
3273
  // stream (measured on live node: its client sends last=0,
3090
3274
  // h2lean sent last=1 and the node server answered ERR_HTTP2_ERROR).
3275
+ // The C++ substitution also applies to an explicitly non-positive id
3276
+ // (node_http2.cc Http2Session::Goaway), so -1 is not sent as 0xffffffff.
3091
3277
  lastStreamID = this._maxPushSid;
3092
3278
  }
3093
- const tail = reason ? Buffer.byteLength(reason) : 0;
3094
- const body = Buffer.alloc(8 + tail);
3279
+ // node accepts Buffer and any TypedArray/DataView as opaqueData; keep the
3280
+ // older string form accepted here too (see the server's sendGoaway).
3281
+ let opaque;
3282
+ if (reason !== undefined && reason !== null) {
3283
+ opaque = ArrayBuffer.isView(reason)
3284
+ ? Buffer.from(reason.buffer, reason.byteOffset, reason.byteLength)
3285
+ : Buffer.from(String(reason), 'latin1');
3286
+ }
3287
+ const tail = opaque === undefined ? 0 : opaque.length;
3288
+ const body = Buffer.allocUnsafe(8 + tail);
3095
3289
  body.writeUInt32BE(lastStreamID >>> 0, 0);
3096
3290
  body.writeUInt32BE(code >>> 0, 4);
3097
3291
  if (tail) {
3098
- body.write(reason, 8);
3292
+ opaque.copy(body, 8);
3099
3293
  }
3100
3294
  this._frame(GOAWAY, 0, 0, body, true);
3101
3295
  // No closed marking here: node's goaway() (core.js:1602-1618) validates and submits
@@ -3531,7 +3725,11 @@ class Http2ClientSession extends EventEmitter {
3531
3725
  this._maybeClose();
3532
3726
  }
3533
3727
 
3534
- _fatal(code, reason) {
3728
+ _recordInvalidFrame() {
3729
+ return this._invalidFrames++ > this._maxInvalidFrames;
3730
+ }
3731
+
3732
+ _fatal(code, reason, errCode, errMessage) {
3535
3733
  if (!this._open) {
3536
3734
  return false;
3537
3735
  }
@@ -3566,8 +3764,9 @@ class Http2ClientSession extends EventEmitter {
3566
3764
  // them: measured off v26.12.1, every fatal code reports 'Protocol error'
3567
3765
  // except FLOW_CONTROL_ERROR's 'Flow control error' (the GOAWAY debug string
3568
3766
  // still carries this frame's own reason).
3569
- const err = httpErr('ERR_HTTP2_ERROR',
3570
- code === FLOW_CONTROL_ERROR ? 'Flow control error' : 'Protocol error');
3767
+ const err = httpErr(errCode !== undefined ? errCode : 'ERR_HTTP2_ERROR',
3768
+ errMessage !== undefined ? errMessage
3769
+ : (code === FLOW_CONTROL_ERROR ? 'Flow control error' : 'Protocol error'));
3571
3770
  err.http2Code = code;
3572
3771
  this.destroy(err);
3573
3772
  return false;
@@ -3807,8 +4006,10 @@ function checkRequestOptions(options) {
3807
4006
  }
3808
4007
  }
3809
4008
 
3810
- function httpErr(code, msg) {
3811
- const err = new Error(msg);
4009
+ // node's internal/errors.js gives these two codes fixed classes; the default stays
4010
+ // Error for the many other callers.
4011
+ function httpErr(code, msg, Ctor = Error) {
4012
+ const err = new Ctor(msg);
3812
4013
  err.code = code;
3813
4014
  return err;
3814
4015
  }