• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

expressjs / express / 15920469752

27 Jun 2025 07:13AM UTC coverage: 99.869% (-0.1%) from 100.0%
15920469752

Pull #6596

github

web-flow
Merge f8e0fd8f9 into a039e4917
Pull Request #6596: fix(req): validate req.range size

1 of 2 new or added lines in 1 file covered. (50.0%)

765 of 766 relevant lines covered (99.87%)

2052.74 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

99.03
/lib/request.js
1
/*!
2
 * express
3
 * Copyright(c) 2009-2013 TJ Holowaychuk
4
 * Copyright(c) 2013 Roman Shtylman
5
 * Copyright(c) 2014-2015 Douglas Christopher Wilson
6
 * MIT Licensed
7
 */
8

9
'use strict';
10

11
/**
12
 * Module dependencies.
13
 * @private
14
 */
15

16
var accepts = require('accepts');
7✔
17
var isIP = require('node:net').isIP;
7✔
18
var typeis = require('type-is');
7✔
19
var http = require('node:http');
7✔
20
var fresh = require('fresh');
7✔
21
var parseRange = require('range-parser');
7✔
22
var parse = require('parseurl');
7✔
23
var proxyaddr = require('proxy-addr');
7✔
24

25
/**
26
 * Request prototype.
27
 * @public
28
 */
29

30
var req = Object.create(http.IncomingMessage.prototype)
7✔
31

32
/**
33
 * Module exports.
34
 * @public
35
 */
36

37
module.exports = req
7✔
38

39
/**
40
 * Return request header.
41
 *
42
 * The `Referrer` header field is special-cased,
43
 * both `Referrer` and `Referer` are interchangeable.
44
 *
45
 * Examples:
46
 *
47
 *     req.get('Content-Type');
48
 *     // => "text/plain"
49
 *
50
 *     req.get('content-type');
51
 *     // => "text/plain"
52
 *
53
 *     req.get('Something');
54
 *     // => undefined
55
 *
56
 * Aliased as `req.header()`.
57
 *
58
 * @param {String} name
59
 * @return {String}
60
 * @public
61
 */
62

63
req.get =
7✔
64
req.header = function header(name) {
65
  if (!name) {
644✔
66
    throw new TypeError('name argument is required to req.get');
7✔
67
  }
68

69
  if (typeof name !== 'string') {
637✔
70
    throw new TypeError('name must be a string to req.get');
7✔
71
  }
72

73
  var lc = name.toLowerCase();
630✔
74

75
  switch (lc) {
630✔
76
    case 'referer':
77
    case 'referrer':
78
      return this.headers.referrer
70✔
79
        || this.headers.referer;
80
    default:
81
      return this.headers[lc];
560✔
82
  }
83
};
84

85
/**
86
 * To do: update docs.
87
 *
88
 * Check if the given `type(s)` is acceptable, returning
89
 * the best match when true, otherwise `undefined`, in which
90
 * case you should respond with 406 "Not Acceptable".
91
 *
92
 * The `type` value may be a single MIME type string
93
 * such as "application/json", an extension name
94
 * such as "json", a comma-delimited list such as "json, html, text/plain",
95
 * an argument list such as `"json", "html", "text/plain"`,
96
 * or an array `["json", "html", "text/plain"]`. When a list
97
 * or array is given, the _best_ match, if any is returned.
98
 *
99
 * Examples:
100
 *
101
 *     // Accept: text/html
102
 *     req.accepts('html');
103
 *     // => "html"
104
 *
105
 *     // Accept: text/*, application/json
106
 *     req.accepts('html');
107
 *     // => "html"
108
 *     req.accepts('text/html');
109
 *     // => "text/html"
110
 *     req.accepts('json, text');
111
 *     // => "json"
112
 *     req.accepts('application/json');
113
 *     // => "application/json"
114
 *
115
 *     // Accept: text/*, application/json
116
 *     req.accepts('image/png');
117
 *     req.accepts('png');
118
 *     // => undefined
119
 *
120
 *     // Accept: text/*;q=.5, application/json
121
 *     req.accepts(['html', 'json']);
122
 *     req.accepts('html', 'json');
123
 *     req.accepts('html, json');
124
 *     // => "json"
125
 *
126
 * @param {String|Array} type(s)
127
 * @return {String|Array|Boolean}
128
 * @public
129
 */
