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.
@@ -57,7 +57,7 @@ const {
57
57
  DATA, HEADERS, PRIORITY, RST_STREAM, SETTINGS, PUSH_PROMISE, PING, GOAWAY,
58
58
  WINDOW_UPDATE, CONTINUATION, ALTSVC, ORIGIN,
59
59
  F_END_STREAM, F_ACK, F_END_HEADERS, F_PADDED, F_PRIORITY,
60
- NO_ERROR, PROTOCOL_ERROR, INTERNAL_ERROR, FLOW_CONTROL_ERROR, STREAM_CLOSED,
60
+ NO_ERROR, CANCEL, PROTOCOL_ERROR, INTERNAL_ERROR, FLOW_CONTROL_ERROR, STREAM_CLOSED,
61
61
  FRAME_SIZE_ERROR, REFUSED_STREAM, COMPRESSION_ERROR, ENHANCE_YOUR_CALM,
62
62
  PREFACE_LEN, HEADER_LEN, readHeader, writeHeader, trimPadding
63
63
  } = f;
@@ -101,6 +101,14 @@ function extError(code, msg) {
101
101
  return err;
102
102
  }
103
103
 
104
+ // node's ERR_OUT_OF_RANGE is a RangeError, unlike the ERR_INVALID_ARG_TYPE above;
105
+ // the code and the message are not the whole surface, the constructor is too.
106
+ function rangeError(code, msg) {
107
+ const err = new RangeError(msg);
108
+ err.code = code;
109
+ return err;
110
+ }
111
+
104
112
  // ERR_HTTP2_INVALID_SESSION is defined off plain Error in node's internal/errors.js, not off
105
113
  // TypeError like the argument validators, so it needs its own constructor rather than extError.
