h2lean 0.19.4 โ†’ 0.19.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -292,7 +292,7 @@ None silently returns a wrong answer: a missing method is `undefined`, so callin
292
292
 
293
293
  **Behavioural differences** (full reasoning in the header comment of the affected file and [AGENTS.md](./AGENTS.md) ยง10):
294
294
 
295
- - ๐ŸŽ›๏ธ **Options accepted but ignored:** `paddingStrategy` (no frame padding is produced), `maxSessionMemory` (no session-memory DoS accounting), `headerHintTimeout`/`headerHintSize` (no 1xx informational-flood guard).
295
+ - ๐ŸŽ›๏ธ **Options accepted but ignored:** `headerHintTimeout`/`headerHintSize` (no 1xx informational-flood guard). `paddingStrategy` (0/1/2, with node's 8-octet-aligned and 255-octet-pad wire shapes) and `maxSessionMemory` (per-stream and retained-header budget with node's ENHANCE_YOUR_CALM refusal and callback-failure teardown) are now implemented; see [SECURITY.md](./SECURITY.md).
296
296
  - ๐Ÿšช The **graceful-close predicate**, the **spurious `200` on `end()` with no body**, a **response queued in the same batch as a refusal**, the **`COMPRESSION_ERROR` vs `FRAME_SIZE_ERROR`** verdict, the **teardown event order**, and **`req.pause()/read()` not slowing the peer** (credit is window-bounded, not per-`read()`) differ from node โ€” each pinned as a KNOWN DIVERGENCE in the test suite.
297
297
 
298
298
  ## ๐Ÿ“š Documentation