130

131
req.accepts = function(){
7✔
132
  var accept = accepts(this);
700✔
133
  return accept.types.apply(accept, arguments);
700✔
134
};
135

136
/**
137
 * Check if the given `encoding`s are accepted.
138
 *
139
 * @param {String} ...encoding
140
 * @return {String|Array}
141
 * @public
142
 */
143

144
req.acceptsEncodings = function(){
7✔
145
  var accept = accepts(this);
21✔
146
  return accept.encodings.apply(accept, arguments);
21✔
147
};
148

149
/**
150
 * Check if the given `charset`s are acceptable,
151
 * otherwise you should respond with 406 "Not Acceptable".
152
 *
153
 * @param {String} ...charset
154
 * @return {String|Array}
155
 * @public
156
 */
157

158
req.acceptsCharsets = function(){
7✔
159
  var accept = accepts(this);
21✔
160
  return accept.charsets.apply(accept, arguments);
21✔
161
};
162

163
/**
164
 * Check if the given `lang`s are acceptable,
165
 * otherwise you should respond with 406 "Not Acceptable".
166
 *
167
 * @param {String} ...lang
168
 * @return {String|Array}
169
 * @public
170
 */
171

172
req.acceptsLanguages = function(...languages) {
7✔
173
  return accepts(this).languages(...languages);
42✔
174
};
175

176
/**
177
 * Parse Range header field, capping to the given `size`.
178
 *
179
 * Unspecified ranges such as "0-" require knowledge of your resource length. In
180
 * the case of a byte range this is of course the total number of bytes. If the
181
 * Range header field is not given `undefined` is returned, `-1` when unsatisfiable,
182
 * and `-2` when syntactically invalid.
183
 *
184
 * When ranges are returned, the array has a "type" property which is the type of
185
 * range that is required (most commonly, "bytes"). Each array element is an object
186
 * with a "start" and "end" property for the portion of the range.
187
 *
188
 * The "combine" option can be set to `true` and overlapping & adjacent ranges
189
 * will be combined into a single range.
190
 *
191
 * NOTE: remember that ranges are inclusive, so for example "Range: users=0-3"
192
 * should respond with 4 users when available, not 3.
193
 *
194
 * @param {number} size
195
 * @param {object} [options]
196
 * @param {boolean} [options.combine=false]
197
 * @return {number|array}
198
 * @throws {TypeError}
199
 * @public
200
 */
201

202
req.range = function range(size, options) {
7✔
203
  if (!Number.isInteger(size) || size < 0) {
49✔
NEW
204
    throw new TypeError('size must be a non-negative integer to req.range');
×
205
  }
206
  var range = this.get('Range');
49✔
207
  if (!range) return;
49✔
208
  return parseRange(size, range, options);
42✔
209
};
210

211
/**
212
 * Parse the query string of `req.url`.
213
 *
214
 * This uses the "query parser" setting to parse the raw
215
 * string into an object.
216
 *
217
 * @return {String}
218
 * @api public
219
 */
220

221
defineGetter(req, 'query', function query(){
7✔
222
  var queryparse = this.app.get('query parser fn');
455✔
223

224
  if (!queryparse) {
455✔
225
    // parsing is disabled
226
    return Object.create(null);
7✔
227
  }
228

229
  var querystring = parse(this).query;
448✔
230

231
  return queryparse(querystring);
448✔
232
});
233

234
/**
235
 * Check if the incoming request contains the "Content-Type"
236
 * header field, and it contains the given mime `type`.
237
 *
238
 * Examples:
239
 *
240
 *      // With Content-Type: text/html; charset=utf-8
241
 *      req.is('html');
242
 *      req.is('text/html');
243
 *      req.is('text/*');
244
 *      // => true
245
 *
246
 *      // When Content-Type is application/json
247
 *      req.is('json');
248
 *      req.is('application/json');
249
 *      req.is('application/*');
250
 *      // => true
251
 *
252
 *      req.is('html');
253
 *      // => false
254
 *
255
 * @param {String|Array} types...
256
 * @return {String|false|null}
257
 * @public
258
 */
