h2lean 0.8.0 → 0.9.1

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/server.js CHANGED
@@ -136,6 +136,26 @@ function attachSession(server, socket) {
136
136
  const session = new Http2Session(socket, server._sessionOptions);
137
137
  session.server = server;
138
138
  server._sessions.add(session);
139
+ // node's connectionListener (internal/http2/core.js) arms every session accepted while
140
+ // server.timeout is set: `if (this.timeout) session.setTimeout(this.timeout, sessionOnTimeout)`.
141
+ // sessionOnTimeout emits on the SERVER -- `server.emit('timeout', this)` -- and destroys the
142
+ // session when nobody listens ("No error code, just things down"). Measured on a live node
143
+ // server with setTimeout(500) before listen: an idle connection produces one server 'timeout'
144
+ // after 500 ms of silence with a listener attached, and the client sees the session torn down
145
+ // when there is none. Calling server.setTimeout later does NOT arm sessions that already
146
+ // exist -- the check runs in the accept path only -- which test/idle-timeout.test.js pins on
147
+ // both stacks. session.setTimeout() itself is the per-connection policy and is node's
148
+ // setStreamTimeout: silence counts, every read refreshes, `setTimeout(0)` disarms.
149
+ if (server.timeout) {
150
+ session.setTimeout(server.timeout, function onSessionTimeout() {
151
+ if (this.destroyed || this.closed) {
152
+ return;
153
+ }
154
+ if (!server.emit('timeout', this)) {
155
+ this.destroy();
156
+ }
157
+ });
158
+ }
139
159
  session.on('stream', (stream, headers, options, rawHeaders) =>
140
160
  server.emit('stream', stream, headers, options, rawHeaders));
141
161
  session.on('error', (err) => {
@@ -215,14 +235,14 @@ function applyHttp2ServerApi(proto) {
215
235
  enumerable: false
216
236
  });
217
237
 
218
- // node's own Http2Server.setTimeout (internal/http2/core.js:3541) only records the value --
238
+ // node's Http2Server.setTimeout (internal/http2/core.js) only records the value --
219
239
  // `this.timeout = msecs`, the same field net.Server uses -- and attaches the callback. It
220
- // does NOT walk the sessions. Measured against node with an idle connection and
221
- // server.setTimeout(300): no 'timeout' on the session, no close, the connection simply
222
- // stays. Arming a session idle timeout for every live session (what this used to do) both
223
- // invented an event node does not emit and applied to connections that already existed,
224
- // silently skipping the ones accepted later. The per-connection idle policy is
225
- // session.setTimeout(), which is implemented on the session.
240
+ // does NOT arm the sessions that already exist. Arming happens in the accept path instead:
241
+ // connectionListener hands every session accepted while this.timeout is set a
242
+ // session.setTimeout() with a callback that reports to the server and tears the session
243
+ // down when the server has no 'timeout' listener -- that is attachSession's onSessionTimeout
244
+ // above. server.setTimeout(300) after a connection came up therefore changes nothing for it,
245
+ // which test/idle-timeout.test.js pins on both stacks.
226
246
  proto.setTimeout = function (msecs, cb) {
227
247
  this.timeout = msecs;
228
248
  if (cb !== undefined) {
package/lib/session.js CHANGED
@@ -37,7 +37,7 @@ const FlatList = require('./flat-list');
37
37
  // shrink back to the preallocation.
38
38
  const FLAT = new FlatList(64);
39
39
  const { pieceCopyTo, pieceSlice, pieceConcat, pieceEquals } = require('./pieces');
40
- const { nullProto, hasBadValue, SINGLE_VALUE_FIELDS } = require('./headers');
40
+ const { nullProto, hasBadValue, neverNames, SINGLE_VALUE_FIELDS, KSensitiveHeaders } = require('./headers');
41
41
 
42
42
  // The socket's ownership mark, shared with the client session (node keeps it as
43
43
  // socket[kBoundSession] in the one Http2Session base constructor both kinds run
@@ -570,10 +570,6 @@ function hashPieces(pieces, start, end) {
570
570
  function onIdleTimeout(session) {
571
571
  session._idleTimer = null;
572
572
  session.emit('timeout');
573
- const cb = session._idleCb;
574
- if (cb !== null) {
575
- cb.call(session);
576
- }
577
573
  }
578
574
 
579
575
  // node's proxySocketHandler (internal/http2/core.js): `session.socket` is a Proxy over the
@@ -784,6 +780,20 @@ class Http2Session extends EventEmitter {
784
780
  this._heldBytes = 0; // bytes of response parked on streams that lack credit
785
781
  this._frozenLen = 0; // bytes handed over, callback still owed
786
782
  this._writing = false;
783
+ // Where a stream's END_STREAM DATA frame sits in the not-yet-written outbound
784
+ // queue, keyed by stream id. nghttp2 queues PUSH_PROMISE as a control frame and
785
+ // its send cycle flushes control frames before DATA (nghttp2_session.c
786
+ // nghttp2_session_send), so on node's wire a PUSH_PROMISE opened in the same turn
787
+ // as the parent's end() -- upstream's respond({})/end()/pushStream() shape --
788
+ // precedes the parent's END_STREAM. An nghttp2 client refuses a push whose parent
789
+ // stream it already closed, i.e. one whose END_STREAM arrived first (measured:
790
+ // PUSH_PROMISE before the parent's DATA/ES surfaces the push, the same frame after
791
+ // it draws RST_STREAM(CANCEL) for the promised stream and no push event), so
792
+ // sendPushPromise moves the parent's END_STREAM behind itself while the bytes are
793
+ // still ours to reorder. Cleared when the batch leaves for the socket. Frames
794
+ // already cut out of the queue wait in _esRequeue for the same reason.
795
+ this._esMarkers = new Map();
796
+ this._esRequeue = [];
787
797
  this._connSendWin = PEER_DEFAULTS.initialWindowSize;
788
798
  this._prevInitialWin = PEER_DEFAULTS.initialWindowSize;
789
799
  this._connRecvUsed = 0; // consumed bytes owed back to the connection
@@ -888,7 +898,6 @@ class Http2Session extends EventEmitter {
888
898
  this._liveStreams = 0;
889
899
  this._goawaySent = false;
890
900
  this._idleTimer = null;
891
- this._idleCb = null;
892
901
  this._inBatch = false;
893
902
  this._flushScheduled = false;
894
903
  this._flushSoon = () => {
@@ -1009,6 +1018,9 @@ class Http2Session extends EventEmitter {
1009
1018
  const head = Buffer.allocUnsafe(HEADER_LEN);
1010
1019
  writeHeader(head, 0, len, type, flags, sid);
1011
1020
  this._outQ.push(head, payload);
1021
+ if (type === DATA && (flags & F_END_STREAM)) {
1022
+ this._esMarkers.set(sid, { q0: this._outQ.length - 2, head });
1023
+ }
1012
1024
  } else {
1013
1025
  this._need(HEADER_LEN + len);
1014
1026
  const off = this._stageLen;
@@ -1017,6 +1029,9 @@ class Http2Session extends EventEmitter {
1017
1029
  payload.copy(this._stage, off + HEADER_LEN);
1018
1030
  }
1019
1031
  this._stageLen = off + HEADER_LEN + len;
1032
+ if (type === DATA && (flags & F_END_STREAM)) {
1033
+ this._esMarkers.set(sid, { stage: true, off, len: HEADER_LEN + len });
1034
+ }
1020
1035
  }
1021
1036
  this._outLen += HEADER_LEN + len;
1022
1037
  if (!this._inBatch) {
@@ -1046,7 +1061,18 @@ class Http2Session extends EventEmitter {
1046
1061
  if (this._stageLen === 0) {
1047
1062
  return;
1048
1063
  }
1049
- this._outQ.push(this._stage.subarray(0, this._stageLen));
1064
+ const chunk = this._stage.subarray(0, this._stageLen);
1065
+ // stage-marker forms point into the buffer that is about to leave; turn them into
1066
+ // buffer-relative ones so a later pushStream can still cut the frame out
1067
+ if (this._esMarkers.size) {
1068
+ for (const m of this._esMarkers.values()) {
1069
+ if (m.stage) {
1070
+ m.buf = chunk;
1071
+ m.stage = false;
1072
+ }
1073
+ }
1074
+ }
1075
+ this._outQ.push(chunk);
1050
1076
  this._stage = null; // the queued bytes are not ours to write
1051
1077
  this._stageLen = 0;
1052
1078
  }
@@ -1093,6 +1119,8 @@ class Http2Session extends EventEmitter {
1093
1119
  this._stageLen = 0;
1094
1120
  this._outLen = 0;
1095
1121
  this._writing = false;
1122
+ this._esMarkers.clear();
1123
+ this._esRequeue = [];
1096
1124
  return;
1097
1125
  }
1098
1126
  if (this._writing) {
@@ -1102,6 +1130,22 @@ class Http2Session extends EventEmitter {
1102
1130
  this._commit();
1103
1131
  const batch = this._outQ;
1104
1132
  this._outQ = [];
1133
+ // from here the bytes belong to the socket; there is nothing left to reorder
1134
+ this._esMarkers.clear();
1135
+ // END_STREAM frames cut out for a push go last: nghttp2's cycle flushes control
1136
+ // frames before DATA, and this point -- after the staging buffer's commit -- is
1137
+ // the tail of whatever the turn produced
1138
+ if (this._esRequeue.length) {
1139
+ const tail = this._esRequeue;
1140
+ this._esRequeue = [];
1141
+ for (const t of tail) {
1142
+ if (t.bytes !== null) {
1143
+ this._outQ.push(t.bytes);
1144
+ } else {
1145
+ this._outQ.push(t.pair[0], t.pair[1]);
1146
+ }
1147
+ }
1148
+ }
1105
1149
  this._frozenLen = this._outLen;
1106
1150
  this._outLen = 0;
1107
1151
  const socket = this._socket;
@@ -1285,6 +1329,48 @@ class Http2Session extends EventEmitter {
1285
1329
  // Returns true when the block was refused, so pushStream can mark the promised stream
1286
1330
  // before its callback runs (the same contract sendHeaders has with respond()).
1287
1331
  sendPushPromise(parentSid, promisedSid, block, bound) {
1332
+ // nghttp2's send cycle flushes control frames before DATA, so a PUSH_PROMISE
1333
+ // opened in the same turn as the parent's end() rides ahead of the parent's
1334
+ // END_STREAM on node's wire. An nghttp2 client refuses a push whose parent is
1335
+ // already closed -- the RST(CANCEL) measured in the marker comment above -- so
1336
+ // the parent's not-yet-written END_STREAM moves behind the promise frames here.
1337
+ // After the batch leaves for the socket (_writePending clears the markers) the
1338
+ // stream is closed nghttp2-side too and pushStream no longer reaches this line.
1339
+ const es = this._esMarkers.get(parentSid);
1340
+ let esBytes = null;
1341
+ let esPair = null;
1342
+ if (es) {
1343
+ this._esMarkers.delete(parentSid);
1344
+ if (es.buf !== undefined) {
1345
+ const i = this._outQ.indexOf(es.buf);
1346
+ if (i !== -1) {
1347
+ const b = es.buf;
1348
+ esBytes = b.subarray(es.off, es.off + es.len);
1349
+ // split the shared buffer so the frame can leave as its own entry
1350
+ const parts = [];
1351
+ if (es.off > 0) {
1352
+ parts.push(b.subarray(0, es.off));
1353
+ }
1354
+ if (es.off + es.len < b.length) {
1355
+ parts.push(b.subarray(es.off + es.len));
1356
+ }
1357
+ this._outQ.splice(i, 1, ...parts);
1358
+ }
1359
+ } else if (es.stage) {
1360
+ esBytes = Buffer.allocUnsafe(es.len);
1361
+ this._stage.copy(esBytes, 0, es.off, es.off + es.len);
1362
+ this._stage.copyWithin(es.off, es.off + es.len, this._stageLen);
1363
+ this._stageLen -= es.len;
1364
+ } else {
1365
+ const i = this._outQ.indexOf(es.head);
1366
+ if (i !== -1) {
1367
+ esPair = this._outQ.splice(i, 2);
1368
+ }
1369
+ }
1370
+ if (esBytes !== null || esPair !== null) {
1371
+ this._esRequeue.push(esBytes !== null ? { bytes: esBytes } : { pair: esPair });
1372
+ }
1373
+ }
1288
1374
  // The same prep-time estimate sendHeaders refuses on, with no priority spec:
1289
1375
  // session_estimate_headers_payload passes 0 for PUSH_PROMISE. Measured on v26.12.1
1290
1376
  // with a push of {':path':'/pushed', ':authority':'a', 'x-big':'X'.repeat(n)} -- node
@@ -2113,14 +2199,17 @@ class Http2Session extends EventEmitter {
2113
2199
  // The frozen headers object for one shape. Object.freeze is shallow and
2114
2200
  // node's toHeaderObject puts set-cookie in an array, so that array has to be
2115
2201
  // frozen too -- otherwise push() would corrupt every other request sharing it.
2116
- _sharedObject(fields, count) {
2117
- const o = this._toObject(fields, count);
2202
+ // The sensitive list under the symbol is an array of the same kind, and
2203
+ // Object.keys skips symbol keys, so it is frozen here explicitly.
2204
+ _sharedObject(fields, count, sensitive) {
2205
+ const o = this._toObject(fields, count, sensitive);
2118
2206
  for (let i = 0; i < count; i += 2) {
2119
2207
  const v = o[fields[i]];
2120
2208
  if (Array.isArray(v)) {
2121
2209
  Object.freeze(v);
2122
2210
  }
2123
2211
  }
2212
+ Object.freeze(o[KSensitiveHeaders]);
2124
2213
  return Object.freeze(o);
2125
2214
  }
2126
2215
 
@@ -2129,7 +2218,15 @@ class Http2Session extends EventEmitter {
2129
2218
  // refused, or { fields } when only fields with illegal names were dropped. See the
2130
2219
  // block comment on the constants above for why each rule exists and where the
2131
2220
  // behaviour came from.
2132
- _requestProblem(src, count, trailer) {
2221
+ //
2222
+ // `flags` is the decoder's never-indexed marker for the same block, or null. The
2223
+ // dropped lines must not reach the sensitive list either: node's list holds the
2224
+ // names that were DELIVERED, and a field this side refused never arrives at the
2225
+ // application (measured on node v26.12.1 with a never-indexed non-token name --
2226
+ // the list comes back empty). So the kept copy -- which already shifts the pair
2227
+ // indices when it drops a line -- carries a parallel flags array, sliced and
2228
+ // pushed at exactly the sites that copy and push the fields.
2229
+ _requestProblem(src, count, trailer, flags) {
2133
2230
  let method = null, path = null, scheme = null, authority = null, host = null;
2134
2231
  let protocol = null, contentLength = null;
2135
2232
  // RFC 9113 8.1: pseudo-header fields, if any, come before all regular fields. Once
@@ -2137,6 +2234,7 @@ class Http2Session extends EventEmitter {
2137
2234
  // no pseudo-header is allowed at all, so the flag starts in that state.
2138
2235
  let pseudoAllowed = !trailer;
2139
2236
  let kept = null; // copied list, only if something is dropped
2237
+ let keptFlags = null; // the never-indexed markers of the kept lines, only with flags
2140
2238
 
2141
2239
  for (let i = 0; i < count; i += 2) {
2142
2240
  const name = src[i];
@@ -2214,6 +2312,9 @@ class Http2Session extends EventEmitter {
2214
2312
  // Illegal character in a regular name: drop the field, keep the stream.
2215
2313
  if (kept === null) {
2216
2314
  kept = src.slice(0, i);
2315
+ if (flags !== null) {
2316
+ keptFlags = Array.from(flags.subarray(0, i >> 1));
2317
+ }
2217
2318
  }
2218
2319
  continue;
2219
2320
  }
@@ -2240,6 +2341,9 @@ class Http2Session extends EventEmitter {
2240
2341
  if (!AUTHORITY_RE.test(value)) {
2241
2342
  if (kept === null) {
2242
2343
  kept = src.slice(0, i);
2344
+ if (flags !== null) {
2345
+ keptFlags = Array.from(flags.subarray(0, i >> 1));
2346
+ }
2243
2347
  } continue;
2244
2348
  }
2245
2349
  if (host !== null) {
@@ -2256,16 +2360,22 @@ class Http2Session extends EventEmitter {
2256
2360
  if (hasBadValue(value)) {
2257
2361
  if (kept === null) {
2258
2362
  kept = src.slice(0, i);
2363
+ if (flags !== null) {
2364
+ keptFlags = Array.from(flags.subarray(0, i >> 1));
2365
+ }
2259
2366
  }
2260
2367
  continue;
2261
2368
  }
2262
2369
  if (kept !== null) {
2263
2370
  kept.push(name, value);
2371
+ if (keptFlags !== null) {
2372
+ keptFlags.push(flags[i >> 1]);
2373
+ }
2264
2374
  }
2265
2375
  }
2266
2376
 
2267
2377
  if (trailer) {
2268
- return kept === null ? null : { fields: kept };
2378
+ return kept === null ? null : { fields: kept, neverFlags: keptFlags };
2269
2379
  }
2270
2380
 
2271
2381
  if (method === null) {
@@ -2280,7 +2390,7 @@ class Http2Session extends EventEmitter {
2280
2390
  if (authority === null) {
2281
2391
  return { problem: 'CONNECT without :authority' };
2282
2392
  }
2283
- return kept === null ? null : { fields: kept };
2393
+ return kept === null ? null : { fields: kept, neverFlags: keptFlags };
2284
2394
  }
2285
2395
  if (protocol !== null && method !== 'CONNECT') {
2286
2396
  return { problem: ':protocol requires CONNECT' };
@@ -2303,7 +2413,7 @@ class Http2Session extends EventEmitter {
2303
2413
  && !(method === 'OPTIONS' && path === '*')) {
2304
2414
  return { problem: `:path ${path} does not start with "/"` };
2305
2415
  }
2306
- return kept === null ? null : { fields: kept };
2416
+ return kept === null ? null : { fields: kept, neverFlags: keptFlags };
2307
2417
  }
2308
2418
 
2309
2419
  // A header block that arrived whole and one that arrived in pieces are the
@@ -2335,6 +2445,12 @@ class Http2Session extends EventEmitter {
2335
2445
  let bytes = 0;
2336
2446
  // verdict of the inbound validator: null means the fields may go to the application
2337
2447
  let verdict;
2448
+ // the never-indexed markers of the DELIVERED lines: the decoder's list when
2449
+ // nothing was dropped, the verdict's parallel copy when it filtered the
2450
+ // fields, the cached snapshot on a shape hit -- null when no line was
2451
+ // never-indexed at all. neverNames() turns them into the names array the
2452
+ // header object hangs under node's `sensitiveHeaders` symbol.
2453
+ let blockFlags;
2338
2454
 
2339
2455
  try {
2340
2456
  if (hit !== undefined && (block !== null
@@ -2349,6 +2465,7 @@ class Http2Session extends EventEmitter {
2349
2465
  fcount = fields.length;
2350
2466
  shared = hit.headers;
2351
2467
  verdict = hit.verdict;
2468
+ blockFlags = hit.flags;
2352
2469
  } else {
2353
2470
  if (block !== null) {
2354
2471
  this._decoder.decode(block, 0, block.length, flat);
@@ -2362,10 +2479,14 @@ class Http2Session extends EventEmitter {
2362
2479
  }
2363
2480
  // 'fields' is name, value, name, value: one entry overhead per field line
2364
2481
  bytes += (fcount >> 1) * ENTRY_OVERHEAD;
2365
- verdict = this._requestProblem(fields, fcount, existing !== undefined);
2482
+ const neverFlags = this._decoder.neverCount > 0 ? this._decoder.neverFlags : null;
2483
+ verdict = this._requestProblem(fields, fcount, existing !== undefined, neverFlags);
2366
2484
  if (verdict !== null && verdict.fields !== undefined) {
2367
2485
  fields = verdict.fields;
2368
2486
  fcount = fields.length;
2487
+ blockFlags = verdict.neverFlags;
2488
+ } else {
2489
+ blockFlags = neverFlags;
2369
2490
  }
2370
2491
  if (shapes !== null) {
2371
2492
  // A client that varies one header per request (x-request-id) makes
@@ -2381,10 +2502,14 @@ class Http2Session extends EventEmitter {
2381
2502
  const entry = {
2382
2503
  block: block !== null ? Buffer.from(block) : pieceConcat(pieces, from, to),
2383
2504
  flat: fields.slice(0, fcount), bytes, headers: null,
2384
- verdict
2505
+ verdict,
2506
+ // a snapshot copy, not the decoder's live array: the next decode
2507
+ // clears the array in place, and this entry must survive it
2508
+ flags: blockFlags !== null ? blockFlags.slice() : null
2385
2509
  };
2386
2510
  if (this._share) {
2387
- entry.headers = this._sharedObject(fields, fcount);
2511
+ entry.headers = this._sharedObject(fields, fcount,
2512
+ neverNames(fields, fcount, blockFlags));
2388
2513
  shared = entry.headers;
2389
2514
  }
2390
2515
  shapes.set(slot, entry);
@@ -2486,7 +2611,8 @@ class Http2Session extends EventEmitter {
2486
2611
  return;
2487
2612
  }
2488
2613
  const trailers = this._share
2489
- ? this._sharedObject(fields, fcount) : this._toObject(fields, fcount);
2614
+ ? this._sharedObject(fields, fcount, neverNames(fields, fcount, blockFlags))
2615
+ : this._toObject(fields, fcount, neverNames(fields, fcount, blockFlags));
2490
2616
  existing.emit('trailers', trailers);
2491
2617
  if (end) {
2492
2618
  existing._remoteEnded();
@@ -2544,8 +2670,10 @@ class Http2Session extends EventEmitter {
2544
2670
  }
2545
2671
 
2546
2672
  const headers = shared !== null ? shared
2547
- : (this._share ? Object.freeze(this._toObject(fields, fcount))
2548
- : this._toObject(fields, fcount));
2673
+ : (this._share
2674
+ ? Object.freeze(this._toObject(fields, fcount,
2675
+ neverNames(fields, fcount, blockFlags)))
2676
+ : this._toObject(fields, fcount, neverNames(fields, fcount, blockFlags)));
2549
2677
  // The one shape in which the content-length promise is already broken before a single body
2550
2678
  // octet could have arrived: the field promises a body and the HEADERS frame ends the message.
2551
2679
  // Refusing at the accept decision -- the same place the parse failures and the size limits are
@@ -2596,13 +2724,19 @@ class Http2Session extends EventEmitter {
2596
2724
  // node's toHeaderObject semantics: null prototype, :status coerced to a
2597
2725
  // number, set-cookie always an array, repeats joined -- except the fields in
2598
2726
  // SINGLE_VALUE_FIELDS, of which the first copy is kept and the rest ignored.
2727
+ // The never-indexed names under node's `sensitiveHeaders` symbol are part of
2728
+ // that surface; the assignment comes FIRST, so the whole shape tree of these
2729
+ // objects shares one symbol transition -- the string-key transitions then all
2730
+ // hang off the one map the symbol creates, and the peer-driven name space
2731
+ // below it grows no larger than before (the §8 transition-tree bound).
2599
2732
  //
2600
2733
  // The map is a fast-properties object with a null prototype rather than a
2601
2734
  // { __proto__: null } literal: the literal is in V8's dictionary mode, and this
2602
2735
  // map is built once per request and read once per request by the application --
2603
2736
  // in the stream path and in the compat path alike (OPTIMIZATION.md item 4).
2604
- _toObject(fields, count) {
2737
+ _toObject(fields, count, sensitive) {
2605
2738
  const o = nullProto();
2739
+ o[KSensitiveHeaders] = sensitive;
2606
2740
  for (let i = 0; i < count; i += 2) {
2607
2741
  const name = fields[i];
2608
2742
  let value = fields[i + 1];
@@ -2812,7 +2946,13 @@ class Http2Session extends EventEmitter {
2812
2946
  }
2813
2947
  const next = stream._sendWin + inc;
2814
2948
  if (next > 0x7fffffff) {
2815
- this._streamError(stream, FLOW_CONTROL_ERROR, 'stream window overflow');
2949
+ // RFC 9113 6.9.1 makes a send-window overflow a connection error, and nghttp2
2950
+ // agrees for the per-stream window exactly as for the connection's (measured on
2951
+ // a live node v26.12.1 server: GOAWAY(FLOW_CONTROL_ERROR) with lastStreamID
2952
+ // naming the stream, no RST_STREAM, ERR_HTTP2_ERROR on the stream and the
2953
+ // session). A stream-level reset here would leave the connection alive for a
2954
+ // peer that has already broken its window budget.
2955
+ this._fatal(FLOW_CONTROL_ERROR, 'stream window overflow');
2816
2956
  return;
2817
2957
  }
2818
2958
  stream._sendWin = next;
@@ -3400,10 +3540,22 @@ class Http2Session extends EventEmitter {
3400
3540
  idleClearTimeout(this._idleTimer);
3401
3541
  this._idleTimer = null;
3402
3542
  }
3403
- this._idleCb = cb === undefined ? null : cb;
3404
3543
  if (ms === 0) {
3544
+ // node's setStreamTimeout removes the passed callback when disarming; re-arming with
3545
+ // a new callback instead leaves the old once-listener standing, the same way node's
3546
+ // clearTimeout leaves it -- only the timer is replaced, never the listeners.
3547
+ if (cb !== undefined) {
3548
+ this.removeListener('timeout', cb);
3549
+ }
3405
3550
  return this;
3406
3551
  }
3552
+ // node's setStreamTimeout registers the callback as a once('timeout') listener rather
3553
+ // than keeping it off to the side, so it runs in listener order, in the middle of the
3554
+ // emission. The server's arming (attachSession) depends on that position: node's
3555
+ // sessionOnTimeout reports to the server before any listener registered after it.
3556
+ if (cb !== undefined) {
3557
+ this.once('timeout', cb);
3558
+ }
3407
3559
  // the session is passed as the timer argument, which both the native and the
3408
3560
  // fast path forward to the callback: nothing is allocated per connection here
3409
3561
  const timer = idleSetTimeout(onIdleTimeout, ms, this);