2
0
mirror of https://github.com/tenrok/axios.git synced 2026-06-17 19:21:29 +03:00
Files
axios/lib/helpers/resolveConfig.js
T
Mohammad Faiz 73a7c55282 fix: clean up error handling, fix a proto-pollution gap, and seal a few loose ends (#10922)
* Clean up error handling, fix a proto-pollution gap, and seal a few loose ends.

Been poking around the codebase and found a handful of things that needed tidying up:

- resolveConfig.js - config.params and config.paramsSerializer were being accessed directly off user input instead of going through the own() guard. If someone crafted a config with inherited params from the prototype, you'd get unexpected behavior. Swapped to own('params') / own('paramsSerializer') like the rest of the module does.

- http.js - there was a stray console.warn('emit error', err) in an abort-event catch block. Debug leftover, shouldn't reach production. Replaced with a quiet catch.

- AxiosHeaders.js - three places were throwing raw Error or TypeError instead of AxiosError. Swapped them over with ERR_BAD_OPTION_VALUE. Also added the missing AxiosError import (creates a circular dep with AxiosError.js which imports AxiosHeaders, but it works fine at runtime since the throws are inside method bodies, not at module eval time).

- toFormData.js - the circular reference detection was throwing a bare Error. Changed to AxiosError without a code, so it stays distinguishable from the depth-exceeded error that uses ERR_FORM_DATA_DEPTH_EXCEEDED. (There's a test that explicitly checks this distinction.)

- formDataToStream.js - two more raw throws (TypeError and Error) → AxiosError.

- buildURL.js - import self-path ../helpers/AxiosURLSearchParams.js when it lives in the same directory as the importer. Changed to ./AxiosURLSearchParams.js.

- index.d.cts - CanceledError was missing readonly name: 'CanceledError' that index.d.ts already has. Added it to keep the CJS declarations in sync.

Lint passes clean, all 770 unit tests green. Nothing breaking - all changes are either internal (no consumer-facing API change) or type-only.

* Update AxiosHeaders.js

* Update AxiosHeaders.js

* fix: revert breaking error-type changes per review feedback

Reverts AxiosError throws back to native Error/TypeError in AxiosHeaders,
formDataToStream, and toFormData to avoid breaking existing consumers
who catch by constructor name or check isAxiosError().

Adds regression tests for resolveConfig own('params')/own('paramsSerializer')
guard as requested in review.

Removes unused AxiosError imports from AxiosHeaders and formDataToStream.

* docs: add pre-release notes for config hardening

---------

Co-authored-by: Jason Saayman <jasonsaayman@gmail.com>
2026-05-26 21:09:03 +02:00

113 lines
3.5 KiB
JavaScript

import platform from '../platform/index.js';
import utils from '../utils.js';
import isURLSameOrigin from './isURLSameOrigin.js';
import cookies from './cookies.js';
import buildFullPath from '../core/buildFullPath.js';
import mergeConfig from '../core/mergeConfig.js';
import AxiosHeaders from '../core/AxiosHeaders.js';
import buildURL from './buildURL.js';
const FORM_DATA_CONTENT_HEADERS = ['content-type', 'content-length'];
function setFormDataHeaders(headers, formHeaders, policy) {
if (policy !== 'content-only') {
headers.set(formHeaders);
return;
}
Object.entries(formHeaders).forEach(([key, val]) => {
if (FORM_DATA_CONTENT_HEADERS.includes(key.toLowerCase())) {
headers.set(key, val);
}
});
}
/**
* Encode a UTF-8 string to a Latin-1 byte string for use with btoa().
* This is a modern replacement for the deprecated unescape(encodeURIComponent(str)) pattern.
*
* @param {string} str The string to encode
*
* @returns {string} UTF-8 bytes as a Latin-1 string
*/
const encodeUTF8 = (str) =>
encodeURIComponent(str).replace(/%([0-9A-F]{2})/gi, (_, hex) =>
String.fromCharCode(parseInt(hex, 16))
);
function resolveConfig(config) {
const newConfig = mergeConfig({}, config);
// Read only own properties to prevent prototype pollution gadgets
// (e.g. Object.prototype.baseURL = 'https://evil.com').
const own = (key) => (utils.hasOwnProp(newConfig, key) ? newConfig[key] : undefined);
const data = own('data');
let withXSRFToken = own('withXSRFToken');
const xsrfHeaderName = own('xsrfHeaderName');
const xsrfCookieName = own('xsrfCookieName');
let headers = own('headers');
const auth = own('auth');
const baseURL = own('baseURL');
const allowAbsoluteUrls = own('allowAbsoluteUrls');
const url = own('url');
newConfig.headers = headers = AxiosHeaders.from(headers);
newConfig.url = buildURL(
buildFullPath(baseURL, url, allowAbsoluteUrls),
own('params'),
own('paramsSerializer')
);
// HTTP basic authentication
if (auth) {
headers.set(
'Authorization',
'Basic ' +
btoa((auth.username || '') + ':' + (auth.password ? encodeUTF8(auth.password) : ''))
);
}
if (utils.isFormData(data)) {
if (
platform.hasStandardBrowserEnv ||
platform.hasStandardBrowserWebWorkerEnv ||
utils.isReactNative(data)
) {
headers.setContentType(undefined); // browser/web worker/RN handles it
} else if (utils.isFunction(data.getHeaders)) {
// Node.js FormData (like form-data package)
setFormDataHeaders(headers, data.getHeaders(), own('formDataHeaderPolicy'));
}
}
// Add xsrf header
// This is only done if running in a standard browser environment.
// Specifically not if we're in a web worker, or react-native.
if (platform.hasStandardBrowserEnv) {
if (utils.isFunction(withXSRFToken)) {
withXSRFToken = withXSRFToken(newConfig);
}
// Strict boolean check — prevents proto-pollution gadgets (e.g. Object.prototype.withXSRFToken = 1)
// and misconfigurations (e.g. "false") from short-circuiting the same-origin check and leaking
// the XSRF token cross-origin.
const shouldSendXSRF =
withXSRFToken === true || (withXSRFToken == null && isURLSameOrigin(newConfig.url));
if (shouldSendXSRF) {
const xsrfValue = xsrfHeaderName && xsrfCookieName && cookies.read(xsrfCookieName);
if (xsrfValue) {
headers.set(xsrfHeaderName, xsrfValue);
}
}
}
return newConfig;
}
export default resolveConfig;