259

260
req.is = function is(types) {
7✔
261
  var arr = types;
77✔
262

263
  // support flattened arguments
264
  if (!Array.isArray(types)) {
77✔
265
    arr = new Array(arguments.length);
77✔
266
    for (var i = 0; i < arr.length; i++) {
77✔
267
      arr[i] = arguments[i];
77✔
268
    }
269
  }
270

271
  return typeis(this, arr);
77✔
272
};
273

274
/**
275
 * Return the protocol string "http" or "https"
276
 * when requested with TLS. When the "trust proxy"
277
 * setting trusts the socket address, the
278
 * "X-Forwarded-Proto" header field will be trusted
279
 * and used if present.
280
 *
281
 * If you're running behind a reverse proxy that
282
 * supplies https for you this may be enabled.
283
 *
284
 * @return {String}
285
 * @public
286
 */
287

288
defineGetter(req, 'protocol', function protocol(){
7✔
289
  var proto = this.connection.encrypted
119✔
290
    ? 'https'
291
    : 'http';
292
  var trust = this.app.get('trust proxy fn');
119✔
293

294
  if (!trust(this.connection.remoteAddress, 0)) {
119✔
295
    return proto;
63✔
296
  }
297

298
  // Note: X-Forwarded-Proto is normally only ever a
299
  //       single value, but this is to be safe.
300
  var header = this.get('X-Forwarded-Proto') || proto
56✔
301
  var index = header.indexOf(',')
56✔
302

303
  return index !== -1
56✔
304
    ? header.substring(0, index).trim()
305
    : header.trim()
306
});
307

308
/**
309
 * Short-hand for:
310
 *
311
 *    req.protocol === 'https'
312
 *
313
 * @return {Boolean}
314
 * @public
315
 */
316

317
defineGetter(req, 'secure', function secure(){
7✔
318
  return this.protocol === 'https';
42✔
319
});
320

321
/**
322
 * Return the remote address from the trusted proxy.
323
 *
324
 * The is the remote address on the socket unless
325
 * "trust proxy" is set.
326
 *
327
 * @return {String}
328
 * @public
329
 */
330

331
defineGetter(req, 'ip', function ip(){
7✔
332
  var trust = this.app.get('trust proxy fn');
42✔
333
  return proxyaddr(this, trust);
42✔
334
});
335

336
/**
337
 * When "trust proxy" is set, trusted proxy addresses + client.
338
 *
339
 * For example if the value were "client, proxy1, proxy2"
340
 * you would receive the array `["client", "proxy1", "proxy2"]`
341
 * where "proxy2" is the furthest down-stream and "proxy1" and
342
 * "proxy2" were trusted.
343
 *
344
 * @return {Array}
345
 * @public
346
 */
347

348
defineGetter(req, 'ips', function ips() {
7✔
349
  var trust = this.app.get('trust proxy fn');
28✔
350
  var addrs = proxyaddr.all(this, trust);
28✔
351

352
  // reverse the order (to farthest -> closest)
353
  // and remove socket address
354
  addrs.reverse().pop()
28✔
355

356
  return addrs
28✔
357
});
358

359
/**
360
 * Return subdomains as an array.
361
 *
362
 * Subdomains are the dot-separated parts of the host before the main domain of
363
 * the app. By default, the domain of the app is assumed to be the last two
364
 * parts of the host. This can be changed by setting "subdomain offset".
365
 *
366
 * For example, if the domain is "tobi.ferrets.example.com":
367
 * If "subdomain offset" is not set, req.subdomains is `["ferrets", "tobi"]`.
368
 * If "subdomain offset" is 3, req.subdomains is `["tobi"]`.
369
 *
370
 * @return {Array}
371
 * @public
372
 */
373

374
defineGetter(req, 'subdomains', function subdomains() {
7✔
375
  var hostname = this.hostname;
77✔
376

377
  if (!hostname) return [];
77✔
378

379
  var offset = this.app.get('subdomain offset');
70✔
380
  var subdomains = !isIP(hostname)
70✔
381
    ? hostname.split('.').reverse()
382
    : [hostname];
383

384
  return subdomains.slice(offset);
70✔
385
});
386

