http.js 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609
  1. import utils from '../utils.js';
  2. import settle from '../core/settle.js';
  3. import buildFullPath from '../core/buildFullPath.js';
  4. import buildURL from '../helpers/buildURL.js';
  5. import { getProxyForUrl } from 'proxy-from-env';
  6. import HttpsProxyAgent from 'https-proxy-agent';
  7. import http from 'http';
  8. import https from 'https';
  9. import http2 from 'http2';
  10. import util from 'util';
  11. import { resolve as resolvePath } from 'path';
  12. import followRedirects from 'follow-redirects';
  13. import zlib from 'zlib';
  14. import { VERSION } from '../env/data.js';
  15. import transitionalDefaults from '../defaults/transitional.js';
  16. import AxiosError from '../core/AxiosError.js';
  17. import CanceledError from '../cancel/CanceledError.js';
  18. import platform from '../platform/index.js';
  19. import fromDataURI from '../helpers/fromDataURI.js';
  20. import stream from 'stream';
  21. import AxiosHeaders from '../core/AxiosHeaders.js';
  22. import setFormDataHeaders from '../core/setFormDataHeaders.js';
  23. import AxiosTransformStream from '../helpers/AxiosTransformStream.js';
  24. import { EventEmitter } from 'events';
  25. import formDataToStream from '../helpers/formDataToStream.js';
  26. import readBlob from '../helpers/readBlob.js';
  27. import ZlibHeaderTransformStream from '../helpers/ZlibHeaderTransformStream.js';
  28. import Http2Sessions from '../helpers/Http2Sessions.js';
  29. import callbackify from '../helpers/callbackify.js';
  30. import shouldBypassProxy from '../helpers/shouldBypassProxy.js';
  31. import bind from '../helpers/bind.js';
  32. import { toByteStringHeaderObject } from '../helpers/sanitizeHeaderValue.js';
  33. import {
  34. progressEventReducer,
  35. progressEventDecorator,
  36. asyncDecorator,
  37. } from '../helpers/progressEventReducer.js';
  38. import { estimateDataURLBufferAllocation } from '../helpers/estimateDataURLDecodedBytes.js';
  39. const zlibOptions = {
  40. flush: zlib.constants.Z_SYNC_FLUSH,
  41. finishFlush: zlib.constants.Z_SYNC_FLUSH,
  42. };
  43. const brotliOptions = {
  44. flush: zlib.constants.BROTLI_OPERATION_FLUSH,
  45. finishFlush: zlib.constants.BROTLI_OPERATION_FLUSH,
  46. };
  47. const zstdOptions = {
  48. flush: zlib.constants.ZSTD_e_flush,
  49. finishFlush: zlib.constants.ZSTD_e_flush,
  50. };
  51. const isBrotliSupported = utils.isFunction(zlib.createBrotliDecompress);
  52. const isZstdSupported = utils.isFunction(zlib.createZstdDecompress);
  53. const ACCEPT_ENCODING = 'gzip, compress, deflate' + (isBrotliSupported ? ', br' : '');
  54. const ACCEPT_ENCODING_WITH_ZSTD = ACCEPT_ENCODING + (isZstdSupported ? ', zstd' : '');
  55. const scheduleProgress =
  56. typeof process !== 'undefined' && process.nextTick ? process.nextTick.bind(process) : utils.asap;
  57. const { http: httpFollow, https: httpsFollow } = followRedirects;
  58. const isHttps = /https:?/;
  59. // Symbols used to bind a single 'error' listener to a pooled socket and track
  60. // the request currently owning that socket across keep-alive reuse (issue #10780).
  61. const kAxiosSocketListener = Symbol('axios.http.socketListener');
  62. const kAxiosCurrentReq = Symbol('axios.http.currentReq');
  63. // A shared listener avoids retaining an adapter context for the lifetime of a
  64. // pooled socket. EventEmitter invokes listeners with `this` set to the emitter.
  65. function handleSocketError(err) {
  66. const current = this[kAxiosCurrentReq];
  67. if (current && !current.destroyed) {
  68. current.destroy(err);
  69. }
  70. }
  71. // Tags HttpsProxyAgent instances installed by setProxy() so the redirect path
  72. // can strip them without clobbering a user-supplied agent that happens to be
  73. // an HttpsProxyAgent.
  74. const kAxiosInstalledTunnel = Symbol('axios.http.installedTunnel');
  75. // Cache of CONNECT-tunneling agents keyed by proxy config so repeat requests
  76. // through the same proxy reuse a single agent (and its socket pool). The
  77. // keyspace is bounded by the set of distinct proxy configs the process uses,
  78. // so unbounded growth is not a concern in practice.
  79. const tunnelingAgentCache = new Map();
  80. const tunnelingAgentCacheUser = new WeakMap();
  81. const directAgents = new WeakMap();
  82. const directAgentHooks = ['createConnection', 'getName'];
  83. const nativeAgentPoolHooks = [
  84. 'addRequest',
  85. 'createSocket',
  86. 'removeSocket',
  87. 'keepSocketAlive',
  88. 'reuseSocket',
  89. '_getSession',
  90. '_cacheSession',
  91. '_evictSession',
  92. ];
  93. // Minimum minor versions where Node's HTTP Agent supports native proxyEnv
  94. // handling. Checking the selected agent below also covers startup modes such
  95. // as NODE_OPTIONS=--use-env-proxy and --no-use-env-proxy precedence.
  96. const NODE_NATIVE_ENV_PROXY_SUPPORT = {
  97. 22: 21,
  98. 24: 5,
  99. };
  100. function isNodeNativeEnvProxySupported(nodeVersion = process.versions && process.versions.node) {
  101. if (!nodeVersion) {
  102. return false;
  103. }
  104. const [major, minor] = nodeVersion.split('.').map((part) => Number(part));
  105. if (!Number.isInteger(major) || !Number.isInteger(minor)) {
  106. return false;
  107. }
  108. if (major > 24) {
  109. return true;
  110. }
  111. return (
  112. NODE_NATIVE_ENV_PROXY_SUPPORT[major] != null && minor >= NODE_NATIVE_ENV_PROXY_SUPPORT[major]
  113. );
  114. }
  115. function isNodeEnvProxyEnabled(agent, nodeVersion = process.versions && process.versions.node) {
  116. if (!isNodeNativeEnvProxySupported(nodeVersion)) {
  117. return false;
  118. }
  119. const agentOptions = agent && agent.options;
  120. return Boolean(
  121. agentOptions && utils.hasOwnProp(agentOptions, 'proxyEnv') && agentOptions.proxyEnv != null
  122. );
  123. }
  124. function getProxyEnvAgent(options, configHttpAgent, configHttpsAgent) {
  125. return isHttps.test(options.protocol)
  126. ? configHttpsAgent || https.globalAgent
  127. : configHttpAgent || http.globalAgent;
  128. }
  129. function getDirectAgent(configuredAgent, transport) {
  130. if (
  131. !process.allowedNodeEnvironmentFlags ||
  132. !process.allowedNodeEnvironmentFlags.has('--use-env-proxy')
  133. ) {
  134. return configuredAgent;
  135. }
  136. const agent = configuredAgent || transport.globalAgent;
  137. const options = agent && agent.options;
  138. if (
  139. !(agent instanceof transport.Agent) ||
  140. agent.protocol !== transport.globalAgent.protocol ||
  141. !options ||
  142. !utils.hasOwnProp(options, 'proxyEnv') ||
  143. typeof options.proxyEnv !== 'object' ||
  144. options.proxyEnv === null
  145. ) {
  146. return configuredAgent;
  147. }
  148. // These hooks own pool queues or TLS session state. Neither binding them to
  149. // the source agent nor copying them without subclass state preserves their
  150. // behavior on a separate direct pool.
  151. for (const hook of nativeAgentPoolHooks) {
  152. if (
  153. utils.isFunction(transport.Agent.prototype[hook]) &&
  154. agent[hook] !== transport.Agent.prototype[hook]
  155. ) {
  156. throw new AxiosError(
  157. 'proxy: false cannot adapt an agent overriding ' +
  158. hook +
  159. '; use an agent constructed without proxyEnv',
  160. AxiosError.ERR_BAD_OPTION_VALUE
  161. );
  162. }
  163. }
  164. // Node snapshots proxyEnv when constructing the agent. Keep this check
  165. // conservative even when the caller later removes protocol-specific entries.
  166. let direct = directAgents.get(agent);
  167. if (!direct) {
  168. direct = new transport.Agent({ ...options, proxyEnv: undefined });
  169. // Agent.destroy() does not emit an event. Keep the associated pool under
  170. // the configured agent's lifetime, including agents reused after destroy().
  171. const destroy = agent.destroy;
  172. agent.destroy = function destroyWithDirectAgent() {
  173. try {
  174. return destroy.apply(this, arguments);
  175. } finally {
  176. direct.destroy();
  177. }
  178. };
  179. directAgents.set(agent, direct);
  180. }
  181. // Connections and pool keys do not own the direct pool's queues. Preserve
  182. // their configured receiver and refresh hooks that change between requests.
  183. for (const hook of directAgentHooks) {
  184. direct[hook] =
  185. agent[hook] === transport.Agent.prototype[hook]
  186. ? transport.Agent.prototype[hook]
  187. : bind(agent[hook], agent);
  188. }
  189. return direct;
  190. }
  191. function setDirectAgent(options, configHttpAgent, configHttpsAgent) {
  192. const secure = isHttps.test(options.protocol);
  193. const agent = getDirectAgent(secure ? configHttpsAgent : configHttpAgent, secure ? https : http);
  194. options.agent = agent;
  195. if (options.agents) {
  196. options.agents[secure ? 'https' : 'http'] = agent;
  197. }
  198. }
  199. function getTunnelingAgent(agentOptions, userHttpsAgent) {
  200. const key =
  201. agentOptions.protocol +
  202. '//' +
  203. agentOptions.hostname +
  204. ':' +
  205. (agentOptions.port || '') +
  206. '#' +
  207. (agentOptions.auth || '');
  208. const cache = userHttpsAgent
  209. ? tunnelingAgentCacheUser.get(userHttpsAgent) ||
  210. tunnelingAgentCacheUser.set(userHttpsAgent, new Map()).get(userHttpsAgent)
  211. : tunnelingAgentCache;
  212. let agent = cache.get(key);
  213. if (agent) return agent;
  214. // Preserve per-request TLS options for the proxy connection, with our proxy
  215. // fields taking precedence. Global-agent options belong only to the origin
  216. // TLS upgrade in the callback below.
  217. const merged =
  218. userHttpsAgent && userHttpsAgent.options
  219. ? { ...userHttpsAgent.options, ...agentOptions }
  220. : agentOptions;
  221. agent = new HttpsProxyAgent(merged);
  222. const callback = agent.callback;
  223. agent.callback = function axiosTunnelingAgentCallback(req, opts) {
  224. // Without a proxy the origin TLS connection would be made by https.globalAgent,
  225. // so its options have to reach the tunneled origin too. Resolved per request
  226. // because the tunneling agent outlives any one of them.
  227. const originTLSAgent = userHttpsAgent || https.globalAgent;
  228. const originTLSOptions = originTLSAgent && originTLSAgent.options;
  229. // HttpsProxyAgent v5 reads callback opts for the post-CONNECT origin TLS upgrade.
  230. return callback.call(this, req, { ...originTLSOptions, ...opts });
  231. };
  232. agent[kAxiosInstalledTunnel] = true;
  233. cache.set(key, agent);
  234. return agent;
  235. }
  236. const supportedProtocols = platform.protocols.map((protocol) => {
  237. return protocol + ':';
  238. });
  239. // Node's WHATWG URL parser returns `username` and `password` percent-encoded.
  240. // Decode before composing the `auth` option so credentials such as
  241. // `my%40email.com:pass` are sent as `my@email.com:pass`. Falls back to the
  242. // original value for malformed input so a bad encoding never throws.
  243. const decodeURIComponentSafe = (value) => {
  244. if (!utils.isString(value)) {
  245. return value;
  246. }
  247. try {
  248. return decodeURIComponent(value);
  249. } catch (error) {
  250. return value;
  251. }
  252. };
  253. const flushOnFinish = (stream, [throttled, flush]) => {
  254. stream.on('end', flush).on('error', flush);
  255. return throttled;
  256. };
  257. const http2Sessions = new Http2Sessions();
  258. /**
  259. * If the proxy, auth, sensitive header, or config beforeRedirects functions are defined,
  260. * call them with the options object.
  261. *
  262. * @param {Object<string, any>} options - The options object that was passed to the request.
  263. *
  264. * @returns {Object<string, any>}
  265. */
  266. function dispatchBeforeRedirect(options, responseDetails, requestDetails) {
  267. if (!isSameOriginRedirect(options, requestDetails)) {
  268. stripMatchingHeaders(options.headers, new Set(['authorization', 'cookie']));
  269. delete options.auth;
  270. }
  271. if (options.beforeRedirects.proxy) {
  272. options.beforeRedirects.proxy(options);
  273. }
  274. if (options.beforeRedirects.auth) {
  275. options.beforeRedirects.auth(options);
  276. }
  277. if (options.beforeRedirects.sensitiveHeaders) {
  278. options.beforeRedirects.sensitiveHeaders(options, requestDetails);
  279. }
  280. if (options.beforeRedirects.direct) {
  281. options.beforeRedirects.direct(options);
  282. }
  283. if (options.beforeRedirects.config) {
  284. options.beforeRedirects.config(options, responseDetails, requestDetails);
  285. }
  286. }
  287. function stripMatchingHeaders(headers, sensitiveSet) {
  288. if (!headers) {
  289. return;
  290. }
  291. Object.keys(headers).forEach((header) => {
  292. if (sensitiveSet.has(header.toLowerCase())) {
  293. delete headers[header];
  294. }
  295. });
  296. }
  297. function isSameOriginRedirect(redirectOptions, requestDetails) {
  298. if (!requestDetails) {
  299. return false;
  300. }
  301. try {
  302. return new URL(requestDetails.url).origin === new URL(redirectOptions.href).origin;
  303. } catch (e) {
  304. // If origin comparison fails, treat the redirect as unsafe.
  305. return false;
  306. }
  307. }
  308. /**
  309. * If the proxy or config afterRedirects functions are defined, call them with the options
  310. *
  311. * @param {http.ClientRequestArgs} options
  312. * @param {AxiosProxyConfig} configProxy configuration from Axios options object
  313. * @param {string} location
  314. * @param {boolean} [allowEnvProxy=true] whether environment proxy configuration can be used
  315. *
  316. * @returns {boolean} whether a proxy applies to the selected transport
  317. */
  318. function setProxy(
  319. options,
  320. configProxy,
  321. location,
  322. isRedirect,
  323. configHttpsAgent,
  324. configHttpAgent,
  325. allowEnvProxy = true
  326. ) {
  327. let proxy = configProxy;
  328. const proxyEnvAgent = getProxyEnvAgent(options, configHttpAgent, configHttpsAgent);
  329. if (!proxy && proxy !== false && allowEnvProxy && !isNodeEnvProxyEnabled(proxyEnvAgent)) {
  330. const proxyUrl = getProxyForUrl(location);
  331. if (proxyUrl) {
  332. if (!shouldBypassProxy(location)) {
  333. proxy = new URL(proxyUrl);
  334. }
  335. }
  336. }
  337. // On redirect re-invocation, strip any stale Proxy-Authorization header carried
  338. // over from the prior request (e.g. new target no longer uses a proxy, or uses
  339. // a different proxy). Skip on the initial request so user-supplied headers are
  340. // preserved. Header names are case-insensitive, so remove every case variant.
  341. if (isRedirect && options.headers) {
  342. for (const name of Object.keys(options.headers)) {
  343. if (name.toLowerCase() === 'proxy-authorization') {
  344. delete options.headers[name];
  345. }
  346. }
  347. }
  348. // Strip any tunneling agent we installed for the previous hop so a redirect
  349. // that drops the proxy or crosses an HTTPS↔HTTP boundary doesn't reuse a
  350. // stale one. Match on our Symbol marker so a user-supplied HttpsProxyAgent
  351. // (which won't carry the marker) is left alone.
  352. if (isRedirect && options.agent && options.agent[kAxiosInstalledTunnel]) {
  353. options.agent = undefined;
  354. }
  355. if (
  356. isRedirect &&
  357. options.agents &&
  358. options.agents.https &&
  359. options.agents.https[kAxiosInstalledTunnel]
  360. ) {
  361. options.agents.https = configHttpsAgent;
  362. }
  363. if (proxy) {
  364. // Read proxy fields without traversing the prototype chain. URL instances expose
  365. // username/password/hostname/host/port/protocol via getters on URL.prototype (so
  366. // direct reads are shielded), but plain object proxies — and the `auth` field
  367. // (which URL does not expose) — must be guarded so a polluted Object.prototype
  368. // (e.g. Object.prototype.auth = { username, password }) cannot inject
  369. // attacker-controlled credentials into the Proxy-Authorization header or
  370. // redirect proxying to an attacker-controlled host.
  371. const isProxyURL = proxy instanceof URL;
  372. const readProxyField = (key) =>
  373. isProxyURL || utils.hasOwnProp(proxy, key) ? proxy[key] : undefined;
  374. const proxyUsername = readProxyField('username');
  375. const proxyPassword = readProxyField('password');
  376. let proxyAuth = utils.hasOwnProp(proxy, 'auth') ? proxy.auth : undefined;
  377. // Basic proxy authorization
  378. if (proxyUsername) {
  379. proxyAuth = (proxyUsername || '') + ':' + (proxyPassword || '');
  380. }
  381. if (proxyAuth) {
  382. // Support proxy auth object form. Read sub-fields via own-prop checks so a
  383. // plain object inheriting from polluted Object.prototype cannot leak creds.
  384. const authIsObject = typeof proxyAuth === 'object';
  385. const authUsername =
  386. authIsObject && utils.hasOwnProp(proxyAuth, 'username') ? proxyAuth.username : undefined;
  387. const authPassword =
  388. authIsObject && utils.hasOwnProp(proxyAuth, 'password') ? proxyAuth.password : undefined;
  389. const validProxyAuth = Boolean(authUsername || authPassword);
  390. if (validProxyAuth) {
  391. proxyAuth = (authUsername || '') + ':' + (authPassword || '');
  392. } else if (authIsObject) {
  393. throw new AxiosError('Invalid proxy authorization', AxiosError.ERR_BAD_OPTION, { proxy });
  394. }
  395. }
  396. const targetIsHttps = isHttps.test(options.protocol);
  397. if (targetIsHttps) {
  398. // CONNECT-tunneling path for HTTPS targets. Preserves end-to-end TLS to
  399. // the origin so the proxy cannot inspect the URL, headers, or body — the
  400. // behavior already promised by THREATMODEL.md (T-R9). HttpsProxyAgent
  401. // sends Proxy-Authorization on the CONNECT request only, never on the
  402. // wrapped TLS request, which is why we don't stamp it onto
  403. // options.headers here. If the user already supplied an HttpsProxyAgent,
  404. // they own tunneling end-to-end and we leave them alone; otherwise we
  405. // install our own tunneling agent and forward their TLS options (if any)
  406. // so a custom httpsAgent for cert pinning / rejectUnauthorized still
  407. // applies to the origin TLS upgrade.
  408. if (!(configHttpsAgent instanceof HttpsProxyAgent)) {
  409. const proxyHost = readProxyField('hostname') || readProxyField('host');
  410. const proxyPort = readProxyField('port');
  411. const rawProxyProtocol = readProxyField('protocol');
  412. const normalizedProtocol = rawProxyProtocol
  413. ? rawProxyProtocol.includes(':')
  414. ? rawProxyProtocol
  415. : `${rawProxyProtocol}:`
  416. : 'http:';
  417. // Bracket IPv6 literals for URL parsing; URL.hostname strips the
  418. // brackets again on read so the agent receives the raw form.
  419. const proxyHostForURL =
  420. proxyHost && proxyHost.includes(':') && !proxyHost.startsWith('[')
  421. ? `[${proxyHost}]`
  422. : proxyHost;
  423. const proxyURL = new URL(
  424. `${normalizedProtocol}//${proxyHostForURL}${proxyPort ? ':' + proxyPort : ''}`
  425. );
  426. const agentOptions = {
  427. protocol: proxyURL.protocol,
  428. hostname: proxyURL.hostname.replace(/^\[|\]$/g, ''),
  429. port: proxyURL.port,
  430. auth: proxyAuth && typeof proxyAuth === 'string' ? proxyAuth : undefined,
  431. };
  432. if (proxyURL.protocol === 'https:') {
  433. agentOptions.ALPNProtocols = ['http/1.1'];
  434. }
  435. const tunnelingAgent = getTunnelingAgent(agentOptions, configHttpsAgent);
  436. // Set both: `options.agent` is consumed by the native https.request path
  437. // (maxRedirects === 0); `options.agents.https` is consumed by
  438. // follow-redirects, which ignores `options.agent` when `options.agents`
  439. // is present.
  440. options.agent = tunnelingAgent;
  441. if (options.agents) {
  442. options.agents.https = tunnelingAgent;
  443. }
  444. }
  445. } else {
  446. // Forward-proxy mode for plaintext HTTP targets. The request line carries
  447. // the absolute URL and the proxy sees everything — acceptable for plain
  448. // HTTP since the wire was already plaintext.
  449. if (proxyAuth) {
  450. const base64 = Buffer.from(proxyAuth, 'utf8').toString('base64');
  451. options.headers['Proxy-Authorization'] = 'Basic ' + base64;
  452. }
  453. // Preserve a user-supplied Host header (case-insensitive) so callers can override
  454. // the value forwarded to the proxy; otherwise default to the request URL's host.
  455. let hasUserHostHeader = false;
  456. for (const name of Object.keys(options.headers)) {
  457. if (name.toLowerCase() === 'host') {
  458. hasUserHostHeader = true;
  459. break;
  460. }
  461. }
  462. if (!hasUserHostHeader) {
  463. options.headers.host = options.hostname + (options.port ? ':' + options.port : '');
  464. }
  465. const proxyHost = readProxyField('hostname') || readProxyField('host');
  466. options.hostname = proxyHost;
  467. // Replace 'host' since options is not a URL object
  468. options.host = proxyHost;
  469. options.port = readProxyField('port');
  470. options.path = location;
  471. const proxyProtocol = readProxyField('protocol');
  472. if (proxyProtocol) {
  473. options.protocol = proxyProtocol.includes(':') ? proxyProtocol : `${proxyProtocol}:`;
  474. }
  475. }
  476. }
  477. options.beforeRedirects.proxy = function beforeRedirect(redirectOptions) {
  478. // Configure proxy for redirected request, passing the original config proxy to apply
  479. // the exact same logic as if the redirected request was performed by axios directly.
  480. setProxy(
  481. redirectOptions,
  482. configProxy,
  483. redirectOptions.href,
  484. true,
  485. configHttpsAgent,
  486. configHttpAgent,
  487. allowEnvProxy
  488. );
  489. };
  490. return Boolean(
  491. proxy || (configProxy !== false && allowEnvProxy && isNodeEnvProxyEnabled(proxyEnvAgent))
  492. );
  493. }
  494. const isHttpAdapterSupported =
  495. typeof process !== 'undefined' && utils.kindOf(process) === 'process';
  496. // temporary hotfix
  497. const wrapAsync = (asyncExecutor) => {
  498. return new Promise((resolve, reject) => {
  499. let onDone;
  500. let isDone;
  501. const done = (value, isRejected) => {
  502. if (isDone) return;
  503. isDone = true;
  504. onDone && onDone(value, isRejected);
  505. };
  506. const _resolve = (value) => {
  507. done(value);
  508. resolve(value);
  509. };
  510. const _reject = (reason) => {
  511. done(reason, true);
  512. reject(reason);
  513. };
  514. asyncExecutor(_resolve, _reject, (onDoneHandler) => (onDone = onDoneHandler)).catch(_reject);
  515. });
  516. };
  517. const resolveFamily = ({ address, family }) => {
  518. if (!utils.isString(address)) {
  519. throw new AxiosError('address must be a string', AxiosError.ERR_BAD_OPTION_VALUE);
  520. }
  521. return {
  522. address,
  523. family: family || (address.indexOf('.') < 0 ? 6 : 4),
  524. };
  525. };
  526. const buildAddressEntry = (address, family) =>
  527. resolveFamily(utils.isObject(address) ? address : { address, family });
  528. const normalizedLookupCache = new WeakMap();
  529. const normalizeLookup = (lookup) => {
  530. let normalized = normalizedLookupCache.get(lookup);
  531. if (normalized) {
  532. return normalized;
  533. }
  534. const callbackLookup = callbackify(lookup, (value) => (utils.isArray(value) ? value : [value]));
  535. // Support opt.all, which is required by current Node.js releases.
  536. normalized = (hostname, opt, cb) => {
  537. callbackLookup(hostname, opt, (err, arg0, arg1) => {
  538. if (err) {
  539. return cb(err);
  540. }
  541. let addresses;
  542. try {
  543. addresses = utils.isArray(arg0)
  544. ? arg0.map((addr) => buildAddressEntry(addr))
  545. : [buildAddressEntry(arg0, arg1)];
  546. } catch (error) {
  547. return cb(error);
  548. }
  549. opt.all ? cb(err, addresses) : cb(err, addresses[0].address, addresses[0].family);
  550. });
  551. };
  552. normalizedLookupCache.set(lookup, normalized);
  553. return normalized;
  554. };
  555. const http2Transport = {
  556. request(options, cb) {
  557. const authority =
  558. options.protocol +
  559. '//' +
  560. options.hostname +
  561. ':' +
  562. (options.port || (options.protocol === 'https:' ? 443 : 80));
  563. const { http2Options, headers } = options;
  564. const session = http2Sessions.getSession(authority, http2Options);
  565. const { HTTP2_HEADER_SCHEME, HTTP2_HEADER_METHOD, HTTP2_HEADER_PATH, HTTP2_HEADER_STATUS } =
  566. http2.constants;
  567. const http2Headers = {
  568. [HTTP2_HEADER_SCHEME]: options.protocol.replace(':', ''),
  569. [HTTP2_HEADER_METHOD]: options.method,
  570. [HTTP2_HEADER_PATH]: options.path,
  571. };
  572. utils.forEach(headers, (header, name) => {
  573. name.charAt(0) !== ':' && (http2Headers[name] = header);
  574. });
  575. const req = session.request(http2Headers);
  576. req.once('response', (responseHeaders) => {
  577. const response = req; //duplex
  578. responseHeaders = Object.assign({}, responseHeaders);
  579. const status = responseHeaders[HTTP2_HEADER_STATUS];
  580. delete responseHeaders[HTTP2_HEADER_STATUS];
  581. response.headers = responseHeaders;
  582. response.statusCode = +status;
  583. cb(response);
  584. });
  585. return req;
  586. },
  587. };
  588. /*eslint consistent-return:0*/
  589. export default isHttpAdapterSupported &&
  590. function httpAdapter(config) {
  591. return wrapAsync(async function dispatchHttpRequest(resolve, reject, onDone) {
  592. // Read config pollution-safely: own properties and members inherited from
  593. // a non-Object.prototype source (e.g. an Object.create(defaults) template)
  594. // are honored, but values injected onto a polluted Object.prototype are
  595. // ignored. All behavior-affecting reads in this adapter go through own()
  596. // so the protection boundary stays consistent.
  597. const own = (key) => utils.getSafeProp(config, key);
  598. const transitional = own('transitional') || transitionalDefaults;
  599. let data = own('data');
  600. let lookup = own('lookup');
  601. let family = own('family');
  602. let httpVersion = own('httpVersion');
  603. if (httpVersion === undefined) httpVersion = 1;
  604. const rawHttpVersion = httpVersion;
  605. let http2Options = own('http2Options');
  606. const configProxy = own('proxy');
  607. const httpAgent = own('httpAgent');
  608. const httpsAgent = own('httpsAgent');
  609. const responseType = own('responseType');
  610. const responseEncoding = own('responseEncoding');
  611. const socketPath = own('socketPath');
  612. const method = own('method').toUpperCase();
  613. const maxRedirects = own('maxRedirects');
  614. const maxBodyLength = own('maxBodyLength');
  615. const maxContentLength = own('maxContentLength');
  616. const decompress = own('decompress');
  617. let isDone;
  618. let rejected = false;
  619. let req;
  620. let connectPhaseTimer;
  621. try {
  622. httpVersion = +httpVersion;
  623. } catch (err) {
  624. throw new AxiosError(
  625. 'Invalid protocol version: value is not a number',
  626. AxiosError.ERR_BAD_OPTION_VALUE,
  627. config
  628. );
  629. }
  630. if (Number.isNaN(httpVersion)) {
  631. throw new AxiosError(
  632. `Invalid protocol version: '${rawHttpVersion}' is not a number`,
  633. AxiosError.ERR_BAD_OPTION_VALUE,
  634. config
  635. );
  636. }
  637. if (httpVersion !== 1 && httpVersion !== 2) {
  638. throw new AxiosError(
  639. `Unsupported protocol version '${httpVersion}'`,
  640. AxiosError.ERR_BAD_OPTION_VALUE,
  641. config
  642. );
  643. }
  644. const isHttp2 = httpVersion === 2;
  645. if (lookup) {
  646. lookup = normalizeLookup(lookup);
  647. }
  648. const abortEmitter = new EventEmitter();
  649. function abort(reason) {
  650. try {
  651. abortEmitter.emit(
  652. 'abort',
  653. !reason || reason.type ? new CanceledError(null, config, req) : reason
  654. );
  655. } catch (err) {
  656. // ignore emit errors
  657. }
  658. }
  659. function clearConnectPhaseTimer() {
  660. if (connectPhaseTimer) {
  661. clearTimeout(connectPhaseTimer);
  662. connectPhaseTimer = null;
  663. }
  664. }
  665. function createTimeoutError() {
  666. const configTimeout = own('timeout');
  667. let timeoutErrorMessage = configTimeout
  668. ? 'timeout of ' + configTimeout + 'ms exceeded'
  669. : 'timeout exceeded';
  670. const configTimeoutErrorMessage = own('timeoutErrorMessage');
  671. if (configTimeoutErrorMessage) {
  672. timeoutErrorMessage = configTimeoutErrorMessage;
  673. }
  674. return new AxiosError(
  675. timeoutErrorMessage,
  676. transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED,
  677. config,
  678. req
  679. );
  680. }
  681. abortEmitter.once('abort', reject);
  682. const onFinished = () => {
  683. clearConnectPhaseTimer();
  684. if (config.cancelToken) {
  685. config.cancelToken.unsubscribe(abort);
  686. }
  687. if (config.signal) {
  688. config.signal.removeEventListener('abort', abort);
  689. }
  690. abortEmitter.removeAllListeners();
  691. };
  692. if (config.cancelToken || config.signal) {
  693. config.cancelToken && config.cancelToken.subscribe(abort);
  694. if (config.signal) {
  695. config.signal.aborted ? abort() : config.signal.addEventListener('abort', abort);
  696. }
  697. }
  698. onDone((response, isRejected) => {
  699. isDone = true;
  700. clearConnectPhaseTimer();
  701. if (isRejected) {
  702. rejected = true;
  703. onFinished();
  704. return;
  705. }
  706. const { data } = response;
  707. if (data instanceof stream.Readable || data instanceof stream.Duplex) {
  708. const offListeners = stream.finished(data, () => {
  709. offListeners();
  710. onFinished();
  711. });
  712. } else {
  713. onFinished();
  714. }
  715. });
  716. // Parse url
  717. const fullPath = buildFullPath(own('baseURL'), own('url'), own('allowAbsoluteUrls'), config);
  718. // Unix-socket requests (own socketPath) commonly pass a path-only url
  719. // like '/foo'; supply a synthetic base so new URL() can still parse it.
  720. // Use the own-property value (not config.socketPath) so a polluted
  721. // prototype cannot influence URL base selection.
  722. const urlBase = socketPath
  723. ? 'http://localhost'
  724. : platform.hasBrowserEnv
  725. ? platform.origin
  726. : undefined;
  727. const parsed = new URL(fullPath, urlBase);
  728. const protocol = parsed.protocol || supportedProtocols[0];
  729. if (protocol === 'data:') {
  730. // Apply the same semantics as HTTP: only enforce if a finite, non-negative cap is set.
  731. if (maxContentLength > -1) {
  732. // Use the exact string passed to fromDataURI (the configured url); fall back to fullPath if needed.
  733. const dataUrl = String(own('url') || fullPath || '');
  734. const estimated = estimateDataURLBufferAllocation(dataUrl);
  735. if (estimated > maxContentLength) {
  736. return reject(
  737. new AxiosError(
  738. 'maxContentLength size of ' + maxContentLength + ' exceeded',
  739. AxiosError.ERR_BAD_RESPONSE,
  740. config
  741. )
  742. );
  743. }
  744. }
  745. let convertedData;
  746. if (method !== 'GET') {
  747. return settle(resolve, reject, {
  748. status: 405,
  749. statusText: 'method not allowed',
  750. headers: {},
  751. config,
  752. });
  753. }
  754. try {
  755. convertedData = fromDataURI(own('url'), responseType === 'blob', {
  756. Blob: config.env && config.env.Blob,
  757. });
  758. } catch (err) {
  759. throw AxiosError.from(err, AxiosError.ERR_BAD_REQUEST, config);
  760. }
  761. // Check bytes before converting the result to text or a stream.
  762. if (
  763. maxContentLength > -1 &&
  764. (responseType === 'blob' ? convertedData.size : convertedData.length) > maxContentLength
  765. ) {
  766. return reject(
  767. new AxiosError(
  768. 'maxContentLength size of ' + maxContentLength + ' exceeded',
  769. AxiosError.ERR_BAD_RESPONSE,
  770. config
  771. )
  772. );
  773. }
  774. if (responseType === 'text') {
  775. convertedData = convertedData.toString(responseEncoding);
  776. if (!responseEncoding || responseEncoding === 'utf8') {
  777. convertedData = utils.stripBOM(convertedData);
  778. }
  779. } else if (responseType === 'stream') {
  780. convertedData = stream.Readable.from(convertedData);
  781. }
  782. return settle(resolve, reject, {
  783. data: convertedData,
  784. status: 200,
  785. statusText: 'OK',
  786. headers: new AxiosHeaders(),
  787. config,
  788. });
  789. }
  790. if (supportedProtocols.indexOf(protocol) === -1) {
  791. return reject(
  792. new AxiosError('Unsupported protocol ' + protocol, AxiosError.ERR_BAD_REQUEST, config)
  793. );
  794. }
  795. const headers = AxiosHeaders.from(config.headers).normalize();
  796. // Set User-Agent (required by some servers)
  797. // See https://github.com/axios/axios/issues/69
  798. // User-Agent is specified; handle case where no UA header is desired
  799. // Only set header if it hasn't been set in config
  800. headers.set('User-Agent', 'axios/' + VERSION, false);
  801. const { onUploadProgress, onDownloadProgress } = config;
  802. const maxRate = config.maxRate;
  803. let maxUploadRate = undefined;
  804. let maxDownloadRate = undefined;
  805. // support for spec compliant FormData objects
  806. if (utils.isSpecCompliantForm(data)) {
  807. const userBoundary = headers.getContentType(/boundary=([-_\w\d]{10,70})/i);
  808. data = formDataToStream(
  809. data,
  810. (formHeaders) => {
  811. headers.set(formHeaders);
  812. },
  813. {
  814. tag: `axios-${VERSION}-boundary`,
  815. boundary: (userBoundary && userBoundary[1]) || undefined,
  816. }
  817. );
  818. // support for https://www.npmjs.com/package/form-data api
  819. } else if (
  820. utils.isFormData(data) &&
  821. utils.isFunction(data.getHeaders) &&
  822. data.getHeaders !== Object.prototype.getHeaders
  823. ) {
  824. setFormDataHeaders(headers, data.getHeaders(), own('formDataHeaderPolicy'));
  825. if (!headers.hasContentLength()) {
  826. try {
  827. const knownLength = await util.promisify(data.getLength).call(data);
  828. Number.isFinite(knownLength) &&
  829. knownLength >= 0 &&
  830. headers.setContentLength(knownLength);
  831. /*eslint no-empty:0*/
  832. } catch (e) {}
  833. }
  834. } else if (utils.isBlob(data) || utils.isFile(data)) {
  835. data.size && headers.setContentType(data.type || 'application/octet-stream');
  836. headers.setContentLength(data.size || 0);
  837. data = stream.Readable.from(readBlob(data));
  838. } else if (data && !utils.isStream(data)) {
  839. if (Buffer.isBuffer(data)) {
  840. // Nothing to do...
  841. } else if (utils.isArrayBuffer(data)) {
  842. data = Buffer.from(new Uint8Array(data));
  843. } else if (utils.isString(data)) {
  844. data = Buffer.from(data, 'utf-8');
  845. } else {
  846. return reject(
  847. new AxiosError(
  848. 'Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream',
  849. AxiosError.ERR_BAD_REQUEST,
  850. config
  851. )
  852. );
  853. }
  854. // Add Content-Length header if data exists
  855. headers.setContentLength(data.length, false);
  856. if (maxBodyLength > -1 && data.length > maxBodyLength) {
  857. return reject(
  858. new AxiosError(
  859. 'Request body larger than maxBodyLength limit',
  860. AxiosError.ERR_BAD_REQUEST,
  861. config
  862. )
  863. );
  864. }
  865. }
  866. const contentLength = utils.toFiniteNumber(headers.getContentLength());
  867. if (utils.isArray(maxRate)) {
  868. maxUploadRate = maxRate[0];
  869. maxDownloadRate = maxRate[1];
  870. } else {
  871. maxUploadRate = maxDownloadRate = maxRate;
  872. }
  873. if (data && (onUploadProgress || maxUploadRate)) {
  874. if (!utils.isStream(data)) {
  875. data = stream.Readable.from(data, { objectMode: false });
  876. }
  877. data = stream.pipeline(
  878. [
  879. data,
  880. new AxiosTransformStream({
  881. maxRate: utils.toFiniteNumber(maxUploadRate),
  882. }),
  883. ],
  884. utils.noop
  885. );
  886. onUploadProgress &&
  887. data.on(
  888. 'progress',
  889. flushOnFinish(
  890. data,
  891. progressEventDecorator(
  892. contentLength,
  893. progressEventReducer(asyncDecorator(onUploadProgress, scheduleProgress), false, 3)
  894. )
  895. )
  896. );
  897. }
  898. // HTTP basic authentication
  899. let auth = undefined;
  900. const configAuth = own('auth');
  901. if (configAuth) {
  902. const username = utils.getSafeProp(configAuth, 'username') || '';
  903. const password = utils.getSafeProp(configAuth, 'password') || '';
  904. auth = username + ':' + password;
  905. }
  906. if (!auth && (parsed.username || parsed.password)) {
  907. const urlUsername = decodeURIComponentSafe(parsed.username);
  908. const urlPassword = decodeURIComponentSafe(parsed.password);
  909. auth = urlUsername + ':' + urlPassword;
  910. }
  911. auth && headers.delete('authorization');
  912. let path;
  913. try {
  914. path = buildURL(
  915. parsed.pathname + parsed.search,
  916. own('params'),
  917. own('paramsSerializer')
  918. ).replace(/^\?/, '');
  919. } catch (err) {
  920. return reject(
  921. AxiosError.from(err, AxiosError.ERR_BAD_REQUEST, config, null, null, {
  922. url: own('url'),
  923. exists: true,
  924. })
  925. );
  926. }
  927. headers.set(
  928. 'Accept-Encoding',
  929. utils.hasOwnProp(transitional, 'advertiseZstdAcceptEncoding') &&
  930. transitional.advertiseZstdAcceptEncoding === true
  931. ? ACCEPT_ENCODING_WITH_ZSTD
  932. : ACCEPT_ENCODING,
  933. false
  934. );
  935. if (isHttp2 && lookup) {
  936. http2Options = Object.assign(Object.create(null), http2Options, { lookup });
  937. }
  938. // Null-prototype to block prototype pollution gadgets on properties read
  939. // directly by Node's http.request (e.g. insecureHTTPParser, lookup).
  940. const options = Object.assign(Object.create(null), {
  941. path,
  942. method: method,
  943. headers: toByteStringHeaderObject(headers),
  944. agents: { http: httpAgent, https: httpsAgent },
  945. auth,
  946. protocol,
  947. family,
  948. beforeRedirect: dispatchBeforeRedirect,
  949. beforeRedirects: Object.create(null),
  950. http2Options,
  951. createConnection: undefined,
  952. });
  953. // cacheable-lookup integration hotfix
  954. !utils.isUndefined(lookup) && (options.lookup = lookup);
  955. let proxyApplied = false;
  956. if (socketPath) {
  957. if (typeof socketPath !== 'string') {
  958. return reject(
  959. new AxiosError('socketPath must be a string', AxiosError.ERR_BAD_OPTION_VALUE, config)
  960. );
  961. }
  962. const allowedSocketPaths = own('allowedSocketPaths');
  963. if (allowedSocketPaths != null) {
  964. const allowed = Array.isArray(allowedSocketPaths)
  965. ? allowedSocketPaths
  966. : [allowedSocketPaths];
  967. const resolvedSocket = resolvePath(socketPath);
  968. const isAllowed = allowed.some(
  969. (entry) => typeof entry === 'string' && resolvePath(entry) === resolvedSocket
  970. );
  971. if (!isAllowed) {
  972. return reject(
  973. new AxiosError(
  974. `socketPath "${socketPath}" is not permitted by allowedSocketPaths`,
  975. AxiosError.ERR_BAD_OPTION_VALUE,
  976. config
  977. )
  978. );
  979. }
  980. }
  981. options.socketPath = socketPath;
  982. } else {
  983. options.hostname = parsed.hostname.startsWith('[')
  984. ? parsed.hostname.slice(1, -1)
  985. : parsed.hostname;
  986. options.port = parsed.port;
  987. proxyApplied = setProxy(
  988. options,
  989. configProxy,
  990. protocol + '//' + parsed.hostname + (parsed.port ? ':' + parsed.port : '') + options.path,
  991. false,
  992. httpsAgent,
  993. httpAgent,
  994. // The HTTP/2 transport connects independently of HTTP/1 agents, so it
  995. // cannot apply either axios-resolved or agent-local environment proxies.
  996. // Explicit proxy config is still processed and rejected below.
  997. !isHttp2
  998. );
  999. }
  1000. let transport;
  1001. let isNativeTransport = false;
  1002. const isHttpsRequest = isHttps.test(options.protocol);
  1003. // Don't clobber a CONNECT-tunneling agent installed by setProxy() for an
  1004. // HTTPS target.
  1005. if (!isHttp2 && configProxy === false) {
  1006. setDirectAgent(options, httpAgent, httpsAgent);
  1007. options.beforeRedirects.direct = (redirectOptions) => {
  1008. setDirectAgent(redirectOptions, httpAgent, httpsAgent);
  1009. };
  1010. } else if (options.agent == null) {
  1011. options.agent = isHttpsRequest ? httpsAgent : httpAgent;
  1012. }
  1013. if (isHttp2) {
  1014. if (proxyApplied) {
  1015. return reject(
  1016. new AxiosError(
  1017. 'HTTP/2 requests with a proxy are not supported',
  1018. AxiosError.ERR_NOT_SUPPORT,
  1019. config
  1020. )
  1021. );
  1022. }
  1023. transport = http2Transport;
  1024. } else {
  1025. const configTransport = own('transport');
  1026. if (configTransport) {
  1027. transport = configTransport;
  1028. } else if (maxRedirects === 0) {
  1029. transport = isHttpsRequest ? https : http;
  1030. isNativeTransport = true;
  1031. } else {
  1032. options.sensitiveHeaders = [];
  1033. if (maxRedirects) {
  1034. options.maxRedirects = maxRedirects;
  1035. }
  1036. const configBeforeRedirect = own('beforeRedirect');
  1037. if (configBeforeRedirect) {
  1038. options.beforeRedirects.config = configBeforeRedirect;
  1039. }
  1040. if (auth) {
  1041. // Restore HTTP Basic credentials on same-origin redirects only.
  1042. // follow-redirects >= 1.15.8 strips Authorization on every redirect (see #6929);
  1043. // cross-origin stripping is the documented mitigation for T-R2 in THREATMODEL.md
  1044. // and is preserved by deliberately not restoring on origin change.
  1045. const requestOrigin = parsed.origin;
  1046. const authToRestore = auth;
  1047. options.beforeRedirects.auth = function beforeRedirectAuth(redirectOptions) {
  1048. try {
  1049. if (new URL(redirectOptions.href).origin === requestOrigin) {
  1050. redirectOptions.auth = authToRestore;
  1051. }
  1052. } catch (e) {
  1053. // ignore malformed URL: leaving auth stripped is fail-safe
  1054. }
  1055. };
  1056. }
  1057. const sensitiveHeaders = own('sensitiveHeaders');
  1058. if (sensitiveHeaders != null) {
  1059. if (!utils.isArray(sensitiveHeaders)) {
  1060. return reject(
  1061. new AxiosError(
  1062. 'sensitiveHeaders must be an array of strings',
  1063. AxiosError.ERR_BAD_OPTION_VALUE,
  1064. config
  1065. )
  1066. );
  1067. }
  1068. const sensitiveSet = new Set();
  1069. for (const header of sensitiveHeaders) {
  1070. if (!utils.isString(header)) {
  1071. return reject(
  1072. new AxiosError(
  1073. 'sensitiveHeaders must be an array of strings',
  1074. AxiosError.ERR_BAD_OPTION_VALUE,
  1075. config
  1076. )
  1077. );
  1078. }
  1079. sensitiveSet.add(header.toLowerCase());
  1080. }
  1081. if (sensitiveSet.size) {
  1082. options.sensitiveHeaders = Array.from(sensitiveSet);
  1083. options.beforeRedirects.sensitiveHeaders = function beforeRedirectSensitiveHeaders(
  1084. redirectOptions,
  1085. requestDetails
  1086. ) {
  1087. if (!isSameOriginRedirect(redirectOptions, requestDetails)) {
  1088. stripMatchingHeaders(redirectOptions.headers, sensitiveSet);
  1089. }
  1090. };
  1091. }
  1092. }
  1093. transport = isHttpsRequest ? httpsFollow : httpFollow;
  1094. }
  1095. }
  1096. // Set an explicit maxBodyLength option for transports that inspect it.
  1097. // When maxBodyLength is -1 (default/unlimited), use Infinity so
  1098. // follow-redirects does not fall back to its own 10MB default.
  1099. if (maxBodyLength > -1) {
  1100. options.maxBodyLength = maxBodyLength;
  1101. } else {
  1102. options.maxBodyLength = Infinity;
  1103. }
  1104. // Always set an explicit own value so a polluted
  1105. // Object.prototype.insecureHTTPParser cannot enable the lenient parser
  1106. // through Node's internal options copy
  1107. options.insecureHTTPParser = Boolean(own('insecureHTTPParser'));
  1108. // Create the request
  1109. req = transport.request(options, function handleResponse(res) {
  1110. clearConnectPhaseTimer();
  1111. if (req.destroyed) return;
  1112. const streams = [res];
  1113. const responseLength = utils.toFiniteNumber(res.headers['content-length']);
  1114. if (onDownloadProgress || maxDownloadRate) {
  1115. const transformStream = new AxiosTransformStream({
  1116. maxRate: utils.toFiniteNumber(maxDownloadRate),
  1117. });
  1118. onDownloadProgress &&
  1119. transformStream.on(
  1120. 'progress',
  1121. flushOnFinish(
  1122. transformStream,
  1123. progressEventDecorator(
  1124. responseLength,
  1125. progressEventReducer(
  1126. asyncDecorator(onDownloadProgress, scheduleProgress),
  1127. true,
  1128. 3
  1129. )
  1130. )
  1131. )
  1132. );
  1133. streams.push(transformStream);
  1134. }
  1135. // decompress the response body transparently if required
  1136. let responseStream = res;
  1137. // return the last request in case of redirects
  1138. const lastRequest = res.req || req;
  1139. // if decompress disabled we should not decompress
  1140. if (decompress !== false && res.headers['content-encoding']) {
  1141. // if no content, but headers still say that it is encoded,
  1142. // remove the header not confuse downstream operations
  1143. if (method === 'HEAD' || res.statusCode === 204) {
  1144. delete res.headers['content-encoding'];
  1145. }
  1146. switch ((res.headers['content-encoding'] || '').toLowerCase()) {
  1147. /*eslint default-case:0*/
  1148. case 'gzip':
  1149. case 'x-gzip':
  1150. case 'compress':
  1151. case 'x-compress':
  1152. // add the unzipper to the body stream processing pipeline
  1153. streams.push(zlib.createUnzip(zlibOptions));
  1154. // remove the content-encoding in order to not confuse downstream operations
  1155. delete res.headers['content-encoding'];
  1156. break;
  1157. case 'deflate':
  1158. streams.push(new ZlibHeaderTransformStream());
  1159. // add the unzipper to the body stream processing pipeline
  1160. streams.push(zlib.createUnzip(zlibOptions));
  1161. // remove the content-encoding in order to not confuse downstream operations
  1162. delete res.headers['content-encoding'];
  1163. break;
  1164. case 'br':
  1165. if (isBrotliSupported) {
  1166. streams.push(zlib.createBrotliDecompress(brotliOptions));
  1167. delete res.headers['content-encoding'];
  1168. }
  1169. break;
  1170. case 'zstd':
  1171. if (isZstdSupported) {
  1172. streams.push(zlib.createZstdDecompress(zstdOptions));
  1173. delete res.headers['content-encoding'];
  1174. }
  1175. break;
  1176. }
  1177. }
  1178. responseStream = streams.length > 1 ? stream.pipeline(streams, utils.noop) : streams[0];
  1179. const response = {
  1180. status: res.statusCode,
  1181. statusText: res.statusMessage,
  1182. headers: new AxiosHeaders(res.headers),
  1183. config,
  1184. request: lastRequest,
  1185. };
  1186. if (responseType === 'stream') {
  1187. // Enforce maxContentLength on streamed responses; previously this
  1188. // was applied only to buffered responses.
  1189. if (maxContentLength > -1) {
  1190. const limit = maxContentLength;
  1191. const source = responseStream;
  1192. async function* enforceMaxContentLength() {
  1193. let totalResponseBytes = 0;
  1194. for await (const chunk of source) {
  1195. totalResponseBytes += chunk.length;
  1196. if (totalResponseBytes > limit) {
  1197. throw new AxiosError(
  1198. 'maxContentLength size of ' + limit + ' exceeded',
  1199. AxiosError.ERR_BAD_RESPONSE,
  1200. config,
  1201. lastRequest
  1202. );
  1203. }
  1204. yield chunk;
  1205. }
  1206. }
  1207. responseStream = stream.Readable.from(enforceMaxContentLength(), {
  1208. objectMode: false,
  1209. });
  1210. }
  1211. response.data = responseStream;
  1212. settle(resolve, reject, response);
  1213. } else {
  1214. const responseBuffer = [];
  1215. let totalResponseBytes = 0;
  1216. responseStream.on('data', function handleStreamData(chunk) {
  1217. responseBuffer.push(chunk);
  1218. totalResponseBytes += chunk.length;
  1219. // make sure the content length is not over the maxContentLength if specified
  1220. if (maxContentLength > -1 && totalResponseBytes > maxContentLength) {
  1221. // stream.destroy() emit aborted event before calling reject() on Node.js v16
  1222. rejected = true;
  1223. responseStream.destroy();
  1224. abort(
  1225. new AxiosError(
  1226. 'maxContentLength size of ' + maxContentLength + ' exceeded',
  1227. AxiosError.ERR_BAD_RESPONSE,
  1228. config,
  1229. lastRequest
  1230. )
  1231. );
  1232. }
  1233. });
  1234. responseStream.on('aborted', function handlerStreamAborted() {
  1235. if (rejected) {
  1236. return;
  1237. }
  1238. const err = new AxiosError(
  1239. 'stream has been aborted',
  1240. AxiosError.ERR_BAD_RESPONSE,
  1241. config,
  1242. lastRequest,
  1243. response
  1244. );
  1245. responseStream.destroy(err);
  1246. reject(err);
  1247. });
  1248. responseStream.on('error', function handleStreamError(err) {
  1249. if (rejected) return;
  1250. reject(AxiosError.from(err, null, config, lastRequest, response));
  1251. });
  1252. responseStream.on('end', function handleStreamEnd() {
  1253. try {
  1254. let responseData =
  1255. responseBuffer.length === 1 ? responseBuffer[0] : Buffer.concat(responseBuffer);
  1256. if (responseType !== 'arraybuffer') {
  1257. responseData = responseData.toString(responseEncoding);
  1258. if (!responseEncoding || responseEncoding === 'utf8') {
  1259. responseData = utils.stripBOM(responseData);
  1260. }
  1261. }
  1262. response.data = responseData;
  1263. } catch (err) {
  1264. return reject(AxiosError.from(err, null, config, response.request, response));
  1265. }
  1266. settle(resolve, reject, response);
  1267. });
  1268. }
  1269. abortEmitter.once('abort', (err) => {
  1270. if (!responseStream.destroyed) {
  1271. responseStream.emit('error', err);
  1272. responseStream.destroy();
  1273. }
  1274. });
  1275. });
  1276. abortEmitter.once('abort', (err) => {
  1277. if (req.close) {
  1278. req.close();
  1279. } else {
  1280. req.destroy(err);
  1281. }
  1282. });
  1283. // Handle errors
  1284. req.on('error', function handleRequestError(err) {
  1285. reject(AxiosError.from(err, null, config, req));
  1286. });
  1287. // set tcp keep alive to prevent drop connection by peer
  1288. // Track every socket bound to this outer RedirectableRequest so a single
  1289. // 'close' listener can release ownership on all of them. follow-redirects
  1290. // re-emits the 'socket' event for each hop's native request onto the same
  1291. // outer request, so attaching per-request listeners inside this handler
  1292. // would accumulate across hops and trigger MaxListenersExceededWarning at
  1293. // >= 11 redirects. Clearing only the last-bound socket would leave stale
  1294. // kAxiosCurrentReq refs on earlier hop sockets returned to the keep-alive
  1295. // pool, causing an idle-pool 'error' to be attributed to a closed req.
  1296. const boundSockets = new Set();
  1297. req.on('socket', function handleRequestSocket(socket) {
  1298. // default interval of sending ack packet is 1 minute
  1299. // proxy agents (e.g. agent-base) may return a generic Duplex stream
  1300. // that doesn't have setKeepAlive, so guard before calling
  1301. if (typeof socket.setKeepAlive === 'function') {
  1302. socket.setKeepAlive(true, 1000 * 60);
  1303. }
  1304. // Install one shared 'error' listener per socket. The symbol follows the
  1305. // currently-active request as pooled sockets are reassigned (issue #10780).
  1306. if (!socket[kAxiosSocketListener]) {
  1307. socket.on('error', handleSocketError);
  1308. socket[kAxiosSocketListener] = true;
  1309. }
  1310. socket[kAxiosCurrentReq] = req;
  1311. boundSockets.add(socket);
  1312. });
  1313. req.once('close', function clearCurrentReq() {
  1314. clearConnectPhaseTimer();
  1315. for (const socket of boundSockets) {
  1316. if (socket[kAxiosCurrentReq] === req) {
  1317. socket[kAxiosCurrentReq] = null;
  1318. }
  1319. }
  1320. boundSockets.clear();
  1321. });
  1322. // Handle request timeout
  1323. if (own('timeout')) {
  1324. // This is forcing a int timeout to avoid problems if the `req` interface doesn't handle other types.
  1325. const timeout = parseInt(own('timeout'), 10);
  1326. if (Number.isNaN(timeout)) {
  1327. abort(
  1328. new AxiosError(
  1329. 'error trying to parse `config.timeout` to int',
  1330. AxiosError.ERR_BAD_OPTION_VALUE,
  1331. config,
  1332. req
  1333. )
  1334. );
  1335. return;
  1336. }
  1337. const handleTimeout = function handleTimeout() {
  1338. if (isDone) return;
  1339. abort(createTimeoutError());
  1340. };
  1341. if (isNativeTransport && timeout > 0) {
  1342. // Native ClientRequest#setTimeout starts from the socket lifecycle and
  1343. // may not fire while TCP connect is still pending. Mirror the
  1344. // follow-redirects wall-clock timer for the maxRedirects === 0 path.
  1345. connectPhaseTimer = setTimeout(handleTimeout, timeout);
  1346. }
  1347. // Sometime, the response will be very slow, and does not respond, the connect event will be block by event loop system.
  1348. // And timer callback will be fired, and abort() will be invoked before connection, then get "socket hang up" and code ECONNRESET.
  1349. // At this time, if we have a large number of request, nodejs will hang up some socket on background. and the number will up and up.
  1350. // And then these socket which be hang up will devouring CPU little by little.
  1351. // ClientRequest.setTimeout will be fired on the specify milliseconds, and can make sure that abort() will be fired after connect.
  1352. req.setTimeout(timeout, handleTimeout);
  1353. } else {
  1354. // explicitly reset the socket timeout value for a possible `keep-alive` request
  1355. req.setTimeout(0);
  1356. }
  1357. // Send the request
  1358. if (utils.isStream(data)) {
  1359. let ended = false;
  1360. let errored = false;
  1361. data.on('end', () => {
  1362. ended = true;
  1363. });
  1364. data.once('error', (err) => {
  1365. errored = true;
  1366. req.destroy(err);
  1367. });
  1368. data.on('close', () => {
  1369. if (!ended && !errored) {
  1370. abort(new CanceledError('Request stream has been aborted', config, req));
  1371. }
  1372. });
  1373. // Transform decodes string chunks to Buffers before counting, so every
  1374. // transport receives at most maxBodyLength encoded bytes.
  1375. let uploadStream = data;
  1376. if (maxBodyLength > -1) {
  1377. const limit = maxBodyLength;
  1378. let bytesSent = 0;
  1379. uploadStream = stream.pipeline(
  1380. [
  1381. data,
  1382. new stream.Transform({
  1383. transform(chunk, _enc, cb) {
  1384. bytesSent += chunk.length;
  1385. if (bytesSent > limit) {
  1386. return cb(
  1387. new AxiosError(
  1388. 'Request body larger than maxBodyLength limit',
  1389. AxiosError.ERR_BAD_REQUEST,
  1390. config,
  1391. req
  1392. )
  1393. );
  1394. }
  1395. cb(null, chunk);
  1396. },
  1397. }),
  1398. ],
  1399. utils.noop
  1400. );
  1401. uploadStream.on('error', (err) => {
  1402. if (!req.destroyed) req.destroy(err);
  1403. });
  1404. }
  1405. uploadStream.pipe(req);
  1406. } else {
  1407. data && req.write(data);
  1408. req.end();
  1409. }
  1410. });
  1411. };
  1412. export const __setProxy = setProxy;
  1413. export const __getDirectAgent = getDirectAgent;
  1414. export const __isNodeNativeEnvProxySupported = isNodeNativeEnvProxySupported;
  1415. export const __isNodeEnvProxyEnabled = isNodeEnvProxyEnabled;
  1416. export const __isSameOriginRedirect = isSameOriginRedirect;