h2lean 0.4.0 → 0.4.2

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
@@ -234,11 +234,32 @@ h2lean terminates **untrusted bytes from the internet** and turns them into obje
234
234
  - **h2spec 146/146** — full RFC 9113/7541 conformance, same verdict as node's own HTTP/2 (`npm run spec`);
235
235
  - **mutation-tested guards** — every defensive limit is rewritten in place and proven to fail the suite ([tools/mutate-guards.js](./tools/mutate-guards.js)).
236
236
 
237
- ## ⚠️ Not Implemented — Said Loudly
237
+ ## ⚠️ Known Divergences From node:http2 — Said Loudly
238
238
 
239
- One API is absent, and it fails **loudly** with `ERR_H2LEAN_NOT_IMPLEMENTED` — never a silent wrong answer:
239
+ The core surface is implemented: server (stream + compat), client (`connect`),
240
+ `performServerHandshake`, and server push (`pushStream` / PUSH_PROMISE reception). The
241
+ remaining gaps against the documented `node:http2` API are enumerated below — each was read
242
+ out of node's docs and confirmed against the current tree (a `in`-probe over live objects).
243
+ None silently returns a wrong answer: a missing method is `undefined`, so calling it throws
244
+ `TypeError`, never a fabricated result.
240
245
 
241
- - **Server push** — removed from browsers in 2022 and considered obsolete; the safer replacement is [Early Hints (103)](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/103).
246
+ **Missing methods / properties** (the compat `(req, res)` request side is complete):
247
+
248
+ - 🌊 **`ServerHttp2Stream` is not a `stream.Duplex`** — it is a bare `EventEmitter`, so `pipe()`, `read()`, `cork()/uncork()`, `setEncoding()` and the `readable*`/`writable*` getters are absent. Deliberate: a Duplex base costs ~1.4 µs/req of intrinsic machinery ([OPTIMIZATION.md](./OPTIMIZATION.md) item 41). `on('data'/'end')`, `pause/resume`, `write/end`, `setTimeout`, `priority`, `sendTrailers` all work.
249
+ - 📄 **`stream.respondWithFD()` / `respondWithFile()`** and the newer **`stream.bufferSize`** — not implemented (nghttp2 `sendfile`-backed in node). Use `createReadStream()` + `stream.write()`; send-side backpressure already gates it.
250
+ - 🔀 **`session.altsvc()` / `session.origin()`** — not implemented (ALTSVC / ORIGIN frames, RFC 7838 / 8336).
251
+ - 🧰 **`ClientHttp2Stream`** inherits the Duplex surface but lacks the base-`Http2Stream` members: `close()`, `priority()`, `setTimeout()`, `sendTrailers()` and the getters `aborted`, `pending`, `state`, `sentTrailers`, `sentInfoHeaders`, `bufferSize`.
252
+ - 📤 **`res.writeEarlyHints()`** (103 Early Hints) is not implemented (`res.writeInformation()` / `createPushResponse()` are); `Http2ServerResponse` is not an `http.ServerResponse`, so `res.cork()/uncork()` are absent (h2lean coalesces per turn already).
253
+ - ⏱️ **`server.timeout`** getter is absent (`setTimeout()` is present).
254
+
255
+ **Events not emitted:**
256
+
257
+ - 🪤 **`'localSettings'`** (only `'remoteSettings'` fires); **`'tlsClientError'`** on a failed TLS handshake; **`'ready'`** on a stream; **`'altsvc'` / `'origin'`** on the client session (tied to the two methods above).
258
+
259
+ **Behavioural differences** (full reasoning in the header comment of the affected file and [AGENTS.md](./AGENTS.md) §10):
260
+
261
+ - 🎛️ **Options accepted but ignored:** `paddingStrategy` (no frame padding is produced), `maxSessionMemory` (no session-memory DoS accounting), `headerHintTimeout`/`headerHintSize` (no 1xx informational-flood guard).
262
+ - 🚪 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.
242
263
 
243
264
  ## 📚 Documentation
244
265
 