@@ -250,6 +250,15 @@ class Http2ClientSession extends EventEmitter {
250
250
  // maxOriginSetSize is client-only and validated by connect(); the server
251
251
  // session leaves it undefined so ORIGIN frames over h2s accumulate unbounded.
252
252
  this._maxOriginSetSize = opts.maxOriginSetSize;
253
+ // paddingStrategy is a per-session node option (internal/http2/util.js:259)
254
+ // and applies to every outbound HEADERS/DATA frame. maxSessionMemory is
255
+ // accepted by connect() and forwarded to the C++ session, but a client's
256
+ // streams are created locally by request(): measured on a live node 26
257
+ // client with a 1 MB budget and 3000 unanswered requests, none is refused
258
+ // and no session error fires. The server-side budget is the one that bounds
259
+ // untrusted inbound work; there is nothing for the client to enforce here.
260
+ this._padding = opts.paddingStrategy === f.PADDING_ALIGNED ? f.PADDING_ALIGNED
261
+ : opts.paddingStrategy === f.PADDING_MAX ? f.PADDING_MAX : f.PADDING_NONE;
253
262
  // enablePush defaults to true on the client (node's initializeOptions sets
254
263
  // NGHTTP2_SETTINGS_ENABLE_PUSH = 1 for clients; the server's OUR_DEFAULTS has
255
264
  // false because a server does not receive pushes). The application can override
@@ -653,19 +662,46 @@ class Http2ClientSession extends EventEmitter {
653
662
  // staging buffer, because it is a view into memory the next call rewrites -- the HPACK
654
663
  // scratch block -- and those payloads are tens of bytes.
655
664
  _frame(type, flags, sid, payload, owned) {
656
- const len = payload === null || payload === undefined ? 0 : payload.length;
657
- if (owned && len >= BODY_MIN) {
665
+ const bodyLen = payload === null || payload === undefined ? 0 : payload.length;
666
+ let len = bodyLen;
667
+ let pad = 0;
668
+ let padded = false;
669
+ if (this._padding !== f.PADDING_NONE && (type === f.DATA || type === f.HEADERS)) {
670
+ const total = f.padTotal(len, this._padding, this.remoteSettings.maxFrameSize);
671
+ if (total > len) {
672
+ pad = total - len - 1;
673
+ padded = true;
674
+ flags |= f.F_PADDED;
675
+ len = total;
676
+ }
677
+ }
678
+ if (owned && bodyLen >= BODY_MIN) {
658
679
  this._commit(); // what is staged was produced earlier, so it
659
680
  // has to go out first
660
681
  const head = Buffer.allocUnsafe(HEADER_LEN);
661
682
  writeHeader(head, 0, len, type, flags, sid);
662
- this._outQ.push(head, payload);
683
+ let body = payload;
684
+ if (padded) {
685
+ body = Buffer.allocUnsafe(len);
686
+ body[0] = pad;
687
+ if (bodyLen) {
688
+ f.copyInto(body, 1, payload, 0, bodyLen);
689
+ }
690
+ body.fill(0, 1 + bodyLen, len);
691
+ }
692
+ this._outQ.push(head, body);
663
693
  } else {
664
694
  this._need(HEADER_LEN + len);
665
695
  const off = this._stageLen;
666
696
  writeHeader(this._stage, off, len, type, flags, sid);
667
- if (len) {
668
- f.copyInto(this._stage, off + HEADER_LEN, payload, 0, len);
697
+ if (padded) {
698
+ this._stage[off + HEADER_LEN] = pad;
699
+ if (bodyLen) {
700
+ f.copyInto(this._stage, off + HEADER_LEN + 1, payload, 0, bodyLen);
701
+ }
702
+ this._stage.fill(0, off + HEADER_LEN + 1 + bodyLen, off + HEADER_LEN + len);
703
+ } else if (bodyLen) {
704
+ f.copyInto(this._stage, off + HEADER_LEN, payload, 0, bodyLen);
669
705
  }
670
706
  this._stageLen = off + HEADER_LEN + len;
671
707
  }
@@ -1277,6 +1313,23 @@ class Http2ClientSession extends EventEmitter {
1277
1313
  }
1278
1314
  sentBound = bound;
1279
1315
  const max = this.remoteSettings.maxFrameSize;
1316
+ if (this._padding !== f.PADDING_NONE) {
1317
+ // Padding is opt-in, so keep the single-stage layout of the common path.
1318
+ // Encode into one owned buffer and let _sendHeaders/_frame pad each frame;
1319
+ // the table-size update has to be written before the fields either way.
1320
+ const raw = Buffer.allocUnsafe(cap);
1321
+ let endOff = enc.takeSizeUpdateInto(raw, 0);
1322
+ enc.unsettled = false;
1323
+ for (let i = 0; i < list.length; i += 3) {
1324
+ endOff = enc.write(raw, endOff, list[i], list[i + 1], list[i + 2]);
1325
+ }
1326
+ if (hp !== undefined && hp !== null && typeof hp === 'object') {
1327
+ this._blocks.set(hp, { epoch: enc.epoch,
1328
+ block: Buffer.from(raw.subarray(0, endOff)), bound });
1329
+ }
1330
+ this._sendHeaders(sid, raw.subarray(0, endOff), end, bound, true);
1331
+ return;
1332
+ }
1280
1333
  const frames = Math.max(1, Math.ceil(cap / max));
1281
1334
  this._need(HEADER_LEN + cap + HEADER_LEN * (frames - 1));
1282
1335
  const dst = this._stage;
@@ -1518,6 +1571,12 @@ class Http2ClientSession extends EventEmitter {
1518
1571
  // withheld from the body rides on a zero-length DATA instead (the same rule the
1519
1572
  // server path applies in lib/Http2Stream.js sendTrailers, measured against node). A
1520
1573
  // pending table-size update makes the block non-empty, so it is never dropped here.
1574
+ // With padding enabled the empty DATA end() submits alongside the
1575
+ // trailers carries a pad-length octet and becomes visible on the wire,
1576
+ // ahead of the END_STREAM frame (measured on node 26).
1577
+ if (this._padding !== f.PADDING_NONE) {
1578
+ this._frame(DATA, 0, stream.id, null, false);
1579
+ }
1521
1580
  this._frame(DATA, F_END_STREAM, stream.id, null, false);
1522
1581
  } else {
1523
1582
  if (this._sendHeaders(stream.id, block, true, bound, false)) {
@@ -2121,10 +2180,17 @@ class Http2ClientSession extends EventEmitter {
2121
2180
  this._hdrLen += len;
2122
2181
  return;
2123
2182
  }
2183
+ // Size the first buffer for the frame in hand: a 16 KiB HEADERS would
2184
+ // otherwise allocate the 8 KiB default and immediately discard it for a
2185
+ // doubled one. The backing store stays with the session, so the first
2186
+ // capacity is the one the whole block is assembled into.
2124
2187
  if (this._hdr === null) {
2125
- this._hdr = Buffer.allocUnsafe(8192);
2126
- }
2127
- if (this._hdrLen + len > this._hdr.length) {
2188
+ let cap = STAGE_MIN;
2189
+ while (cap < len) {
2190
+ cap *= 2;
2191
+ }
2192
+ this._hdr = Buffer.allocUnsafe(cap);
2193
+ } else if (this._hdrLen + len > this._hdr.length) {
2128
2194
  let cap = this._hdr.length * 2;
2129
2195
  while (cap < this._hdrLen + len) {
2130
2196
  cap *= 2;
package/lib/frames.js CHANGED
@@ -70,6 +70,45 @@ function writeHeader(dst, off, len, type, flags, streamId) {
70
70
  dst.writeUInt32BE(streamId >>> 0, off + 5); // reserved bit stays 0
71
71
  }
72
72
 
73
+ // Outbound padding strategies. node passes the raw option through to C++
74
+ // (internal/http2/util.js:259) and its switch (node_http2.cc OnSelectPadding)
75
+ // only has cases for 0, 1 and 2; every other number falls through to "no
76
+ // padding" (measured: 16/32/.../1024 produce unpadded frames).
77
+ const PADDING_NONE = 0, PADDING_ALIGNED = 1, PADDING_MAX = 2;
78
+
79
+ // Total payload length of a padded frame, given its unpadded length and the
80
+ // peer's SETTINGS_MAX_FRAME_SIZE. Mirrors node's OnSelectPadding and the two
81
+ // helpers it calls (node_http2.cc:954/971): ALIGNED rounds the whole frame
82
+ // (length + 9-octet header) up to a multiple of eight, MAX asks for the full
83
+ // frame size, and nghttp2 caps the result at one pad-length octet plus 255
84
+ // pad octets. A result that leaves no room for the pad-length octet means no
85
+ // PADDED flag. Returns the unpadded length when no padding applies.
86
+ function padTotal(len, strategy, maxPayload) {
87
+ if (strategy === PADDING_NONE) {
88
+ return len;
89
+ }
90
+ let total;
91
+ if (strategy === PADDING_MAX) {
92
+ total = maxPayload;
93
+ } else {
94
+ const r = (len + HEADER_LEN) & 7;
95
+ if (r === 0) {
96
+ return len;
97
+ }
98
+ total = len + (8 - r);
99
+ }
100
+ if (total > len + 256) {
101
+ total = len + 256;
102
+ }
103
+ if (total > maxPayload) {
104
+ total = maxPayload;
105
+ }
106
+ // A zero pad length is still a PADDED frame: the pad-length octet itself is
107
+ // the padding (measured: a 6-octet body under ALIGNED goes out as len=7,
108
+ // padlen=0 on node 26).
109
+ return total >= len + 1 ? total : len;
110
+ }
111
+
73
112
  // RFC 9113 6.1: a padded DATA frame's payload is one octet of pad length, then
74
113
  // the data, then that many octets of padding. The views a payload arrived in are
75
114
  // therefore not the payload: the pad length has to come off the front and the
@@ -147,6 +186,7 @@ module.exports = {
147
186
  DATA, HEADERS, PRIORITY, RST_STREAM, SETTINGS, PUSH_PROMISE, PING, GOAWAY,
148
187
  WINDOW_UPDATE, CONTINUATION, ALTSVC, ORIGIN,
149
188
  F_END_STREAM, F_ACK, F_END_HEADERS, F_PADDED, F_PRIORITY,
189
+ PADDING_NONE, PADDING_ALIGNED, PADDING_MAX, padTotal,
150
190
  NO_ERROR, PROTOCOL_ERROR, INTERNAL_ERROR, FLOW_CONTROL_ERROR, SETTINGS_TIMEOUT,
151
191
  STREAM_CLOSED, FRAME_SIZE_ERROR, REFUSED_STREAM, CANCEL, COMPRESSION_ERROR,
152
192
  CONNECT_ERROR, ENHANCE_YOUR_CALM, INADEQUATE_SECURITY, HTTP_1_1_REQUIRED,
@@ -1039,6 +1039,32 @@ const DEFAULT_MAX_INVALID_FRAMES = 1000;
1039
1039
  const DEFAULT_MAX_REJECTED_STREAMS = 100;
1040
1040
  const DEFAULT_MAX_OUTSTANDING_PINGS = 10;
1041
1041
 
1042
+ // maxSessionMemory is expressed in decimal megabytes by node's JS layer
1043
+ // (util.js:279, MathMax(1, ...)) and multiplied by 1 000 000 by the C++ layer
1044
+ // (node_http2.cc:210), whose default is 10 000 000 (node_http2.h:40).
1045
+ const DEFAULT_MAX_SESSION_MEMORY = 10 * 1000 * 1000;
1046
+ // node checks and charges sizeof(Http2Stream) per live stream
1047
+ // (node_http2.cc:915/925) plus name.length + value.length + 32 per header
1048
+ // (:2745). sizeof is a C++ compile-time constant: compiled against the v26.12.1
1049
+ // headers it is 360 octets, not the ~800 an earlier indirect estimate assigned
1050
+ // it. nghttp2 also charges its own per-stream allocation to the same budget
1051
+ // (current_session_memory(), node_http2.h:792); h2lean has no nghttp2, so it
1052
+ // adds a 131-octet allowance derived from the live trip point with this test's
1053
+ // header block. The sum is a bound, not a byte-exact model: indexed
1054
+ // pseudo-headers and nghttp2's hash-table growth move node's trip point.
1055
+ const STREAM_MEM_CHARGE = 360 + 131;
1056
+ // The session's own persistent buffers count against node's budget too: node
1057
+ // includes sizeof(Http2Session) (760 octets in the same probe) in
1058
+ // current_session_memory(). h2lean's JS counterpart is the pair of scratch
1059
+ // buffers plus the first staging buffer; the header assembly buffer is charged
1060
+ // when it is actually allocated, in _appendHdr.
1061
+ const SESSION_MEM_CHARGE = HEADER_LEN + 6 + STAGE_MIN;
1062
+ // nghttp2 answers a failed stream-open callback with this session error
1063
+ // (node_http2.cc:1073-1085, NGHTTP2_ERR_CALLBACK_FAILURE). Measured on a live
1064
+ // node 26 server: ERR_HTTP2_ERROR with this message on both 'sessionError' and
1065
+ // the session's 'error', and GOAWAY(INTERNAL_ERROR) with empty debug data.
1066
+ const CALLBACK_FAILURE = 'The user callback function failed';
1067
+
1042
1068
  // The error the invalid-frame budget dies of: node's OnInvalidFrame sets
1043
1069
  // custom_recv_error_code_ = "ERR_HTTP2_TOO_MANY_INVALID_FRAMES" (node_http2.cc),
1044
1070
  // whose message internal/errors defines as this string. Measured on a live
@@ -1312,6 +1338,21 @@ class Http2ServerSession extends EventEmitter {
1312
1338
  this._rejectedStreams = 0;
1313
1339
  this._maxRejectedStreams = typeof opts.maxSessionRejectedStreams === 'number'
1314
1340
  ? opts.maxSessionRejectedStreams : DEFAULT_MAX_REJECTED_STREAMS;
1341
+ // maxSessionMemory: charge each live stream its record and its retained
1342
+ // header block, and refuse a new one with ENHANCE_YOUR_CALM when the charge
1343
+ // would cross the budget (node_http2.cc CanAddStream / OnHeader). The charge
1344
+ // leaves with the stream in _dropStream, so a connection that drains can open
1345
+ // new streams again. node counts queued outbound bytes too; those are already
1346
+ // bounded separately by _heldCost (MAX_SESSION_HOLD). The session's own
1347
+ // scratch and staging buffers open the budget, as sizeof(Http2Session) does
1348
+ // on node; _appendHdr adds the header assembly buffer when it exists.
1349
+ this._memLimit = typeof opts.maxSessionMemory === 'number'
1350
+ ? Math.max(1, opts.maxSessionMemory) * 1000000 : DEFAULT_MAX_SESSION_MEMORY;
1351
+ this._memUsed = SESSION_MEM_CHARGE;
1352
+ // Outbound padding: node's C++ switch only acts on 0/1/2; every other
1353
+ // number is an unpadded session (measured on a live node 26 server).
1354
+ this._padding = opts.paddingStrategy === f.PADDING_ALIGNED ? f.PADDING_ALIGNED
1355
+ : opts.paddingStrategy === f.PADDING_MAX ? f.PADDING_MAX : f.PADDING_NONE;
1315
1356
  // The settings submissions this side sent and has not had answered, oldest first: one entry
1316
1357
  // per SETTINGS frame awaiting its ACK. Queue order is node's answer rule too (client-side
1317
1358
  // _settingsAcks). Each entry holds { cb, values } where values are the ackValues from
@@ -1629,13 +1670,40 @@ class Http2ServerSession extends EventEmitter {
1629
1670
  // because it is a view into memory the next call rewrites -- the HPACK scratch block
1630
1671
  // in lib/headers.js -- and those payloads are tens of bytes.
1631
1672
  _frame(type, flags, sid, payload, owned) {
1632
- const len = payload === null || payload === undefined ? 0 : payload.length;
1633
- if (owned && len >= BODY_MIN) {
1673
+ const bodyLen = payload === null || payload === undefined ? 0 : payload.length;
1674
+ let len = bodyLen;
1675
+ // Only DATA and HEADERS carry padding (RFC 9113 6.1/6.2). node's nghttp2
1676
+ // callback selects the total padded payload length; the frame gets PADDED
1677
+ // and a leading pad-length octet only when the selection actually grew it.
1678
+ let pad = 0;
1679
+ let padded = false;
1680
+ if (this._padding !== f.PADDING_NONE && (type === DATA || type === HEADERS)) {
1681
+ const total = f.padTotal(len, this._padding, this.remoteSettings.maxFrameSize);
1682
+ if (total > len) {
1683
+ pad = total - len - 1;
1684
+ padded = true;
1685
+ flags |= f.F_PADDED;
1686
+ len = total;
1687
+ }
1688
+ }
1689
+ if (owned && bodyLen >= BODY_MIN) {
1634
1690
  this._commit(); // what is staged was produced earlier, so it
1635
1691
  // has to go out first
1636
1692
  const head = Buffer.allocUnsafe(HEADER_LEN);
1637
1693
  writeHeader(head, 0, len, type, flags, sid);
1638
- this._outQ.push(head, payload);
1694
+ let body = payload;
1695
+ if (padded) {
1696
+ // A padded payload cannot travel by reference: the pad-length octet
1697
+ // goes in front and the zero tail has to be written. This buffer is
1698
+ // ours, so it may still go into _outQ as an owned view.
1699
+ body = Buffer.allocUnsafe(len);
1700
+ body[0] = pad;
1701
+ if (bodyLen) {
1702
+ f.copyInto(body, 1, payload, 0, bodyLen);
1703
+ }
1704
+ body.fill(0, 1 + bodyLen, len);
1705
+ }
1706
+ this._outQ.push(head, body);
1639
1707
  if (type === DATA && (flags & F_END_STREAM)) {
1640
1708
  this._esMarkers.set(sid, { q0: this._outQ.length - 2, head });
1641
1709
  }
@@ -1643,8 +1711,14 @@ class Http2ServerSession extends EventEmitter {
1643
1711
  this._need(HEADER_LEN + len);
1644
1712
  const off = this._stageLen;
1645
1713
  writeHeader(this._stage, off, len, type, flags, sid);
1646
- if (len) {
1647
- f.copyInto(this._stage, off + HEADER_LEN, payload, 0, len);
1714
+ if (padded) {
1715
+ this._stage[off + HEADER_LEN] = pad;
1716
+ if (bodyLen) {
1717
+ f.copyInto(this._stage, off + HEADER_LEN + 1, payload, 0, bodyLen);
1718
+ }
1719
+ this._stage.fill(0, off + HEADER_LEN + 1 + bodyLen, off + HEADER_LEN + len);
1720
+ } else if (bodyLen) {
1721
+ f.copyInto(this._stage, off + HEADER_LEN, payload, 0, bodyLen);
1648
1722
  }
1649
1723
  this._stageLen = off + HEADER_LEN + len;
1650
1724
  if (type === DATA && (flags & F_END_STREAM)) {
@@ -1882,6 +1956,34 @@ class Http2ServerSession extends EventEmitter {
1882
1956
  const prefix = prefixSid === undefined ? 0 : 4;
1883
1957
  const cap = prep.hit === undefined ? prep.cap : prep.hit.bytes.length;
1884
1958
  const frames = Math.max(1, Math.ceil((prefix + cap) / max));
1959
+ if (this._padding !== f.PADDING_NONE) {
1960
+ // Padding is opt-in, so the in-place single-stage layout is left to the
1961
+ // common path: a padded frame needs a leading pad-length octet and a
1962
+ // zero tail inserted into every frame of the block, which cannot be done
1963
+ // by shifting the already-written CONTINUATION headers. Encode into one
1964
+ // owned buffer and let _frame() pad each HEADERS/CONTINUATION on the way
1965
+ // out (CONTINUATION itself is not padding-eligible in RFC 9113 6.3).
1966
+ const raw = Buffer.allocUnsafe(prefix + cap);
1967
+ if (prefix !== 0) {
1968
+ raw.writeUInt32BE(prefixSid, 0);
1969
+ }
1970
+ const rawLen = hdr.writePrepared(prep, this, raw, prefix);
1971
+ const count = Math.max(1, Math.ceil(rawLen / max));
1972
+ for (let i = 0; i < count; i++) {
1973
+ const take = Math.min(rawLen - i * max, max);
1974
+ let bits = 0;
1975
+ if (count === 1) {
1976
+ bits = F_END_HEADERS | (end ? F_END_STREAM : 0);
1977
+ } else if (i === 0) {
1978
+ bits = end ? F_END_STREAM : 0;
1979
+ } else if (i === count - 1) {
1980
+ bits = F_END_HEADERS;
1981
+ }
1982
+ this._frame(i === 0 ? type : f.CONTINUATION, bits, sid,
1983
+ raw.subarray(i * max, i * max + take), true);
1984
+ }
1985
+ return false;
1986
+ }
1885
1987
  this._need(HEADER_LEN + prefix + cap + HEADER_LEN * (frames - 1));
1886
1988
  const dst = this._stage;
1887
1989
  const off = this._stageLen;
@@ -2820,9 +2922,6 @@ class Http2ServerSession extends EventEmitter {
2820
2922
  this._hdrLen += len;
2821
2923
  return;
2822
2924
  }
2823
- if (this._hdr === null) {
2824
- this._hdr = Buffer.allocUnsafe(8192);
2825
- }
2826
2925
  // No maxHeaderListSize test here, although this is where the octets are counted: the limit
2827
2926
  // is about the size of the header LIST, which is only known once the block is decoded, and
2828
2927
  // h2lean applies it there (_processHeaders). Measured against node, an over-limit block
@@ -2831,14 +2930,28 @@ class Http2ServerSession extends EventEmitter {
2831
2930
  // which turns one bad request into an error for every other client on the session. The
2832
2931
  // buffer is bounded without it: MAX_CONTINUATIONS frames of at most
2833
2932
  // localSettings.maxFrameSize octets each, 8 x 16 KiB by default.
2834
- if (this._hdrLen + len > this._hdr.length) {
2835
- let cap = this._hdr.length * 2;
2933
+ // Size the first buffer for the frame in hand: a 16 KiB HEADERS would
2934
+ // otherwise allocate the 8 KiB default and immediately throw it away for
2935
+ // a doubled one. STAGE_MIN is the same starting size as the staging buffer,
2936
+ // and the backing store stays with the session for its whole life, so its
2937
+ // octets join the other persistent buffers in the maxSessionMemory budget.
2938
+ if (this._hdr === null) {
2939
+ let cap = STAGE_MIN;
2940
+ while (cap < len) {
2941
+ cap *= 2;
2942
+ }
2943
+ this._hdr = Buffer.allocUnsafe(cap);
2944
+ this._memUsed += cap;
2945
+ } else if (this._hdrLen + len > this._hdr.length) {
2946
+ const old = this._hdr.length;
2947
+ let cap = old * 2;
2836
2948
  while (cap < this._hdrLen + len) {
2837
2949
  cap *= 2;
2838
2950
  }
2839
2951
  const bigger = Buffer.allocUnsafe(cap);
2840
2952
  f.copyInto(bigger, 0, this._hdr, 0, this._hdrLen);
2841
2953
  this._hdr = bigger;
2954
+ this._memUsed += cap - old;
2842
2955
  }
2843
2956
  f.copyInto(this._hdr, this._hdrLen, buf, start, start + len);
2844
2957
  this._hdrLen += len;
@@ -3468,6 +3581,28 @@ class Http2ServerSession extends EventEmitter {
3468
3581
  return;
3469
3582
  }
3470
3583
 
3584
+ // maxSessionMemory: node refuses a stream it cannot account for with the same
3585
+ // code and the same rejected-stream escalation as a concurrency refusal
3586
+ // (node_http2.cc:1073-1085). The charge is one stream record plus the header
3587
+ // block the application may keep alive for the stream's lifetime. Charging
3588
+ // here -- after the block is decoded, before the stream is created -- is the
3589
+ // only place the peer is still refused without a handler holding its object.
3590
+ const memCharge = STREAM_MEM_CHARGE + bytes;
3591
+ if (this._memUsed + memCharge > this._memLimit) {
3592
+ // node compares the PRE-increment count (rejected_stream_count_++ > max)
3593
+ // and submits no RST on the frame that trips it: max+1 refusals go out,
3594
+ // the next opens nothing and ends the session.
3595
+ if (this._rejectedStreams++ > this._maxRejectedStreams) {
3596
+ return this._fatal(INTERNAL_ERROR, CALLBACK_FAILURE, 'ERR_HTTP2_ERROR', '');
3597
+ }
3598
+ this.sendRst(sid, ENHANCE_YOUR_CALM);
3599
+ this._refused.push(sid);
3600
+ if (this._refused.length > MAX_REFUSED_HISTORY) {
3601
+ this._refused.shift();
3602
+ }
3603
+ return;
3604
+ }
3605
+
3471
3606
  // The request object is built here only when a reader is already known: a
3472
3607
  // session 'stream' listener takes it as the event argument, and the compat
3473
3608
  // request materializes it at the first req.headers access (lib/server/compat.js),
@@ -3544,6 +3679,8 @@ class Http2ServerSession extends EventEmitter {
3544
3679
  }
3545
3680
  this._streams.set(sid, stream);
3546
3681
  this._liveStreams++;
3682
+ stream._memCharge = memCharge;
3683
+ this._memUsed += memCharge;
3547
3684
  if (promised !== undefined) {
3548
3685
  stream._expLen = +promised;
3549
3686
  }
@@ -4193,6 +4330,12 @@ class Http2ServerSession extends EventEmitter {
4193
4330
  return;
4194
4331
  }
4195
4332
  this._liveStreams--;
4333
+ // the stream record and its retained header block no longer count against
4334
+ // maxSessionMemory, so a drained connection can open streams again
4335
+ if (stream._memCharge !== undefined) {
4336
+ this._memUsed -= stream._memCharge;
4337
+ stream._memCharge = undefined;
4338
+ }
4196
4339
  // inbound bytes the application never got still owe the connection window
4197
4340
  this._abandon(stream);
4198
4341
  if (killed) {
@@ -763,6 +763,12 @@ class Http2ServerStream extends Http2Stream {
763
763
  // end() sets _ending before anything is sent, and the peer-reset 'aborted' rule
764
764
  // reads it -- the fast path must carry the same state (test/compat.test.js).
765
765
  this._ending = true;
766
+ // node's compat end() also submits an empty DATA before the trailer END.
767
+ // Without padding that zero-payload frame is invisible; with padding its
768
+ // pad-length octet reaches the peer ahead of the END_STREAM frame.
769
+ if (this.session._padding !== frames.PADDING_NONE) {
770
+ this.session._frame(frames.DATA, 0, this.id, null);
771
+ }
766
772
  this.session._frame(frames.DATA, frames.F_END_STREAM, this.id, null);
767
773
  this._esStaged = true;
768
774
  this._endLocalSide();
@@ -846,6 +852,13 @@ class Http2ServerStream extends Http2Stream {
846
852
  return this;
847
853
  }
848
854
  if (empty) {
855
+ // node's compat end() submits an empty DATA before the trailers arrive.
856
+ // Without padding that zero-payload frame is invisible on the wire; with
857
+ // padding it carries a pad-length octet, so it goes out here ahead of the
858
+ // END_STREAM frame (measured: f=8 then f=9 on a live node 26 server).
859
+ if (this.session._padding !== frames.PADDING_NONE) {
860
+ this.session._frame(frames.DATA, 0, this.id, null);
861
+ }
849
862
  // sendData() frames the zero-length DATA and ends the local half with it.
850
863
  this.session.sendData(this, EMPTY, true);
851
864
  return this;
@@ -145,6 +145,13 @@ function initHttp2Server(server, options) {
145
145
  maxSessionRejectedStreams: opts.maxSessionRejectedStreams,
146
146
  // Connection-level send window override (separate from per-stream initialWindowSize).
147
147
  connectionWindowSize: opts.connectionWindowSize,
148
+ // Per-session memory budget in decimal MB (node multiplies by 1e6 in C++) and
149
+ // the outbound frame-padding strategy. Both ride through raw: util.js only
150
+ // tests `typeof === 'number'` for each, so the session constructor applies
151
+ // the same test, Math.max(1, ...) for the budget, and the C++ switch's
152
+ // "anything but 0/1/2 is unpadded" rule for the strategy.
153
+ maxSessionMemory: opts.maxSessionMemory,
154
+ paddingStrategy: opts.paddingStrategy,
148
155
  // Validated and copied above, where node's initializeOptions runs
149
156
  // validateSessionOptions -- synchronously, at createServer. The per-entry checks
150
157
  // wait for the session constructor (setupHandle), where node runs them per
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "h2lean",
3
- "version": "0.19.4",
3
+ "version": "0.19.6",
4
4
  "description": "Pure-JavaScript HTTP/2 for Node.js โ€” a drop-in node:http2 replacement (server and client, h2c and TLS) with zero dependencies",
5
5
  "main": "index.js",
6
6
  "files": [