106
114
  function invalidSession() {
@@ -769,6 +777,34 @@ function strictSingleValueFields(opts) {
769
777
  return v;
770
778
  }
771
779
 
780
+ // node's connectionWindowSize option, validated by validateSessionOptions
781
+ // (internal/http2/core.js) with validateInt32(value, name, 1, kMaxInitialWindowSize).
782
+ // The checks are in node's order: type, integer, then range; `undefined` is the one
783
+ // value that skips all of them, so null reaches the type check. ERR_INVALID_ARG_TYPE
784
+ // uses received() and ERR_OUT_OF_RANGE uses outOfRangeValue() above, the same two
785
+ // helpers the other validated options in this file use.
786
+ function validateConnectionWindowSize(opts) {
787
+ const value = opts.connectionWindowSize;
788
+ if (value === undefined) {
789
+ return;
790
+ }
791
+ const name = 'options.connectionWindowSize';
792
+ if (typeof value !== 'number') {
793
+ throw extError('ERR_INVALID_ARG_TYPE',
794
+ `The "${name}" property must be of type number. Received ${received(value)}`);
795
+ }
796
+ if (!Number.isInteger(value)) {
797
+ throw rangeError('ERR_OUT_OF_RANGE',
798
+ `The value of "${name}" is out of range. It must be an integer. `
799
+ + `Received ${outOfRangeValue(value)}`);
800
+ }
801
+ if (value < 1 || value > 2147483647) {
802
+ throw rangeError('ERR_OUT_OF_RANGE',
803
+ `The value of "${name}" is out of range. It must be >= 1 && <= 2147483647. `
804
+ + `Received ${outOfRangeValue(value)}`);
805
+ }
806
+ }
807
+
772
808
  // RFC 7541 4.1: the size of an entry is the length of its name plus the length of its value
773
809
  // plus 32 -- the computation RFC 9113 6.5.2 states SETTINGS_MAX_HEADER_LIST_SIZE in terms of.
774
810
  // That is the number node's `maxHeaderListSize` is compared against, measured on
@@ -795,20 +831,19 @@ const ENTRY_OVERHEAD = 32;
795
831
  // worst case -- 256 KiB held per session -- against a peer that stops reading.
796
832
  const MAX_OUT_BATCH = 256 * 1024;
797
833
 
798
- // How much a connection may make this session hold for answers it is not allowed to send. A body
834
+ // What a connection may make this session hold for answers it is not allowed to send. A body
799
835
  // that flow control will not pass is parked on its stream until the peer opens the window, which is
800
836
  // right per request and unbounded per connection: a client that never sends a WINDOW_UPDATE can
801
837
  // make the server keep a live stream plus its unsent body for every HEADERS it puts on the wire.
802
838
  // Measured with tools/probe-stream-concurrency.js -- 200 000 streams on one connection, a 14-byte
803
839
  // response each, no credit ever granted -- the session held 195 319 live streams and 170 MB after a
804
840
  // forced collection, i.e. 892 bytes per parked stream whose queue entry was 23 bytes: what costs
805
- // here is the stream record, not its payload. So the charge has both terms, and the number is then
806
- // a statement about memory rather than about one dimension of it -- at the measured cost, about
807
- // 8 000 parked streams per connection, the same order as the point where node's own session bound
808
- // stopped the identical flood (13 454 streams, same probe, maxSessionMemory left at its default).
809
- // The socket-queue half of the retention is not counted because it is already bounded absolutely by
810
- // MAX_OUT_BATCH above.
811
- const MAX_SESSION_HOLD = 8 * 1024 * 1024;
841
+ // here is the stream record, not its payload. So the charge has both terms. The ceiling is the
842
+ // same maxSessionMemory budget node uses for queued outbound bytes (node_http2.cc DoWrite):
843
+ // measured on v26.12.1 with 100 x 139837-byte responses, node served all 100 at m=1000 where a
844
+ // fixed 8 MiB ceiling refused 39, and the counts agree at m=1/10/100/1000 once the ceiling is
845
+ // the caller's option (the default is 10 MB). The socket-queue half of the retention is not
846
+ // counted because it is already bounded absolutely by MAX_OUT_BATCH above.
812
847
  const STREAM_HOLD_CHARGE = 1024;
813
848
 
814
849
  // Smallest payload that is worth queuing by reference instead of copying into the
@@ -824,12 +859,6 @@ const STAGE_MIN = 8192;
824
859
  // for reuse is bounded independently of how many sessions the server accepts.
825
860
  const MAX_STAGE_POOL = 32;
826
861
 
827
- // The 'stream' event carries node's options object. Two constants instead of a
828
- // literal per request: the payload never changes, and 1.9M requests is 1.9M
829
- // objects the young generation would otherwise have to collect.
830
- const OPT_END_STREAM = { endStream: true };
831
- const OPT_NO_END_STREAM = { endStream: false };
832
-
833
862
  // How long the teardown waits for the goodbye to reach the peer before the socket is
834
863
  // taken away anyway. The FIN is queued behind whatever we wrote, so a peer that stopped
835
864
  // reading would hold it forever -- node does not have that problem because its data sits
@@ -1301,11 +1330,22 @@ class Http2ServerSession extends EventEmitter {
1301
1330
  }
1302
1331
  this._addCustomEntries(built.rest);
1303
1332
  this.remoteSettings = { ...PEER_DEFAULTS };
1333
+ // connectionWindowSize is the connection-level RECEIVE window (validateSessionOptions
1334
+ // validates it at createServer/connect/handshake time). node reports the option as
1335
+ // effectiveLocalWindowSize even below the default, but the live window cannot shrink:
1336
+ // measured on v26.12.1, { connectionWindowSize: 1 } reports eff=1/local=65535 and
1337
+ // sends no WINDOW_UPDATE, while larger options raise both and announce the difference
1338
+ // with one WINDOW_UPDATE(stream 0) in _start().
1339
+ const connectionWindowSize = opts.connectionWindowSize === undefined
1340
+ ? 65535 : opts.connectionWindowSize;
1304
1341
  this.state = {
1305
- effectiveLocalWindowSize: this.localSettings.initialWindowSize,
1342
+ // SETTINGS_INITIAL_WINDOW_SIZE is per-stream: it does not move either connection
1343
+ // window (measured at 'session' on the running binary with
1344
+ // { initialWindowSize: 16384 }); connectionWindowSize does.
1345
+ effectiveLocalWindowSize: connectionWindowSize,
1306
1346
  effectiveRecvDataLength: 0,
1307
1347
  nextStreamID: 2,
1308
- localWindowSize: this.localSettings.initialWindowSize,
1348
+ localWindowSize: Math.max(65535, connectionWindowSize),
1309
1349
  lastProcStreamID: 0,
1310
1350
  remoteWindowSize: 65535,
1311
1351
  outboundQueueSize: 0,
@@ -1343,11 +1383,18 @@ class Http2ServerSession extends EventEmitter {
1343
1383
  // would cross the budget (node_http2.cc CanAddStream / OnHeader). The charge
1344
1384
  // leaves with the stream in _dropStream, so a connection that drains can open
1345
1385
  // new streams again. node counts queued outbound bytes too; those are already
1346
- // bounded separately by _heldCost (MAX_SESSION_HOLD). The session's own
1386
+ // bounded by the same budget through _holdLimit / _heldCost. The session's own
1347
1387
  // scratch and staging buffers open the budget, as sizeof(Http2Session) does
1348
1388
  // on node; _appendHdr adds the header assembly buffer when it exists.
1349
1389
  this._memLimit = typeof opts.maxSessionMemory === 'number'
1350
1390
  ? Math.max(1, opts.maxSessionMemory) * 1000000 : DEFAULT_MAX_SESSION_MEMORY;
1391
+ // nghttp2 charges queued outbound bytes against the SAME session budget that
1392
+ // bounds stream records and headers (node_http2.cc DoWrite / CanAddStream), so
1393
+ // the parked-body ceiling is the caller's maxSessionMemory, not a separate
1394
+ // fixed number. Measured on v26.12.1: 100 x 139837-byte responses at m=1000
1395
+ // all go out on node, while the fixed 8 MiB ceiling refused 39 of them; with
1396
+ // this ceiling the counts agree at m=1/10/100/1000 and the DoS guard stays.
1397
+ this._holdLimit = this._memLimit;
1351
1398
  this._memUsed = SESSION_MEM_CHARGE;
1352
1399
  // Outbound padding: node's C++ switch only acts on 0/1/2; every other
1353
1400
  // number is an unpadded session (measured on a live node 26 server).
@@ -1450,10 +1497,10 @@ class Http2ServerSession extends EventEmitter {
1450
1497
  // already cut out of the queue wait in _esRequeue for the same reason.
1451
1498
  this._esMarkers = new Map();
1452
1499
  this._esRequeue = [];
1453
- // Connection-level send window: starts at the peer default (initialWindowSize), but
1454
- // can be overridden by the `connectionWindowSize` option (node's Http2Session option).
1455
- this._connSendWin = typeof opts.connectionWindowSize === 'number'
1456
- ? opts.connectionWindowSize : PEER_DEFAULTS.initialWindowSize;
1500
+ // Connection-level SEND window: the peer's 65535 until it grants more. The
1501
+ // connectionWindowSize option belongs to the RECEIVE side above -- applying it here
1502
+ // made remoteWindowSize echo our own choice instead of the peer's.
1503
+ this._connSendWin = PEER_DEFAULTS.initialWindowSize;
1457
1504
  this._prevInitialWin = PEER_DEFAULTS.initialWindowSize;
1458
1505
  this._connRecvUsed = 0; // consumed bytes owed back to the connection
1459
1506
  this._blocked = null; // streams waiting on credit
@@ -1568,7 +1615,16 @@ class Http2ServerSession extends EventEmitter {
1568
1615
  this._onWrittenCb = () => this._onWritten();
1569
1616
 
1570
1617
  socket.on('error', (err) => this._onSocketError(err));
1571
- socket.on('end', () => this.destroy(NO_ERROR));
1618
+ socket.on('end', () => {
1619
+ // node has no socket 'end' teardown: its socketOnClose (core.js:3653)
1620
+ // sweeps live streams with NGHTTP2_CANCEL before closeSession destroys
1621
+ // the session. Here 'end' is the first half of that same close, so the
1622
+ // sweep has to precede the NO_ERROR destroy the next line performs.
1623
+ for (const stream of [...this._streams.values()]) {
1624
+ stream.close(CANCEL);
1625
+ }
1626
+ this.destroy(NO_ERROR);
1627
+ });
1572
1628
  // 'finish' means everything we wrote reached the OS, so the GOAWAY of a close() is never
1573
1629
  // cut off by a destroy -- but it is not the end of the session either. node keeps reading
1574
1630
  // until the PEER closes, which is what lets it receive and report the peer's answer to that
@@ -1648,6 +1704,14 @@ class Http2ServerSession extends EventEmitter {
1648
1704
  this.alpnProtocol = 'h2c';
1649
1705
  }
1650
1706
  this._sendSettings();
1707
+ // node's setupHandle raises the connection-level receive window at start with exactly
1708
+ // one WINDOW_UPDATE on stream 0, right after the initial SETTINGS and before 'connect'
1709
+ // (measured on v26.12.1: option 1048576 -> increment 983041). The default and any
1710
+ // option at or below it cannot shrink a live window, so node sends nothing then.
1711
+ if (this.state.effectiveLocalWindowSize > 65535) {
1712
+ this._windowUpdate(0, this.state.effectiveLocalWindowSize - 65535);
1713
+ this._flush();
1714
+ }
1651
1715
  // node's setupHandle announces the server `origins` option with one ORIGIN frame -- server
1652
1716
  // sessions only, and only when the option is an array -- right after the initial SETTINGS and
1653
1717
  // before 'connect'. A bad entry throws out of origin() synchronously, from this connect
@@ -2266,12 +2330,21 @@ class Http2ServerSession extends EventEmitter {
2266
2330
  // "sending a goaway frame has no other effect"), so the application's 'goaway' listener is
2267
2331
  // the peer's decision, never our own. Announcing our own here made a listener fire on a
2268
2332
  // shutdown it had no part in.
2269
- const tail = reason ? Buffer.byteLength(reason) : 0;
2270
- const body = Buffer.alloc(8 + tail);
2333
+ // node's validateBuffer admits Buffer and any TypedArray/DataView as opaqueData and
2334
+ // nghttp2 writes its bytes verbatim (measured v26.12.1). Keep the older string form
2335
+ // accepted here too -- callers on this stack already use it.
2336
+ let opaque;
2337
+ if (reason !== undefined && reason !== null) {
2338
+ opaque = ArrayBuffer.isView(reason)
2339
+ ? Buffer.from(reason.buffer, reason.byteOffset, reason.byteLength)
2340
+ : Buffer.from(String(reason), 'latin1');
2341
+ }
2342
+ const tail = opaque === undefined ? 0 : opaque.length;
2343
+ const body = Buffer.allocUnsafe(8 + tail);
2271
2344
  body.writeUInt32BE(lastStreamID >>> 0, 0);
2272
2345
  body.writeUInt32BE(code, 4);
2273
2346
  if (tail) {
2274
- body.write(reason, 8);
2347
+ opaque.copy(body, 8);
2275
2348
  }
2276
2349
  this._frame(GOAWAY, 0, 0, body, true);
2277
2350
  this._goawaySent = true;
@@ -2862,6 +2935,9 @@ class Http2ServerSession extends EventEmitter {
2862
2935
  return;
2863
2936
  }
2864
2937
  this._hdrCont = 0; // one block, however many frames it takes
2938
+ // node hands the HEADERS frame flags to 'stream' as its third argument (5 for
2939
+ // a normal GET). Keep the flags of the opening frame, not the CONTINUATION's.
2940
+ this._hdrFlags = flags;
2865
2941
  const p = this._headersPrefix(buf, start, len, sid, flags, len);
2866
2942
  if (p < 0) {
2867
2943
  return;
@@ -3513,6 +3589,14 @@ class Http2ServerSession extends EventEmitter {
3513
3589
  const trailers = this._share
3514
3590
  ? this._sharedObject(fields, fcount, neverNames(fields, fcount, blockFlags))
3515
3591
  : this._toObject(fields, fcount, neverNames(fields, fcount, blockFlags));
3592
+ // node's inbound trailers callback delivers (trailers, flags, rawTrailers)
3593
+ // to compat. The compat dispatch takes one argument, so the flat raw
3594
+ // name/value list travels on a private event first; the merged map stays
3595
+ // the single argument of the public 'trailers' event. The slice owns the
3596
+ // pairs (the decoder reuses its backing array on the next block).
3597
+ if (existing._compatDispatch !== null) {
3598
+ existing.emit(Symbol.for('h2lean.compat.rawTrailers'), fields.slice(0, fcount));
3599
+ }
3516
3600
  existing.emit('trailers', trailers);
3517
3601
  if (end) {
3518
3602
  existing._remoteEnded();
@@ -3545,7 +3629,7 @@ class Http2ServerSession extends EventEmitter {
3545
3629
  // refusal clears itself: credit returns, _release drains, the charge drops below the bound.
3546
3630
  // What is bounded is the cost of accepting, not the total ever: an application that ignores
3547
3631
  // backpressure can still write into a stalled stream without limit.
3548
- if (this._heldCost() >= MAX_SESSION_HOLD) {
3632
+ if (this._heldCost() >= this._holdLimit) {
3549
3633
  this.sendRst(sid, REFUSED_STREAM);
3550
3634
  this._refused.push(sid);
3551
3635
  this._rejectedStreams++;
@@ -3668,11 +3752,15 @@ class Http2ServerSession extends EventEmitter {
3668
3752
  stream._reqPath = reqPath;
3669
3753
  stream._reqSensitive = sensitive;
3670
3754
  // node's argument order; the field list is the session's shared decode array
3671
- // or a cached one, so the raw list handed out is always a copy. In the compat
3672
- // path the copy is also the stable list the lazy request object builds from
3673
- // (the scratch's backing array is cleared in place by the next decode), so it
3674
- // travels with the stream even when no emit will carry it.
3675
- const raw = this._wantRaw ? fields.slice(0, fcount) : null;
3755
+ // or a cached one, so the raw list handed out is always a copy. Every plain
3756
+ // 'stream' delivery gets that copy as its fourth argument -- flat decoded pairs
3757
+ // including pseudo-headers, duplicates and wire order -- whether or not compat
3758
+ // is armed. In the compat path it is also the stable list the lazy request
3759
+ // object builds from (the scratch's backing array is cleared in place by the
3760
+ // next decode), so it travels with the stream even when no emit will carry it.
3761
+ // Sessions with neither listeners keep the old no-allocation path.
3762
+ const raw = this._wantRaw || this.listenerCount('stream') > 0
3763
+ ? fields.slice(0, fcount) : null;
3676
3764
  stream._reqFields = raw;
3677
3765
  if (headers !== undefined) {
3678
3766
  stream._requestHeaders = headers;
@@ -3695,7 +3783,7 @@ class Http2ServerSession extends EventEmitter {
3695
3783
  // does, and emitting it into a listenerless session would drop the request
3696
3784
  // the compat callback was meant to receive.
3697
3785
  if (this.listenerCount('stream') > 0) {
3698
- this.emit('stream', stream, headers, end ? OPT_END_STREAM : OPT_NO_END_STREAM, raw);
3786
+ this.emit('stream', stream, headers, this._hdrFlags, raw);
3699
3787
  } else if (this._onStreamCompat !== null) {
3700
3788
  this._onStreamCompat(stream);
3701
3789
  }
@@ -3946,7 +4034,8 @@ class Http2ServerSession extends EventEmitter {
3946
4034
 
3947
4035
  // What this connection currently costs in answers it cannot send. Two terms because the flood
3948
4036
  // that needs bounding is many small stalled responses, and charging only their payloads would let
3949
- // 8 MiB of bound stand for 350 000 live stream records -- see MAX_SESSION_HOLD for the measurement.
4037
+ // 10 MB of bound stand for hundreds of thousands of live stream records -- see the charge comment
4038
+ // above for the measurement.
3950
4039
  _heldCost() {
3951
4040
  return this._heldBytes
3952
4041
  + (this._blocked === null ? 0 : this._blocked.size * STREAM_HOLD_CHARGE);
@@ -4105,7 +4194,17 @@ class Http2ServerSession extends EventEmitter {
4105
4194
  if (len < 8) {
4106
4195
  this._fatal(FRAME_SIZE_ERROR, 'GOAWAY payload too short'); return;
4107
4196
  }
4108
- this._goawayLastStreamID = buf.readUInt32BE(start);
4197
+ const lastStreamID = buf.readUInt32BE(start);
4198
+ // nghttp2 refuses an odd Last-Stream-ID on an inbound GOAWAY: measured on v26.12.1,
4199
+ // every odd id (1, 3, 5, 0x7fffffff) raises ERR_HTTP2_ERROR/"Protocol error" no matter
4200
+ // which streams the peer opened, while every even id -- even one above the highest
4201
+ // received -- is accepted. The check lives in the C layer, not in core.js's onGoawayData.
4202
+ if ((lastStreamID & 1) !== 0) {
4203
+ this._fatal(PROTOCOL_ERROR, 'Protocol error', 'ERR_HTTP2_ERROR',
4204
+ 'GOAWAY: invalid last_stream_id');
4205
+ return;
4206
+ }
4207
+ this._goawayLastStreamID = lastStreamID;
4109
4208
  this._goawayCode = buf.readUInt32BE(start + 4);
4110
4209
  // the debug data goes to the application, which may keep it: the same reason as
4111
4210
  // the PING payload above. allocUnsafe + copy instead of Buffer.from(subarray) for
@@ -4177,10 +4276,13 @@ class Http2ServerSession extends EventEmitter {
4177
4276
  // 640 KiB upload (tools/probe-conn-credit.js): node releases the connection window in steps of
4178
4277
  // 32768 octets -- half the 65535 it advertises -- and the same threshold here takes h2lean's
4179
4278
  // cadence from one frame per read batch to the same half-window steps, at the same throughput.
4180
- // A peer that keeps sending is therefore credited before its window can run out, so the
4181
- // anti-deadlock rule that this counter exists for still holds; below the threshold the bytes
4182
- // stay owed, and the next batch pays them.
4183
- if (this._connRecvUsed < this.localSettings.initialWindowSize >> 1) {
4279
+ // connectionWindowSize raises the connection's receive window, so the step has to follow the
4280
+ // effective window, not the per-stream SETTINGS value (measured with the option at 1048576:
4281
+ // node grants 524288 at a time after the start-of-session increase). A peer that keeps
4282
+ // sending is therefore credited before its window can run out, so the anti-deadlock rule that
4283
+ // this counter exists for still holds; below the threshold the bytes stay owed, and the next
4284
+ // batch pays them.
4285
+ if (this._connRecvUsed < this.state.effectiveLocalWindowSize >> 1) {
4184
4286
  return;
4185
4287
  }
4186
4288
  const inc = this._connRecvUsed;
@@ -4584,6 +4686,14 @@ class Http2ServerSession extends EventEmitter {
4584
4686
  // node cleanupSession also nulls the socket proxy so session.socket reads gone after close
4585
4687
  this._proxySocket = undefined;
4586
4688
  this._open = false;
4689
+ // node's socketOnClose (internal/http2/core.js:3653) sweeps every live and
4690
+ // pending stream with NGHTTP2_CANCEL *before* closeSession destroys the
4691
+ // session with NO_ERROR. closeStream records the code at entry and the later
4692
+ // destroy sees an already-closed stream, so rstCode stays 8. Do the same here;
4693
+ // the socket is already gone, and _destroy() skips sendRst once _open is false.
4694
+ for (const stream of [...this._streams.values()]) {
4695
+ stream.close(CANCEL);
4696
+ }
4587
4697
  if (!this.destroyed) {
4588
4698
  this.destroy(NO_ERROR);
4589
4699
  }
@@ -4642,8 +4752,27 @@ class Http2ServerSession extends EventEmitter {
4642
4752
  return this;
4643
4753
  }
4644
4754
 
4755
+ // Http2Session.setNextStreamID (core.js:1441-1452) moves the handle's next id,
4756
+ // which is also the id nghttp2 reserves for the next PUSH_PROMISE. h2lean's
4757
+ // reservation counter is _nextPushSid, so both have to move together; the
4758
+ // state field is the read-only view of the same handle value. node validates
4759
+ // and returns undefined on every session, server half included.
4645
4760
  setNextStreamID(id) {
4646
- this.state.nextStreamID = id; return this;
4761
+ if (this.destroyed) {
4762
+ throw invalidSession();
4763
+ }
4764
+ if (typeof id !== 'number') {
4765
+ throw extError('ERR_INVALID_ARG_TYPE',
4766
+ `The "id" argument must be of type number. Received ${received(id)}`);
4767
+ }
4768
+ if (id <= 0 || id > 0xffffffff) {
4769
+ const err = new RangeError('The value of "id" is out of range. '
4770
+ + `It must be > 0 and <= 4294967295. Received ${outOfRangeValue(id)}`);
4771
+ err.code = 'ERR_OUT_OF_RANGE';
4772
+ throw err;
4773
+ }
4774
+ this.state.nextStreamID = id;
4775
+ this._nextPushSid = id;
4647
4776
  }
4648
4777
 
4649
4778
  // Advertise new settings to the peer. node's session.settings() returns nothing -- measured
@@ -4746,6 +4875,12 @@ class Http2ServerSession extends EventEmitter {
4746
4875
  }
4747
4876
 
4748
4877
  goaway(code = NO_ERROR, lastStreamID = this._maxInboundSid, reason) {
4878
+ // node_http2.cc Http2Session::Goaway: `if (lastStreamID <= 0) lastStreamID =
4879
+ // nghttp2_session_get_last_proc_stream_id(session)`. For a server that is the highest
4880
+ // stream id received from the peer, so an explicit 0 keeps an open request alive.
4881
+ if (lastStreamID <= 0) {
4882
+ lastStreamID = this._maxInboundSid;
4883
+ }
4749
4884
  this.sendGoaway(lastStreamID, code, reason);
4750
4885
  this._flush();
4751
4886
  return this;
@@ -4841,9 +4976,9 @@ class Http2ServerSession extends EventEmitter {
4841
4976
  }
4842
4977
 
4843
4978
  module.exports = { Http2ServerSession, OUR_DEFAULTS, PEER_DEFAULTS, SETTINGS_BY_ID,
4844
- ID_BY_SETTING, MAX_OUT_BATCH, MAX_SESSION_HOLD, STREAM_HOLD_CHARGE, BODY_MIN,
4979
+ ID_BY_SETTING, MAX_OUT_BATCH, STREAM_HOLD_CHARGE, BODY_MIN,
4845
4980
  STAGE_MIN, MAX_SHAPES, MAX_SEND_BLOCK, PRIORITY_SPECLEN,
4846
- strictSingleValueFields, hashBlock, hashPieces, kBoundSession,
4981
+ strictSingleValueFields, validateConnectionWindowSize, hashBlock, hashPieces, kBoundSession,
4847
4982
  proxySocketHandler, extError, urlOrigin, checkAltSvc, buildOriginPayload,
4848
4983
  checkPing, invalidSession, pingCancelled, checkSettings, buildSubmission,
4849
4984
  submissionValues, accumulateCustom, customView, validateRemoteCustomSettings,
@@ -214,6 +214,13 @@ class Http2ServerStream extends Http2Stream {
214
214
  get destroyed() {
215
215
  return this._destroyed;
216
216
  }
217
+ // node's stream exposes these as writable fields (Duplex's data properties;
218
+ // `destroyed` writes _destroyed). The compat socket proxy forwards an
219
+ // assignment to them. Prototype-only accessors keep the per-request shape
220
+ // unchanged; the override fields exist only after an assignment.
221
+ set destroyed(value) {
222
+ this._destroyed = value;
223
+ }
217
224
 
218
225
  get closed() {
219
226
  // node's STREAM_FLAGS_CLOSED (core.js:2458) -- set by close() at entry, so the
@@ -238,8 +245,15 @@ class Http2ServerStream extends Http2Stream {
238
245
  }
239
246
 
240
247
  get readable() {
248
+ if (this._readableOverridden === true) {
249
+ return this._readableOverride;
250
+ }
241
251
  return !this._destroyed && this._errorEmitted !== true && this._eofEmitted !== true;
242
252
  }
253
+ set readable(value) {
254
+ this._readableOverridden = true;
255
+ this._readableOverride = value;
256
+ }
243
257
 
244
258
  get readableEnded() {
245
259
  return this._eofEmitted === true;
@@ -284,8 +298,15 @@ class Http2ServerStream extends Http2Stream {
284
298
  }
285
299
 
286
300
  get writable() {
301
+ if (this._writableOverridden === true) {
302
+ return this._writableOverride;
303
+ }
287
304
  return !this._destroyed && !this._ending && this._streamErrored === undefined;
288
305
  }
306
+ set writable(value) {
307
+ this._writableOverridden = true;
308
+ this._writableOverride = value;
309
+ }
289
310
 
290
311
  get writableEnded() {
291
312
  return this._ending || (this._destroyed && this._streamErrored === undefined);
@@ -728,12 +749,14 @@ class Http2ServerStream extends Http2Stream {
728
749
  // node's Writable.end flips _writableState.ending here, before anything is sent
729
750
  // -- even when the body is still parked on window credit. 'aborted' reads it.
730
751
  this._ending = true;
731
- if (!this.headersSent) {
752
+ if (!this.headersSent && !this._closing) {
732
753
  // A body takes the auto-respond of write() above; an empty end() is where h2lean and node
733
754
  // part company, and the split is written down in AGENTS.md section 10: node puts NOTHING on
734
755
  // the wire for `end()` before respond() -- no HEADERS, no DATA, no END_STREAM, and
735
756
  // headersSent stays false -- while h2lean answers a plain 200 rather than leave a stream
736
- // that no peer will ever see an answer on.
757
+ // that no peer will ever see an answer on. close() ends the writable side too, but node's
758
+ // closeStream does not start a response there, so the flag close() sets at entry keeps
759
+ // this h2lean-only answer out of the teardown.
737
760
  this.respond({ ':status': 200 });
738
761
  }
739
762
  if (this._state.localClose === 1) {
@@ -744,6 +767,19 @@ class Http2ServerStream extends Http2Stream {
744
767
  }
745
768
  return this;
746
769
  }
770
+ if (this._closing && !this.headersSent) {
771
+ // A stream close ends the writable side of an unresponded stream without
772
+ // staging anything: node's shutdownWritable has no HEADERS and no DATA to
773
+ // submit there, and a DATA/ES on an unopened stream is a protocol error
774
+ // for the peer. The RST_STREAM close() submits is the only wire work;
775
+ // close()'s _destroy records the local half after this returns. The
776
+ // writable 'finish' is still owed before that teardown, as on node.
777
+ this._scheduleFinish();
778
+ if (cb) {
779
+ this._tick(cb);
780
+ }
781
+ return this;
782
+ }
747
783
  const buf = chunk == null ? EMPTY : (typeof chunk === 'string'
748
784
  ? Buffer.from(chunk, encoding || 'utf8') : chunk);
749
785
  // A stream that still owes a trailer block must not close the stream with its body.
@@ -893,18 +929,19 @@ class Http2ServerStream extends Http2Stream {
893
929
  // closeStream (core.js:2071-2101) is the base method both sides share. It sets
894
930
  // STREAM_FLAGS_CLOSED and rstCode at ENTRY, before the abort and the RST decision
895
931
  // -- a second close() is a no-op even while the teardown still waits on 'finish'.
896
- // h2lean sets the flag after the end() below instead: this end() is the one place
897
- // the auto-respond runs, and respond() refuses a closed stream -- setting the flag
898
- // first would throw out of close() on the unresponded shape node's plain end()
899
- // never reaches (AGENTS.md section 10).
932
+ // The end() below still ends the writable side, but its h2lean-only auto-respond
933
+ // is suppressed through _closing: respond() refuses a closed stream, so the
934
+ // marker cannot be deferred past that call the way it used to be.
935
+ this._closedFlag = true;
936
+ this.rstCode = code;
900
937
  const ending = this._ending;
901
938
  if (!ending) {
902
939
  this.aborted = true;
903
940
  this.emit('aborted');
941
+ this._closing = true;
904
942
  this.end();
943
+ this._closing = false;
905
944
  }
906
- this._closedFlag = true;
907
- this.rstCode = code;
908
945
  if (ending && this._writableFinished !== true && code === NO_ERROR) {
909
946
  this.once('finish', () => this._destroy(code, true));
910
947
  } else {
@@ -927,6 +964,14 @@ class Http2ServerStream extends Http2Stream {
927
964
  if (this._destroyed || this.closed) {
928
965
  throw errorOf('ERR_HTTP2_INVALID_STREAM', 'The stream has been destroyed');
929
966
  }
967
+ // node checks headersSent immediately after the liveness rule
968
+ // (internal/http2/core.js:3260, v26.12.1): a call after respond() throws
969
+ // ERR_HTTP2_HEADERS_AFTER_RESPOND before validation or framing, so no extra
970
+ // HEADERS reaches the peer (message from internal/errors.js:1271).
971
+ if (this.headersSent) {
972
+ throw errorOf('ERR_HTTP2_HEADERS_AFTER_RESPOND',
973
+ 'Cannot specify additional headers after response initiated');
974
+ }
930
975
  // `{ info: true }` is node's separate rule for these blocks: :status must be 100..199
931
976
  // (101 has its own error), there is no default status and no generated date.
932
977
  // prepare() performs that validation before the copy is made, and the plan it
@@ -949,13 +994,13 @@ class Http2ServerStream extends Http2Stream {
949
994
 
950
995
  priority() {
951
996
  // RFC 9218 deprecates the priority scheme; node still accepts the call but
952
- // refuses a destroyed stream (internal/http2/core.js:2617). Returning true
953
- // without reordering anything is the honest v1 answer. The DEP0194 warning
954
- // is attached below the class, byte-identical to node's (typo included).
997
+ // refuses a destroyed stream (internal/http2/core.js:2617) and returns
998
+ // undefined -- the shared prototype method has no return statement. The
999
+ // DEP0194 warning is attached below the class, byte-identical to node's
1000
+ // (typo included).
955
1001
  if (this._destroyed) {
956
1002
  throw errorOf('ERR_HTTP2_INVALID_STREAM', 'The stream has been destroyed');
957
1003
  }
958
- return true;
959
1004
  }
960
1005
 
961
1006
  get pushAllowed() {