@@ -164,7 +164,25 @@ class ClientHttp2Session extends EventEmitter {
164
164
  // ignore late frames for a pushed stream the application already destroyed
165
165
  // (node does the same: session stays alive, measured v26.12.1).
166
166
  this._maxPushSid = 0;
167
+ // node's maxReservedRemoteStreams connect option: the cap on pushed streams
168
+ // still waiting for their response HEADERS (reserved(remote) in RFC 9113
169
+ // terms). The default 200 and the refusal shape -- RST_STREAM(CANCEL), no
170
+ // 'stream' event, no client error -- were measured on v26.12.1 with 500
171
+ // silent pushes; nghttp2 owns the
172
+ // counter in node, the count is rebuilt from the live streams here.
173
+ this._maxReservedRemoteStreams = opts.maxReservedRemoteStreams === undefined
174
+ ? 200 : opts.maxReservedRemoteStreams;
167
175
  this._streams = new Map();
176
+ // Streams whose wire life is over (_dropStream) but whose Duplex has not
177
+ // emitted 'close' yet -- an unread response body keeps the readable half
178
+ // open. node's session counts a stream until it is destroyed, not until
179
+ // END_STREAM (internal/http2/core.js kMaybeDestroy reads state.streams.size,
180
+ // and the stream leaves that map in its destroy path), so a graceful close
181
+ // waits for these too. Without the wait the session destroyed itself ahead
182
+ // of the stream's 'close' and orphaned it: the event never fired at all
183
+ // (measured on live node: it emits req end/close then session
184
+ // close; h2lean hung with the stream alive and unreachable).
185
+ this._wireDone = new Set();
168
186
  this._outboundQueue = []; // requests waiting for a concurrency slot
169
187
  this._decoder = new Decoder(this.localSettings.headerTableSize);
170
188
  this._encoder = new Encoder(this.remoteSettings.headerTableSize,
@@ -244,6 +262,7 @@ class ClientHttp2Session extends EventEmitter {
244
262
  this._hdrLen = 0;
245
263
  this._hdrSid = -1;
246
264
  this._hdrEnd = false;
265
+ this._hdrFlags = 0; // the HEADERS frame's flags, surfaced on 'response'/'push'
247
266
  this._hdrCont = 0;
248
267
  // Non-zero while a PUSH_PROMISE block is being assembled: the promised even
249
268
  // stream id. _finishHeaders routes to _processPushPromise when this is set.
@@ -268,6 +287,15 @@ class ClientHttp2Session extends EventEmitter {
268
287
  this._started = false;
269
288
  this._queuedReq = null; // requests made before 'connect'
270
289
  this._closeRequested = false; // close()/goaway asked to end once drained
290
+ // The error destroy() was handed, and whether destroy() owns the pending
291
+ // 'close' emission. A fatal inbound frame destroys with an ERR_HTTP2_ERROR
292
+ // that must reach the session 'error' event; the deferred emissions below
293
+ // (_onSocketClose / _trackClose) are for the graceful peer-FIN shape only and
294
+ // must neither steal destroy()'s error-carrying nextTick nor fire ahead of it
295
+ // (the documented teardown order is stream error, stream close, session
296
+ // error, session close -- test/client/client-fatal.test.js).
297
+ this._closeError = null;
298
+ this._destroyScheduled = false;
271
299
  this._goawayCode = null;
272
300
  this._goawayLastStreamID = null;
273
301
  this._pings = new Map(); // 8-octet payload -> callback
@@ -536,7 +564,13 @@ class ClientHttp2Session extends EventEmitter {
536
564
  if (this.closed) {
537
565
  throw httpErr('ERR_HTTP2_GOAWAY_SESSION', 'New streams cannot be created after receiving a GOAWAY');
538
566
  }
539
- const options2 = options ? { ...options } : {};
567
+ // No defensive copy of options: node spreads it because it validates and
568
+ // then MUTATES the copy (setAndValidatePriorityOptions, options.endStream =
569
+ // ... in internal/http2/core.js request()); h2lean has no priority options
570
+ // and only reads endStream below, so the copy had no reader -- one object
571
+ // allocation per request removed. A null options now throws where it used
572
+ // to be silently accepted; node throws ERR_INVALID_ARG_TYPE there too
573
+ // (assertIsObject, measured live), so the throw is the closer shape.
540
574
  const list = [];
541
575
  let method = DEFAULT_METHOD;
542
576
  let sawMethod = false;
@@ -570,12 +604,13 @@ class ClientHttp2Session extends EventEmitter {
570
604
  list.push(':method', method);
571
605
  }
572
606
 
573
- let endStream = options2.endStream;
607
+ let endStream = options === undefined ? undefined : options.endStream;
574
608
  if (endStream === undefined) {
575
609
  endStream = payloadMeaningless(method);
576
610
  }
577
611
 
578
612
  const stream = new ClientHttp2Stream(this, this._nextSid, {});
613
+ this._trackClose(stream);
579
614
  this._nextSid += 2; // the id is reserved now, HEADERS may wait
580
615
  stream.endAfterHeaders = endStream;
581
616
  if (endStream) {
@@ -1305,11 +1340,12 @@ class ClientHttp2Session extends EventEmitter {
1305
1340
  }
1306
1341
  this._hdrCont = 0;
1307
1342
  if (flags & F_END_HEADERS) {
1308
- this._processHeaders(sid, (flags & F_END_STREAM) !== 0, buf.subarray(p, p + l));
1343
+ this._processHeaders(sid, (flags & F_END_STREAM) !== 0, buf.subarray(p, p + l), flags);
1309
1344
  return;
1310
1345
  }
1311
1346
  this._hdrSid = sid;
1312
1347
  this._hdrEnd = (flags & F_END_STREAM) !== 0;
1348
+ this._hdrFlags = flags;
1313
1349
  this._hdrLen = 0;
1314
1350
  this._appendHdr(buf, p, l);
1315
1351
  }
@@ -1342,11 +1378,12 @@ class ClientHttp2Session extends EventEmitter {
1342
1378
  l = 0;
1343
1379
  }
1344
1380
  if (flags & F_END_HEADERS) {
1345
- this._processBlockPieces(sid, (flags & F_END_STREAM) !== 0, pieces, p, p + l);
1381
+ this._processBlockPieces(sid, (flags & F_END_STREAM) !== 0, pieces, p, p + l, flags);
1346
1382
  return;
1347
1383
  }
1348
1384
  this._hdrSid = sid;
1349
1385
  this._hdrEnd = (flags & F_END_STREAM) !== 0;
1386
+ this._hdrFlags = flags;
1350
1387
  this._hdrLen = 0;
1351
1388
  this._appendHdrPieces(pieces, p, p + l);
1352
1389
  }
@@ -1392,7 +1429,7 @@ class ClientHttp2Session extends EventEmitter {
1392
1429
  }
1393
1430
 
1394
1431
  _finishHeaders() {
1395
- const sid = this._hdrSid, end = this._hdrEnd;
1432
+ const sid = this._hdrSid, end = this._hdrEnd, flags = this._hdrFlags;
1396
1433
  const push = this._hdrPush;
1397
1434
  this._hdrPush = 0;
1398
1435
  if (this._hdrPieces !== null) {
@@ -1404,7 +1441,7 @@ class ClientHttp2Session extends EventEmitter {
1404
1441
  if (push !== 0) {
1405
1442
  this._processPushPromise(sid, push, pieceConcat(pieces, 0, len));
1406
1443
  } else {
1407
- this._processBlockPieces(sid, end, pieces, 0, len);
1444
+ this._processBlockPieces(sid, end, pieces, 0, len, flags);
1408
1445
  }
1409
1446
  return;
1410
1447
  }
@@ -1414,7 +1451,7 @@ class ClientHttp2Session extends EventEmitter {
1414
1451
  if (push !== 0) {
1415
1452
  this._processPushPromise(sid, push, block);
1416
1453
  } else {
1417
- this._processHeaders(sid, end, block);
1454
+ this._processHeaders(sid, end, block, flags);
1418
1455
  }
1419
1456
  }
1420
1457
 
@@ -1493,11 +1530,33 @@ class ClientHttp2Session extends EventEmitter {
1493
1530
  }
1494
1531
  const fields = flat.items;
1495
1532
  const fcount = flat.count;
1533
+ // maxReservedRemoteStreams: a pushed stream stays reserved until its
1534
+ // response HEADERS arrive (measured: the count releases on the HEADERS,
1535
+ // not on 'end'). Over the cap the promise is refused with RST_STREAM(CANCEL)
1536
+ // and no stream is created -- the late HEADERS/DATA for the id are then the
1537
+ // silent discards below (_maxPushSid covers them). node's nghttp2 does the
1538
+ // same refusal; the block was decoded above either way, HPACK state advances.
1539
+ let reserved = 0;
1540
+ for (const s of this._streams.values()) {
1541
+ if (s._pushed && !s.responseEmitted) {
1542
+ reserved++;
1543
+ }
1544
+ }
1545
+ if (reserved >= this._maxReservedRemoteStreams) {
1546
+ if (promisedSid > this._maxPushSid) {
1547
+ this._maxPushSid = promisedSid;
1548
+ }
1549
+ const body = Buffer.allocUnsafe(4);
1550
+ body.writeUInt32BE(CANCEL, 0);
1551
+ this._frame(RST_STREAM, 0, promisedSid, body, true);
1552
+ return;
1553
+ }
1496
1554
  const headers = this._toObject(fields, fcount);
1497
1555
  // Create the pushed stream. Its writable half is pre-ended: the client never
1498
1556
  // sends a request body for a push (node: writableEnded=true, writableFinished=true
1499
1557
  // at the 'stream' event, measured v26.12.1).
1500
1558
  const stream = new ClientHttp2Stream(this, promisedSid);
1559
+ this._trackClose(stream);
1501
1560
  stream._pushed = true;
1502
1561
  stream.rstCode = 0;
1503
1562
  stream._headersSent = true;
@@ -1550,15 +1609,15 @@ class ClientHttp2Session extends EventEmitter {
1550
1609
  // same block: the octets are the same, so the hash, the cache entry and the
1551
1610
  // fields are the same. `block` is null for the split one, and the range
1552
1611
  // [from, to) of `pieces` is where the block sits in the views.
1553
- _processHeaders(sid, end, block) {
1554
- this._processBlock(sid, end, block, null, 0, 0);
1612
+ _processHeaders(sid, end, block, flags) {
1613
+ this._processBlock(sid, end, block, null, 0, 0, flags);
1555
1614
  }
1556
1615
 
1557
- _processBlockPieces(sid, end, pieces, from, to) {
1558
- this._processBlock(sid, end, null, pieces, from, to);
1616
+ _processBlockPieces(sid, end, pieces, from, to, flags) {
1617
+ this._processBlock(sid, end, null, pieces, from, to, flags);
1559
1618
  }
1560
1619
 
1561
- _processBlock(sid, end, block, pieces, from, to) {
1620
+ _processBlock(sid, end, block, pieces, from, to, flags) {
1562
1621
  const stream = this._streams.get(sid);
1563
1622
  const flat = FLAT;
1564
1623
  // The cache is disabled (null) when stream === undefined (we must decode for
@@ -1636,7 +1695,7 @@ class ClientHttp2Session extends EventEmitter {
1636
1695
  return;
1637
1696
  }
1638
1697
  const headers = this._toObject(fields, fcount);
1639
- stream._onHeaders(headers, end);
1698
+ stream._onHeaders(headers, end, flags);
1640
1699
  if (end) {
1641
1700
  this._dropStream(sid);
1642
1701
  }
@@ -1854,8 +1913,13 @@ class ClientHttp2Session extends EventEmitter {
1854
1913
  // data (not an empty buffer), so the measured event shape matches only if we do.
1855
1914
  this.emit('goaway', code, lastStreamID, debug === null || debug.length === 0
1856
1915
  ? undefined : debug);
1857
- // A GOAWAY with no live streams left ends the connection for a client too.
1858
- if (this._streams.size === 0) {
1916
+ // node begins the graceful shutdown on a NO_ERROR goaway regardless of the
1917
+ // live streams (internal/http2/core.js onGoawayData: `session.close()` --
1918
+ // "No new streams permitted, but existing streams may close naturally on
1919
+ // their own"). Closing only when the stream map is already empty left the
1920
+ // session open forever when the last stream ended after the GOAWAY arrived
1921
+ // (measured on live node: it closes, h2lean hung).
1922
+ if (code === NO_ERROR) {
1859
1923
  this.close();
1860
1924
  }
1861
1925
  return this._open;
@@ -1937,10 +2001,17 @@ class ClientHttp2Session extends EventEmitter {
1937
2001
  code = NO_ERROR;
1938
2002
  }
1939
2003
  if (lastStreamID === undefined || lastStreamID === null) {
1940
- lastStreamID = this._nextSid % 2 === 0 ? this._nextSid - 1 : this._nextSid - 2;
1941
- if (lastStreamID < 0) {
1942
- lastStreamID = 0;
1943
- }
2004
+ // node's goaway() defaults lastStreamID to 0 and the C layer substitutes
2005
+ // nghttp2_session_get_last_proc_stream_id (src/node_http2.cc Http2Session::Goaway:
2006
+ // `if (lastStreamID <= 0) lastStreamID = ...get_last_proc_stream_id`). For a
2007
+ // CLIENT the processed streams are the server-initiated pushes (even ids), so
2008
+ // that number is the highest promised id seen -- _maxPushSid, 0 with no pushes.
2009
+ // Deriving it from _nextSid (the next odd request id) named a client-initiated
2010
+ // stream the server itself opened, which nghttp2 reads as PROTOCOL_ERROR: a
2011
+ // graceful close() echo after the peer's GOAWAY then killed the peer's open
2012
+ // stream (measured on live node: its client sends last=0,
2013
+ // h2lean sent last=1 and the node server answered ERR_HTTP2_ERROR).
2014
+ lastStreamID = this._maxPushSid;
1944
2015
  }
1945
2016
  const tail = reason ? Buffer.byteLength(reason) : 0;
1946
2017
  const body = Buffer.alloc(8 + tail);
@@ -1971,6 +2042,46 @@ class ClientHttp2Session extends EventEmitter {
1971
2042
  }
1972
2043
  }
1973
2044
 
2045
+ // node's routing for an async listener's rejection when EventEmitter
2046
+ // captureRejections is on (internal/http2/core.js:1668, the shared
2047
+ // Http2Session base): a 'stream' listener's rejection destroys that stream
2048
+ // -- for a push, the pushed stream the listener was handed -- every other
2049
+ // event's destroys the session.
2050
+ [EventEmitter.captureRejectionSymbol](err, event, ...args) {
2051
+ if (event === 'stream') {
2052
+ const stream = args[0];
2053
+ // node's streams run with autoDestroy:false (measured on live node:
2054
+ // _readableState.autoDestroy false on a pushed stream), so the rejection's
2055
+ // destroy(err) always reaches a live Duplex and emits 'error'. h2lean's
2056
+ // ClientHttp2Stream auto-destroys when both halves complete, and streams.destroy()
2057
+ // silently drops an error handed to an already-destroyed stream -- a rejection
2058
+ // that lands after a small push body has been fully read would then close the
2059
+ // stream with no 'error' at all (the upstream capture-rejection block-4 shape,
2060
+ // measured on live node: it routes 'kaboom', h2lean went silent). A destroy(err)
2061
+ // that lands while the completion-driven autoDestroy is still queued loses the
2062
+ // error the same way, so the emission is caught by a flag: a stream that does
2063
+ // not report the error synchronously is finished by a direct 'error' emit --
2064
+ // reproducing node's observable behaviour for that race, while a still-live
2065
+ // stream keeps the normal destroy(err) path and its RST.
2066
+ if (stream.destroyed) {
2067
+ if (!stream._readableState.errorEmitted && !stream._writableState.errorEmitted) {
2068
+ stream.emit('error', err);
2069
+ }
2070
+ return;
2071
+ }
2072
+ let reported = false;
2073
+ stream.once('error', () => {
2074
+ reported = true;
2075
+ });
2076
+ stream.destroy(err);
2077
+ if (!reported) {
2078
+ stream.emit('error', err);
2079
+ }
2080
+ } else {
2081
+ this.destroy(err);
2082
+ }
2083
+ }
2084
+
1974
2085
  destroy(err) {
1975
2086
  if (this.destroyed) {
1976
2087
  return;
@@ -1978,6 +2089,8 @@ class ClientHttp2Session extends EventEmitter {
1978
2089
  this.destroyed = true;
1979
2090
  this.closed = true;
1980
2091
  this._open = false;
2092
+ this._closeError = err || null;
2093
+ this._destroyScheduled = true;
1981
2094
  for (const s of this._streams.values()) {
1982
2095
  if (!s.destroyed) {
1983
2096
  s.destroy(err);
@@ -2075,12 +2188,33 @@ class ClientHttp2Session extends EventEmitter {
2075
2188
  if (this.destroyed || this._closeEmitted) {
2076
2189
  return;
2077
2190
  }
2078
- if (this._closeRequested && this._streams.size === 0 && this._outboundQueue.length === 0
2079
- && this._outLen === 0) {
2191
+ if (this._closeRequested && this._streams.size === 0 && this._wireDone.size === 0
2192
+ && this._outboundQueue.length === 0 && this._outLen === 0) {
2080
2193
  this.destroy();
2081
2194
  }
2082
2195
  }
2083
2196
 
2197
+ // The 'close' subscription is installed at construction, before any event can
2198
+ // fire, so the wire-done bookkeeping never races the Duplex's own teardown.
2199
+ // It is the one subscription per stream the session keeps: the mark it clears
2200
+ // is what lets a graceful close outlive an unread response body (see _wireDone).
2201
+ _trackClose(stream) {
2202
+ stream.on('close', () => {
2203
+ this._wireDone.delete(stream);
2204
+ if (this.destroyed && !this._closeEmitted && !this._destroyScheduled
2205
+ && this._wireDone.size === 0) {
2206
+ // The socket is already gone (_onSocketClose deferred to this moment):
2207
+ // the last wire-done stream has closed, so the session 'close' is owed
2208
+ // now -- after the stream's, the order node emits them in. When
2209
+ // destroy() owns the emission (_destroyScheduled) it runs its own
2210
+ // error-carrying nextTick after the streams close; this must not race it.
2211
+ this._emitClose();
2212
+ } else {
2213
+ this._maybeClose();
2214
+ }
2215
+ });
2216
+ }
2217
+
2084
2218
  // _debt is drained at every point that ends a stream's life -- _dropStream (inbound
2085
2219
  // END_STREAM, RST, outbound reset, and the destroy path, which goes through
2086
2220
  // rstStream) -- so the list never grows across a long-lived connection and never
@@ -2109,6 +2243,11 @@ class ClientHttp2Session extends EventEmitter {
2109
2243
  this._removeDebt(stream);
2110
2244
  }
2111
2245
  this._streams.delete(sid);
2246
+ if (stream !== undefined) {
2247
+ // The wire life is over; the Duplex may still owe 'end'/'close' (an unread
2248
+ // body). The session's graceful close waits for that 'close' (_wireDone).
2249
+ this._wireDone.add(stream);
2250
+ }
2112
2251
  this._drainQueue();
2113
2252
  this._maybeClose();
2114
2253
  }
@@ -2163,6 +2302,23 @@ class ClientHttp2Session extends EventEmitter {
2163
2302
  return;
2164
2303
  }
2165
2304
  this.destroyed = true;
2305
+ // destroy() owns the emission when it was called (fatal or graceful): its
2306
+ // nextTick carries the error and runs after the streams' 'close'. Only the
2307
+ // pure peer-FIN shape -- destroyed here, no destroy() pending -- defers to
2308
+ // _trackClose below.
2309
+ if (this._destroyScheduled) {
2310
+ return;
2311
+ }
2312
+ // A wire-done stream whose Duplex has not closed yet (an empty response body
2313
+ // ends on the next tick) still owes its 'close'. node emits the session
2314
+ // 'close' after the streams', not ahead of them (kMaybeDestroy waits for
2315
+ // state.streams to empty), so the emission waits for _wireDone to clear --
2316
+ // _trackClose finishes it. Without this the peer's FIN raced the stream's
2317
+ // 'close' and the application never saw the stream event at all (measured on
2318
+ // live node, the upstream capture-rejection shape).
2319
+ if (this._wireDone.size > 0) {
2320
+ return;
2321
+ }
2166
2322
  this._emitClose();
2167
2323
  }
2168
2324
 
@@ -2171,6 +2327,11 @@ class ClientHttp2Session extends EventEmitter {
2171
2327
  return;
2172
2328
  }
2173
2329
  this._closeEmitted = true;
2330
+ // A deferred emission (the graceful peer-FIN path) still carries whatever
2331
+ // error destroy() was handed, so a fatal teardown never loses its 'error'.
2332
+ if (!err) {
2333
+ err = this._closeError;
2334
+ }
2174
2335
  if (err) {
2175
2336
  this.emit('error', err);
2176
2337
  }
@@ -54,7 +54,12 @@ class ClientHttp2Stream extends Duplex {
54
54
  this.endAfterHeaders = false;
55
55
  // The readable half has seen END_STREAM (server finished the response body).
56
56
  this._remoteEnded = false;
57
- this.rstCode = null;
57
+ // node keeps rstCode in the stream's C-side state, initialised with
58
+ // NGHTTP2_NO_ERROR (internal/http2/core.js:2152 `rstCode: NGHTTP2_NO_ERROR`), so a
59
+ // stream that closed without a reset reports 0 -- the upstream
60
+ // max-reserved-streams test reads exactly that off the parent request.
61
+ // h2lean only overwrites it on a real reset (_onRst).
62
+ this.rstCode = 0;
58
63
  this.headersSent = false; // node flips this once HEADERS are sent
59
64
  this.sentHeaders = null;
60
65
  this.sentStatus = null;
@@ -107,7 +112,7 @@ class ClientHttp2Stream extends Duplex {
107
112
  // `headers` is a null-prototype object with `:status` coerced to a number and
108
113
  // `set-cookie` as an array, built the way the server's `_toObject` builds a
109
114
  // request, so both stacks hand the application the same shape.
110
- _onHeaders(headers, end) {
115
+ _onHeaders(headers, end, flags) {
111
116
  const status = headers[':status'];
112
117
  if (status !== undefined && status >= 100 && status < 200 && !this.responseEmitted) {
113
118
  // 1xx informational (including the 100 Continue that node surfaces as
@@ -122,7 +127,11 @@ class ClientHttp2Stream extends Duplex {
122
127
  this.responseEmitted = true;
123
128
  this.responseHeaders = headers;
124
129
  this.sentStatus = status;
125
- this.emit(this._pushed ? 'push' : 'response', headers);
130
+ // node passes the raw HEADERS frame flags as the second argument and a
131
+ // rawHeaders array as the third (core.js: emit(stream, event, obj, flags,
132
+ // headers)); the rawHeaders array is deliberately not built -- one flat
133
+ // array per response is a cost no h2lean consumer has asked for.
134
+ this.emit(this._pushed ? 'push' : 'response', headers, flags);
126
135
  } else {
127
136
  // A second final-status block after the response is the trailer block.
128
137
  this.trailers = headers;
@@ -145,6 +154,17 @@ class ClientHttp2Stream extends Duplex {
145
154
  }
146
155
  this._remoteEnded = true;
147
156
  this.push(null);
157
+ // node kicks the readable half here so an unconsumed response still reaches
158
+ // 'end' (and, with the writable finished, autoDestroy's 'close'): its
159
+ // onStreamClose calls stream.read(0) on the client branch
160
+ // (internal/http2/core.js:641). push(null) alone only sets state.ended; the
161
+ // 'end' event waits for a read(), so a request the application never resumed
162
+ // -- the upstream capture-rejection shape, an empty 500 body -- never closed
163
+ // (measured on live node: req 'close' fires, h2lean did
164
+ // not). read(0) is harmless when a consumer is already draining: endReadable
165
+ // de-dupes the scheduled tick, and a buffered body keeps length > 0 so 'end'
166
+ // still waits for the last chunk.
167
+ this.read(0);
148
168
  }
149
169
 
150
170
  // The peer reset this stream, or we reset it locally.
package/lib/compat.js CHANGED
@@ -12,8 +12,6 @@
12
12
  // frame produced in one turn of the loop into a single write().
13
13
  // * res.write() returning false is honest backpressure, and 'drain' is emitted
14
14
  // when the send window reopens.
15
- // * createPushResponse() throws ERR_H2LEAN_NOT_IMPLEMENTED (no server push in
16
- // v1) instead of failing later with a protocol error.
17
15
  // * res 'finish' means the local half of the stream was closed, which for
18
16
  // h2lean happens as the frames are queued for the socket; node reports it
19
17
  // when the stream closes, which is later. A response the peer cut short
@@ -304,8 +302,11 @@ class Http2ServerRequest extends Readable {
304
302
 
305
303
  // node hands out a Proxy over the stream pretending to be a socket. The real
306
304
  // socket is smaller, faster and answers the same questions (remoteAddress).
305
+ // The session reference is cleared when the stream dies (lib/stream.js
306
+ // _destroy, node core.js:2546), so the socket goes with it.
307
307
  get socket() {
308
- return this._stream.session.socket;
308
+ const session = this._stream.session;
309
+ return session === undefined ? undefined : session.socket;
309
310
  }
310
311
  get connection() {
311
312
  return this.socket;
@@ -371,7 +372,7 @@ class Http2ServerRequest extends Readable {
371
372
  } else {
372
373
  stream._startConsuming();
373
374
  }
374
- if (!owedEnd && stream.state.remoteClose === 1) {
375
+ if (!owedEnd && stream._state.remoteClose === 1) {
375
376
  this._ended = true;
376
377
  this.push(null);
377
378
  }
@@ -458,7 +459,11 @@ class Http2ServerResponse extends Stream {
458
459
  return this._stream;
459
460
  }
460
461
  get socket() {
461
- return this._state.closed ? undefined : this._stream.session.socket;
462
+ if (this._state.closed) {
463
+ return undefined;
464
+ }
465
+ const session = this._stream.session;
466
+ return session === undefined ? undefined : session.socket;
462
467
  }
463
468
  get connection() {
464
469
  return this.socket;
@@ -471,7 +476,7 @@ class Http2ServerResponse extends Stream {
471
476
  return this._state.ending;
472
477
  }
473
478
  get writableFinished() {
474
- return this._stream.state.localClose === 1;
479
+ return this._stream._state.localClose === 1;
475
480
  }
476
481
  get writableNeedDrain() {
477
482
  return this._stream._queued !== null;
@@ -802,11 +807,31 @@ class Http2ServerResponse extends Stream {
802
807
  }
803
808
 
804
809
  createPushResponse(headers, callback) {
805
- const e = err('ERR_H2LEAN_NOT_IMPLEMENTED', 'h2lean v1 does not implement server push');
810
+ // node: validateFunction(callback) first, then the closed-response check,
811
+ // then pushStream with an empty options object (internal/http2/compat,
812
+ // createPushResponse; pinned by test/upstream-push.test.js).
806
813
  if (typeof callback !== 'function') {
814
+ const e = new TypeError(
815
+ `The "callback" argument must be of type function. Received ${describeType(callback)}`);
816
+ e.code = 'ERR_INVALID_ARG_TYPE';
807
817
  throw e;
808
818
  }
809
- process.nextTick(callback, e);
819
+ if (this._state.closed) {
820
+ process.nextTick(callback, err('ERR_HTTP2_INVALID_STREAM', 'The stream has been destroyed'));
821
+ return;
822
+ }
823
+ this._stream.pushStream(headers, {}, (e, stream) => {
824
+ if (e) {
825
+ callback(e);
826
+ return;
827
+ }
828
+ const push = new Http2ServerResponse(stream);
829
+ // A pushed stream has no request, so nothing else installs the compat
830
+ // dispatch on it; the response's handlers need it the same way the
831
+ // request's constructor installs it for a normal exchange.
832
+ stream._compatDispatch = compatDispatch;
833
+ callback(null, push);
834
+ });
810
835
  }
811
836
  }
812
837
 
package/lib/headers.js CHANGED
@@ -418,8 +418,12 @@ function parse(headers, sensitive,
418
418
  throw httpError('ERR_INVALID_HTTP_TOKEN', `${key} is an invalid header token`);
419
419
  }
420
420
  if (CONNECTION_SPECIFIC.has(key)) {
421
- throw httpError('ERR_HTTP2_INVALID_CONNECTION_HEADERS',
422
- `HTTP/1 Connection specific header is forbidden: ${key}`);
421
+ // node's ERR_HTTP2_INVALID_CONNECTION_HEADERS is a TypeError with the
422
+ // plural, quoted form (internal/errors.js; measured on v26.12.1 via
423
+ // pushStream({'connection':'test'}), pinned by test/upstream-push.test.js).
424
+ const err = new TypeError(`HTTP/1 Connection specific headers are forbidden: "${key}"`);
425
+ err.code = 'ERR_HTTP2_INVALID_CONNECTION_HEADERS';
426
+ throw err;
423
427
  }
424
428
  const never = neverList !== null && neverList.has(key);
425
429
  if (Array.isArray(raw)) {
package/lib/server.js CHANGED
@@ -64,6 +64,7 @@
64
64
 
65
65
  const net = require('node:net');
66
66
  const tls = require('node:tls');
67
+ const { EventEmitter } = require('node:events');
67
68
  const { Http2Session, OUR_DEFAULTS, strictSingleValueFields } = require('./session');
68
69
  const { onServerStream, Http2ServerRequest, Http2ServerResponse, describeType } = require('./compat');
69
70
 
@@ -478,6 +479,46 @@ function performServerHandshake(socket, options) {
478
479
  return new Http2Session(socket, opts);
479
480
  }
480
481
 
482
+ // node's routing for an async listener's rejection when EventEmitter
483
+ // captureRejections is on (Http2Server.prototype[captureRejectionSymbol],
484
+ // internal/http2/core.js:3608), shared by both transports: a 'stream' rejection
485
+ // destroys the stream once it has responded and answers 500 before it has;
486
+ // a 'request' rejection strips the headers the handler set and answers 500
487
+ // with the status text, or destroys the response once it is under way.
488
+ function serverRejection(err, event, ...args) {
489
+ switch (event) {
490
+ case 'stream': {
491
+ const stream = args[0];
492
+ if (stream.sentHeaders) {
493
+ stream.destroy(err);
494
+ } else {
495
+ stream.respond({ ':status': 500 });
496
+ stream.end();
497
+ }
498
+ break;
499
+ }
500
+ case 'request': {
501
+ const res = args[1];
502
+ if (!res.headersSent && !res.finished) {
503
+ // Don't leak headers.
504
+ for (const name of res.getHeaderNames()) {
505
+ res.removeHeader(name);
506
+ }
507
+ res.statusCode = 500;
508
+ res.end(require('node:http').STATUS_CODES[500]);
509
+ } else {
510
+ res.destroy();
511
+ }
512
+ break;
513
+ }
514
+ default:
515
+ net.Server.prototype[EventEmitter.captureRejectionSymbol]
516
+ .call(this, err, event, ...args);
517
+ }
518
+ }
519
+ Http2Server.prototype[EventEmitter.captureRejectionSymbol] = serverRejection;
520
+ Http2SecureServer.prototype[EventEmitter.captureRejectionSymbol] = serverRejection;
521
+
481
522
  module.exports = {
482
523
  Http2Server, Http2SecureServer, createServer, createSecureServer, performServerHandshake,
483
524
  notImplemented, Http2ServerRequest, Http2ServerResponse
package/lib/session.js CHANGED
@@ -508,10 +508,10 @@ class Http2Session extends EventEmitter {
508
508
  // (which node reports as state.lastProcStreamID and puts in GOAWAY's last-stream
509
509
  // id) moves there. A GOAWAY sent for a frame refused after that point therefore
510
510
  // names the stream of the refused frame, measured on v26.12.1 for an undecodable
511
- // block and a header list over maxHeaderListSize (last=1 against h2lean's 0,
512
- // out/probe-last-id.js) -- the shape a client reads as its retry boundary, so a
511
+ // block and a header list over maxHeaderListSize (last=1 against h2lean's 0) --
512
+ // the shape a client reads as its retry boundary, so a
513
513
  // lower id makes it resend a request that was already acted on. Control frames
514
- // never move it -- measured on the same probe: WINDOW_UPDATE, RST_STREAM and DATA
514
+ // never move it -- measured the same way: WINDOW_UPDATE, RST_STREAM and DATA
515
515
  // refused above the line all answer last=1, the served stream, on BOTH stacks --
516
516
  // and frames refused before the acceptance point (over max frame size, malformed
517
517
  // padding or priority, an even id) do not either: nghttp2 fails them before the
@@ -1372,6 +1372,15 @@ class Http2Session extends EventEmitter {
1372
1372
  this._fatal(PROTOCOL_ERROR, 'SETTINGS_ENABLE_PUSH must be 0 or 1');
1373
1373
  return;
1374
1374
  }
1375
+ // The two boolean settings land in remoteSettings as booleans, the way node's
1376
+ // getUnpackedSettings turns them (`settings.enablePush = value !== 0`,
1377
+ // internal/http2/core.js:3786). The upstream push-disabled test reads
1378
+ // `settings.enablePush === false` off the remoteSettings event; the wire is a
1379
+ // uint32, and handing the raw 0/1 to the application diverged from node.
1380
+ if (id === 0x2 || id === 0x6) {
1381
+ seen[name] = value !== 0;
1382
+ continue;
1383
+ }
1375
1384
  seen[name] = value;
1376
1385
  }
1377
1386
  // RFC 9113 6.9.2: a new INITIAL_WINDOW_SIZE shifts every open stream window
@@ -1906,7 +1915,7 @@ class Http2Session extends EventEmitter {
1906
1915
  // those is RFC 7540's ("MUST treat that as a connection error of type STREAM_CLOSED") where
1907
1916
  // RFC 9113 says "MAY". Answering them with an error is not a fix -- it would end the connection
1908
1917
  // on a frame the RFC lets the server keep quiet about (AGENTS.md 10).
1909
- if (existing !== undefined ? existing.state.remoteClose === 1
1918
+ if (existing !== undefined ? existing._state.remoteClose === 1
1910
1919
  : (!this._isGone(sid) && this._ended.includes(sid))) {
1911
1920
  this._fatal(STREAM_CLOSED, 'HEADERS after the peer ended the stream');
1912
1921
  return;
@@ -2173,7 +2182,7 @@ class Http2Session extends EventEmitter {
2173
2182
  this._connRecvUsed += l;
2174
2183
  return undefined;
2175
2184
  }
2176
- if (stream.state.remoteClose === 1) {
2185
+ if (stream._state.remoteClose === 1) {
2177
2186
  // The same rule while the stream is still in the table, which is how it reaches a server that
2178
2187
  // has not answered yet: measured on node (probe cases U10, U11) in both batching shapes, the
2179
2188
  // connection ends. RFC 9113 6.1 reads a DATA on a stream outside "open"/"half-closed(local)"
@@ -2207,7 +2216,7 @@ class Http2Session extends EventEmitter {
2207
2216
  stream._bodyLen += l;
2208
2217
  this.state.localWindowSize -= l;
2209
2218
  this.state.effectiveRecvDataLength += l;
2210
- stream.state.localWindowSize -= l;
2219
+ stream._state.localWindowSize -= l;
2211
2220
  return stream;
2212
2221
  }
2213
2222
 
@@ -2510,7 +2519,7 @@ class Http2Session extends EventEmitter {
2510
2519
  if (stream._unannounced << 2 >= this.localSettings.initialWindowSize) {
2511
2520
  const inc = stream._unannounced;
2512
2521
  stream._unannounced = 0;
2513
- stream.state.localWindowSize += inc;
2522
+ stream._state.localWindowSize += inc;
2514
2523
  this._windowUpdate(stream.id, inc);
2515
2524
  }
2516
2525
  // A reader that shows up between batches (a timer, an await) has to be able
@@ -2558,7 +2567,14 @@ class Http2Session extends EventEmitter {
2558
2567
  this._creditConnection();
2559
2568
  this._flush();
2560
2569
  if (this._closing && this._liveStreams === 0) {
2561
- this.socket.end();
2570
+ // The same finish the stream teardown uses, not a raw socket.end(): the
2571
+ // flush above only HANDS the batch to the socket (_frozenLen covers it
2572
+ // until the write callback), and ending here ahead of that callback put
2573
+ // the FIN in front of a response still in flight -- the write after end
2574
+ // was dropped and the peer never saw the HEADERS (measured on live node, the
2575
+ // upstream capture-rejection shape).
2576
+ // _maybeFinishClose waits for _outLen/_frozenLen/_stageLen to clear.
2577
+ this._maybeFinishClose();
2562
2578
  }
2563
2579
  }
2564
2580
 
@@ -2698,13 +2714,30 @@ class Http2Session extends EventEmitter {
2698
2714
  if (!this.closed || this.destroyed) {
2699
2715
  return;
2700
2716
  }
2701
- if (this._liveStreams > 0 || this._outLen > 0 || this._frozenLen > 0) {
2717
+ // _stageLen counts bytes serialised into the staging buffer but not yet
2718
+ // committed to a write (_outLen only sees them once _writePending runs).
2719
+ // Without it a response staged in the same turn as close() -- the handler
2720
+ // answers and then calls server.close() -- was dropped: the FIN went out
2721
+ // ahead of the flush and the peer never saw the HEADERS (measured on live
2722
+ // node, the upstream capture-rejection shape).
2723
+ if (this._liveStreams > 0 || this._outLen > 0 || this._frozenLen > 0 || this._stageLen > 0) {
2702
2724
  return;
2703
2725
  }
2704
2726
  this.socket.end();
2705
2727
  this.destroy(NO_ERROR);
2706
2728
  }
2707
2729
 
2730
+ // node's routing for an async listener's rejection when EventEmitter
2731
+ // captureRejections is on (internal/http2/core.js:1668): a 'stream' listener's
2732
+ // rejection destroys that stream, every other event's destroys the session.
2733
+ [EventEmitter.captureRejectionSymbol](err, event, ...args) {
2734
+ if (event === 'stream') {
2735
+ args[0].destroy(err);
2736
+ } else {
2737
+ this.destroy(err);
2738
+ }
2739
+ }
2740
+
2708
2741
  // node's signature is destroy(error = NGHTTP2_NO_ERROR, code): the first argument may be the
2709
2742
  // Error the application is handed, in which case the second is the code that goes on the wire.
2710
2743
  // That is exactly what a peer's GOAWAY does -- destroy(new ERR_HTTP2_SESSION_ERROR(code),
package/lib/stream.js CHANGED
@@ -25,6 +25,7 @@
25
25
  'use strict';
26
26
 
27
27
  const { EventEmitter } = require('node:events');
28
+ const { deprecate } = require('node:util');
28
29
  const frames = require('./frames');
29
30
  const hdr = require('./headers');
30
31
 
@@ -68,7 +69,8 @@ function autoCloseNT(stream) {
68
69
  }
69
70
 
70
71
  const {
71
- ST_OPEN, ST_HALF_CLOSED_LOCAL, ST_HALF_CLOSED_REMOTE, ST_CLOSED, NO_ERROR, PROTOCOL_ERROR
72
+ ST_OPEN, ST_HALF_CLOSED_LOCAL, ST_HALF_CLOSED_REMOTE, ST_CLOSED, NO_ERROR, PROTOCOL_ERROR,
73
+ INTERNAL_ERROR
72
74
  } = frames;
73
75
 
74
76
  class Http2Stream extends EventEmitter {
@@ -85,7 +87,7 @@ class Http2Stream extends EventEmitter {
85
87
  this.aborted = false;
86
88
  this.endAfterHeaders = false;
87
89
  this.allowHalfOpen = false;
88
- this.state = {
90
+ this._state = {
89
91
  state: ST_OPEN,
90
92
  weight: 16,
91
93
  sumDependencyWeight: 0,
@@ -103,6 +105,7 @@ class Http2Stream extends EventEmitter {
103
105
  this._endPending = false; // END_STREAM arrived with no reader
104
106
  this._consumeState = 0; // 0 no reader, 1 delivering, 2 reader is full
105
107
  this._endQueued = false;
108
+ this._gracefulClose = false; // both halves closed on their own terms (_closeNow)
106
109
  this._waitForTrailers = false;
107
110
  this._pendingTrailers = null; // trailer block waiting behind a queued body
108
111
  this._destroyed = false;
@@ -115,20 +118,42 @@ class Http2Stream extends EventEmitter {
115
118
  return this._destroyed;
116
119
  }
117
120
  get closed() {
118
- return this.state.state === ST_CLOSED;
121
+ return this._state.state === ST_CLOSED;
122
+ }
123
+ // node's public state getter answers {} once the stream is destroyed
124
+ // (internal/http2/core.js:2304, `if (this.destroyed || id === undefined)`);
125
+ // internal code reads _state directly, the way node reads kState.
126
+ get state() {
127
+ return this._destroyed ? {} : this._state;
119
128
  }
120
129
 
121
130
  respond(headers, options) {
122
- // node only throws here (internal/http2/core.js respond(): `if (this.headersSent)
123
- // throw new ERR_HTTP2_HEADERS_SENT()`) and does not emit 'error' on the stream --
131
+ // node guards the stream's life first (internal/http2/core.js respond():
132
+ // `if (this.destroyed || this.closed) throw new ERR_HTTP2_INVALID_STREAM()`),
133
+ // then the one-response rule. Neither throws emits 'error' on the stream --
124
134
  // measured on v26.12.1: a second respond() throws ERR_HTTP2_HEADERS_SENT
125
135
  // ("Response has already been initiated.") with no 'error' event. An emit here
126
136
  // throws out of a stream that has no 'error' listener, which turns the
127
137
  // application's own throw into an uncaught exception node never produces.
138
+ if (this._destroyed || this.closed) {
139
+ throw errorOf('ERR_HTTP2_INVALID_STREAM', 'The stream has been destroyed');
140
+ }
128
141
  if (this.headersSent) {
129
142
  throw errorOf('ERR_HTTP2_HEADERS_SENT', 'Response has already been initiated.');
130
143
  }
144
+ // respond() with no headers is legal (node's prepareResponseHeaders defaults
145
+ // the block to {}; the upstream HEAD-push test answers a push that way).
146
+ if (headers === undefined) {
147
+ headers = {};
148
+ }
131
149
  const opts = options || {};
150
+ // node closes the writable itself for a HEAD request (respond(),
151
+ // internal/http2/core.js: `this.headRequest === true -> this.end()`), and a
152
+ // pushed stream whose end() already ran answers with END_STREAM on the
153
+ // HEADERS. Measured on the wire against live node: node puts
154
+ // HEADERS/ES/EH and no DATA for both shapes; h2lean used to leave a regular
155
+ // HEAD answer open and send the body, which nghttp2 reads as a protocol error.
156
+ const head = this._requestHeaders !== undefined && this._requestHeaders[':method'] === 'HEAD';
132
157
  // node puts a `date` on every response of this API too: prepareResponseHeadersObject()
133
158
  // (internal/http2/core.js:2702) adds one unless the application set one itself or
134
159
  // `options.sendDate` says otherwise -- and its test is `sendDate == null || sendDate`,
@@ -143,8 +168,9 @@ class Http2Stream extends EventEmitter {
143
168
  this.pending = false;
144
169
  this._waitForTrailers = !!opts.waitForTrailers;
145
170
  // node does not infer END_STREAM from the request having ended: the local
146
- // side only closes when the application says so
147
- const empty = opts.endStream === true;
171
+ // side only closes when the application says so -- except for the two shapes
172
+ // above, where node's own end() has already run or runs inside respond().
173
+ const empty = opts.endStream === true || head || this._endQueued;
148
174
  this.session.sendHeaders(this.id, block, empty);
149
175
  if (empty) {
150
176
  // This response has already carried END_STREAM, and nothing may follow it on this
@@ -163,22 +189,40 @@ class Http2Stream extends EventEmitter {
163
189
  if (typeof encoding === 'function') {
164
190
  cb = encoding; encoding = undefined;
165
191
  }
166
- if (this._endQueued || this.state.localClose === 1) {
167
- const err = errorOf('ERR_HTTP2_STREAM_CANCEL', 'stream write after end');
168
- if (cb) {
169
- return process.nextTick(cb, err);
170
- }
171
- this.emit('error', err);
172
- return false;
173
- }
174
192
  // The response starts itself if the application never called respond(). Node does this on
175
193
  // the first WRITE of a server stream, not on the first end(): measured, `write('x')` alone
176
194
  // puts HEADERS{:status 200} on the wire ahead of the DATA. Doing it here as well is what
177
195
  // keeps DATA from arriving on a stream that has no response headers yet -- a peer that sees
178
196
  // DATA first has nothing to attach it to, and nghttp2 answers that with a stream error.
179
- if (!this.headersSent) {
197
+ // The started response may itself end the writable (a HEAD request, see respond()),
198
+ // so the after-end check below runs after this, not before.
199
+ if (!this.headersSent && !this._endQueued && this._state.localClose !== 1) {
180
200
  this.respond({ ':status': 200 });
181
201
  }
202
+ if (this._endQueued || this._state.localClose === 1) {
203
+ // node: Writable's _write answers ERR_STREAM_WRITE_AFTER_END ("write after
204
+ // end") through the callback and errorOrDestroy -- which emits 'error' and
205
+ // destroys a LIVE stream, but is a no-op on one already destroyed
206
+ // (internal/streams/writable.js; measured v26.12.1, pinned by
207
+ // test/upstream-push.test.js, session-destroy).
208
+ const err = errorOf('ERR_STREAM_WRITE_AFTER_END', 'write after end');
209
+ if (cb) {
210
+ process.nextTick(cb, err);
211
+ }
212
+ if (!this._destroyed) {
213
+ this.destroy(err);
214
+ } else if (this._gracefulClose) {
215
+ // node's close is asynchronous, so a write in the same turn as the
216
+ // respond()/end() that finished the stream still hits a LIVE writable:
217
+ // errorOrDestroy emits 'error' (measured on live node: the HEAD-push shape,
218
+ // respond() then write()). h2lean closes synchronously, so
219
+ // the event is owed here instead. A reset or a session destroy is not
220
+ // this shape -- there node's errorOrDestroy is a no-op and no 'error'
221
+ // goes out (the session-destroy case of test/upstream-push.test.js).
222
+ process.nextTick(emitNT, this, 'error', err);
223
+ }
224
+ return false;
225
+ }
182
226
  const buf = typeof chunk === 'string' ? Buffer.from(chunk, encoding || 'utf8') : chunk;
183
227
  const canContinue = this.session.sendData(this, buf, false);
184
228
  if (cb) {
@@ -193,6 +237,17 @@ class Http2Stream extends EventEmitter {
193
237
  } else if (typeof encoding === 'function') {
194
238
  cb = encoding; encoding = null;
195
239
  }
240
+ if (this._endQueued || this._state.localClose === 1) {
241
+ // node: Writable.end() on an ended writable is a no-op that still answers
242
+ // the callback (internal/streams/writable.js end() -> writableEnded checks;
243
+ // measured v26.12.1: respond() on a HEAD request ends the writable itself,
244
+ // and the application's end() after it neither errors nor destroys).
245
+ // write() after end IS the error -- see write() above.
246
+ if (cb) {
247
+ process.nextTick(cb);
248
+ }
249
+ return this;
250
+ }
196
251
  if (!this.headersSent) {
197
252
  // A body takes the auto-respond of write() above; an empty end() is where h2lean and node
198
253
  // part company, and the split is written down in AGENTS.md section 10: node puts NOTHING on
@@ -201,6 +256,14 @@ class Http2Stream extends EventEmitter {
201
256
  // that no peer will ever see an answer on.
202
257
  this.respond({ ':status': 200 });
203
258
  }
259
+ if (this._state.localClose === 1) {
260
+ // the auto-respond above already carried END_STREAM (a HEAD request):
261
+ // there is no body to send, RFC 9113 8.1 forbids one on a HEAD answer
262
+ if (cb) {
263
+ process.nextTick(cb);
264
+ }
265
+ return this;
266
+ }
204
267
  const buf = chunk == null ? EMPTY : (typeof chunk === 'string'
205
268
  ? Buffer.from(chunk, encoding || 'utf8') : chunk);
206
269
  // A stream that still owes a trailer block must not close the stream with its body.
@@ -249,13 +312,22 @@ class Http2Stream extends EventEmitter {
249
312
  }
250
313
 
251
314
  destroy(codeOrError, reason) {
252
- const code = typeof codeOrError === 'number' ? codeOrError : NO_ERROR;
315
+ // node: an Error argument means NGHTTP2_INTERNAL_ERROR on the wire
316
+ // (Http2Stream._destroy, internal/http2/core.js:2518); a number is the RST
317
+ // code itself, and no argument at all is a graceful NO_ERROR close.
318
+ const code = typeof codeOrError === 'number' ? codeOrError
319
+ : (codeOrError != null ? INTERNAL_ERROR : NO_ERROR);
253
320
  this._destroy(code, reason, true, typeof codeOrError === 'object' ? codeOrError : null);
254
321
  }
255
322
 
256
323
  // An informational (1xx) HEADERS block, sent before the final response.
257
324
  // node: Http2Stream.additionalHeaders().
258
325
  additionalHeaders(headers) {
326
+ // node: `if (this.destroyed || this.closed) throw new ERR_HTTP2_INVALID_STREAM()`
327
+ // (internal/http2/core.js additionalHeaders()).
328
+ if (this._destroyed || this.closed) {
329
+ throw errorOf('ERR_HTTP2_INVALID_STREAM', 'The stream has been destroyed');
330
+ }
259
331
  // `{ info: true }` is node's separate rule for these blocks: :status must be 100..199
260
332
  // (101 has its own error), there is no default status and no generated date.
261
333
  const block = hdr.block(headers, undefined, { info: true }, this.session);
@@ -265,8 +337,13 @@ class Http2Stream extends EventEmitter {
265
337
  }
266
338
 
267
339
  priority() {
268
- // RFC 9218 deprecates the priority scheme; node still accepts the call.
269
- // Returning true without reordering anything is the honest v1 answer.
340
+ // RFC 9218 deprecates the priority scheme; node still accepts the call but
341
+ // refuses a destroyed stream (internal/http2/core.js:2617). Returning true
342
+ // without reordering anything is the honest v1 answer. The DEP0194 warning
343
+ // is attached below the class, byte-identical to node's (typo included).
344
+ if (this._destroyed) {
345
+ throw errorOf('ERR_HTTP2_INVALID_STREAM', 'The stream has been destroyed');
346
+ }
270
347
  return true;
271
348
  }
272
349
 
@@ -286,7 +363,7 @@ class Http2Stream extends EventEmitter {
286
363
  // the application answers it through the normal respond()/write()/end() path.
287
364
  pushStream(headers, options, callback) {
288
365
  if (!this.pushAllowed) {
289
- throw errorOf('ERR_HTTP2_PUSH_DISABLED', 'Push is disabled');
366
+ throw errorOf('ERR_HTTP2_PUSH_DISABLED', 'HTTP/2 client has disabled push streams');
290
367
  }
291
368
  if ((this.id & 1) === 0) {
292
369
  throw errorOf('ERR_HTTP2_NESTED_PUSH', 'Nested push is not allowed');
@@ -295,6 +372,18 @@ class Http2Stream extends EventEmitter {
295
372
  callback = options;
296
373
  options = undefined;
297
374
  }
375
+ // node: validateFunction(callback, 'callback') -- the callback is mandatory,
376
+ // checked before options/headers, and the error names what was received
377
+ // (measured v26.12.1: pushStream(h, {}, 'callback') and pushStream(h) both
378
+ // throw ERR_INVALID_ARG_TYPE; pinned by test/upstream-push.test.js).
379
+ if (typeof callback !== 'function') {
380
+ const received = callback === undefined ? 'Received undefined'
381
+ : `Received type ${typeof callback}` +
382
+ (typeof callback === 'string' ? ` ('${callback}')` : '');
383
+ const err = new TypeError(`The "callback" argument must be of type function. ${received}`);
384
+ err.code = 'ERR_INVALID_ARG_TYPE';
385
+ throw err;
386
+ }
298
387
  if (options === undefined || options === null) {
299
388
  options = {};
300
389
  }
@@ -303,11 +392,6 @@ class Http2Stream extends EventEmitter {
303
392
  err.code = 'ERR_INVALID_ARG_TYPE';
304
393
  throw err;
305
394
  }
306
- if (callback !== undefined && typeof callback !== 'function') {
307
- const err = new TypeError('The "callback" argument must be of type function');
308
- err.code = 'ERR_INVALID_ARG_TYPE';
309
- throw err;
310
- }
311
395
  const endStream = !!options.endStream;
312
396
 
313
397
  // Defaults from the parent request (node: core.js pushStream fills :method GET,
@@ -335,11 +419,8 @@ class Http2Stream extends EventEmitter {
335
419
  try {
336
420
  promisedId = this.session._allocPushSid();
337
421
  } catch (err) {
338
- if (callback) {
339
- process.nextTick(callback, err);
340
- return;
341
- }
342
- throw err;
422
+ process.nextTick(callback, err);
423
+ return;
343
424
  }
344
425
 
345
426
  // Validation errors are synchronous in node (buildNgHeaderString throws before
@@ -358,11 +439,14 @@ class Http2Stream extends EventEmitter {
358
439
  stream._remoteEnded();
359
440
 
360
441
  if (endStream || isHead) {
361
- stream.end();
362
- }
363
- if (callback) {
364
- process.nextTick(callback, null, stream, h, 0);
442
+ // node runs stream.end() here, but its Writable end only shuts the writable
443
+ // half down -- the stream stays alive for the application's respond(), which
444
+ // then carries END_STREAM (measured on live node: destroyed:false, closed:false
445
+ // inside the callback). Marking the end instead of closing is
446
+ // what keeps that shape; respond() reads _endQueued, write() refuses it.
447
+ stream._endQueued = true;
365
448
  }
449
+ process.nextTick(callback, null, stream, h, 0);
366
450
  }
367
451
 
368
452
  // Readable-side control, node's contract: while paused no credit is released,
@@ -395,7 +479,7 @@ class Http2Stream extends EventEmitter {
395
479
  // that removes the stream from the session -- without it every request leaks
396
480
  // an Http2Stream (and _liveStreams never falls, so close() never finishes).
397
481
  _remoteEnded() {
398
- if (this.state.remoteClose === 1) {
482
+ if (this._state.remoteClose === 1) {
399
483
  return;
400
484
  }
401
485
  // The other half of the content-length promise: too many octets is caught as they arrive
@@ -409,18 +493,18 @@ class Http2Stream extends EventEmitter {
409
493
  `${this._bodyLen} octets received`);
410
494
  return;
411
495
  }
412
- this.state.remoteClose = 1;
496
+ this._state.remoteClose = 1;
413
497
  this.endAfterHeaders = true;
414
498
  // the readable side is done: 'end' after the last 'data', like a Readable.
415
499
  // No auto-destroy: the application still has to answer. node keeps the
416
500
  // writable side of an unanswered request open as well.
417
- if (this.state.localClose === 1) {
501
+ if (this._state.localClose === 1) {
418
502
  this._closeNow();
419
503
  process.nextTick(emitEndCloseNT, this);
420
504
  return;
421
505
  }
422
- if (this.state.state === ST_OPEN) {
423
- this.state.state = ST_HALF_CLOSED_REMOTE;
506
+ if (this._state.state === ST_OPEN) {
507
+ this._state.state = ST_HALF_CLOSED_REMOTE;
424
508
  }
425
509
  if (!this._isConsuming()) {
426
510
  // Nothing has read the buffered bytes yet, so 'end' must not overtake them:
@@ -432,11 +516,11 @@ class Http2Stream extends EventEmitter {
432
516
  }
433
517
 
434
518
  _endLocalSide() {
435
- const first = this.state.localClose !== 1;
436
- this.state.localClose = 1;
519
+ const first = this._state.localClose !== 1;
520
+ this._state.localClose = 1;
437
521
  this._endQueued = false;
438
- if (this.state.state === ST_OPEN) {
439
- this.state.state = ST_HALF_CLOSED_LOCAL;
522
+ if (this._state.state === ST_OPEN) {
523
+ this._state.state = ST_HALF_CLOSED_LOCAL;
440
524
  }
441
525
  if (this._waitForTrailers) {
442
526
  // one shot: a later end() must not ask for trailers a second time. The flag
@@ -446,7 +530,7 @@ class Http2Stream extends EventEmitter {
446
530
  }
447
531
  return;
448
532
  }
449
- if (this.state.remoteClose === 1) {
533
+ if (this._state.remoteClose === 1) {
450
534
  this._closeIfBothDone();
451
535
  } else {
452
536
  // the response is over and the peer's half is not: this is the shape node
@@ -486,7 +570,7 @@ class Http2Stream extends EventEmitter {
486
570
  }
487
571
 
488
572
  _closeIfBothDone() {
489
- if (this._destroyed || this.state.localClose !== 1 || this.state.remoteClose !== 1) {
573
+ if (this._destroyed || this._state.localClose !== 1 || this._state.remoteClose !== 1) {
490
574
  return;
491
575
  }
492
576
  this._closeNow();
@@ -506,10 +590,14 @@ class Http2Stream extends EventEmitter {
506
590
  }
507
591
 
508
592
  _closeNow() {
509
- this.state.state = ST_CLOSED;
593
+ this._state.state = ST_CLOSED;
510
594
  this._destroyed = true;
595
+ this._gracefulClose = true;
511
596
  this._pending = null;
512
597
  this.session._dropStream(this, false);
598
+ // node drops the session reference when the stream dies
599
+ // (Http2Stream._destroy: `this[kSession] = undefined`, internal/http2/core.js:2546).
600
+ this.session = undefined;
513
601
  }
514
602
 
515
603
  _destroy(code, reason, sendRst, err) {
@@ -524,9 +612,9 @@ class Http2Stream extends EventEmitter {
524
612
  // server: a peer that resets a stream whose request has already ended but
525
613
  // whose response never started does report 'aborted', and a peer that resets
526
614
  // a stream whose response was ended does not.
527
- const responseOpen = this.state.localClose !== 1;
528
- this.state.localClose = 1;
529
- this.state.state = ST_CLOSED;
615
+ const responseOpen = this._state.localClose !== 1;
616
+ this._state.localClose = 1;
617
+ this._state.state = ST_CLOSED;
530
618
  if (sendRst && this.session._open) {
531
619
  this.session.sendRst(this.id, code, reason);
532
620
  }
@@ -535,11 +623,15 @@ class Http2Stream extends EventEmitter {
535
623
  // The event is emitted synchronously -- before the 'end' that an already-queued
536
624
  // tick would otherwise deliver first. Marking the remote half closed keeps a
537
625
  // late END_STREAM from emitting 'end' after 'close'.
538
- this.state.remoteClose = 1;
626
+ this._state.remoteClose = 1;
539
627
  if (responseOpen) {
540
628
  this.aborted = true;
541
629
  this.emit('aborted');
542
630
  }
631
+ // node clears the session reference before 'error'/'close' go out
632
+ // (internal/http2/core.js:2546); 'aborted' above still sees it, the way
633
+ // node's closeStream emits 'aborted' before _destroy runs.
634
+ this.session = undefined;
543
635
  if (err) {
544
636
  process.nextTick(emitErrorCloseNT, this, err);
545
637
  } else {
@@ -656,6 +748,14 @@ class Http2Stream extends EventEmitter {
656
748
  }
657
749
  }
658
750
 
751
+ // node wraps the whole method in util.deprecate, so the warning fires once per
752
+ // process with this exact message -- typo included, byte-identical to
753
+ // internal/http2/core.js:2620 (DEP0194).
754
+ Http2Stream.prototype.priority = deprecate(
755
+ Http2Stream.prototype.priority,
756
+ 'http2Stream.priority is longer supported after priority signalling was deprecated in RFC 9113',
757
+ 'DEP0194');
758
+
659
759
  function errorOf(code, msg) {
660
760
  const err = new Error(msg);
661
761
  err.code = code;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "h2lean",
3
- "version": "0.4.0",
3
+ "version": "0.4.2",
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": [
@@ -46,9 +46,10 @@
46
46
  },
47
47
  "devDependencies": {
48
48
  "@eslint/js": "^10.0.1",
49
+ "@passcod/faith": "^1.1.0",
49
50
  "eslint": "^10.14.0",
50
- "fastify": "^5.12.8",
51
51
  "fast-xml-parser": "^5.12.0",
52
+ "fastify": "^5.12.8",
52
53
  "uWebSockets.js": "github:uNetworking/UWebSockets.js#v20.70.0"
53
54
  }
54
55
  }