h2lean 0.4.2 → 0.8.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/session.js CHANGED
@@ -21,8 +21,8 @@
21
21
  const { EventEmitter } = require('node:events');
22
22
  const tls = require('node:tls');
23
23
  const f = require('./frames');
24
- const { Decoder, Encoder, HPackError } = require('./hpack');
25
- const { Http2Stream, errorOf, emitNT } = require('./stream');
24
+ const { Decoder, Encoder, HPackError, latin1, latin1Into } = require('./hpack');
25
+ const { Http2Stream, errorOf, streamErrorOf, emitNT } = require('./stream');
26
26
  const FlatList = require('./flat-list');
27
27
  // The process-wide inbound decode scratch: one list per module instance, shared by
28
28
  // every session it serves, instead of one array per live session. Why sharing is
@@ -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
@@ -51,13 +51,254 @@ const { setTimeout: idleSetTimeout, clearTimeout: idleClearTimeout } =
51
51
 
52
52
  const {
53
53
  DATA, HEADERS, PRIORITY, RST_STREAM, SETTINGS, PUSH_PROMISE, PING, GOAWAY,
54
- WINDOW_UPDATE, CONTINUATION,
54
+ WINDOW_UPDATE, CONTINUATION, ALTSVC, ORIGIN,
55
55
  F_END_STREAM, F_ACK, F_END_HEADERS, F_PADDED, F_PRIORITY,
56
56
  NO_ERROR, PROTOCOL_ERROR, INTERNAL_ERROR, FLOW_CONTROL_ERROR, STREAM_CLOSED,
57
57
  FRAME_SIZE_ERROR, REFUSED_STREAM, COMPRESSION_ERROR, ENHANCE_YOUR_CALM,
58
58
  PREFACE_LEN, HEADER_LEN, readHeader, writeHeader, trimPadding
59
59
  } = f;
60
60
 
61
+ // ---- ALTSVC (RFC 7807) / ORIGIN (RFC 8336): the shared parts of the two sessions ------------
62
+ //
63
+ // The wire layout, every error code and message, and the receive behaviour below were read out
64
+ // of node v26.12.1's own JS (internal/http2/core.js Http2Session.altsvc/.origin and
65
+ // onAltSvc/onOrigin/initOriginSet) and confirmed against the frames a live node server put on
66
+ // the wire and the events a live node client emitted, in one session (AGENTS.md 3).
67
+ //
68
+ // ALTSVC frame payload: [uint16 originLen][origin octets][field-value octets]
69
+ // origin form -> frame on stream 0, originLen = origin.length, origin = the URL origin
70
+ // stream form -> frame on that stream id, originLen = 0, no origin octets
71
+ // (RFC 7807 3.1; the C++ side asserts (originLen != 0 && id == 0) || (originLen == 0 &&
72
+ // id != 0), so a call with neither -- altsvc(alt) alone -- aborts node outright. h2lean
73
+ // cannot reproduce a process abort; it throws ERR_HTTP2_ALTSVC_INVALID_ORIGIN instead,
74
+ // the closest node error, and that is the one documented divergence on this method.)
75
+ // ORIGIN frame payload: repeated [uint16 len][origin octets], always on stream 0
76
+ // (RFC 8336 3; node hands the C++ the origins joined by NUL plus a count.)
77
+ //
78
+ // The alt field-value is validated with the exact character class nghttp2 accepts, copied from
79
+ // node's kQuotedString; the length ceiling kMaxALTSVC = 2**14 - 2 is node's too.
80
+ const kQuotedString = /^[\x09\x20-\x5b\x5d-\x7e\x80-\xff]*$/;
81
+ const kMaxALTSVC = (2 ** 14) - 2;
82
+
83
+ // node derives a URL origin with internal/url's getURLOrigin, which for an absolute URL string
84
+ // returns the serialised origin and for anything unparseable throws ERR_INVALID_URL. `new URL`
85
+ // gives the identical string and the identical throw (measured: 'not a url' and '/foo' both raise
86
+ // ERR_INVALID_URL, a data: URL yields the string 'null'), so the origin form is a thin wrapper.
87
+ function urlOrigin(input) {
88
+ return new URL(input).origin;
89
+ }
90
+
91
+ // node's error shape for the ORIGIN/ALTSVC family: ERR_HTTP2_* are TypeErrors, ERR_INVALID_ARG_TYPE
92
+ // and ERR_OUT_OF_RANGE keep their node codes. The code is the observable; the message is written
93
+ // out to match node where node's is a fixed string.
94
+ function extError(code, msg) {
95
+ const err = new TypeError(msg);
96
+ err.code = code;
97
+ return err;
98
+ }
99
+
100
+ // node's ERR_INVALID_ARG_TYPE messages do not say `Received object` -- they say what the
101
+ // value *is*: `Received an instance of Array`, `Received type bigint (1n)`, `Received null`,
102
+ // `Received function namedFn`. That wording comes from `determineSpecificType` in node's
103
+ // internal/errors.js, read here in full and ported, because a drop-in has to produce the
104
+ // same string an application may already be matching on. Two details of it are easy to
105
+ // lose: the `-0` case has to be told apart from `0` by its reciprocal (plain `String(-0)`
106
+ // is '0'), and an object with no usable constructor name -- a null-prototype one, for
107
+ // instance -- is printed by `util.inspect` at depth -1, which is what yields node's
108
+ // '[Object: null prototype] {}'.
109
+ const { inspect } = require('node:util');
110
+ function received(value) {
111
+ if (value === null) {
112
+ return 'null';
113
+ }
114
+ if (value === undefined) {
115
+ return 'undefined';
116
+ }
117
+ switch (typeof value) {
118
+ case 'bigint':
119
+ return `type bigint (${value}n)`;
120
+ case 'number':
121
+ if (value === 0) {
122
+ return 1 / value === -Infinity ? 'type number (-0)' : 'type number (0)';
123
+ } else if (value !== value) {
124
+ return 'type number (NaN)';
125
+ } else if (value === Infinity) {
126
+ return 'type number (Infinity)';
127
+ } else if (value === -Infinity) {
128
+ return 'type number (-Infinity)';
129
+ }
130
+ return `type number (${value})`;
131
+ case 'boolean':
132
+ return value ? 'type boolean (true)' : 'type boolean (false)';
133
+ case 'symbol':
134
+ return `type symbol (${String(value)})`;
135
+ case 'function':
136
+ return `function ${value.name}`;
137
+ case 'string': {
138
+ const cut = value.length > 28 ? `${value.slice(0, 25)}...` : value;
139
+ return cut.includes("'") ? `type string (${inspect(cut)})` : `type string ('${cut}')`;
140
+ }
141
+ default: {
142
+ const name = value.constructor?.name;
143
+ if (typeof name === 'string' && name !== '') {
144
+ return `an instance of ${name}`;
145
+ }
146
+ return `${inspect(value, { depth: -1 })}`;
147
+ }
148
+ }
149
+ }
150
+
151
+ // The received-value half of node's ERR_OUT_OF_RANGE message (internal/errors.js): an
152
+ // integer beyond 2**32 is re-printed with '_' as the digit separator -- node's
153
+ // addNumericalSeparator, ported literally, counting from the right and leaving the leading
154
+ // group short -- and anything else goes through util.inspect, which is again what keeps -0
155
+ // readable as '-0'. Measured against a live node: 2**32 itself prints undivided, 2**40
156
+ // prints as 1_099_511_627_776.
157
+ function addNumericalSeparator(val) {
158
+ let res = '';
159
+ let i = val.length;
160
+ const start = val[0] === '-' ? 1 : 0;
161
+ for (; i >= start + 4; i -= 3) {
162
+ res = `_${val.slice(i - 3, i)}${res}`;
163
+ }
164
+ return `${val.slice(0, i)}${res}`;
165
+ }
166
+
167
+ function outOfRangeValue(value) {
168
+ if (Number.isInteger(value) && Math.abs(value) > 2 ** 32) {
169
+ return addNumericalSeparator(String(value));
170
+ }
171
+ return inspect(value);
172
+ }
173
+
174
+ // Validate one altsvc() call and return what the frame needs: {sid, origin, alt}. Mirrors the JS
175
+ // half of node's Http2Session.altsvc argument handling in order.
176
+ function checkAltSvc(alt, originOrStream) {
177
+ let sid = 0;
178
+ let origin;
179
+ if (typeof originOrStream === 'string') {
180
+ origin = urlOrigin(originOrStream); // throws ERR_INVALID_URL for a bad URL, as node does
181
+ if (origin === 'null') {
182
+ throw extError('ERR_HTTP2_ALTSVC_INVALID_ORIGIN',
183
+ 'HTTP/2 ALTSVC frames require a valid origin');
184
+ }
185
+ } else if (typeof originOrStream === 'number') {
186
+ if (originOrStream >>> 0 !== originOrStream || originOrStream === 0) {
187
+ const err = new RangeError('The value of "originOrStream" is out of range. '
188
+ + `It must be > 0 && < ${2 ** 32}. Received ${outOfRangeValue(originOrStream)}`);
189
+ err.code = 'ERR_OUT_OF_RANGE';
190
+ throw err;
191
+ }
192
+ sid = originOrStream;
193
+ } else if (originOrStream !== undefined) {
194
+ // an object or URL: read .origin without verifying it (node's own caveat)
195
+ if (originOrStream !== null && typeof originOrStream === 'object') {
196
+ origin = originOrStream.origin;
197
+ }
198
+ if (typeof origin !== 'string') {
199
+ throw extError('ERR_INVALID_ARG_TYPE',
200
+ 'The "originOrStream" argument must be one of type string or number '
201
+ + `or an instance of URL or Object. Received ${received(originOrStream)}`);
202
+ } else if (origin === 'null' || origin.length === 0) {
203
+ throw extError('ERR_HTTP2_ALTSVC_INVALID_ORIGIN',
204
+ 'HTTP/2 ALTSVC frames require a valid origin');
205
+ }
206
+ }
207
+ if (typeof alt !== 'string') {
208
+ throw extError('ERR_INVALID_ARG_TYPE',
209
+ `The "alt" argument must be of type string. Received ${received(alt)}`);
210
+ }
211
+ if (!kQuotedString.test(alt)) {
212
+ throw extError('ERR_INVALID_CHAR', 'Invalid character in alt');
213
+ }
214
+ if (alt.length + (origin !== undefined ? origin.length : 0) > kMaxALTSVC) {
215
+ throw extError('ERR_HTTP2_ALTSVC_LENGTH', 'HTTP/2 ALTSVC frames are limited to 16382 bytes');
216
+ }
217
+ // node hands '' for origin in the stream/undefined form; sid===0 with an empty origin is the
218
+ // case node's C++ aborts on (see the header). h2lean refuses it with the invalid-origin error.
219
+ if (sid === 0 && (origin === undefined || origin.length === 0)) {
220
+ throw extError('ERR_HTTP2_ALTSVC_INVALID_ORIGIN',
221
+ 'HTTP/2 ALTSVC frames require a valid origin');
222
+ }
223
+ return { sid, origin: origin === undefined ? '' : origin, alt };
224
+ }
225
+
226
+ // Validate one origin() call and build its ORIGIN payload; null when there is nothing to send
227
+ // (node returns without a frame for zero arguments). Mirrors node's join-with-NUL loop, but
228
+ // writes the RFC 8336 length-prefixed list the C++ would emit for that same string.
229
+ function buildOriginPayload(origins) {
230
+ if (origins.length === 0) {
231
+ return null;
232
+ }
233
+ let total = 0;
234
+ const list = [];
235
+ for (let i = 0; i < origins.length; i++) {
236
+ let origin = origins[i];
237
+ if (typeof origin === 'string') {
238
+ origin = urlOrigin(origin); // throws ERR_INVALID_URL, as node's getURLOrigin does
239
+ } else if (origin !== null && typeof origin === 'object') {
240
+ origin = origin.origin;
241
+ }
242
+ if (typeof origin !== 'string') {
243
+ throw extError('ERR_INVALID_ARG_TYPE',
244
+ `The "origin" argument must be of type string. Received ${received(origin)}`);
245
+ }
246
+ if (origin === 'null') {
247
+ throw extError('ERR_HTTP2_INVALID_ORIGIN', 'HTTP/2 ORIGIN frames require a valid origin');
248
+ }
249
+ total += origin.length;
250
+ list.push(origin);
251
+ }
252
+ if (total > kMaxALTSVC) {
253
+ throw extError('ERR_HTTP2_ORIGIN_LENGTH', 'HTTP/2 ORIGIN frames are limited to 16382 bytes');
254
+ }
255
+ // latin1 is one octet per code unit, so each origin's byte length is its string
256
+ // length and the payload size is known from `total` alone. The octets go straight
257
+ // into the payload with latin1Into() -- no per-origin buffer to allocate and copy.
258
+ const payload = Buffer.allocUnsafe(total + 2 * list.length);
259
+ let off = 0;
260
+ for (const origin of list) {
261
+ payload.writeUInt16BE(origin.length, off);
262
+ off = latin1Into(payload, off + 2, origin);
263
+ }
264
+ return payload;
265
+ }
266
+
267
+ // Decode a received ALTSVC payload. Tolerant by design: node answers a malformed ALTSVC by
268
+ // discarding it and keeping the connection (measured: a 1-octet type-10 frame leaves node serving
269
+ // the next request), and the same holds for a length that overruns the frame. Returns null to mean
270
+ // "ignore", or {sid is supplied by the caller, origin, alt} with origin/alt as latin1 strings.
271
+ function parseAltSvc(buf, start, len) {
272
+ if (len < 2) {
273
+ return null;
274
+ }
275
+ const originLen = buf.readUInt16BE(start);
276
+ if (2 + originLen > len) {
277
+ return null;
278
+ }
279
+ const origin = latin1(buf, start + 2, start + 2 + originLen);
280
+ const alt = latin1(buf, start + 2 + originLen, start + len);
281
+ return { origin, alt };
282
+ }
283
+
284
+ // Decode a received ORIGIN payload into the array of origin strings, or null when the length
285
+ // prefixes do not tile the frame (malformed -> discard, never fatal, as node measured).
286
+ function parseOrigins(buf, start, len) {
287
+ const origins = [];
288
+ let off = 0;
289
+ while (off + 2 <= len) {
290
+ const olen = buf.readUInt16BE(start + off);
291
+ off += 2;
292
+ if (off + olen > len) {
293
+ return null;
294
+ }
295
+ origins.push(latin1(buf, start + off, start + off + olen));
296
+ off += olen;
297
+ }
298
+ return origins;
299
+ }
300
+
301
+
61
302
  // The values the session operates on when the application says nothing. Derived from node's own
62
303
  // getDefaultSettings() so the numbers the guards compare against are the ones node's guards compare
63
304
  // against. They are NOT advertised by default: what goes into a SETTINGS frame is decided by
@@ -98,6 +339,19 @@ const MAX_REFUSED_HISTORY = 32;
98
339
  const MAX_DROPPED_HISTORY = 256;
99
340
  const MAX_SHAPES = 128;
100
341
 
342
+ // The default outbound header-block bound: NGHTTP2_MAX_HEADERSLEN (nghttp2_frame.h),
343
+ // installed by nghttp2_session_new and overridable per session with the
344
+ // `maxSendHeaderBlockLength` option. nghttp2 compares an *estimate* against it, not the
345
+ // encoded length -- see lib/headers.js encodeAt for the formula -- and refuses the frame
346
+ // at prep time, so the JS call that submitted it has already returned.
347
+ const MAX_SEND_BLOCK = 65536;
348
+ // HEADERS carries a 5-octet priority spec in the estimate
349
+ // (session_estimate_headers_payload(..., NGHTTP2_PRIORITY_SPECLEN), nghttp2_session.c);
350
+ // PUSH_PROMISE passes 0. Measured on v26.12.1 with a {'test-trailer': 'X'.repeat(n)}
351
+ // block: the estimate is 41+n, so under a bound of 200 n=159 is served and n=160 refused,
352
+ // and under the default n=65495 is served and n=65496 refused.
353
+ const PRIORITY_SPECLEN = 5;
354
+
101
355
  // node's strictSingleValueFields option (validateSessionOptions, internal/http2/core.js):
102
356
  // undefined is true, and a non-boolean is ERR_INVALID_ARG_TYPE at createServer/connect
103
357
  // time. It gates the strict-single-value rule in both directions: the outbound blocks
@@ -322,6 +576,82 @@ function onIdleTimeout(session) {
322
576
  }
323
577
  }
324
578
 
579
+ // node's proxySocketHandler (internal/http2/core.js): `session.socket` is a Proxy over the
580
+ // SESSION, not over the socket. setTimeout/ref/unref/destroy are re-bound to the session; the
581
+ // raw-socket mutation methods throw ERR_HTTP2_NO_SOCKET_MANIPULATION; everything else falls
582
+ // through to the real socket (the session's `_socket`), throwing ERR_HTTP2_SOCKET_UNBOUND once
583
+ // close has dropped it. node's docs name only emit/end/pause/read/resume/write as refused, but
584
+ // the running binary refuses setEncoding/setKeepAlive/setNoDelay too -- this mirrors the nine.
585
+ const proxySocketHandler = {
586
+ get(session, prop) {
587
+ switch (prop) {
588
+ case 'setTimeout':
589
+ case 'ref':
590
+ case 'unref':
591
+ case 'destroy':
592
+ return session[prop].bind(session);
593
+ case 'emit':
594
+ case 'end':
595
+ case 'pause':
596
+ case 'read':
597
+ case 'resume':
598
+ case 'write':
599
+ case 'setEncoding':
600
+ case 'setKeepAlive':
601
+ case 'setNoDelay':
602
+ throw errorOf('ERR_HTTP2_NO_SOCKET_MANIPULATION',
603
+ 'HTTP/2 sockets should not be directly manipulated (e.g. read and written)');
604
+ default: {
605
+ const socket = session._socket;
606
+ if (socket === undefined) {
607
+ throw errorOf('ERR_HTTP2_SOCKET_UNBOUND',
608
+ 'The socket has been disconnected from the Http2Session');
609
+ }
610
+ const value = socket[prop];
611
+ return typeof value === 'function' ? value.bind(socket) : value;
612
+ }
613
+ }
614
+ },
615
+ getPrototypeOf(session) {
616
+ const socket = session._socket;
617
+ if (socket === undefined) {
618
+ throw errorOf('ERR_HTTP2_SOCKET_UNBOUND',
619
+ 'The socket has been disconnected from the Http2Session');
620
+ }
621
+ return Reflect.getPrototypeOf(socket);
622
+ },
623
+ set(session, prop, value) {
624
+ switch (prop) {
625
+ case 'setTimeout':
626
+ case 'ref':
627
+ case 'unref':
628
+ case 'destroy':
629
+ session[prop] = value;
630
+ return true;
631
+ case 'emit':
632
+ case 'end':
633
+ case 'pause':
634
+ case 'read':
635
+ case 'resume':
636
+ case 'write':
637
+ case 'setEncoding':
638
+ case 'setKeepAlive':
639
+ case 'setNoDelay':
640
+ throw errorOf('ERR_HTTP2_NO_SOCKET_MANIPULATION',
641
+ 'HTTP/2 sockets should not be directly manipulated (e.g. read and written)');
642
+ default: {
643
+ const socket = session._socket;
644
+ if (socket === undefined) {
645
+ throw errorOf('ERR_HTTP2_SOCKET_UNBOUND',
646
+ 'The socket has been disconnected from the Http2Session');
647
+ }
648
+ socket[prop] = value;
649
+ return true;
650
+ }
651
+ }
652
+ }
653
+ };
654
+
325
655
  class Http2Session extends EventEmitter {
326
656
  constructor(socket, options) {
327
657
  super();
@@ -332,7 +662,10 @@ class Http2Session extends EventEmitter {
332
662
  throw err;
333
663
  }
334
664
  socket[kBoundSession] = this;
335
- this.socket = socket;
665
+ this._socket = socket;
666
+ // The public `socket` accessor builds node's safe Proxy lazily and caches it here;
667
+ // close sets it to undefined so `session.socket` reads gone afterwards, as node does.
668
+ this._proxySocket = null;
336
669
  // undefined until a server attaches itself; a performServerHandshake session has
337
670
  // no server, and node's `session.server` getter reads undefined there (core.js).
338
671
  this.server = undefined;
@@ -356,7 +689,18 @@ class Http2Session extends EventEmitter {
356
689
  this._goawayCode = null;
357
690
  this._goawayLastStreamID = null;
358
691
  this.pendingSettingsAck = true;
359
- this.originSet = [];
692
+ // node keeps the origin set in private state and exposes `session.originSet` through a getter
693
+ // that returns a COPY of it -- or undefined unless the session is encrypted (measured on a live
694
+ // node h2c server: `session.originSet` reads undefined there, whatever a peer sends). It is a
695
+ // Set, seeded lazily by _initOriginSet (the same as node's initOriginSet).
696
+ this._originSet = undefined;
697
+ // node caps the ORIGIN-reception set at options.maxOriginSetSize (default 128) on the CLIENT
698
+ // only: connect() assigns session[kMaxOriginSetSize], and a ServerHttp2Session never has it, so
699
+ // its check `size >= undefined` is always false and a server never bounds what a peer drives it
700
+ // to. Matching node means the same here -- a peer's budget against an h2lean server is its
701
+ // budget against node (AGENTS.md 8B). The server default is therefore undefined; the client
702
+ // constructor overrides it from options.
703
+ this._maxOriginSetSize = undefined;
360
704
  this.localSettings = { ...OUR_DEFAULTS, ...opts.settings };
361
705
  // Which of those values the application asked for, in the order it asked for them, and only
362
706
  // those go on the wire. Measured on a live node server: created with no options its first
@@ -409,6 +753,17 @@ class Http2Session extends EventEmitter {
409
753
  // (OPTIMIZATION.md item 22 for both sides of the trade-off).
410
754
  this._share = opts.shareHeaders === true;
411
755
  this._strictSingle = strictSingleValueFields(opts);
756
+ // node reads this option with a `typeof === 'number'` gate and no range check
757
+ // (updateOptionsBuffer, internal/http2/util.js) into the binding's Uint32Array.
758
+ // Measured on v26.12.1: a bound of 200.9 refuses exactly what 200 refuses, and -1
759
+ // serves a 64 KiB trailer -- so the coercion is ToUint32, not a clamp.
760
+ this._maxSendBlock = typeof opts.maxSendHeaderBlockLength === 'number'
761
+ ? opts.maxSendHeaderBlockLength >>> 0 : MAX_SEND_BLOCK;
762
+ // The server `origins` option: an array of origin strings the session announces with an ORIGIN
763
+ // frame as soon as it is up, the way node's setupHandle does for type SERVER. Held raw; it is
764
+ // validated by origin() at send time, so a bad entry surfaces on the session exactly as it
765
+ // would through a direct session.origin() call.
766
+ this._origins = opts.origins;
412
767
  // The compat layer needs the decoded field list as it came off the wire.
413
768
  // Copying it is a per-request allocation, so it only happens for servers
414
769
  // that actually listen for 'request'.
@@ -612,21 +967,29 @@ class Http2Session extends EventEmitter {
612
967
  // (setupHandle's destroyed branch), so the handlers at least run and clear out.
613
968
  if (!this._connectEmitted) {
614
969
  this._connectEmitted = true;
615
- process.nextTick(() => this.emit('connect', this, this.socket));
970
+ process.nextTick(() => this.emit('connect', this, this._socket));
616
971
  }
617
972
  return;
618
973
  }
619
974
  this.connecting = false;
620
- if (this.socket.encrypted) {
975
+ if (this._socket.encrypted) {
621
976
  this.encrypted = true;
622
- this.alpnProtocol = this.socket.alpnProtocol;
977
+ this.alpnProtocol = this._socket.alpnProtocol;
623
978
  } else {
624
979
  this.encrypted = false;
625
980
  this.alpnProtocol = 'h2c';
626
981
  }
627
982
  this._sendSettings();
983
+ // node's setupHandle announces the server `origins` option with one ORIGIN frame -- server
984
+ // sessions only, and only when the option is an array -- right after the initial SETTINGS and
985
+ // before 'connect'. A bad entry throws out of origin() synchronously, from this connect
986
+ // listener, which is an uncaught exception: measured against a live node server (a
987
+ // non-URL origin option raises ERR_INVALID_URL that nothing catches), so this lets it stand.
988
+ if (Array.isArray(this._origins)) {
989
+ this.origin(...this._origins);
990
+ }
628
991
  this._connectEmitted = true;
629
- process.nextTick(() => this.emit('connect', this, this.socket));
992
+ process.nextTick(() => this.emit('connect', this, this._socket));
630
993
  }
631
994
 
632
995
  // ---- outbound queue --------------------------------------------------------
@@ -741,7 +1104,7 @@ class Http2Session extends EventEmitter {
741
1104
  this._outQ = [];
742
1105
  this._frozenLen = this._outLen;
743
1106
  this._outLen = 0;
744
- const socket = this.socket;
1107
+ const socket = this._socket;
745
1108
  if (batch.length === 1) {
746
1109
  // the common case for a small response: everything the batch holds went into one
747
1110
  // staging buffer, so there is nothing to coalesce and corking would only add a
@@ -808,27 +1171,100 @@ class Http2Session extends EventEmitter {
808
1171
  this._flush();
809
1172
  }
810
1173
 
811
- sendHeaders(sid, block, end) {
1174
+ // Returns true when the block was refused, so the caller knows the wire state its
1175
+ // HEADERS would have advanced never happened (see _blockRefused in lib/stream.js).
1176
+ sendHeaders(sid, block, end, bound) {
1177
+ // nghttp2 refuses an outbound header block whose estimate exceeds the session's
1178
+ // maxSendHeaderBlockLength, and it does so at *prep* time -- after the JS call that
1179
+ // submitted it returned (nghttp2_session.c, the NGHTTP2_HEADERS case of
1180
+ // session_prep_frame). So this is not a throw: node emits 'frameError' on the stream
1181
+ // and closes both it and the session a turn later (onFrameError,
1182
+ // internal/http2/core.js). Measured on v26.12.1 for an oversize trailer block:
1183
+ // frameError(1, 6, sid), ERR_HTTP2_STREAM_ERROR naming NGHTTP2_FRAME_SIZE_ERROR,
1184
+ // rstCode 6, and RST_STREAM(6) then GOAWAY(0) on the wire.
1185
+ if (bound + PRIORITY_SPECLEN > this._maxSendBlock) {
1186
+ this._refuseBlock(sid, HEADERS);
1187
+ return true;
1188
+ }
812
1189
  this.state.deflateDynamicTableSize = this._encoder.size;
813
1190
  const max = this.remoteSettings.maxFrameSize;
1191
+ // END_STREAM rides on the HEADERS frame even when CONTINUATION frames follow it:
1192
+ // RFC 9113 6.2 ("a HEADERS frame with the END_STREAM flag set can be followed by
1193
+ // CONTINUATION frames ... logically, the CONTINUATION frames are part of the HEADERS
1194
+ // frame"), 5.1 ("CONTINUATION frames do not result in state transitions") and 8.1,
1195
+ // which says it outright for trailers -- "a sequence starting with a HEADERS frame,
1196
+ // followed by zero or more CONTINUATION frames, where the HEADERS frame bears an
1197
+ // END_STREAM flag". Measured on node's wire for a trailer block over one frame:
1198
+ // HEADERS flags 0x1 len 16384, CONTINUATION flags 0x4. On the last CONTINUATION
1199
+ // instead, node's client answers ERR_HTTP2_STREAM_ERROR / rstCode 1 and h2lean's own
1200
+ // receiver -- which reads the flag off HEADERS -- never sees the message end.
1201
+ const es = end ? F_END_STREAM : 0;
814
1202
  if (block.length <= max) {
815
- this._frame(HEADERS, F_END_HEADERS | (end ? F_END_STREAM : 0), sid, block);
816
- return;
1203
+ this._frame(HEADERS, F_END_HEADERS | es, sid, block);
1204
+ return false;
817
1205
  }
818
- this._frame(HEADERS, 0, sid, block.subarray(0, max));
1206
+ this._frame(HEADERS, es, sid, block.subarray(0, max));
819
1207
  let off = max;
820
1208
  for (;;) {
821
1209
  const n = Math.min(block.length - off, max);
822
1210
  const last = off + n >= block.length;
823
- this._frame(CONTINUATION, last ? F_END_HEADERS | (end ? F_END_STREAM : 0) : 0,
1211
+ this._frame(CONTINUATION, last ? F_END_HEADERS : 0,
824
1212
  sid, block.subarray(off, off + n));
825
1213
  off += n;
826
1214
  if (last) {
827
- return;
1215
+ return false;
828
1216
  }
829
1217
  }
830
1218
  }
831
1219
 
1220
+ // node's onFrameError (internal/http2/core.js): the emitter is the stream while the
1221
+ // session still holds it and the session otherwise, 'frameError' goes out synchronously,
1222
+ // and the close is deferred a turn -- node's own comment says the delay is there to let
1223
+ // a GOAWAY already in flight arrive first. `stream.close(code)` is guarded by `closed`,
1224
+ // so a stream that finished on its own terms keeps its own rstCode: measured, an
1225
+ // oversize *informational* block is refused and the final response still goes out and
1226
+ // closes the stream with NO_ERROR before this runs.
1227
+ _refuseBlock(sid, type) {
1228
+ const stream = this._streams.get(sid);
1229
+ if (stream !== undefined) {
1230
+ stream.emit('frameError', type, FRAME_SIZE_ERROR, sid);
1231
+ } else {
1232
+ this.emit('frameError', type, FRAME_SIZE_ERROR, sid);
1233
+ }
1234
+ setImmediate(() => {
1235
+ if (stream !== undefined && !stream.closed) {
1236
+ stream._destroy(FRAME_SIZE_ERROR, undefined, true, streamErrorOf(FRAME_SIZE_ERROR));
1237
+ }
1238
+ this.close();
1239
+ });
1240
+ }
1241
+
1242
+ // The PUSH_PROMISE half of the same refusal, and the one place the whole verdict is
1243
+ // deferred rather than just the close: pushStream hands its callback to process.nextTick
1244
+ // (core.js:3048), so node's 'frameError' -- emitted from the send loop, after that tick --
1245
+ // is measured to arrive AFTER the callback ran with no error. Emitting it here
1246
+ // synchronously would put it first. The promised stream does not exist yet either:
1247
+ // pushStream constructs it after this call returns, which is another reason the lookup
1248
+ // has to wait for the turn.
1249
+ _refusePush(parentSid, promisedSid) {
1250
+ // The parent is captured now, not in the deferred turn: node's onFrameError looks it
1251
+ // up while the send loop runs, and its own close is still pending then, so the
1252
+ // 'frameError' lands on the parent stream even though that stream finishes with
1253
+ // NO_ERROR a moment later. h2lean's server stream leaves _streams at its close, which
1254
+ // here happens synchronously inside the application's end() -- a lookup in the
1255
+ // setImmediate would miss it and emit on the session instead (measured).
1256
+ const parent = this._streams.get(parentSid);
1257
+ setImmediate(() => {
1258
+ (parent === undefined ? this : parent)
1259
+ .emit('frameError', PUSH_PROMISE, FRAME_SIZE_ERROR, parentSid);
1260
+ const pushed = this._streams.get(promisedSid);
1261
+ if (pushed !== undefined && !pushed.closed) {
1262
+ pushed._destroy(INTERNAL_ERROR, undefined, true, streamErrorOf(INTERNAL_ERROR));
1263
+ }
1264
+ this.close();
1265
+ });
1266
+ }
1267
+
832
1268
  // Reserve the next even stream id for a PUSH_PROMISE. RFC 9113 5.1.1: server-initiated
833
1269
  // streams use even ids; the 31-bit space is exhausted at 2^31-1 (the R bit is not an id).
834
1270
  // node: nghttp2_session_get_next_stream_id returns NGHTTP2_ERR_STREAM_ID_NOT_AVAILABLE,
@@ -846,7 +1282,23 @@ class Http2Session extends EventEmitter {
846
1282
  // followed by the header block fragment. The frame rides on the PARENT stream id (odd);
847
1283
  // the promised id inside the payload is even. CONTINUATION split mirrors sendHeaders,
848
1284
  // with the first frame carrying the 4-octet prefix and the block fragment that fits.
849
- sendPushPromise(parentSid, promisedSid, block) {
1285
+ // Returns true when the block was refused, so pushStream can mark the promised stream
1286
+ // before its callback runs (the same contract sendHeaders has with respond()).
1287
+ sendPushPromise(parentSid, promisedSid, block, bound) {
1288
+ // The same prep-time estimate sendHeaders refuses on, with no priority spec:
1289
+ // session_estimate_headers_payload passes 0 for PUSH_PROMISE. Measured on v26.12.1
1290
+ // with a push of {':path':'/pushed', ':authority':'a', 'x-big':'X'.repeat(n)} -- node
1291
+ // fills :method and :scheme, so five fields and an estimate of 121+n: under a bound of
1292
+ // 150 n=29 is pushed and n=30 is refused, and under the default n=65415 / 65416
1293
+ // (test/outbound-bound.test.js). The refusal lands on the PARENT's
1294
+ // 'frameError' (the frame rides on its id) and closes the PROMISED stream with
1295
+ // INTERNAL_ERROR, while the parent's own response still goes out and closes it with
1296
+ // NO_ERROR -- nghttp2_session_close_stream(promised_sid, NGHTTP2_INTERNAL_ERROR) on
1297
+ // the PUSH_PROMISE prep-error path, nghttp2_session.c.
1298
+ if (bound > this._maxSendBlock) {
1299
+ this._refusePush(parentSid, promisedSid);
1300
+ return true;
1301
+ }
850
1302
  this.state.deflateDynamicTableSize = this._encoder.size;
851
1303
  const max = this.remoteSettings.maxFrameSize;
852
1304
  // The payload is the 4-byte promised id + the block. The first frame can carry
@@ -857,7 +1309,7 @@ class Http2Session extends EventEmitter {
857
1309
  payload.writeUInt32BE(promisedSid, 0);
858
1310
  block.copy(payload, 4);
859
1311
  this._frame(PUSH_PROMISE, F_END_HEADERS, parentSid, payload);
860
- return;
1312
+ return false;
861
1313
  }
862
1314
  const first = Buffer.allocUnsafe(4 + firstCap);
863
1315
  first.writeUInt32BE(promisedSid, 0);
@@ -871,7 +1323,7 @@ class Http2Session extends EventEmitter {
871
1323
  block.subarray(off, off + n));
872
1324
  off += n;
873
1325
  if (last) {
874
- return;
1326
+ return false;
875
1327
  }
876
1328
  }
877
1329
  }
@@ -879,6 +1331,15 @@ class Http2Session extends EventEmitter {
879
1331
  // Writes DATA within the stream and connection windows. Returns true when
880
1332
  // everything went out; false means the caller should wait for WINDOW_UPDATE.
881
1333
  sendData(stream, buf, end) {
1334
+ if (stream._blockRefused) {
1335
+ // Nothing this stream submits reaches the wire any more (_refuseBlock above), but
1336
+ // the application's end() still happened and has to be recorded -- node's 'aborted'
1337
+ // turns on `_writableState.ending`, not on the octets going out.
1338
+ if (end) {
1339
+ stream._endLocalSide();
1340
+ }
1341
+ return false;
1342
+ }
882
1343
  if (stream._queued !== null) { // preserve order behind a stall
883
1344
  if (buf.length > 0) {
884
1345
  stream._queued.push(buf);
@@ -1321,13 +1782,55 @@ class Http2Session extends EventEmitter {
1321
1782
  case PUSH_PROMISE:
1322
1783
  this._fatal(PROTOCOL_ERROR, 'peer sent PUSH_PROMISE');
1323
1784
  break;
1785
+ case ALTSVC: {
1786
+ // RFC 7807 3.1. A malformed ALTSVC is discarded, never fatal: measured on node, a 1-octet
1787
+ // type-10 frame leaves the connection up and the next request served (the unknown-frame
1788
+ // case in test/inbound-limits.test.js sends exactly that and still expects ANSWERED).
1789
+ const a = parseAltSvc(buf, start, len);
1790
+ if (a !== null) {
1791
+ this.emit('altsvc', a.alt, a.origin, sid);
1792
+ }
1793
+ return;
1794
+ }
1795
+ case ORIGIN: {
1796
+ // RFC 8336 3. Malformed is discarded, never fatal (measured: a 5-octet type-12 frame
1797
+ // leaves node's connection up). Reception is TLS-gated exactly as node's onOrigin is: over
1798
+ // h2c the frame is parsed and then ignored, with no event and no origin-set change. The
1799
+ // 'origin' event carries the whole array of origin strings, exactly as node's onOrigin
1800
+ // emits; a session that overflows its maxOriginSetSize is destroyed with
1801
+ // ERR_HTTP2_TOO_MANY_ORIGINS. A server session never has a cap (undefined), so the check
1802
+ // reads `size >= undefined` and stays silent.
1803
+ const o = parseOrigins(buf, start, len);
1804
+ if (o === null) {
1805
+ return;
1806
+ }
1807
+ if (!this.encrypted || this.destroyed) {
1808
+ return;
1809
+ }
1810
+ const set = this._initOriginSet();
1811
+ for (let k = 0; k < o.length; k++) {
1812
+ if (set.size >= this._maxOriginSetSize) {
1813
+ const err = new Error(
1814
+ 'The server sent more ORIGIN frames than the allowed number of ' +
1815
+ `${this._maxOriginSetSize}`);
1816
+ err.code = 'ERR_HTTP2_TOO_MANY_ORIGINS';
1817
+ this.destroy(err);
1818
+ return;
1819
+ }
1820
+ set.add(o[k]);
1821
+ }
1822
+ this.emit('origin', o);
1823
+ break;
1824
+ }
1324
1825
 
1325
1826
  default:
1326
1827
  // RFC 9113 5.5: "Implementations MUST discard frames that have unknown or unsupported
1327
- // types." Measured on a live node server with tools/probe-inbound-limits.js: type 10
1328
- // (ALTSVC, RFC 7807), type 99 and type 0xff with a 4 KiB payload all leave the
1329
- // connection up and the next request served, and h2lean answers the same. Answering a
1330
- // fatal error here would break every extension frame a peer has not told us about.
1828
+ // types." Measured on a live node server with tools/probe-inbound-limits.js: type 99 and
1829
+ // type 0xff with a 4 KiB payload all leave the connection up and the next request served,
1830
+ // and h2lean answers the same. Answering a fatal error here would break every extension
1831
+ // frame a peer has not told us about. The two extension frames we do recognise, ALTSVC (10)
1832
+ // and ORIGIN (12), are parsed in their own cases above -- and a malformed one is discarded
1833
+ // there too, so nothing about a frame of a type we can name tears the connection down.
1331
1834
  // What is NOT ignored is a frame that interrupts a field block -- 5.5 forbids those
1332
1835
  // outright, and that is the case above.
1333
1836
  // unknown frame types are ignored
@@ -1610,14 +2113,17 @@ class Http2Session extends EventEmitter {
1610
2113
  // The frozen headers object for one shape. Object.freeze is shallow and
1611
2114
  // node's toHeaderObject puts set-cookie in an array, so that array has to be
1612
2115
  // frozen too -- otherwise push() would corrupt every other request sharing it.
1613
- _sharedObject(fields, count) {
1614
- const o = this._toObject(fields, count);
2116
+ // The sensitive list under the symbol is an array of the same kind, and
2117
+ // Object.keys skips symbol keys, so it is frozen here explicitly.
2118
+ _sharedObject(fields, count, sensitive) {
2119
+ const o = this._toObject(fields, count, sensitive);
1615
2120
  for (let i = 0; i < count; i += 2) {
1616
2121
  const v = o[fields[i]];
1617
2122
  if (Array.isArray(v)) {
1618
2123
  Object.freeze(v);
1619
2124
  }
1620
2125
  }
2126
+ Object.freeze(o[KSensitiveHeaders]);
1621
2127
  return Object.freeze(o);
1622
2128
  }
1623
2129
 
@@ -1626,7 +2132,15 @@ class Http2Session extends EventEmitter {
1626
2132
  // refused, or { fields } when only fields with illegal names were dropped. See the
1627
2133
  // block comment on the constants above for why each rule exists and where the
1628
2134
  // behaviour came from.
1629
- _requestProblem(src, count, trailer) {
2135
+ //
2136
+ // `flags` is the decoder's never-indexed marker for the same block, or null. The
2137
+ // dropped lines must not reach the sensitive list either: node's list holds the
2138
+ // names that were DELIVERED, and a field this side refused never arrives at the
2139
+ // application (measured on node v26.12.1 with a never-indexed non-token name --
2140
+ // the list comes back empty). So the kept copy -- which already shifts the pair
2141
+ // indices when it drops a line -- carries a parallel flags array, sliced and
2142
+ // pushed at exactly the sites that copy and push the fields.
2143
+ _requestProblem(src, count, trailer, flags) {
1630
2144
  let method = null, path = null, scheme = null, authority = null, host = null;
1631
2145
  let protocol = null, contentLength = null;
1632
2146
  // RFC 9113 8.1: pseudo-header fields, if any, come before all regular fields. Once
@@ -1634,6 +2148,7 @@ class Http2Session extends EventEmitter {
1634
2148
  // no pseudo-header is allowed at all, so the flag starts in that state.
1635
2149
  let pseudoAllowed = !trailer;
1636
2150
  let kept = null; // copied list, only if something is dropped
2151
+ let keptFlags = null; // the never-indexed markers of the kept lines, only with flags
1637
2152
 
1638
2153
  for (let i = 0; i < count; i += 2) {
1639
2154
  const name = src[i];
@@ -1711,6 +2226,9 @@ class Http2Session extends EventEmitter {
1711
2226
  // Illegal character in a regular name: drop the field, keep the stream.
1712
2227
  if (kept === null) {
1713
2228
  kept = src.slice(0, i);
2229
+ if (flags !== null) {
2230
+ keptFlags = Array.from(flags.subarray(0, i >> 1));
2231
+ }
1714
2232
  }
1715
2233
  continue;
1716
2234
  }
@@ -1737,6 +2255,9 @@ class Http2Session extends EventEmitter {
1737
2255
  if (!AUTHORITY_RE.test(value)) {
1738
2256
  if (kept === null) {
1739
2257
  kept = src.slice(0, i);
2258
+ if (flags !== null) {
2259
+ keptFlags = Array.from(flags.subarray(0, i >> 1));
2260
+ }
1740
2261
  } continue;
1741
2262
  }
1742
2263
  if (host !== null) {
@@ -1753,16 +2274,22 @@ class Http2Session extends EventEmitter {
1753
2274
  if (hasBadValue(value)) {
1754
2275
  if (kept === null) {
1755
2276
  kept = src.slice(0, i);
2277
+ if (flags !== null) {
2278
+ keptFlags = Array.from(flags.subarray(0, i >> 1));
2279
+ }
1756
2280
  }
1757
2281
  continue;
1758
2282
  }
1759
2283
  if (kept !== null) {
1760
2284
  kept.push(name, value);
2285
+ if (keptFlags !== null) {
2286
+ keptFlags.push(flags[i >> 1]);
2287
+ }
1761
2288
  }
1762
2289
  }
1763
2290
 
1764
2291
  if (trailer) {
1765
- return kept === null ? null : { fields: kept };
2292
+ return kept === null ? null : { fields: kept, neverFlags: keptFlags };
1766
2293
  }
1767
2294
 
1768
2295
  if (method === null) {
@@ -1777,7 +2304,7 @@ class Http2Session extends EventEmitter {
1777
2304
  if (authority === null) {
1778
2305
  return { problem: 'CONNECT without :authority' };
1779
2306
  }
1780
- return kept === null ? null : { fields: kept };
2307
+ return kept === null ? null : { fields: kept, neverFlags: keptFlags };
1781
2308
  }
1782
2309
  if (protocol !== null && method !== 'CONNECT') {
1783
2310
  return { problem: ':protocol requires CONNECT' };
@@ -1800,7 +2327,7 @@ class Http2Session extends EventEmitter {
1800
2327
  && !(method === 'OPTIONS' && path === '*')) {
1801
2328
  return { problem: `:path ${path} does not start with "/"` };
1802
2329
  }
1803
- return kept === null ? null : { fields: kept };
2330
+ return kept === null ? null : { fields: kept, neverFlags: keptFlags };
1804
2331
  }
1805
2332
 
1806
2333
  // A header block that arrived whole and one that arrived in pieces are the
@@ -1832,6 +2359,12 @@ class Http2Session extends EventEmitter {
1832
2359
  let bytes = 0;
1833
2360
  // verdict of the inbound validator: null means the fields may go to the application
1834
2361
  let verdict;
2362
+ // the never-indexed markers of the DELIVERED lines: the decoder's list when
2363
+ // nothing was dropped, the verdict's parallel copy when it filtered the
2364
+ // fields, the cached snapshot on a shape hit -- null when no line was
2365
+ // never-indexed at all. neverNames() turns them into the names array the
2366
+ // header object hangs under node's `sensitiveHeaders` symbol.
2367
+ let blockFlags;
1835
2368
 
1836
2369
  try {
1837
2370
  if (hit !== undefined && (block !== null
@@ -1846,6 +2379,7 @@ class Http2Session extends EventEmitter {
1846
2379
  fcount = fields.length;
1847
2380
  shared = hit.headers;
1848
2381
  verdict = hit.verdict;
2382
+ blockFlags = hit.flags;
1849
2383
  } else {
1850
2384
  if (block !== null) {
1851
2385
  this._decoder.decode(block, 0, block.length, flat);
@@ -1859,10 +2393,14 @@ class Http2Session extends EventEmitter {
1859
2393
  }
1860
2394
  // 'fields' is name, value, name, value: one entry overhead per field line
1861
2395
  bytes += (fcount >> 1) * ENTRY_OVERHEAD;
1862
- verdict = this._requestProblem(fields, fcount, existing !== undefined);
2396
+ const neverFlags = this._decoder.neverCount > 0 ? this._decoder.neverFlags : null;
2397
+ verdict = this._requestProblem(fields, fcount, existing !== undefined, neverFlags);
1863
2398
  if (verdict !== null && verdict.fields !== undefined) {
1864
2399
  fields = verdict.fields;
1865
2400
  fcount = fields.length;
2401
+ blockFlags = verdict.neverFlags;
2402
+ } else {
2403
+ blockFlags = neverFlags;
1866
2404
  }
1867
2405
  if (shapes !== null) {
1868
2406
  // A client that varies one header per request (x-request-id) makes
@@ -1878,10 +2416,14 @@ class Http2Session extends EventEmitter {
1878
2416
  const entry = {
1879
2417
  block: block !== null ? Buffer.from(block) : pieceConcat(pieces, from, to),
1880
2418
  flat: fields.slice(0, fcount), bytes, headers: null,
1881
- verdict
2419
+ verdict,
2420
+ // a snapshot copy, not the decoder's live array: the next decode
2421
+ // clears the array in place, and this entry must survive it
2422
+ flags: blockFlags !== null ? blockFlags.slice() : null
1882
2423
  };
1883
2424
  if (this._share) {
1884
- entry.headers = this._sharedObject(fields, fcount);
2425
+ entry.headers = this._sharedObject(fields, fcount,
2426
+ neverNames(fields, fcount, blockFlags));
1885
2427
  shared = entry.headers;
1886
2428
  }
1887
2429
  shapes.set(slot, entry);
@@ -1983,7 +2525,8 @@ class Http2Session extends EventEmitter {
1983
2525
  return;
1984
2526
  }
1985
2527
  const trailers = this._share
1986
- ? this._sharedObject(fields, fcount) : this._toObject(fields, fcount);
2528
+ ? this._sharedObject(fields, fcount, neverNames(fields, fcount, blockFlags))
2529
+ : this._toObject(fields, fcount, neverNames(fields, fcount, blockFlags));
1987
2530
  existing.emit('trailers', trailers);
1988
2531
  if (end) {
1989
2532
  existing._remoteEnded();
@@ -2041,8 +2584,10 @@ class Http2Session extends EventEmitter {
2041
2584
  }
2042
2585
 
2043
2586
  const headers = shared !== null ? shared
2044
- : (this._share ? Object.freeze(this._toObject(fields, fcount))
2045
- : this._toObject(fields, fcount));
2587
+ : (this._share
2588
+ ? Object.freeze(this._toObject(fields, fcount,
2589
+ neverNames(fields, fcount, blockFlags)))
2590
+ : this._toObject(fields, fcount, neverNames(fields, fcount, blockFlags)));
2046
2591
  // The one shape in which the content-length promise is already broken before a single body
2047
2592
  // octet could have arrived: the field promises a body and the HEADERS frame ends the message.
2048
2593
  // Refusing at the accept decision -- the same place the parse failures and the size limits are
@@ -2093,13 +2638,19 @@ class Http2Session extends EventEmitter {
2093
2638
  // node's toHeaderObject semantics: null prototype, :status coerced to a
2094
2639
  // number, set-cookie always an array, repeats joined -- except the fields in
2095
2640
  // SINGLE_VALUE_FIELDS, of which the first copy is kept and the rest ignored.
2641
+ // The never-indexed names under node's `sensitiveHeaders` symbol are part of
2642
+ // that surface; the assignment comes FIRST, so the whole shape tree of these
2643
+ // objects shares one symbol transition -- the string-key transitions then all
2644
+ // hang off the one map the symbol creates, and the peer-driven name space
2645
+ // below it grows no larger than before (the §8 transition-tree bound).
2096
2646
  //
2097
2647
  // The map is a fast-properties object with a null prototype rather than a
2098
2648
  // { __proto__: null } literal: the literal is in V8's dictionary mode, and this
2099
2649
  // map is built once per request and read once per request by the application --
2100
2650
  // in the stream path and in the compat path alike (OPTIMIZATION.md item 4).
2101
- _toObject(fields, count) {
2651
+ _toObject(fields, count, sensitive) {
2102
2652
  const o = nullProto();
2653
+ o[KSensitiveHeaders] = sensitive;
2103
2654
  for (let i = 0; i < count; i += 2) {
2104
2655
  const name = fields[i];
2105
2656
  let value = fields[i + 1];
@@ -2379,10 +2930,21 @@ class Http2Session extends EventEmitter {
2379
2930
  // A trailer block stashed by sendTrailers() belongs after the body it follows, and it
2380
2931
  // carries the END_STREAM the body was not allowed to send (RFC 9113 6.1: a trailing
2381
2932
  // HEADERS precedes the close -- measured against node: HEADERS/EH DATA HEADERS/ES/EH).
2933
+ // A zero-length stash is the marker for an empty trailer map: no HEADERS goes out at
2934
+ // all, the withheld END_STREAM rides on an empty DATA (lib/stream.js sendTrailers).
2382
2935
  if (stream._pendingTrailers !== null) {
2383
2936
  const trailers = stream._pendingTrailers;
2937
+ const bound = stream._pendingTrailersBound;
2384
2938
  stream._pendingTrailers = null;
2385
- this._frame(HEADERS, F_END_HEADERS | F_END_STREAM, stream.id, trailers, true);
2939
+ if (trailers.length === 0) {
2940
+ this._frame(DATA, F_END_STREAM, stream.id, null);
2941
+ } else if (this.sendHeaders(stream.id, trailers, true, bound)) {
2942
+ // The bound is checked when the block is framed, not when sendTrailers() stashed
2943
+ // it: nghttp2 compares the estimate at prep time, whenever that happens. Measured
2944
+ // on v26.12.1 with a 200 000-octet body ahead of a 64 KiB trailer: frameError
2945
+ // (1, 6, sid), rstCode 6, session close -- the transcript of the unstashed case.
2946
+ stream._blockRefused = true;
2947
+ }
2386
2948
  stream._endLocalSide();
2387
2949
  }
2388
2950
  // the writable side accepted bytes again: res.on('drain') is how an
@@ -2445,8 +3007,9 @@ class Http2Session extends EventEmitter {
2445
3007
  }
2446
3008
  // The peer's RST_STREAM closes both halves at once: same teardown as our own
2447
3009
  // reset. Whether the application hears 'aborted' is decided there, by
2448
- // whether the response was still open (lib/stream.js, _destroy).
2449
- stream._destroy(code, undefined, false);
3010
+ // whether the response was still open (lib/stream.js, _destroy). The error it
3011
+ // hears is the code's own name, and codes 0 and 8 are not errors at all.
3012
+ stream._destroy(code, undefined, false, streamErrorOf(code));
2450
3013
  }
2451
3014
 
2452
3015
  get goawayCode() {
@@ -2602,9 +3165,16 @@ class Http2Session extends EventEmitter {
2602
3165
  this.sendRst(stream.id, code);
2603
3166
  this._flush();
2604
3167
  stream._destroy(code, msg, false);
2605
- if (this.listenerCount('frameError') > 0) {
2606
- this.emit('frameError', DATA, stream.id, code);
2607
- }
3168
+ // No 'frameError' here. node's onFrameError is the SEND-error path -- its own comment
3169
+ // says "Called by the native layer when an error has occurred sending a frame. This
3170
+ // should be exceedingly rare." (core.js:675) -- and it emits (type, code, id). An
3171
+ // inbound refusal is not that: measured on a live node 26 server for a trailer block
3172
+ // carrying a pseudo-header, a trailer block without END_STREAM, a WINDOW_UPDATE
3173
+ // overflowing the send window, a connection-specific request field and an unknown
3174
+ // request pseudo-header, node emitted no 'frameError' on the stream or the session in
3175
+ // any of the five (out/probe-frameerror.js). This used to emit one on the session with
3176
+ // the id and the code swapped and DATA hardcoded as the type; the outbound sites
3177
+ // (_refuseSend, the PUSH_PROMISE bound) are the ones that match node's event.
2608
3178
  process.nextTick(emitNT, stream, 'error', errorOf('ERR_HTTP2_STREAM_ERROR', msg));
2609
3179
  }
2610
3180
 
@@ -2723,7 +3293,7 @@ class Http2Session extends EventEmitter {
2723
3293
  if (this._liveStreams > 0 || this._outLen > 0 || this._frozenLen > 0 || this._stageLen > 0) {
2724
3294
  return;
2725
3295
  }
2726
- this.socket.end();
3296
+ this._socket.end();
2727
3297
  this.destroy(NO_ERROR);
2728
3298
  }
2729
3299
 
@@ -2791,7 +3361,7 @@ class Http2Session extends EventEmitter {
2791
3361
  // the connection with a reset whenever the write had not reached the OS yet -- under
2792
3362
  // load that is what h2spec's http2/7 reads as a failure ("connection reset by peer"
2793
3363
  // where node's "connection closed" passes), measured in bench/micro/probe-goaway-ping.js.
2794
- const socket = this.socket;
3364
+ const socket = this._socket;
2795
3365
  if (socket.destroyed) {
2796
3366
  socket.destroy();
2797
3367
  } else {
@@ -2854,7 +3424,9 @@ class Http2Session extends EventEmitter {
2854
3424
 
2855
3425
  _onSocketClose() {
2856
3426
  // release the ownership mark (node cleanupSession clears socket[kBoundSession])
2857
- this.socket[kBoundSession] = undefined;
3427
+ this._socket[kBoundSession] = undefined;
3428
+ // node cleanupSession also nulls the socket proxy so session.socket reads gone after close
3429
+ this._proxySocket = undefined;
2858
3430
  this._open = false;
2859
3431
  if (!this.destroyed) {
2860
3432
  this.destroy(NO_ERROR);
@@ -2946,15 +3518,98 @@ class Http2Session extends EventEmitter {
2946
3518
  return this;
2947
3519
  }
2948
3520
 
3521
+ // node's initOriginSet (internal/http2/core.js): the set is seeded once, from the peer's
3522
+ // identity as the TLS socket reports it -- the SNI name the client offered, or its address -- as
3523
+ // an https origin. It is only ever reached through the encrypted getter or an ORIGIN frame, so
3524
+ // an h2c session never builds one. getURLOrigin re-serialises the string; a socket with no
3525
+ // servername and no remote address yields the origin of 'https://null', which is what node gets
3526
+ // too, so this follows node field for field rather than second-guessing it.
3527
+ _initOriginSet() {
3528
+ let set = this._originSet;
3529
+ if (set === undefined) {
3530
+ const socket = this._socket;
3531
+ set = this._originSet = new Set();
3532
+ let hostName = socket.servername;
3533
+ if (hostName === null || hostName === false || hostName === undefined) {
3534
+ hostName = socket.remoteFamily === 'IPv6'
3535
+ ? `[${socket.remoteAddress}]`
3536
+ : socket.remoteAddress;
3537
+ }
3538
+ let originString = `https://${hostName}`;
3539
+ if (socket.remotePort != null) {
3540
+ originString += `:${socket.remotePort}`;
3541
+ }
3542
+ set.add(urlOrigin(originString));
3543
+ }
3544
+ return set;
3545
+ }
3546
+
3547
+ // node's `session.originSet` getter: a fresh ArrayFrom of the seeded set, or undefined for a
3548
+ // cleartext or destroyed session (measured on a live node h2c server: reads undefined there).
3549
+ get originSet() {
3550
+ if (!this.encrypted || this.destroyed) {
3551
+ return undefined;
3552
+ }
3553
+ return [...this._initOriginSet()];
3554
+ }
3555
+
3556
+ // node's Http2Session.origin(...origins): one ORIGIN frame listing the given origins, or nothing
3557
+ // at all for no arguments. Returns undefined like node (it is not a chaining method).
3558
+ origin(...origins) {
3559
+ if (this.destroyed) {
3560
+ throw extError('ERR_HTTP2_INVALID_SESSION', 'The session has been destroyed');
3561
+ }
3562
+ const payload = buildOriginPayload(origins);
3563
+ if (payload === null) {
3564
+ return;
3565
+ }
3566
+ this._frame(ORIGIN, 0, 0, payload, true);
3567
+ this._flush();
3568
+ }
3569
+
3570
+ // node's Http2Session.altsvc(alt, originOrStream): an ALTSVC frame naming either a URL origin
3571
+ // (stream 0) or a live stream id (empty origin). Returns undefined like node. The one divergence
3572
+ // from node is written beside checkAltSvc: a call with no origin and no stream -- which node's
3573
+ // C++ CHECK aborts on -- throws ERR_HTTP2_ALTSVC_INVALID_ORIGIN here instead of ending the
3574
+ // process, since a pure-JS library has no abort to fall back to.
3575
+ altsvc(alt, originOrStream) {
3576
+ if (this.destroyed) {
3577
+ throw extError('ERR_HTTP2_INVALID_SESSION', 'The session has been destroyed');
3578
+ }
3579
+ const { sid, origin, alt: value } = checkAltSvc(alt, originOrStream);
3580
+ // latin1 truncates every code unit to its low byte and is one octet per code
3581
+ // unit, so the byte lengths come from the string lengths and the two strings
3582
+ // go straight into the payload -- no intermediate buffers to allocate or copy.
3583
+ const originLen = origin.length;
3584
+ const payload = Buffer.allocUnsafe(2 + originLen + value.length);
3585
+ payload.writeUInt16BE(originLen, 0);
3586
+ latin1Into(payload, 2, origin);
3587
+ latin1Into(payload, 2 + originLen, value);
3588
+ this._frame(ALTSVC, 0, sid, payload, true);
3589
+ this._flush();
3590
+ }
3591
+
2949
3592
  ref() {
2950
- this.socket.ref(); return this;
3593
+ this._socket.ref(); return this;
2951
3594
  }
2952
3595
 
2953
3596
  unref() {
2954
- this.socket.unref(); return this;
3597
+ this._socket.unref(); return this;
3598
+ }
3599
+
3600
+ // node's session.socket: the safe Proxy, built once and cached. After _onSocketClose drops
3601
+ // it, this reads undefined -- matching node's cleanupSession, which nulls the proxy.
3602
+ get socket() {
3603
+ if (this._proxySocket === null) {
3604
+ this._proxySocket = new Proxy(this, proxySocketHandler);
3605
+ }
3606
+ return this._proxySocket;
2955
3607
  }
2956
3608
  }
2957
3609
 
2958
3610
  module.exports = { Http2Session, OUR_DEFAULTS, PEER_DEFAULTS, SETTINGS_BY_ID,
2959
3611
  ID_BY_SETTING, MAX_OUT_BATCH, MAX_SESSION_HOLD, STREAM_HOLD_CHARGE, BODY_MIN,
2960
- STAGE_MIN, MAX_SHAPES, strictSingleValueFields, hashBlock, hashPieces, kBoundSession };
3612
+ STAGE_MIN, MAX_SHAPES, MAX_SEND_BLOCK, PRIORITY_SPECLEN,
3613
+ strictSingleValueFields, hashBlock, hashPieces, kBoundSession,
3614
+ proxySocketHandler, extError, urlOrigin, checkAltSvc, buildOriginPayload,
3615
+ parseAltSvc, parseOrigins, received, outOfRangeValue };