h2lean 0.19.9 → 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.
package/lib/headers.js CHANGED
@@ -243,8 +243,11 @@ function neverNames(fields, count, flags) {
243
243
  return names;
244
244
  }
245
245
 
246
- function httpError(code, msg) {
247
- const err = new Error(msg);
246
+ // node's internal/errors.js gives these codes fixed classes; most of this module's
247
+ // validation errors are plain Error, so callers opt into node's class explicitly rather
248
+ // than changing the helper's default for every other site.
249
+ function httpError(code, msg, Ctor = Error) {
250
+ const err = new Ctor(msg);
248
251
  err.code = code;
249
252
  return err;
250
253
  }
@@ -384,7 +387,8 @@ function parse(headers,
384
387
  // pseudo-headers are the ones RFC 9113 8.3.1 defines.
385
388
  if (key !== ':method' && key !== ':path' && key !== ':scheme'
386
389
  && key !== ':authority' && key !== ':protocol') {
387
- throw httpError('ERR_HTTP2_PSEUDOHEADER_NOT_ALLOWED', `cannot send ${key} in a request`);
390
+ throw httpError('ERR_HTTP2_INVALID_PSEUDOHEADER',
391
+ `"${key}" is an invalid pseudoheader or is used incorrectly`, TypeError);
388
392
  }
389
393
  const val = String(Array.isArray(raw) ? raw[0] : raw);
390
394
  if (key === ':method' && !isToken.test(val)) {
@@ -400,7 +404,8 @@ function parse(headers,
400
404
  continue;
401
405
  }
402
406
  if (key !== ':status') {
403
- throw httpError('ERR_HTTP2_PSEUDOHEADER_NOT_ALLOWED', `cannot send ${key} in a response`);
407
+ throw httpError('ERR_HTTP2_INVALID_PSEUDOHEADER',
408
+ `"${key}" is an invalid pseudoheader or is used incorrectly`, TypeError);
404
409
  }
405
410
  const single = Array.isArray(raw) ? raw[0] : raw;
406
411
  // node coerces with `statusCode | 0` -- not Number(), and not a range check on the
@@ -419,11 +424,12 @@ function parse(headers,
419
424
  // upgrade can only be expressed as a connection-specific field, and RFC 9113 8.2.2
420
425
  // removes those from this protocol.
421
426
  if (code === 101) {
422
- throw httpError('ERR_HTTP2_STATUS_101', 'HTTP status code 101 is disallowed');
427
+ throw httpError('ERR_HTTP2_STATUS_101',
428
+ 'HTTP status code 101 (Switching Protocols) is forbidden in HTTP/2');
423
429
  }
424
430
  if (code < 100 || code >= 200) {
425
431
  throw httpError('ERR_HTTP2_INVALID_INFO_STATUS',
426
- `invalid informational status code: ${single}`);
432
+ `Invalid informational status code: ${single}`, RangeError);
427
433
  }
428
434
  }
429
435
  status = code;
@@ -432,7 +438,8 @@ function parse(headers,
432
438
  }
433
439
 
434
440
  if (!isFieldName(key)) {
435
- throw httpError('ERR_INVALID_HTTP_TOKEN', `${key} is an invalid header token`);
441
+ throw httpError('ERR_INVALID_HTTP_TOKEN',
442
+ `Header name must be a valid HTTP token ["${key}"]`, TypeError);
436
443
  }
437
444
  if (CONNECTION_SPECIFIC.has(key)) {
438
445
  // node's ERR_HTTP2_INVALID_CONNECTION_HEADERS is a TypeError with the
@@ -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,14 +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
- // SETTINGS_INITIAL_WINDOW_SIZE is per-stream: node's connection receive
1306
- // window stays at 65535 (measured at 'session' on the running binary with
1307
- // { initialWindowSize: 16384 }), and only new streams take the setting.
1308
- effectiveLocalWindowSize: 65535,
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,
1309
1346
  effectiveRecvDataLength: 0,
1310
1347
  nextStreamID: 2,
1311
- localWindowSize: 65535,
1348
+ localWindowSize: Math.max(65535, connectionWindowSize),
1312
1349
  lastProcStreamID: 0,
1313
1350
  remoteWindowSize: 65535,
1314
1351
  outboundQueueSize: 0,
@@ -1346,11 +1383,18 @@ class Http2ServerSession extends EventEmitter {
1346
1383
  // would cross the budget (node_http2.cc CanAddStream / OnHeader). The charge
1347
1384
  // leaves with the stream in _dropStream, so a connection that drains can open
1348
1385
  // new streams again. node counts queued outbound bytes too; those are already
1349
- // bounded separately by _heldCost (MAX_SESSION_HOLD). The session's own
1386
+ // bounded by the same budget through _holdLimit / _heldCost. The session's own
1350
1387
  // scratch and staging buffers open the budget, as sizeof(Http2Session) does
1351
1388
  // on node; _appendHdr adds the header assembly buffer when it exists.
1352
1389
  this._memLimit = typeof opts.maxSessionMemory === 'number'
1353
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;
1354
1398
  this._memUsed = SESSION_MEM_CHARGE;
1355
1399
  // Outbound padding: node's C++ switch only acts on 0/1/2; every other
1356
1400
  // number is an unpadded session (measured on a live node 26 server).
@@ -1453,10 +1497,10 @@ class Http2ServerSession extends EventEmitter {
1453
1497
  // already cut out of the queue wait in _esRequeue for the same reason.
1454
1498
  this._esMarkers = new Map();
1455
1499
  this._esRequeue = [];
1456
- // Connection-level send window: starts at the peer default (initialWindowSize), but
1457
- // can be overridden by the `connectionWindowSize` option (node's Http2Session option).
1458
- this._connSendWin = typeof opts.connectionWindowSize === 'number'
1459
- ? 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;
1460
1504
  this._prevInitialWin = PEER_DEFAULTS.initialWindowSize;
1461
1505
  this._connRecvUsed = 0; // consumed bytes owed back to the connection
1462
1506
  this._blocked = null; // streams waiting on credit
@@ -1660,6 +1704,14 @@ class Http2ServerSession extends EventEmitter {
1660
1704
  this.alpnProtocol = 'h2c';
1661
1705
  }
1662
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
+ }
1663
1715
  // node's setupHandle announces the server `origins` option with one ORIGIN frame -- server
1664
1716
  // sessions only, and only when the option is an array -- right after the initial SETTINGS and
1665
1717
  // before 'connect'. A bad entry throws out of origin() synchronously, from this connect
@@ -2278,12 +2330,21 @@ class Http2ServerSession extends EventEmitter {
2278
2330
  // "sending a goaway frame has no other effect"), so the application's 'goaway' listener is
2279
2331
  // the peer's decision, never our own. Announcing our own here made a listener fire on a
2280
2332
  // shutdown it had no part in.
2281
- const tail = reason ? Buffer.byteLength(reason) : 0;
2282
- 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);
2283
2344
  body.writeUInt32BE(lastStreamID >>> 0, 0);
2284
2345
  body.writeUInt32BE(code, 4);
2285
2346
  if (tail) {
2286
- body.write(reason, 8);
2347
+ opaque.copy(body, 8);
2287
2348
  }
2288
2349
  this._frame(GOAWAY, 0, 0, body, true);
2289
2350
  this._goawaySent = true;
@@ -2874,6 +2935,9 @@ class Http2ServerSession extends EventEmitter {
2874
2935
  return;
2875
2936
  }
2876
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;
2877
2941
  const p = this._headersPrefix(buf, start, len, sid, flags, len);
2878
2942
  if (p < 0) {
2879
2943
  return;
@@ -3565,7 +3629,7 @@ class Http2ServerSession extends EventEmitter {
3565
3629
  // refusal clears itself: credit returns, _release drains, the charge drops below the bound.
3566
3630
  // What is bounded is the cost of accepting, not the total ever: an application that ignores
3567
3631
  // backpressure can still write into a stalled stream without limit.
3568
- if (this._heldCost() >= MAX_SESSION_HOLD) {
3632
+ if (this._heldCost() >= this._holdLimit) {
3569
3633
  this.sendRst(sid, REFUSED_STREAM);
3570
3634
  this._refused.push(sid);
3571
3635
  this._rejectedStreams++;
@@ -3688,11 +3752,15 @@ class Http2ServerSession extends EventEmitter {
3688
3752
  stream._reqPath = reqPath;
3689
3753
  stream._reqSensitive = sensitive;
3690
3754
  // node's argument order; the field list is the session's shared decode array
3691
- // or a cached one, so the raw list handed out is always a copy. In the compat
3692
- // path the copy is also the stable list the lazy request object builds from
3693
- // (the scratch's backing array is cleared in place by the next decode), so it
3694
- // travels with the stream even when no emit will carry it.
3695
- 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;
3696
3764
  stream._reqFields = raw;
3697
3765
  if (headers !== undefined) {
3698
3766
  stream._requestHeaders = headers;
@@ -3715,7 +3783,7 @@ class Http2ServerSession extends EventEmitter {
3715
3783
  // does, and emitting it into a listenerless session would drop the request
3716
3784
  // the compat callback was meant to receive.
3717
3785
  if (this.listenerCount('stream') > 0) {
3718
- this.emit('stream', stream, headers, end ? OPT_END_STREAM : OPT_NO_END_STREAM, raw);
3786
+ this.emit('stream', stream, headers, this._hdrFlags, raw);
3719
3787
  } else if (this._onStreamCompat !== null) {
3720
3788
  this._onStreamCompat(stream);
3721
3789
  }
@@ -3966,7 +4034,8 @@ class Http2ServerSession extends EventEmitter {
3966
4034
 
3967
4035
  // What this connection currently costs in answers it cannot send. Two terms because the flood
3968
4036
  // that needs bounding is many small stalled responses, and charging only their payloads would let
3969
- // 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.
3970
4039
  _heldCost() {
3971
4040
  return this._heldBytes
3972
4041
  + (this._blocked === null ? 0 : this._blocked.size * STREAM_HOLD_CHARGE);
@@ -4125,7 +4194,17 @@ class Http2ServerSession extends EventEmitter {
4125
4194
  if (len < 8) {
4126
4195
  this._fatal(FRAME_SIZE_ERROR, 'GOAWAY payload too short'); return;
4127
4196
  }
4128
- 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;
4129
4208
  this._goawayCode = buf.readUInt32BE(start + 4);
4130
4209
  // the debug data goes to the application, which may keep it: the same reason as
4131
4210
  // the PING payload above. allocUnsafe + copy instead of Buffer.from(subarray) for
@@ -4197,10 +4276,13 @@ class Http2ServerSession extends EventEmitter {
4197
4276
  // 640 KiB upload (tools/probe-conn-credit.js): node releases the connection window in steps of
4198
4277
  // 32768 octets -- half the 65535 it advertises -- and the same threshold here takes h2lean's
4199
4278
  // cadence from one frame per read batch to the same half-window steps, at the same throughput.
4200
- // A peer that keeps sending is therefore credited before its window can run out, so the
4201
- // anti-deadlock rule that this counter exists for still holds; below the threshold the bytes
4202
- // stay owed, and the next batch pays them.
4203
- 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) {
4204
4286
  return;
4205
4287
  }
4206
4288
  const inc = this._connRecvUsed;
@@ -4793,6 +4875,12 @@ class Http2ServerSession extends EventEmitter {
4793
4875
  }
4794
4876
 
4795
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
+ }
4796
4884
  this.sendGoaway(lastStreamID, code, reason);
4797
4885
  this._flush();
4798
4886
  return this;
@@ -4888,9 +4976,9 @@ class Http2ServerSession extends EventEmitter {
4888
4976
  }
4889
4977
 
4890
4978
  module.exports = { Http2ServerSession, OUR_DEFAULTS, PEER_DEFAULTS, SETTINGS_BY_ID,
4891
- 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,
4892
4980
  STAGE_MIN, MAX_SHAPES, MAX_SEND_BLOCK, PRIORITY_SPECLEN,
4893
- strictSingleValueFields, hashBlock, hashPieces, kBoundSession,
4981
+ strictSingleValueFields, validateConnectionWindowSize, hashBlock, hashPieces, kBoundSession,
4894
4982
  proxySocketHandler, extError, urlOrigin, checkAltSvc, buildOriginPayload,
4895
4983
  checkPing, invalidSession, pingCancelled, checkSettings, buildSubmission,
4896
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