387
/**
388
 * Short-hand for `url.parse(req.url).pathname`.
389
 *
390
 * @return {String}
391
 * @public
392
 */
393

394
defineGetter(req, 'path', function path() {
7✔
395
  return parse(this).pathname;
21✔
396
});
397

398
/**
399
 * Parse the "Host" header field to a host.
400
 *
401
 * When the "trust proxy" setting trusts the socket
402
 * address, the "X-Forwarded-Host" header field will
403
 * be trusted.
404
 *
405
 * @return {String}
406
 * @public
407
 */
408

409
defineGetter(req, 'host', function host(){
7✔
410
  var trust = this.app.get('trust proxy fn');
231✔
411
  var val = this.get('X-Forwarded-Host');
231✔
412

413
  if (!val || !trust(this.connection.remoteAddress, 0)) {
231✔
414
    val = this.get('Host');
182✔
415
  } else if (val.indexOf(',') !== -1) {
49✔
416
    // Note: X-Forwarded-Host is normally only ever a
417
    //       single value, but this is to be safe.
418
    val = val.substring(0, val.indexOf(',')).trimRight()
21✔
419
  }
420

421
  return val || undefined;
231✔
422
});
423

424
/**
425
 * Parse the "Host" header field to a hostname.
426
 *
427
 * When the "trust proxy" setting trusts the socket
428
 * address, the "X-Forwarded-Host" header field will
429
 * be trusted.
430
 *
431
 * @return {String}
432
 * @api public
433
 */
434

435
defineGetter(req, 'hostname', function hostname(){
7✔
436
  var host = this.host;
161✔
437

438
  if (!host) return;
161✔
439

440
  // IPv6 literal support
441
  var offset = host[0] === '['
147✔
442
    ? host.indexOf(']') + 1
443
    : 0;
444
  var index = host.indexOf(':', offset);
147✔
445

446
  return index !== -1
147✔
447
    ? host.substring(0, index)
448
    : host;
449
});
450

451
/**
452
 * Check if the request is fresh, aka
453
 * Last-Modified or the ETag
454
 * still match.
455
 *
456
 * @return {Boolean}
457
 * @public
458
 */
459

460
defineGetter(req, 'fresh', function(){
7✔
461
  var method = this.method;
4,717✔
462
  var res = this.res
4,717✔
463
  var status = res.statusCode
4,717✔
464

465
  // GET or HEAD for weak freshness validation only
466
  if ('GET' !== method && 'HEAD' !== method) return false;
4,717✔
467

468
  // 2xx or 304 as per rfc2616 14.26
469
  if ((status >= 200 && status < 300) || 304 === status) {
2,723✔
470
    return fresh(this.headers, {
2,366✔
471
      'etag': res.get('ETag'),
472
      'last-modified': res.get('Last-Modified')
473
    })
474
  }
475

476
  return false;
357✔
477
});
478

479
/**
480
 * Check if the request is stale, aka
481
 * "Last-Modified" and / or the "ETag" for the
482
 * resource has changed.
483
 *
484
 * @return {Boolean}
485
 * @public
486
 */
487

488
defineGetter(req, 'stale', function stale(){
7✔
489
  return !this.fresh;
21✔
490
});
491

492
/**
493
 * Check if the request was an _XMLHttpRequest_.
494
 *
495
 * @return {Boolean}
496
 * @public
497
 */
498

499
defineGetter(req, 'xhr', function xhr(){
7✔
500
  var val = this.get('X-Requested-With') || '';
28✔
501
  return val.toLowerCase() === 'xmlhttprequest';
28✔
502
});
503

504
/**
505
 * Helper function for creating a getter on an object.
506
 *
507
 * @param {Object} obj
508
 * @param {String} name
509
 * @param {Function} getter
510
 * @private
511
 */
512
function defineGetter(obj, name, getter) {
513
  Object.defineProperty(obj, name, {
84✔
514
    configurable: true,
515
    enumerable: true,
516
    get: getter
517
  });
518
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc