source: node_modules/follow-redirects/index.js@ d24f17c

main
Last change on this file since d24f17c was d24f17c, checked in by Aleksandar Panovski <apano77@…>, 15 months ago

Initial commit

  • Property mode set to 100644
File size: 19.6 KB
Line 
1var url = require("url");
2var URL = url.URL;
3var http = require("http");
4var https = require("https");
5var Writable = require("stream").Writable;
6var assert = require("assert");
7var debug = require("./debug");
8
9// Whether to use the native URL object or the legacy url module
10var useNativeURL = false;
11try {
12 assert(new URL());
13}
14catch (error) {
15 useNativeURL = error.code === "ERR_INVALID_URL";
16}
17
18// URL fields to preserve in copy operations
19var preservedUrlFields = [
20 "auth",
21 "host",
22 "hostname",
23 "href",
24 "path",
25 "pathname",
26 "port",
27 "protocol",
28 "query",
29 "search",
30 "hash",
31];
32
33// Create handlers that pass events from native requests
34var events = ["abort", "aborted", "connect", "error", "socket", "timeout"];
35var eventHandlers = Object.create(null);
36events.forEach(function (event) {
37 eventHandlers[event] = function (arg1, arg2, arg3) {
38 this._redirectable.emit(event, arg1, arg2, arg3);
39 };
40});
41
42// Error types with codes
43var InvalidUrlError = createErrorType(
44 "ERR_INVALID_URL",
45 "Invalid URL",
46 TypeError
47);
48var RedirectionError = createErrorType(
49 "ERR_FR_REDIRECTION_FAILURE",
50 "Redirected request failed"
51);
52var TooManyRedirectsError = createErrorType(
53 "ERR_FR_TOO_MANY_REDIRECTS",
54 "Maximum number of redirects exceeded",
55 RedirectionError
56);
57var MaxBodyLengthExceededError = createErrorType(
58 "ERR_FR_MAX_BODY_LENGTH_EXCEEDED",
59 "Request body larger than maxBodyLength limit"
60);
61var WriteAfterEndError = createErrorType(
62 "ERR_STREAM_WRITE_AFTER_END",
63 "write after end"
64);
65
66// istanbul ignore next
67var destroy = Writable.prototype.destroy || noop;
68
69// An HTTP(S) request that can be redirected
70function RedirectableRequest(options, responseCallback) {
71 // Initialize the request
72 Writable.call(this);
73 this._sanitizeOptions(options);
74 this._options = options;
75 this._ended = false;
76 this._ending = false;
77 this._redirectCount = 0;
78 this._redirects = [];
79 this._requestBodyLength = 0;
80 this._requestBodyBuffers = [];
81
82 // Attach a callback if passed
83 if (responseCallback) {
84 this.on("response", responseCallback);
85 }
86
87 // React to responses of native requests
88 var self = this;
89 this._onNativeResponse = function (response) {
90 try {
91 self._processResponse(response);
92 }
93 catch (cause) {
94 self.emit("error", cause instanceof RedirectionError ?
95 cause : new RedirectionError({ cause: cause }));
96 }
97 };
98
99 // Perform the first request
100 this._performRequest();
101}
102RedirectableRequest.prototype = Object.create(Writable.prototype);
103
104RedirectableRequest.prototype.abort = function () {
105 destroyRequest(this._currentRequest);
106 this._currentRequest.abort();
107 this.emit("abort");
108};
109
110RedirectableRequest.prototype.destroy = function (error) {
111 destroyRequest(this._currentRequest, error);
112 destroy.call(this, error);
113 return this;
114};
115
116// Writes buffered data to the current native request
117RedirectableRequest.prototype.write = function (data, encoding, callback) {
118 // Writing is not allowed if end has been called
119 if (this._ending) {
120 throw new WriteAfterEndError();
121 }
122
123 // Validate input and shift parameters if necessary
124 if (!isString(data) && !isBuffer(data)) {
125 throw new TypeError("data should be a string, Buffer or Uint8Array");
126 }
127 if (isFunction(encoding)) {
128 callback = encoding;
129 encoding = null;
130 }
131
132 // Ignore empty buffers, since writing them doesn't invoke the callback
133 // https://github.com/nodejs/node/issues/22066
134 if (data.length === 0) {
135 if (callback) {
136 callback();
137 }
138 return;
139 }
140 // Only write when we don't exceed the maximum body length
141 if (this._requestBodyLength + data.length <= this._options.maxBodyLength) {
142 this._requestBodyLength += data.length;
143 this._requestBodyBuffers.push({ data: data, encoding: encoding });
144 this._currentRequest.write(data, encoding, callback);
145 }
146 // Error when we exceed the maximum body length
147 else {
148 this.emit("error", new MaxBodyLengthExceededError());
149 this.abort();
150 }
151};
152
153// Ends the current native request
154RedirectableRequest.prototype.end = function (data, encoding, callback) {
155 // Shift parameters if necessary
156 if (isFunction(data)) {
157 callback = data;
158 data = encoding = null;
159 }
160 else if (isFunction(encoding)) {
161 callback = encoding;
162 encoding = null;
163 }
164
165 // Write data if needed and end
166 if (!data) {
167 this._ended = this._ending = true;
168 this._currentRequest.end(null, null, callback);
169 }
170 else {
171 var self = this;
172 var currentRequest = this._currentRequest;
173 this.write(data, encoding, function () {
174 self._ended = true;
175 currentRequest.end(null, null, callback);
176 });
177 this._ending = true;
178 }
179};
180
181// Sets a header value on the current native request
182RedirectableRequest.prototype.setHeader = function (name, value) {
183 this._options.headers[name] = value;
184 this._currentRequest.setHeader(name, value);
185};
186
187// Clears a header value on the current native request
188RedirectableRequest.prototype.removeHeader = function (name) {
189 delete this._options.headers[name];
190 this._currentRequest.removeHeader(name);
191};
192
193// Global timeout for all underlying requests
194RedirectableRequest.prototype.setTimeout = function (msecs, callback) {
195 var self = this;
196
197 // Destroys the socket on timeout
198 function destroyOnTimeout(socket) {
199 socket.setTimeout(msecs);
200 socket.removeListener("timeout", socket.destroy);
201 socket.addListener("timeout", socket.destroy);
202 }
203
204 // Sets up a timer to trigger a timeout event
205 function startTimer(socket) {
206 if (self._timeout) {
207 clearTimeout(self._timeout);
208 }
209 self._timeout = setTimeout(function () {
210 self.emit("timeout");
211 clearTimer();
212 }, msecs);
213 destroyOnTimeout(socket);
214 }
215
216 // Stops a timeout from triggering
217 function clearTimer() {
218 // Clear the timeout
219 if (self._timeout) {
220 clearTimeout(self._timeout);
221 self._timeout = null;
222 }
223
224 // Clean up all attached listeners
225 self.removeListener("abort", clearTimer);
226 self.removeListener("error", clearTimer);
227 self.removeListener("response", clearTimer);
228 self.removeListener("close", clearTimer);
229 if (callback) {
230 self.removeListener("timeout", callback);
231 }
232 if (!self.socket) {
233 self._currentRequest.removeListener("socket", startTimer);
234 }
235 }
236
237 // Attach callback if passed
238 if (callback) {
239 this.on("timeout", callback);
240 }
241
242 // Start the timer if or when the socket is opened
243 if (this.socket) {
244 startTimer(this.socket);
245 }
246 else {
247 this._currentRequest.once("socket", startTimer);
248 }
249
250 // Clean up on events
251 this.on("socket", destroyOnTimeout);
252 this.on("abort", clearTimer);
253 this.on("error", clearTimer);
254 this.on("response", clearTimer);
255 this.on("close", clearTimer);
256
257 return this;
258};
259
260// Proxy all other public ClientRequest methods
261[
262 "flushHeaders", "getHeader",
263 "setNoDelay", "setSocketKeepAlive",
264].forEach(function (method) {
265 RedirectableRequest.prototype[method] = function (a, b) {
266 return this._currentRequest[method](a, b);
267 };
268});
269
270// Proxy all public ClientRequest properties
271["aborted", "connection", "socket"].forEach(function (property) {
272 Object.defineProperty(RedirectableRequest.prototype, property, {
273 get: function () { return this._currentRequest[property]; },
274 });
275});
276
277RedirectableRequest.prototype._sanitizeOptions = function (options) {
278 // Ensure headers are always present
279 if (!options.headers) {
280 options.headers = {};
281 }
282
283 // Since http.request treats host as an alias of hostname,
284 // but the url module interprets host as hostname plus port,
285 // eliminate the host property to avoid confusion.
286 if (options.host) {
287 // Use hostname if set, because it has precedence
288 if (!options.hostname) {
289 options.hostname = options.host;
290 }
291 delete options.host;
292 }
293
294 // Complete the URL object when necessary
295 if (!options.pathname && options.path) {
296 var searchPos = options.path.indexOf("?");
297 if (searchPos < 0) {
298 options.pathname = options.path;
299 }
300 else {
301 options.pathname = options.path.substring(0, searchPos);
302 options.search = options.path.substring(searchPos);
303 }
304 }
305};
306
307
308// Executes the next native request (initial or redirect)
309RedirectableRequest.prototype._performRequest = function () {
310 // Load the native protocol
311 var protocol = this._options.protocol;
312 var nativeProtocol = this._options.nativeProtocols[protocol];
313 if (!nativeProtocol) {
314 throw new TypeError("Unsupported protocol " + protocol);
315 }
316
317 // If specified, use the agent corresponding to the protocol
318 // (HTTP and HTTPS use different types of agents)
319 if (this._options.agents) {
320 var scheme = protocol.slice(0, -1);
321 this._options.agent = this._options.agents[scheme];
322 }
323
324 // Create the native request and set up its event handlers
325 var request = this._currentRequest =
326 nativeProtocol.request(this._options, this._onNativeResponse);
327 request._redirectable = this;
328 for (var event of events) {
329 request.on(event, eventHandlers[event]);
330 }
331
332 // RFC7230§5.3.1: When making a request directly to an origin server, […]
333 // a client MUST send only the absolute path […] as the request-target.
334 this._currentUrl = /^\//.test(this._options.path) ?
335 url.format(this._options) :
336 // When making a request to a proxy, […]
337 // a client MUST send the target URI in absolute-form […].
338 this._options.path;
339
340 // End a redirected request
341 // (The first request must be ended explicitly with RedirectableRequest#end)
342 if (this._isRedirect) {
343 // Write the request entity and end
344 var i = 0;
345 var self = this;
346 var buffers = this._requestBodyBuffers;
347 (function writeNext(error) {
348 // Only write if this request has not been redirected yet
349 /* istanbul ignore else */
350 if (request === self._currentRequest) {
351 // Report any write errors
352 /* istanbul ignore if */
353 if (error) {
354 self.emit("error", error);
355 }
356 // Write the next buffer if there are still left
357 else if (i < buffers.length) {
358 var buffer = buffers[i++];
359 /* istanbul ignore else */
360 if (!request.finished) {
361 request.write(buffer.data, buffer.encoding, writeNext);
362 }
363 }
364 // End the request if `end` has been called on us
365 else if (self._ended) {
366 request.end();
367 }
368 }
369 }());
370 }
371};
372
373// Processes a response from the current native request
374RedirectableRequest.prototype._processResponse = function (response) {
375 // Store the redirected response
376 var statusCode = response.statusCode;
377 if (this._options.trackRedirects) {
378 this._redirects.push({
379 url: this._currentUrl,
380 headers: response.headers,
381 statusCode: statusCode,
382 });
383 }
384
385 // RFC7231§6.4: The 3xx (Redirection) class of status code indicates
386 // that further action needs to be taken by the user agent in order to
387 // fulfill the request. If a Location header field is provided,
388 // the user agent MAY automatically redirect its request to the URI
389 // referenced by the Location field value,
390 // even if the specific status code is not understood.
391
392 // If the response is not a redirect; return it as-is
393 var location = response.headers.location;
394 if (!location || this._options.followRedirects === false ||
395 statusCode < 300 || statusCode >= 400) {
396 response.responseUrl = this._currentUrl;
397 response.redirects = this._redirects;
398 this.emit("response", response);
399
400 // Clean up
401 this._requestBodyBuffers = [];
402 return;
403 }
404
405 // The response is a redirect, so abort the current request
406 destroyRequest(this._currentRequest);
407 // Discard the remainder of the response to avoid waiting for data
408 response.destroy();
409
410 // RFC7231§6.4: A client SHOULD detect and intervene
411 // in cyclical redirections (i.e., "infinite" redirection loops).
412 if (++this._redirectCount > this._options.maxRedirects) {
413 throw new TooManyRedirectsError();
414 }
415
416 // Store the request headers if applicable
417 var requestHeaders;
418 var beforeRedirect = this._options.beforeRedirect;
419 if (beforeRedirect) {
420 requestHeaders = Object.assign({
421 // The Host header was set by nativeProtocol.request
422 Host: response.req.getHeader("host"),
423 }, this._options.headers);
424 }
425
426 // RFC7231§6.4: Automatic redirection needs to done with
427 // care for methods not known to be safe, […]
428 // RFC7231§6.4.2–3: For historical reasons, a user agent MAY change
429 // the request method from POST to GET for the subsequent request.
430 var method = this._options.method;
431 if ((statusCode === 301 || statusCode === 302) && this._options.method === "POST" ||
432 // RFC7231§6.4.4: The 303 (See Other) status code indicates that
433 // the server is redirecting the user agent to a different resource […]
434 // A user agent can perform a retrieval request targeting that URI
435 // (a GET or HEAD request if using HTTP) […]
436 (statusCode === 303) && !/^(?:GET|HEAD)$/.test(this._options.method)) {
437 this._options.method = "GET";
438 // Drop a possible entity and headers related to it
439 this._requestBodyBuffers = [];
440 removeMatchingHeaders(/^content-/i, this._options.headers);
441 }
442
443 // Drop the Host header, as the redirect might lead to a different host
444 var currentHostHeader = removeMatchingHeaders(/^host$/i, this._options.headers);
445
446 // If the redirect is relative, carry over the host of the last request
447 var currentUrlParts = parseUrl(this._currentUrl);
448 var currentHost = currentHostHeader || currentUrlParts.host;
449 var currentUrl = /^\w+:/.test(location) ? this._currentUrl :
450 url.format(Object.assign(currentUrlParts, { host: currentHost }));
451
452 // Create the redirected request
453 var redirectUrl = resolveUrl(location, currentUrl);
454 debug("redirecting to", redirectUrl.href);
455 this._isRedirect = true;
456 spreadUrlObject(redirectUrl, this._options);
457
458 // Drop confidential headers when redirecting to a less secure protocol
459 // or to a different domain that is not a superdomain
460 if (redirectUrl.protocol !== currentUrlParts.protocol &&
461 redirectUrl.protocol !== "https:" ||
462 redirectUrl.host !== currentHost &&
463 !isSubdomain(redirectUrl.host, currentHost)) {
464 removeMatchingHeaders(/^(?:authorization|cookie)$/i, this._options.headers);
465 }
466
467 // Evaluate the beforeRedirect callback
468 if (isFunction(beforeRedirect)) {
469 var responseDetails = {
470 headers: response.headers,
471 statusCode: statusCode,
472 };
473 var requestDetails = {
474 url: currentUrl,
475 method: method,
476 headers: requestHeaders,
477 };
478 beforeRedirect(this._options, responseDetails, requestDetails);
479 this._sanitizeOptions(this._options);
480 }
481
482 // Perform the redirected request
483 this._performRequest();
484};
485
486// Wraps the key/value object of protocols with redirect functionality
487function wrap(protocols) {
488 // Default settings
489 var exports = {
490 maxRedirects: 21,
491 maxBodyLength: 10 * 1024 * 1024,
492 };
493
494 // Wrap each protocol
495 var nativeProtocols = {};
496 Object.keys(protocols).forEach(function (scheme) {
497 var protocol = scheme + ":";
498 var nativeProtocol = nativeProtocols[protocol] = protocols[scheme];
499 var wrappedProtocol = exports[scheme] = Object.create(nativeProtocol);
500
501 // Executes a request, following redirects
502 function request(input, options, callback) {
503 // Parse parameters, ensuring that input is an object
504 if (isURL(input)) {
505 input = spreadUrlObject(input);
506 }
507 else if (isString(input)) {
508 input = spreadUrlObject(parseUrl(input));
509 }
510 else {
511 callback = options;
512 options = validateUrl(input);
513 input = { protocol: protocol };
514 }
515 if (isFunction(options)) {
516 callback = options;
517 options = null;
518 }
519
520 // Set defaults
521 options = Object.assign({
522 maxRedirects: exports.maxRedirects,
523 maxBodyLength: exports.maxBodyLength,
524 }, input, options);
525 options.nativeProtocols = nativeProtocols;
526 if (!isString(options.host) && !isString(options.hostname)) {
527 options.hostname = "::1";
528 }
529
530 assert.equal(options.protocol, protocol, "protocol mismatch");
531 debug("options", options);
532 return new RedirectableRequest(options, callback);
533 }
534
535 // Executes a GET request, following redirects
536 function get(input, options, callback) {
537 var wrappedRequest = wrappedProtocol.request(input, options, callback);
538 wrappedRequest.end();
539 return wrappedRequest;
540 }
541
542 // Expose the properties on the wrapped protocol
543 Object.defineProperties(wrappedProtocol, {
544 request: { value: request, configurable: true, enumerable: true, writable: true },
545 get: { value: get, configurable: true, enumerable: true, writable: true },
546 });
547 });
548 return exports;
549}
550
551function noop() { /* empty */ }
552
553function parseUrl(input) {
554 var parsed;
555 /* istanbul ignore else */
556 if (useNativeURL) {
557 parsed = new URL(input);
558 }
559 else {
560 // Ensure the URL is valid and absolute
561 parsed = validateUrl(url.parse(input));
562 if (!isString(parsed.protocol)) {
563 throw new InvalidUrlError({ input });
564 }
565 }
566 return parsed;
567}
568
569function resolveUrl(relative, base) {
570 /* istanbul ignore next */
571 return useNativeURL ? new URL(relative, base) : parseUrl(url.resolve(base, relative));
572}
573
574function validateUrl(input) {
575 if (/^\[/.test(input.hostname) && !/^\[[:0-9a-f]+\]$/i.test(input.hostname)) {
576 throw new InvalidUrlError({ input: input.href || input });
577 }
578 if (/^\[/.test(input.host) && !/^\[[:0-9a-f]+\](:\d+)?$/i.test(input.host)) {
579 throw new InvalidUrlError({ input: input.href || input });
580 }
581 return input;
582}
583
584function spreadUrlObject(urlObject, target) {
585 var spread = target || {};
586 for (var key of preservedUrlFields) {
587 spread[key] = urlObject[key];
588 }
589
590 // Fix IPv6 hostname
591 if (spread.hostname.startsWith("[")) {
592 spread.hostname = spread.hostname.slice(1, -1);
593 }
594 // Ensure port is a number
595 if (spread.port !== "") {
596 spread.port = Number(spread.port);
597 }
598 // Concatenate path
599 spread.path = spread.search ? spread.pathname + spread.search : spread.pathname;
600
601 return spread;
602}
603
604function removeMatchingHeaders(regex, headers) {
605 var lastValue;
606 for (var header in headers) {
607 if (regex.test(header)) {
608 lastValue = headers[header];
609 delete headers[header];
610 }
611 }
612 return (lastValue === null || typeof lastValue === "undefined") ?
613 undefined : String(lastValue).trim();
614}
615
616function createErrorType(code, message, baseClass) {
617 // Create constructor
618 function CustomError(properties) {
619 Error.captureStackTrace(this, this.constructor);
620 Object.assign(this, properties || {});
621 this.code = code;
622 this.message = this.cause ? message + ": " + this.cause.message : message;
623 }
624
625 // Attach constructor and set default properties
626 CustomError.prototype = new (baseClass || Error)();
627 Object.defineProperties(CustomError.prototype, {
628 constructor: {
629 value: CustomError,
630 enumerable: false,
631 },
632 name: {
633 value: "Error [" + code + "]",
634 enumerable: false,
635 },
636 });
637 return CustomError;
638}
639
640function destroyRequest(request, error) {
641 for (var event of events) {
642 request.removeListener(event, eventHandlers[event]);
643 }
644 request.on("error", noop);
645 request.destroy(error);
646}
647
648function isSubdomain(subdomain, domain) {
649 assert(isString(subdomain) && isString(domain));
650 var dot = subdomain.length - domain.length - 1;
651 return dot > 0 && subdomain[dot] === "." && subdomain.endsWith(domain);
652}
653
654function isString(value) {
655 return typeof value === "string" || value instanceof String;
656}
657
658function isFunction(value) {
659 return typeof value === "function";
660}
661
662function isBuffer(value) {
663 return typeof value === "object" && ("length" in value);
664}
665
666function isURL(value) {
667 return URL && value instanceof URL;
668}
669
670// Exports
671module.exports = wrap({ http: http, https: https });
672module.exports.wrap = wrap;
Note: See TracBrowser for help on using the repository browser.