h2lean 0.2.1 → 0.2.3

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.
@@ -66,7 +66,7 @@ const { EventEmitter } = require('node:events');
66
66
  const tls = require('node:tls');
67
67
  const f = require('./frames');
68
68
  const { Decoder, Encoder, HPackError } = require('./hpack');
69
- const { nullProto, isFieldName, lowerName, CONNECTION_SPECIFIC } = require('./headers');
69
+ const { nullProto, isFieldName, lowerName, CONNECTION_SPECIFIC, SINGLE_VALUE_FIELDS } = require('./headers');
70
70
  const { ClientHttp2Stream } = require('./client-stream');
71
71
  const { pieceByteAt, pieceSlice, pieceConcat, pieceEquals } = require('./pieces');
72
72
  // The settings tables, defaults and buffer-path constants are the server's, reused
@@ -74,7 +74,7 @@ const { pieceByteAt, pieceSlice, pieceConcat, pieceEquals } = require('./pieces'
74
74
  // SETTINGS id means, what node advertises, or where the copy/reference break-even sits.
75
75
  const {
76
76
  OUR_DEFAULTS, PEER_DEFAULTS, SETTINGS_BY_ID, ID_BY_SETTING, BODY_MIN, MAX_OUT_BATCH,
77
- STAGE_MIN, MAX_SHAPES, hashBlock, hashPieces
77
+ STAGE_MIN, MAX_SHAPES, strictSingleValueFields, hashBlock, hashPieces
78
78
  } = require('./session');
79
79
 
80
80
  const {
@@ -108,6 +108,11 @@ function payloadMeaningless(method) {
108
108
  || method === 'OPTIONS' || method === 'TRACE';
109
109
  }
110
110
 
111
+ // The request method request() fills ':method' from when the application did not
112
+ // supply one. Hoisted for reuse, not for speed: V8 interns string literals, so the
113
+ // measured position is unchanged (OPTIMIZATION.md item 36).
114
+ const DEFAULT_METHOD = 'GET';
115
+
111
116
  class ClientHttp2Session extends EventEmitter {
112
117
  constructor(socket, options, scheme, authority) {
113
118
  super();
@@ -142,6 +147,15 @@ class ClientHttp2Session extends EventEmitter {
142
147
  this.localSettings.headerTableSize);
143
148
  this._blocks = new WeakMap();
144
149
  this._flat = [];
150
+ // node's strictSingleValueFields option (validateSessionOptions, default true,
151
+ // internal/http2/core.js): gates the strict-single-value rule on the request list
152
+ // (_addField below). The connect() call surfaces the validation the way
153
+ // node's connect() does.
154
+ this._strictSingle = strictSingleValueFields(opts);
155
+ // scratch for the duplicate half of that rule: one array per session, cleared
156
+ // per request. node grows a fresh one lazily per call (buildNgHeaderString);
157
+ // the reuse is measured in OPTIMIZATION.md item 36.
158
+ this._singlesSeen = [];
145
159
 
146
160
  // Send-side windows: our budget to write, governed by the peer's window. Both
147
161
  // start at 65535 and move with the peer's SETTINGS delta and its WINDOW_UPDATEs.
@@ -498,13 +512,16 @@ class ClientHttp2Session extends EventEmitter {
498
512
  }
499
513
  const options2 = options ? { ...options } : {};
500
514
  const list = [];
501
- let method = 'GET';
515
+ let method = DEFAULT_METHOD;
502
516
  let sawMethod = false;
503
517
 
504
- const pushPseudo = (name, value) => {
505
- list.push(name, value);
506
- };
507
518
  const src = headersParam === undefined ? {} : headersParam;
519
+ if (this._strictSingle) {
520
+ // the duplicate check rides _addField's own loop, the way node's
521
+ // processHeader runs it inside buildNgHeaderString's one pass; the scratch
522
+ // survives between calls and is cleared here
523
+ this._singlesSeen.length = 0;
524
+ }
508
525
  if (Array.isArray(src)) {
509
526
  for (let i = 0; i + 1 < src.length; i += 2) {
510
527
  this._addField(list, src[i], src[i + 1]);
@@ -523,7 +540,7 @@ class ClientHttp2Session extends EventEmitter {
523
540
  }
524
541
  }
525
542
  if (!sawMethod) {
526
- pushPseudo(':method', method);
543
+ list.push(':method', method);
527
544
  }
528
545
 
529
546
  let endStream = options2.endStream;
@@ -614,11 +631,36 @@ class ClientHttp2Session extends EventEmitter {
614
631
  // lower-cases names, coerces pseudo/regular, rejects connection-specific fields
615
632
  // (RFC 9113 8.2.2) and a non-token name (RFC 9113 8.2.1) exactly as node's
616
633
  // prepareRequestHeaders* does for a client request.
634
+ //
635
+ // The strict single-value rule rides this same loop, the way node's processHeader
636
+ // runs it inside buildNgHeaderString's one pass (internal/http2/util.js): a
637
+ // multi-element array on one of the fields throws before anything is pushed, and
638
+ // a second copy of a field already seen throws against _singlesSeen. Both verdicts
639
+ // were measured on v26.12.1 -- the array case before the pseudo-header is looked
640
+ // at, which is why the check stands above the pseudo branch; an empty array is
641
+ // skipped before any bookkeeping (node's `case 0: return`), so it neither pushes
642
+ // a value nor spends a slot in _singlesSeen.
617
643
  _addField(list, rawKey, rawValue) {
618
644
  if (rawValue === undefined) {
619
645
  return;
620
646
  }
621
647
  const key = lowerName(rawKey);
648
+ const isArray = Array.isArray(rawValue);
649
+ if (isArray && rawValue.length === 0) {
650
+ return;
651
+ }
652
+ if (this._strictSingle && SINGLE_VALUE_FIELDS.has(key)) {
653
+ if (isArray && rawValue.length > 1) {
654
+ throw httpErr('ERR_HTTP2_HEADER_SINGLE_VALUE',
655
+ `Header field "${key}" must only have a single value`);
656
+ }
657
+ const seen = this._singlesSeen;
658
+ if (seen.indexOf(key) !== -1) {
659
+ throw httpErr('ERR_HTTP2_HEADER_SINGLE_VALUE',
660
+ `Header field "${key}" must only have a single value`);
661
+ }
662
+ seen.push(key);
663
+ }
622
664
  // The colon test is spelled as a code-point read, where lib/headers.js uses
623
665
  // `key[0] === ':'`. Not a style difference: the one-character read boxes a new
624
666
  // one-char string, and charCodeAt is the cheaper spelling on every input --
@@ -628,8 +670,7 @@ class ClientHttp2Session extends EventEmitter {
628
670
  && key !== ':protocol') {
629
671
  throw httpErr('ERR_HTTP2_PSEUDOHEADER_NOT_ALLOWED', `cannot send ${key}`);
630
672
  }
631
- const single = Array.isArray(rawValue) ? rawValue[0] : rawValue;
632
- list.push(key, String(single));
673
+ list.push(key, String(isArray ? rawValue[0] : rawValue));
633
674
  return;
634
675
  }
635
676
  if (!isFieldName(key)) {
@@ -639,7 +680,7 @@ class ClientHttp2Session extends EventEmitter {
639
680
  throw httpErr('ERR_HTTP2_INVALID_CONNECTION_HEADERS',
640
681
  `HTTP/1 Connection specific header is forbidden: ${key}`);
641
682
  }
642
- if (Array.isArray(rawValue)) {
683
+ if (isArray) {
643
684
  for (let j = 0; j < rawValue.length; j++) {
644
685
  list.push(key, String(rawValue[j]));
645
686
  }
@@ -1514,6 +1555,10 @@ class ClientHttp2Session extends EventEmitter {
1514
1555
  o[name] = `${have}; ${value}`;
1515
1556
  } else if (name === 'set-cookie') {
1516
1557
  have.push(value);
1558
+ } else if (SINGLE_VALUE_FIELDS.has(name)) {
1559
+ // node keeps the first copy and ignores the rest (toHeaderObject,
1560
+ // SINGLE_VALUE_FIELDS in lib/session.js) -- the response path must read a
1561
+ // repeated field the same way the server side does.
1517
1562
  } else {
1518
1563
  o[name] = `${have}, ${value}`;
1519
1564
  }
package/lib/client.js CHANGED
@@ -17,6 +17,7 @@
17
17
  const net = require('node:net');
18
18
  const tls = require('node:tls');
19
19
  const { ClientHttp2Session } = require('./client-session');
20
+ const { strictSingleValueFields } = require('./session');
20
21
 
21
22
  function notImplemented(what) {
22
23
  const err = new Error(`h2lean: not implemented: ${what}`);
@@ -37,6 +38,12 @@ function connect(authority, options, listener) {
37
38
  throw new TypeError('The "authority" argument must be of type string, an object, or a URL');
38
39
  }
39
40
 
41
+ // node validates the session options in validateSessionOptions BEFORE any socket
42
+ // exists, so a bad option throws cleanly out of connect(); validating after the
43
+ // socket was created would leave a live socket with no session attached to
44
+ // receive its errors. The constructor re-checks, which costs one typeof.
45
+ strictSingleValueFields(options);
46
+
40
47
  const protocol = authority.protocol || options.protocol || 'https:';
41
48
  const port = '' + (authority.port !== ''
42
49
  ? authority.port : (authority.protocol === 'http:' ? 80 : 443));
package/lib/headers.js CHANGED
@@ -64,6 +64,32 @@ const isToken = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
64
64
  const VALID_NAMES = new Set();
65
65
  const VALID_NAMES_MAX = 1024;
66
66
 
67
+ // The fields node's toHeaderObject (internal/http2/util.js, kSingleValueFields) reads
68
+ // as a single value in BOTH directions: inbound, a second copy on the wire is IGNORED
69
+ // and the first copy stays the value the application sees (lib/session.js _toObject and
70
+ // lib/client-session.js _toObject); outbound, node refuses a repeated copy or a
71
+ // multi-element array outright (parse() below, and the client's request list). Cookie
72
+ // and set-cookie are NOT in the set, measured on v26.12.1 by putting duplicate lines on
73
+ // the wire and reading the header object back (test/share-headers.test.js): cookie
74
+ // joins with "; " and set-cookie accumulates into one array. Why node keeps one copy
75
+ // inbound: whatever sits behind the server translates these fields into HTTP/1.1
76
+ // lines, and that translator also takes the first copy -- a joined value would be a
77
+ // value no downstream reader agrees with, the CVE-2020-8287 shape. The set is consulted
78
+ // only on the duplicate branch of _toObject, so a request without repeats pays nothing;
79
+ // the pseudo-headers and content-length sit here for parity although the inbound
80
+ // validator refuses their duplicates before _toObject ever runs.
81
+ const SINGLE_VALUE_FIELDS = new Set([
82
+ ':status', ':method', ':authority', ':scheme', ':path', ':protocol',
83
+ 'access-control-allow-credentials', 'access-control-max-age',
84
+ 'access-control-request-method', 'age', 'authorization', 'content-encoding',
85
+ 'content-language', 'content-length', 'content-location', 'content-md5',
86
+ 'content-range', 'content-type', 'date', 'dnt', 'etag', 'expires', 'from',
87
+ 'host', 'if-match', 'if-modified-since', 'if-none-match', 'if-range',
88
+ 'if-unmodified-since', 'last-modified', 'location', 'max-forwards',
89
+ 'proxy-authorization', 'range', 'referer', 'retry-after', 'tk',
90
+ 'upgrade-insecure-requests', 'user-agent', 'x-content-type-options'
91
+ ]);
92
+
67
93
  // RFC 9113 8.2.1: a field name is a token, and it is lower case. The token check is not
68
94
  // cosmetic -- a name carrying CR, LF or NUL is how one header becomes two *lines* again
69
95
  // once a proxy translates this connection to HTTP/1.1, which is the class of CVE-2020-8287
@@ -239,7 +265,8 @@ function refreshDate() {
239
265
  // need no iterator.
240
266
  // `info` marks the informational (1xx) block that additionalHeaders() sends: node applies
241
267
  // a different status rule and different error codes there, and it generates no date for it.
242
- function parse(headers, sensitive, { trailer = false, sendDate = false, info = false } = {}) {
268
+ function parse(headers, sensitive,
269
+ { trailer = false, sendDate = false, info = false, strict = true } = {}) {
243
270
  if (headers === null || typeof headers !== 'object') {
244
271
  throw httpError('ERR_HTTP2_INVALID_HEADER_VALUE', 'headers must be an object');
245
272
  }
@@ -253,16 +280,57 @@ function parse(headers, sensitive, { trailer = false, sendDate = false, info = f
253
280
  let status;
254
281
  let hasDate = false;
255
282
  let sawStatus = false;
256
- const keys = Object.keys(headers);
283
+ // The flat array is the other shape node's buildNgHeaderString accepts from
284
+ // prepareRequestHeadersObject / prepareRequestHeadersArray (internal/http2/util.js):
285
+ // the client's request() has always taken one, and respond() takes one too --
286
+ // measured: respond([':status', 200, 'x-a', '1']) serves like the object form. The
287
+ // pair loop runs by twos and skips an empty name and an absent value.
288
+ const flat = Array.isArray(headers);
289
+ const keys = flat ? headers : Object.keys(headers);
290
+ // node's strict-single-value rule (options.strictSingleValueFields, default on,
291
+ // validateSessionOptions in internal/http2/core.js): a field in SINGLE_VALUE_FIELDS
292
+ // may appear once and carry at most one value. Measured on v26.12.1: request() and
293
+ // respond() both throw ERR_HTTP2_HEADER_SINGLE_VALUE synchronously for a repeated
294
+ // copy -- regular field or pseudo-header alike -- or for a multi-element array on
295
+ // one, before any stream or octet exists. The singles walk stays in field order, so
296
+ // the first problem in the caller's order is the one reported.
297
+ const singles = strict ? new Set() : null;
257
298
  for (let i = 0; i < keys.length; i++) {
258
- const key = lowerName(keys[i]);
259
- const raw = headers[keys[i]];
260
- // Only an absent value is skipped. An empty name is not: node rejects it with
261
- // ERR_INVALID_HTTP_TOKEN, and the token check below does the same, because the
262
- // pattern requires at least one character.
263
- if (raw === undefined) {
299
+ let key;
300
+ let raw;
301
+ if (flat) {
302
+ key = lowerName(keys[i]);
303
+ raw = keys[i + 1];
304
+ if (key === '' || raw === undefined) {
305
+ continue;
306
+ }
307
+ i++; // the value slot is consumed with the name
308
+ } else {
309
+ key = lowerName(keys[i]);
310
+ raw = headers[keys[i]];
311
+ // Only an absent value is skipped. An empty name is not: node rejects it with
312
+ // ERR_INVALID_HTTP_TOKEN, and the token check below does the same, because the
313
+ // pattern requires at least one character.
314
+ if (raw === undefined) {
315
+ continue;
316
+ }
317
+ }
318
+ if (Array.isArray(raw) && raw.length === 0) {
319
+ // node emits nothing and records nothing for an empty array: processHeader
320
+ // returns before the singles bookkeeping runs
264
321
  continue;
265
322
  }
323
+ if (strict && SINGLE_VALUE_FIELDS.has(key)) {
324
+ if (Array.isArray(raw) && raw.length > 1) {
325
+ throw httpError('ERR_HTTP2_HEADER_SINGLE_VALUE',
326
+ `Header field "${key}" must only have a single value`);
327
+ }
328
+ if (singles.has(key)) {
329
+ throw httpError('ERR_HTTP2_HEADER_SINGLE_VALUE',
330
+ `Header field "${key}" must only have a single value`);
331
+ }
332
+ singles.add(key);
333
+ }
266
334
 
267
335
  if (key[0] === ':') {
268
336
  if (trailer) {
@@ -395,7 +463,8 @@ function block(headers, sensitive, opts, session) {
395
463
 
396
464
  const update = enc.takeSizeUpdate();
397
465
  const parsed = parse(headers, sensitive,
398
- { trailer: !!(opts && opts.trailer), sendDate, info: !!(opts && opts.info) });
466
+ { trailer: !!(opts && opts.trailer), sendDate, info: !!(opts && opts.info),
467
+ strict: session._strictSingle });
399
468
 
400
469
  // A shape reaches its final form over two or three responses, the way any HPACK
401
470
  // encoder warms up: the first sends a line as a literal and remembers it, the second
@@ -460,4 +529,4 @@ function encodeAt(parsed, enc, at) {
460
529
  }
461
530
 
462
531
  module.exports = { block, encode, parse, nullProto, isFieldName, trimName, lowerName,
463
- nameCacheSize, hasBadValue, CONNECTION_SPECIFIC, KSensitiveHeaders };
532
+ nameCacheSize, hasBadValue, CONNECTION_SPECIFIC, KSensitiveHeaders, SINGLE_VALUE_FIELDS };
package/lib/server.js CHANGED
@@ -56,7 +56,7 @@
56
56
 
57
57
  const net = require('node:net');
58
58
  const tls = require('node:tls');
59
- const { Http2Session, OUR_DEFAULTS } = require('./session');
59
+ const { Http2Session, OUR_DEFAULTS, strictSingleValueFields } = require('./session');
60
60
  const { onServerStream, Http2ServerRequest, Http2ServerResponse } = require('./compat');
61
61
 
62
62
  const kCompat = Symbol('h2lean.compatListener');
@@ -90,7 +90,10 @@ function initHttp2Server(server, options) {
90
90
  shapeCache: opts.shapeCache !== false,
91
91
  // Opt-in: req.headers is frozen and one object per distinct header block.
92
92
  // Off by default, because node lets the application write into headers.
93
- shareHeaders: opts.shareHeaders === true
93
+ shareHeaders: opts.shareHeaders === true,
94
+ // Validated here, at createServer time, where node's validateSessionOptions runs;
95
+ // the value also rides to each session, whose constructor re-checks it.
96
+ strictSingleValueFields: strictSingleValueFields(opts)
94
97
  };
95
98
  server._sessions = new Set();
96
99
  server[kCompat] = null;
package/lib/session.js CHANGED
@@ -23,7 +23,7 @@ const f = require('./frames');
23
23
  const { Decoder, Encoder, HPackError } = require('./hpack');
24
24
  const { Http2Stream, errorOf, emitNT } = require('./stream');
25
25
  const { pieceCopyTo, pieceSlice, pieceConcat, pieceEquals } = require('./pieces');
26
- const { nullProto, hasBadValue } = require('./headers');
26
+ const { nullProto, hasBadValue, SINGLE_VALUE_FIELDS } = require('./headers');
27
27
  // One shared 499 ms clock for the long idle timeouts, instead of a libuv timer
28
28
  // handle per connection. Vendored verbatim; see lib/fast-timer.js.
29
29
  const { setTimeout: idleSetTimeout, clearTimeout: idleClearTimeout } =
@@ -78,6 +78,23 @@ const MAX_REFUSED_HISTORY = 32;
78
78
  const MAX_DROPPED_HISTORY = 256;
79
79
  const MAX_SHAPES = 128;
80
80
 
81
+ // node's strictSingleValueFields option (validateSessionOptions, internal/http2/core.js):
82
+ // undefined is true, and a non-boolean is ERR_INVALID_ARG_TYPE at createServer/connect
83
+ // time. It gates the strict-single-value rule in both directions: the outbound blocks
84
+ // (parse in lib/headers.js) and the client's request list (lib/client-session.js), while
85
+ // the inbound first-wins reading of a repeated field is not optional -- node's
86
+ // toHeaderObject always reads it that way (SINGLE_VALUE_FIELDS in lib/headers.js).
87
+ function strictSingleValueFields(opts) {
88
+ const v = opts.strictSingleValueFields === undefined ? true : opts.strictSingleValueFields;
89
+ if (typeof v !== 'boolean') {
90
+ const err = new TypeError('The "options.strictSingleValueFields" property must be of '
91
+ + `type boolean. Received type ${typeof v}`);
92
+ err.code = 'ERR_INVALID_ARG_TYPE';
93
+ throw err;
94
+ }
95
+ return v;
96
+ }
97
+
81
98
  // RFC 7541 4.1: the size of an entry is the length of its name plus the length of its value
82
99
  // plus 32 -- the computation RFC 9113 6.5.2 states SETTINGS_MAX_HEADER_LIST_SIZE in terms of.
83
100
  // That is the number node's `maxHeaderListSize` is compared against, measured on
@@ -361,6 +378,7 @@ class Http2Session extends EventEmitter {
361
378
  // so everything the app receives is frozen and the setters throw
362
379
  // (OPTIMIZATION.md item 22 for both sides of the trade-off).
363
380
  this._share = opts.shareHeaders === true;
381
+ this._strictSingle = strictSingleValueFields(opts);
364
382
  this._flat = [];
365
383
  // The compat layer needs the decoded field list as it came off the wire.
366
384
  // Copying it is a per-request allocation, so it only happens for servers
@@ -1870,7 +1888,8 @@ class Http2Session extends EventEmitter {
1870
1888
  }
1871
1889
 
1872
1890
  // node's toHeaderObject semantics: null prototype, :status coerced to a
1873
- // number, set-cookie always an array, repeats joined.
1891
+ // number, set-cookie always an array, repeats joined -- except the fields in
1892
+ // SINGLE_VALUE_FIELDS, of which the first copy is kept and the rest ignored.
1874
1893
  //
1875
1894
  // The map is a fast-properties object with a null prototype rather than a
1876
1895
  // { __proto__: null } literal: the literal is in V8's dictionary mode, and this
@@ -1891,6 +1910,9 @@ class Http2Session extends EventEmitter {
1891
1910
  o[name] = `${have}; ${value}`;
1892
1911
  } else if (name === 'set-cookie') {
1893
1912
  have.push(value);
1913
+ } else if (SINGLE_VALUE_FIELDS.has(name)) {
1914
+ // node keeps the first copy and ignores the rest -- see SINGLE_VALUE_FIELDS
1915
+ // for why joining here would hand the application a smuggled value.
1894
1916
  } else {
1895
1917
  o[name] = `${have}, ${value}`;
1896
1918
  }
@@ -2695,4 +2717,4 @@ class Http2Session extends EventEmitter {
2695
2717
 
2696
2718
  module.exports = { Http2Session, OUR_DEFAULTS, PEER_DEFAULTS, SETTINGS_BY_ID,
2697
2719
  ID_BY_SETTING, MAX_OUT_BATCH, MAX_SESSION_HOLD, STREAM_HOLD_CHARGE, BODY_MIN,
2698
- STAGE_MIN, MAX_SHAPES, hashBlock, hashPieces };
2720
+ STAGE_MIN, MAX_SHAPES, strictSingleValueFields, hashBlock, hashPieces };
package/lib/stream.js CHANGED
@@ -106,10 +106,14 @@ class Http2Stream extends EventEmitter {
106
106
  }
107
107
 
108
108
  respond(headers, options) {
109
+ // node only throws here (internal/http2/core.js respond(): `if (this.headersSent)
110
+ // throw new ERR_HTTP2_HEADERS_SENT()`) and does not emit 'error' on the stream --
111
+ // measured on v26.12.1: a second respond() throws ERR_HTTP2_HEADERS_SENT
112
+ // ("Response has already been initiated.") with no 'error' event. An emit here
113
+ // throws out of a stream that has no 'error' listener, which turns the
114
+ // application's own throw into an uncaught exception node never produces.
109
115
  if (this.headersSent) {
110
- const err = errorOf('ERR_HTTP2_HEADERS_SENT', 'stream has already sent HEADERS');
111
- this.emit('error', err);
112
- throw err;
116
+ throw errorOf('ERR_HTTP2_HEADERS_SENT', 'Response has already been initiated.');
113
117
  }
114
118
  const opts = options || {};
115
119
  // node puts a `date` on every response of this API too: prepareResponseHeadersObject()
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "h2lean",
3
- "version": "0.2.1",
3
+ "version": "0.2.3",
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": [