diff --git a/lib/core/util.js b/lib/core/util.js index ab397f89e74..dfefac6d15c 100644 --- a/lib/core/util.js +++ b/lib/core/util.js @@ -436,46 +436,6 @@ function parseHeaders (headers, obj) { return obj } -function normalizeHeaders (headers) { - const ret = {} - if (headers == null) { - // Do nothing... - } else if (Array.isArray(headers)) { - for (let i = 0; i < headers.length; i += 2) { - if (Array.isArray(headers[i]) && headers[i].length === 2) { - const key = headerNameToString(headers[i][0]) - const val = ret[key] - if (val == null) { - ret[key] = String(headers[i][1]) - } else if (typeof val === 'string') { - ret[key] = [val, String(headers[i][1])] - } else { - val.push(String(headers[i][1])) - } - } else { - const key = headerNameToString(headers[i]) - const val = ret[key] - if (val == null) { - ret[key] = String(headers[i + 1]) - } else if (typeof val === 'string') { - ret[key] = [val, String(headers[i + 1])] - } else { - val.push(String(headers[i + 1])) - } - } - } - } else if (typeof headers[Symbol.iterator] === 'function') { - for (const [key, val] of headers) { - ret[headerNameToString(key)] = Array.isArray(val) ? val.map(x => String(x)) : String(val) - } - } else { - for (const [key, val] of Object.entries(headers)) { - ret[headerNameToString(key)] = Array.isArray(val) ? val.map(x => String(x)) : String(val) - } - } - return ret -} - /** * @param {Buffer[]} headers * @returns {string[]} @@ -943,6 +903,5 @@ module.exports = { nodeMajor, nodeMinor, safeHTTPMethods: Object.freeze(['GET', 'HEAD', 'OPTIONS', 'TRACE']), - wrapRequestBody, - normalizeHeaders + wrapRequestBody } diff --git a/lib/handler/redirect-handler.js b/lib/handler/redirect-handler.js index c8c9d60663c..5a36318d89e 100644 --- a/lib/handler/redirect-handler.js +++ b/lib/handler/redirect-handler.js @@ -206,13 +206,26 @@ function shouldRemoveHeader (name, removeContent, unknownOrigin) { // https://tools.ietf.org/html/rfc7231#section-6.4 function cleanRequestHeaders (headers, removeContent, unknownOrigin) { - const ret = util.normalizeHeaders(headers) - for (const name of Object.keys(ret)) { - if (shouldRemoveHeader(name, removeContent, unknownOrigin)) { - delete ret[name] + let ret + if (Array.isArray(headers)) { + for (let i = 0; i < headers.length; i += 2) { + const name = util.headerNameToString(headers[i]) + if (!shouldRemoveHeader(name, removeContent, unknownOrigin)) { + ret ??= { ...headers } + ret[name] = headers[i + 1] + } + } + } else if (headers && typeof headers === 'object') { + const entries = typeof headers[Symbol.iterator] === 'function' ? headers : Object.entries(headers) + for (const [key, value] of entries) { + const name = util.headerNameToString(key) + if (!shouldRemoveHeader(name, removeContent, unknownOrigin)) { + ret ??= { ...headers } + ret[name] = value + } } } - return ret + return ret ?? headers } module.exports = RedirectHandler