index.js 86 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372
  1. // https://github.com/Ethan-Arrowood/undici-fetch
  2. 'use strict'
  3. const {
  4. makeNetworkError,
  5. makeAppropriateNetworkError,
  6. filterResponse,
  7. makeResponse,
  8. fromInnerResponse,
  9. getResponseState
  10. } = require('./response')
  11. const { HeadersList } = require('./headers')
  12. const { Request, cloneRequest, getRequestDispatcher, getRequestState } = require('./request')
  13. const zlib = require('node:zlib')
  14. const {
  15. makePolicyContainer,
  16. clonePolicyContainer,
  17. requestBadPort,
  18. TAOCheck,
  19. appendRequestOriginHeader,
  20. responseLocationURL,
  21. requestCurrentURL,
  22. setRequestReferrerPolicyOnRedirect,
  23. tryUpgradeRequestToAPotentiallyTrustworthyURL,
  24. createOpaqueTimingInfo,
  25. appendFetchMetadata,
  26. corsCheck,
  27. crossOriginResourcePolicyCheck,
  28. determineRequestsReferrer,
  29. coarsenedSharedCurrentTime,
  30. sameOrigin,
  31. isCancelled,
  32. isAborted,
  33. isErrorLike,
  34. fullyReadBody,
  35. readableStreamClose,
  36. urlIsLocal,
  37. urlIsHttpHttpsScheme,
  38. urlHasHttpsScheme,
  39. clampAndCoarsenConnectionTimingInfo,
  40. simpleRangeHeaderValue,
  41. buildContentRange,
  42. createInflate,
  43. extractMimeType,
  44. hasAuthenticationEntry,
  45. includesCredentials,
  46. isTraversableNavigable
  47. } = require('./util')
  48. const assert = require('node:assert')
  49. const { safelyExtractBody, extractBody } = require('./body')
  50. const {
  51. redirectStatusSet,
  52. nullBodyStatus,
  53. safeMethodsSet,
  54. requestBodyHeader,
  55. subresourceSet
  56. } = require('./constants')
  57. const EE = require('node:events')
  58. const { Readable, pipeline, finished, isErrored, isReadable } = require('node:stream')
  59. const { addAbortListener, bufferToLowerCasedHeaderName } = require('../../core/util')
  60. const { dataURLProcessor, serializeAMimeType, minimizeSupportedMimeType } = require('./data-url')
  61. const { getGlobalDispatcher } = require('../../global')
  62. const { webidl } = require('../webidl')
  63. const { STATUS_CODES } = require('node:http')
  64. const { bytesMatch } = require('../subresource-integrity/subresource-integrity')
  65. const { createDeferredPromise } = require('../../util/promise')
  66. const { isomorphicEncode } = require('../infra')
  67. const { runtimeFeatures } = require('../../util/runtime-features')
  68. // Node.js v23.8.0+ and v22.15.0+ supports Zstandard
  69. const hasZstd = runtimeFeatures.has('zstd')
  70. const GET_OR_HEAD = ['GET', 'HEAD']
  71. const defaultUserAgent = typeof __UNDICI_IS_NODE__ !== 'undefined' || typeof esbuildDetection !== 'undefined'
  72. ? 'node'
  73. : 'undici'
  74. /** @type {import('buffer').resolveObjectURL} */
  75. let resolveObjectURL
  76. class Fetch extends EE {
  77. constructor (dispatcher) {
  78. super()
  79. this.dispatcher = dispatcher
  80. this.connection = null
  81. this.dump = false
  82. this.state = 'ongoing'
  83. }
  84. terminate (reason) {
  85. if (this.state !== 'ongoing') {
  86. return
  87. }
  88. this.state = 'terminated'
  89. this.connection?.destroy(reason)
  90. this.emit('terminated', reason)
  91. }
  92. // https://fetch.spec.whatwg.org/#fetch-controller-abort
  93. abort (error) {
  94. if (this.state !== 'ongoing') {
  95. return
  96. }
  97. // 1. Set controller’s state to "aborted".
  98. this.state = 'aborted'
  99. // 2. Let fallbackError be an "AbortError" DOMException.
  100. // 3. Set error to fallbackError if it is not given.
  101. if (!error) {
  102. error = new DOMException('The operation was aborted.', 'AbortError')
  103. }
  104. // 4. Let serializedError be StructuredSerialize(error).
  105. // If that threw an exception, catch it, and let
  106. // serializedError be StructuredSerialize(fallbackError).
  107. // 5. Set controller’s serialized abort reason to serializedError.
  108. this.serializedAbortReason = error
  109. this.connection?.destroy(error)
  110. this.emit('terminated', error)
  111. }
  112. }
  113. function handleFetchDone (response) {
  114. finalizeAndReportTiming(response, 'fetch')
  115. }
  116. // https://fetch.spec.whatwg.org/#fetch-method
  117. function fetch (input, init = undefined) {
  118. webidl.argumentLengthCheck(arguments, 1, 'globalThis.fetch')
  119. // 1. Let p be a new promise.
  120. let p = createDeferredPromise()
  121. // 2. Let requestObject be the result of invoking the initial value of
  122. // Request as constructor with input and init as arguments. If this throws
  123. // an exception, reject p with it and return p.
  124. let requestObject
  125. try {
  126. requestObject = new Request(input, init)
  127. } catch (e) {
  128. p.reject(e)
  129. return p.promise
  130. }
  131. // 3. Let request be requestObject’s request.
  132. const request = getRequestState(requestObject)
  133. // 4. If requestObject’s signal’s aborted flag is set, then:
  134. if (requestObject.signal.aborted) {
  135. // 1. Abort the fetch() call with p, request, null, and
  136. // requestObject’s signal’s abort reason.
  137. abortFetch(p, request, null, requestObject.signal.reason, null)
  138. // 2. Return p.
  139. return p.promise
  140. }
  141. // 5. Let globalObject be request’s client’s global object.
  142. const globalObject = request.client.globalObject
  143. // 6. If globalObject is a ServiceWorkerGlobalScope object, then set
  144. // request’s service-workers mode to "none".
  145. if (globalObject?.constructor?.name === 'ServiceWorkerGlobalScope') {
  146. request.serviceWorkers = 'none'
  147. }
  148. // 7. Let responseObject be null.
  149. let responseObject = null
  150. // 8. Let relevantRealm be this’s relevant Realm.
  151. // 9. Let locallyAborted be false.
  152. let locallyAborted = false
  153. // 10. Let controller be null.
  154. let controller = null
  155. // 11. Add the following abort steps to requestObject’s signal:
  156. addAbortListener(
  157. requestObject.signal,
  158. () => {
  159. // 1. Set locallyAborted to true.
  160. locallyAborted = true
  161. // 2. Assert: controller is non-null.
  162. assert(controller != null)
  163. // 3. Abort controller with requestObject’s signal’s abort reason.
  164. controller.abort(requestObject.signal.reason)
  165. const realResponse = responseObject?.deref()
  166. // 4. Abort the fetch() call with p, request, responseObject,
  167. // and requestObject’s signal’s abort reason.
  168. abortFetch(p, request, realResponse, requestObject.signal.reason, controller.controller)
  169. }
  170. )
  171. // 12. Let handleFetchDone given response response be to finalize and
  172. // report timing with response, globalObject, and "fetch".
  173. // see function handleFetchDone
  174. // 13. Set controller to the result of calling fetch given request,
  175. // with processResponseEndOfBody set to handleFetchDone, and processResponse
  176. // given response being these substeps:
  177. const processResponse = (response) => {
  178. // 1. If locallyAborted is true, terminate these substeps.
  179. if (locallyAborted) {
  180. return
  181. }
  182. // 2. If response’s aborted flag is set, then:
  183. if (response.aborted) {
  184. // 1. Let deserializedError be the result of deserialize a serialized
  185. // abort reason given controller’s serialized abort reason and
  186. // relevantRealm.
  187. // 2. Abort the fetch() call with p, request, responseObject, and
  188. // deserializedError.
  189. abortFetch(p, request, responseObject, controller.serializedAbortReason, controller.controller)
  190. return
  191. }
  192. // 3. If response is a network error, then reject p with a TypeError
  193. // and terminate these substeps.
  194. if (response.type === 'error') {
  195. p.reject(new TypeError('fetch failed', { cause: response.error }))
  196. return
  197. }
  198. // 4. Set responseObject to the result of creating a Response object,
  199. // given response, "immutable", and relevantRealm.
  200. responseObject = new WeakRef(fromInnerResponse(response, 'immutable'))
  201. // 5. Resolve p with responseObject.
  202. p.resolve(responseObject.deref())
  203. p = null
  204. }
  205. controller = fetching({
  206. request,
  207. processResponseEndOfBody: handleFetchDone,
  208. processResponse,
  209. dispatcher: getRequestDispatcher(requestObject) // undici
  210. })
  211. // 14. Return p.
  212. return p.promise
  213. }
  214. // https://fetch.spec.whatwg.org/#finalize-and-report-timing
  215. function finalizeAndReportTiming (response, initiatorType = 'other') {
  216. // 1. If response is an aborted network error, then return.
  217. if (response.type === 'error' && response.aborted) {
  218. return
  219. }
  220. // 2. If response’s URL list is null or empty, then return.
  221. if (!response.urlList?.length) {
  222. return
  223. }
  224. // 3. Let originalURL be response’s URL list[0].
  225. const originalURL = response.urlList[0]
  226. // 4. Let timingInfo be response’s timing info.
  227. let timingInfo = response.timingInfo
  228. // 5. Let cacheState be response’s cache state.
  229. let cacheState = response.cacheState
  230. // 6. If originalURL’s scheme is not an HTTP(S) scheme, then return.
  231. if (!urlIsHttpHttpsScheme(originalURL)) {
  232. return
  233. }
  234. // 7. If timingInfo is null, then return.
  235. if (timingInfo === null) {
  236. return
  237. }
  238. // 8. If response’s timing allow passed flag is not set, then:
  239. if (!response.timingAllowPassed) {
  240. // 1. Set timingInfo to a the result of creating an opaque timing info for timingInfo.
  241. timingInfo = createOpaqueTimingInfo({
  242. startTime: timingInfo.startTime
  243. })
  244. // 2. Set cacheState to the empty string.
  245. cacheState = ''
  246. }
  247. // 9. Set timingInfo’s end time to the coarsened shared current time
  248. // given global’s relevant settings object’s cross-origin isolated
  249. // capability.
  250. // TODO: given global’s relevant settings object’s cross-origin isolated
  251. // capability?
  252. timingInfo.endTime = coarsenedSharedCurrentTime()
  253. // 10. Set response’s timing info to timingInfo.
  254. response.timingInfo = timingInfo
  255. // 11. Mark resource timing for timingInfo, originalURL, initiatorType,
  256. // global, and cacheState.
  257. markResourceTiming(
  258. timingInfo,
  259. originalURL.href,
  260. initiatorType,
  261. globalThis,
  262. cacheState,
  263. '', // bodyType
  264. response.status
  265. )
  266. }
  267. // https://w3c.github.io/resource-timing/#dfn-mark-resource-timing
  268. const markResourceTiming = performance.markResourceTiming
  269. // https://fetch.spec.whatwg.org/#abort-fetch
  270. function abortFetch (p, request, responseObject, error, controller /* undici-specific */) {
  271. // 1. Reject promise with error.
  272. if (p) {
  273. // We might have already resolved the promise at this stage
  274. p.reject(error)
  275. }
  276. // 2. If request’s body is not null and is readable, then cancel request’s
  277. // body with error.
  278. if (request.body?.stream != null && isReadable(request.body.stream)) {
  279. request.body.stream.cancel(error).catch((err) => {
  280. if (err.code === 'ERR_INVALID_STATE') {
  281. // Node bug?
  282. return
  283. }
  284. throw err
  285. })
  286. }
  287. // 3. If responseObject is null, then return.
  288. if (responseObject == null) {
  289. return
  290. }
  291. // 4. Let response be responseObject’s response.
  292. const response = getResponseState(responseObject)
  293. // 5. If response’s body is not null and is readable, then error response’s
  294. // body with error.
  295. if (response.body?.stream != null && isReadable(response.body.stream)) {
  296. controller.error(error)
  297. }
  298. }
  299. // https://fetch.spec.whatwg.org/#fetching
  300. function fetching ({
  301. request,
  302. processRequestBodyChunkLength,
  303. processRequestEndOfBody,
  304. processResponse,
  305. processResponseEndOfBody,
  306. processResponseConsumeBody,
  307. useParallelQueue = false,
  308. dispatcher = getGlobalDispatcher() // undici
  309. }) {
  310. // Ensure that the dispatcher is set accordingly
  311. assert(dispatcher)
  312. // 1. Let taskDestination be null.
  313. let taskDestination = null
  314. // 2. Let crossOriginIsolatedCapability be false.
  315. let crossOriginIsolatedCapability = false
  316. // 3. If request’s client is non-null, then:
  317. if (request.client != null) {
  318. // 1. Set taskDestination to request’s client’s global object.
  319. taskDestination = request.client.globalObject
  320. // 2. Set crossOriginIsolatedCapability to request’s client’s cross-origin
  321. // isolated capability.
  322. crossOriginIsolatedCapability =
  323. request.client.crossOriginIsolatedCapability
  324. }
  325. // 4. If useParallelQueue is true, then set taskDestination to the result of
  326. // starting a new parallel queue.
  327. // TODO
  328. // 5. Let timingInfo be a new fetch timing info whose start time and
  329. // post-redirect start time are the coarsened shared current time given
  330. // crossOriginIsolatedCapability.
  331. const currentTime = coarsenedSharedCurrentTime(crossOriginIsolatedCapability)
  332. const timingInfo = createOpaqueTimingInfo({
  333. startTime: currentTime
  334. })
  335. // 6. Let fetchParams be a new fetch params whose
  336. // request is request,
  337. // timing info is timingInfo,
  338. // process request body chunk length is processRequestBodyChunkLength,
  339. // process request end-of-body is processRequestEndOfBody,
  340. // process response is processResponse,
  341. // process response consume body is processResponseConsumeBody,
  342. // process response end-of-body is processResponseEndOfBody,
  343. // task destination is taskDestination,
  344. // and cross-origin isolated capability is crossOriginIsolatedCapability.
  345. const fetchParams = {
  346. controller: new Fetch(dispatcher),
  347. request,
  348. timingInfo,
  349. processRequestBodyChunkLength,
  350. processRequestEndOfBody,
  351. processResponse,
  352. processResponseConsumeBody,
  353. processResponseEndOfBody,
  354. taskDestination,
  355. crossOriginIsolatedCapability
  356. }
  357. // 7. If request’s body is a byte sequence, then set request’s body to
  358. // request’s body as a body.
  359. // NOTE: Since fetching is only called from fetch, body should already be
  360. // extracted.
  361. assert(!request.body || request.body.stream)
  362. // 8. If request’s window is "client", then set request’s window to request’s
  363. // client, if request’s client’s global object is a Window object; otherwise
  364. // "no-window".
  365. if (request.window === 'client') {
  366. // TODO: What if request.client is null?
  367. request.window =
  368. request.client?.globalObject?.constructor?.name === 'Window'
  369. ? request.client
  370. : 'no-window'
  371. }
  372. // 9. If request’s origin is "client", then set request’s origin to request’s
  373. // client’s origin.
  374. if (request.origin === 'client') {
  375. request.origin = request.client.origin
  376. }
  377. // 10. If all of the following conditions are true:
  378. // TODO
  379. // 11. If request’s policy container is "client", then:
  380. if (request.policyContainer === 'client') {
  381. // 1. If request’s client is non-null, then set request’s policy
  382. // container to a clone of request’s client’s policy container. [HTML]
  383. if (request.client != null) {
  384. request.policyContainer = clonePolicyContainer(
  385. request.client.policyContainer
  386. )
  387. } else {
  388. // 2. Otherwise, set request’s policy container to a new policy
  389. // container.
  390. request.policyContainer = makePolicyContainer()
  391. }
  392. }
  393. // 12. If request’s header list does not contain `Accept`, then:
  394. if (!request.headersList.contains('accept', true)) {
  395. // 1. Let value be `*/*`.
  396. const value = '*/*'
  397. // 2. A user agent should set value to the first matching statement, if
  398. // any, switching on request’s destination:
  399. // "document"
  400. // "frame"
  401. // "iframe"
  402. // `text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8`
  403. // "image"
  404. // `image/png,image/svg+xml,image/*;q=0.8,*/*;q=0.5`
  405. // "style"
  406. // `text/css,*/*;q=0.1`
  407. // TODO
  408. // 3. Append `Accept`/value to request’s header list.
  409. request.headersList.append('accept', value, true)
  410. }
  411. // 13. If request’s header list does not contain `Accept-Language`, then
  412. // user agents should append `Accept-Language`/an appropriate value to
  413. // request’s header list.
  414. if (!request.headersList.contains('accept-language', true)) {
  415. request.headersList.append('accept-language', '*', true)
  416. }
  417. // 14. If request’s priority is null, then use request’s initiator and
  418. // destination appropriately in setting request’s priority to a
  419. // user-agent-defined object.
  420. if (request.priority === null) {
  421. // TODO
  422. }
  423. // 15. If request is a subresource request, then:
  424. if (subresourceSet.has(request.destination)) {
  425. // TODO
  426. }
  427. // 16. Run main fetch given fetchParams.
  428. mainFetch(fetchParams, false)
  429. // 17. Return fetchParam's controller
  430. return fetchParams.controller
  431. }
  432. // https://fetch.spec.whatwg.org/#concept-main-fetch
  433. async function mainFetch (fetchParams, recursive) {
  434. try {
  435. // 1. Let request be fetchParams’s request.
  436. const request = fetchParams.request
  437. // 2. Let response be null.
  438. let response = null
  439. // 3. If request’s local-URLs-only flag is set and request’s current URL is
  440. // not local, then set response to a network error.
  441. if (request.localURLsOnly && !urlIsLocal(requestCurrentURL(request))) {
  442. response = makeNetworkError('local URLs only')
  443. }
  444. // 4. Run report Content Security Policy violations for request.
  445. // TODO
  446. // 5. Upgrade request to a potentially trustworthy URL, if appropriate.
  447. tryUpgradeRequestToAPotentiallyTrustworthyURL(request)
  448. // 6. If should request be blocked due to a bad port, should fetching request
  449. // be blocked as mixed content, or should request be blocked by Content
  450. // Security Policy returns blocked, then set response to a network error.
  451. if (requestBadPort(request) === 'blocked') {
  452. response = makeNetworkError('bad port')
  453. }
  454. // TODO: should fetching request be blocked as mixed content?
  455. // TODO: should request be blocked by Content Security Policy?
  456. // 7. If request’s referrer policy is the empty string, then set request’s
  457. // referrer policy to request’s policy container’s referrer policy.
  458. if (request.referrerPolicy === '') {
  459. request.referrerPolicy = request.policyContainer.referrerPolicy
  460. }
  461. // 8. If request’s referrer is not "no-referrer", then set request’s
  462. // referrer to the result of invoking determine request’s referrer.
  463. if (request.referrer !== 'no-referrer') {
  464. request.referrer = determineRequestsReferrer(request)
  465. }
  466. // 9. Set request’s current URL’s scheme to "https" if all of the following
  467. // conditions are true:
  468. // - request’s current URL’s scheme is "http"
  469. // - request’s current URL’s host is a domain
  470. // - Matching request’s current URL’s host per Known HSTS Host Domain Name
  471. // Matching results in either a superdomain match with an asserted
  472. // includeSubDomains directive or a congruent match (with or without an
  473. // asserted includeSubDomains directive). [HSTS]
  474. // TODO
  475. // 10. If recursive is false, then run the remaining steps in parallel.
  476. // TODO
  477. // 11. If response is null, then set response to the result of running
  478. // the steps corresponding to the first matching statement:
  479. if (response === null) {
  480. const currentURL = requestCurrentURL(request)
  481. if (
  482. // - request’s current URL’s origin is same origin with request’s origin,
  483. // and request’s response tainting is "basic"
  484. (sameOrigin(currentURL, request.url) && request.responseTainting === 'basic') ||
  485. // request’s current URL’s scheme is "data"
  486. (currentURL.protocol === 'data:') ||
  487. // - request’s mode is "navigate" or "websocket"
  488. (request.mode === 'navigate' || request.mode === 'websocket')
  489. ) {
  490. // 1. Set request’s response tainting to "basic".
  491. request.responseTainting = 'basic'
  492. // 2. Return the result of running scheme fetch given fetchParams.
  493. response = await schemeFetch(fetchParams)
  494. // request’s mode is "same-origin"
  495. } else if (request.mode === 'same-origin') {
  496. // 1. Return a network error.
  497. response = makeNetworkError('request mode cannot be "same-origin"')
  498. // request’s mode is "no-cors"
  499. } else if (request.mode === 'no-cors') {
  500. // 1. If request’s redirect mode is not "follow", then return a network
  501. // error.
  502. if (request.redirect !== 'follow') {
  503. response = makeNetworkError(
  504. 'redirect mode cannot be "follow" for "no-cors" request'
  505. )
  506. } else {
  507. // 2. Set request’s response tainting to "opaque".
  508. request.responseTainting = 'opaque'
  509. // 3. Return the result of running scheme fetch given fetchParams.
  510. response = await schemeFetch(fetchParams)
  511. }
  512. // request’s current URL’s scheme is not an HTTP(S) scheme
  513. } else if (!urlIsHttpHttpsScheme(requestCurrentURL(request))) {
  514. // Return a network error.
  515. response = makeNetworkError('URL scheme must be a HTTP(S) scheme')
  516. // - request’s use-CORS-preflight flag is set
  517. // - request’s unsafe-request flag is set and either request’s method is
  518. // not a CORS-safelisted method or CORS-unsafe request-header names with
  519. // request’s header list is not empty
  520. // 1. Set request’s response tainting to "cors".
  521. // 2. Let corsWithPreflightResponse be the result of running HTTP fetch
  522. // given fetchParams and true.
  523. // 3. If corsWithPreflightResponse is a network error, then clear cache
  524. // entries using request.
  525. // 4. Return corsWithPreflightResponse.
  526. // TODO
  527. // Otherwise
  528. } else {
  529. // 1. Set request’s response tainting to "cors".
  530. request.responseTainting = 'cors'
  531. // 2. Return the result of running HTTP fetch given fetchParams.
  532. response = await httpFetch(fetchParams)
  533. }
  534. }
  535. // 12. If recursive is true, then return response.
  536. if (recursive) {
  537. return response
  538. }
  539. // 13. If response is not a network error and response is not a filtered
  540. // response, then:
  541. if (response.status !== 0 && !response.internalResponse) {
  542. // If request’s response tainting is "cors", then:
  543. if (request.responseTainting === 'cors') {
  544. // 1. Let headerNames be the result of extracting header list values
  545. // given `Access-Control-Expose-Headers` and response’s header list.
  546. // TODO
  547. // 2. If request’s credentials mode is not "include" and headerNames
  548. // contains `*`, then set response’s CORS-exposed header-name list to
  549. // all unique header names in response’s header list.
  550. // TODO
  551. // 3. Otherwise, if headerNames is not null or failure, then set
  552. // response’s CORS-exposed header-name list to headerNames.
  553. // TODO
  554. }
  555. // Set response to the following filtered response with response as its
  556. // internal response, depending on request’s response tainting:
  557. if (request.responseTainting === 'basic') {
  558. response = filterResponse(response, 'basic')
  559. } else if (request.responseTainting === 'cors') {
  560. response = filterResponse(response, 'cors')
  561. } else if (request.responseTainting === 'opaque') {
  562. response = filterResponse(response, 'opaque')
  563. } else {
  564. assert(false)
  565. }
  566. }
  567. // 14. Let internalResponse be response, if response is a network error,
  568. // and response’s internal response otherwise.
  569. let internalResponse =
  570. response.status === 0 ? response : response.internalResponse
  571. // 15. If internalResponse’s URL list is empty, then set it to a clone of
  572. // request’s URL list.
  573. if (internalResponse.urlList.length === 0) {
  574. internalResponse.urlList.push(...request.urlList)
  575. }
  576. // 16. If request’s timing allow failed flag is unset, then set
  577. // internalResponse’s timing allow passed flag.
  578. if (!request.timingAllowFailed) {
  579. response.timingAllowPassed = true
  580. }
  581. // 17. If response is not a network error and any of the following returns
  582. // blocked
  583. // - should internalResponse to request be blocked as mixed content
  584. // - should internalResponse to request be blocked by Content Security Policy
  585. // - should internalResponse to request be blocked due to its MIME type
  586. // - should internalResponse to request be blocked due to nosniff
  587. // TODO
  588. // 18. If response’s type is "opaque", internalResponse’s status is 206,
  589. // internalResponse’s range-requested flag is set, and request’s header
  590. // list does not contain `Range`, then set response and internalResponse
  591. // to a network error.
  592. if (
  593. response.type === 'opaque' &&
  594. internalResponse.status === 206 &&
  595. internalResponse.rangeRequested &&
  596. !request.headers.contains('range', true)
  597. ) {
  598. response = internalResponse = makeNetworkError()
  599. }
  600. // 19. If response is not a network error and either request’s method is
  601. // `HEAD` or `CONNECT`, or internalResponse’s status is a null body status,
  602. // set internalResponse’s body to null and disregard any enqueuing toward
  603. // it (if any).
  604. if (
  605. response.status !== 0 &&
  606. (request.method === 'HEAD' ||
  607. request.method === 'CONNECT' ||
  608. nullBodyStatus.includes(internalResponse.status))
  609. ) {
  610. internalResponse.body = null
  611. fetchParams.controller.dump = true
  612. }
  613. // 20. If request’s integrity metadata is not the empty string, then:
  614. if (request.integrity) {
  615. // 1. Let processBodyError be this step: run fetch finale given fetchParams
  616. // and a network error.
  617. const processBodyError = (reason) =>
  618. fetchFinale(fetchParams, makeNetworkError(reason))
  619. // 2. If request’s response tainting is "opaque", or response’s body is null,
  620. // then run processBodyError and abort these steps.
  621. if (request.responseTainting === 'opaque' || response.body == null) {
  622. processBodyError(response.error)
  623. return
  624. }
  625. // 3. Let processBody given bytes be these steps:
  626. const processBody = (bytes) => {
  627. // 1. If bytes do not match request’s integrity metadata,
  628. // then run processBodyError and abort these steps. [SRI]
  629. if (!bytesMatch(bytes, request.integrity)) {
  630. processBodyError('integrity mismatch')
  631. return
  632. }
  633. // 2. Set response’s body to bytes as a body.
  634. response.body = safelyExtractBody(bytes)[0]
  635. // 3. Run fetch finale given fetchParams and response.
  636. fetchFinale(fetchParams, response)
  637. }
  638. // 4. Fully read response’s body given processBody and processBodyError.
  639. fullyReadBody(response.body, processBody, processBodyError)
  640. } else {
  641. // 21. Otherwise, run fetch finale given fetchParams and response.
  642. fetchFinale(fetchParams, response)
  643. }
  644. } catch (err) {
  645. fetchParams.controller.terminate(err)
  646. }
  647. }
  648. // https://fetch.spec.whatwg.org/#concept-scheme-fetch
  649. // given a fetch params fetchParams
  650. function schemeFetch (fetchParams) {
  651. // Note: since the connection is destroyed on redirect, which sets fetchParams to a
  652. // cancelled state, we do not want this condition to trigger *unless* there have been
  653. // no redirects. See https://github.com/nodejs/undici/issues/1776
  654. // 1. If fetchParams is canceled, then return the appropriate network error for fetchParams.
  655. if (isCancelled(fetchParams) && fetchParams.request.redirectCount === 0) {
  656. return Promise.resolve(makeAppropriateNetworkError(fetchParams))
  657. }
  658. // 2. Let request be fetchParams’s request.
  659. const { request } = fetchParams
  660. const { protocol: scheme } = requestCurrentURL(request)
  661. // 3. Switch on request’s current URL’s scheme and run the associated steps:
  662. switch (scheme) {
  663. case 'about:': {
  664. // If request’s current URL’s path is the string "blank", then return a new response
  665. // whose status message is `OK`, header list is « (`Content-Type`, `text/html;charset=utf-8`) »,
  666. // and body is the empty byte sequence as a body.
  667. // Otherwise, return a network error.
  668. return Promise.resolve(makeNetworkError('about scheme is not supported'))
  669. }
  670. case 'blob:': {
  671. if (!resolveObjectURL) {
  672. resolveObjectURL = require('node:buffer').resolveObjectURL
  673. }
  674. // 1. Let blobURLEntry be request’s current URL’s blob URL entry.
  675. const blobURLEntry = requestCurrentURL(request)
  676. // https://github.com/web-platform-tests/wpt/blob/7b0ebaccc62b566a1965396e5be7bb2bc06f841f/FileAPI/url/resources/fetch-tests.js#L52-L56
  677. // Buffer.resolveObjectURL does not ignore URL queries.
  678. if (blobURLEntry.search.length !== 0) {
  679. return Promise.resolve(makeNetworkError('NetworkError when attempting to fetch resource.'))
  680. }
  681. const blob = resolveObjectURL(blobURLEntry.toString())
  682. // 2. If request’s method is not `GET`, blobURLEntry is null, or blobURLEntry’s
  683. // object is not a Blob object, then return a network error.
  684. if (request.method !== 'GET' || !webidl.is.Blob(blob)) {
  685. return Promise.resolve(makeNetworkError('invalid method'))
  686. }
  687. // 3. Let blob be blobURLEntry’s object.
  688. // Note: done above
  689. // 4. Let response be a new response.
  690. const response = makeResponse()
  691. // 5. Let fullLength be blob’s size.
  692. const fullLength = blob.size
  693. // 6. Let serializedFullLength be fullLength, serialized and isomorphic encoded.
  694. const serializedFullLength = isomorphicEncode(`${fullLength}`)
  695. // 7. Let type be blob’s type.
  696. const type = blob.type
  697. // 8. If request’s header list does not contain `Range`:
  698. // 9. Otherwise:
  699. if (!request.headersList.contains('range', true)) {
  700. // 1. Let bodyWithType be the result of safely extracting blob.
  701. // Note: in the FileAPI a blob "object" is a Blob *or* a MediaSource.
  702. // In node, this can only ever be a Blob. Therefore we can safely
  703. // use extractBody directly.
  704. const bodyWithType = extractBody(blob)
  705. // 2. Set response’s status message to `OK`.
  706. response.statusText = 'OK'
  707. // 3. Set response’s body to bodyWithType’s body.
  708. response.body = bodyWithType[0]
  709. // 4. Set response’s header list to « (`Content-Length`, serializedFullLength), (`Content-Type`, type) ».
  710. response.headersList.set('content-length', serializedFullLength, true)
  711. response.headersList.set('content-type', type, true)
  712. } else {
  713. // 1. Set response’s range-requested flag.
  714. response.rangeRequested = true
  715. // 2. Let rangeHeader be the result of getting `Range` from request’s header list.
  716. const rangeHeader = request.headersList.get('range', true)
  717. // 3. Let rangeValue be the result of parsing a single range header value given rangeHeader and true.
  718. const rangeValue = simpleRangeHeaderValue(rangeHeader, true)
  719. // 4. If rangeValue is failure, then return a network error.
  720. if (rangeValue === 'failure') {
  721. return Promise.resolve(makeNetworkError('failed to fetch the data URL'))
  722. }
  723. // 5. Let (rangeStart, rangeEnd) be rangeValue.
  724. let { rangeStartValue: rangeStart, rangeEndValue: rangeEnd } = rangeValue
  725. // 6. If rangeStart is null:
  726. // 7. Otherwise:
  727. if (rangeStart === null) {
  728. // 1. Set rangeStart to fullLength − rangeEnd.
  729. rangeStart = fullLength - rangeEnd
  730. // 2. Set rangeEnd to rangeStart + rangeEnd − 1.
  731. rangeEnd = rangeStart + rangeEnd - 1
  732. } else {
  733. // 1. If rangeStart is greater than or equal to fullLength, then return a network error.
  734. if (rangeStart >= fullLength) {
  735. return Promise.resolve(makeNetworkError('Range start is greater than the blob\'s size.'))
  736. }
  737. // 2. If rangeEnd is null or rangeEnd is greater than or equal to fullLength, then set
  738. // rangeEnd to fullLength − 1.
  739. if (rangeEnd === null || rangeEnd >= fullLength) {
  740. rangeEnd = fullLength - 1
  741. }
  742. }
  743. // 8. Let slicedBlob be the result of invoking slice blob given blob, rangeStart,
  744. // rangeEnd + 1, and type.
  745. const slicedBlob = blob.slice(rangeStart, rangeEnd + 1, type)
  746. // 9. Let slicedBodyWithType be the result of safely extracting slicedBlob.
  747. // Note: same reason as mentioned above as to why we use extractBody
  748. const slicedBodyWithType = extractBody(slicedBlob)
  749. // 10. Set response’s body to slicedBodyWithType’s body.
  750. response.body = slicedBodyWithType[0]
  751. // 11. Let serializedSlicedLength be slicedBlob’s size, serialized and isomorphic encoded.
  752. const serializedSlicedLength = isomorphicEncode(`${slicedBlob.size}`)
  753. // 12. Let contentRange be the result of invoking build a content range given rangeStart,
  754. // rangeEnd, and fullLength.
  755. const contentRange = buildContentRange(rangeStart, rangeEnd, fullLength)
  756. // 13. Set response’s status to 206.
  757. response.status = 206
  758. // 14. Set response’s status message to `Partial Content`.
  759. response.statusText = 'Partial Content'
  760. // 15. Set response’s header list to « (`Content-Length`, serializedSlicedLength),
  761. // (`Content-Type`, type), (`Content-Range`, contentRange) ».
  762. response.headersList.set('content-length', serializedSlicedLength, true)
  763. response.headersList.set('content-type', type, true)
  764. response.headersList.set('content-range', contentRange, true)
  765. }
  766. // 10. Return response.
  767. return Promise.resolve(response)
  768. }
  769. case 'data:': {
  770. // 1. Let dataURLStruct be the result of running the
  771. // data: URL processor on request’s current URL.
  772. const currentURL = requestCurrentURL(request)
  773. const dataURLStruct = dataURLProcessor(currentURL)
  774. // 2. If dataURLStruct is failure, then return a
  775. // network error.
  776. if (dataURLStruct === 'failure') {
  777. return Promise.resolve(makeNetworkError('failed to fetch the data URL'))
  778. }
  779. // 3. Let mimeType be dataURLStruct’s MIME type, serialized.
  780. const mimeType = serializeAMimeType(dataURLStruct.mimeType)
  781. // 4. Return a response whose status message is `OK`,
  782. // header list is « (`Content-Type`, mimeType) »,
  783. // and body is dataURLStruct’s body as a body.
  784. return Promise.resolve(makeResponse({
  785. statusText: 'OK',
  786. headersList: [
  787. ['content-type', { name: 'Content-Type', value: mimeType }]
  788. ],
  789. body: safelyExtractBody(dataURLStruct.body)[0]
  790. }))
  791. }
  792. case 'file:': {
  793. // For now, unfortunate as it is, file URLs are left as an exercise for the reader.
  794. // When in doubt, return a network error.
  795. return Promise.resolve(makeNetworkError('not implemented... yet...'))
  796. }
  797. case 'http:':
  798. case 'https:': {
  799. // Return the result of running HTTP fetch given fetchParams.
  800. return httpFetch(fetchParams)
  801. .catch((err) => makeNetworkError(err))
  802. }
  803. default: {
  804. return Promise.resolve(makeNetworkError('unknown scheme'))
  805. }
  806. }
  807. }
  808. // https://fetch.spec.whatwg.org/#finalize-response
  809. function finalizeResponse (fetchParams, response) {
  810. // 1. Set fetchParams’s request’s done flag.
  811. fetchParams.request.done = true
  812. // 2, If fetchParams’s process response done is not null, then queue a fetch
  813. // task to run fetchParams’s process response done given response, with
  814. // fetchParams’s task destination.
  815. if (fetchParams.processResponseDone != null) {
  816. queueMicrotask(() => fetchParams.processResponseDone(response))
  817. }
  818. }
  819. // https://fetch.spec.whatwg.org/#fetch-finale
  820. function fetchFinale (fetchParams, response) {
  821. // 1. Let timingInfo be fetchParams’s timing info.
  822. let timingInfo = fetchParams.timingInfo
  823. // 2. If response is not a network error and fetchParams’s request’s client is a secure context,
  824. // then set timingInfo’s server-timing headers to the result of getting, decoding, and splitting
  825. // `Server-Timing` from response’s internal response’s header list.
  826. // TODO
  827. // 3. Let processResponseEndOfBody be the following steps:
  828. const processResponseEndOfBody = () => {
  829. // 1. Let unsafeEndTime be the unsafe shared current time.
  830. const unsafeEndTime = Date.now() // ?
  831. // 2. If fetchParams’s request’s destination is "document", then set fetchParams’s controller’s
  832. // full timing info to fetchParams’s timing info.
  833. if (fetchParams.request.destination === 'document') {
  834. fetchParams.controller.fullTimingInfo = timingInfo
  835. }
  836. // 3. Set fetchParams’s controller’s report timing steps to the following steps given a global object global:
  837. fetchParams.controller.reportTimingSteps = () => {
  838. // 1. If fetchParams’s request’s URL’s scheme is not an HTTP(S) scheme, then return.
  839. if (!urlIsHttpHttpsScheme(fetchParams.request.url)) {
  840. return
  841. }
  842. // 2. Set timingInfo’s end time to the relative high resolution time given unsafeEndTime and global.
  843. timingInfo.endTime = unsafeEndTime
  844. // 3. Let cacheState be response’s cache state.
  845. let cacheState = response.cacheState
  846. // 4. Let bodyInfo be response’s body info.
  847. const bodyInfo = response.bodyInfo
  848. // 5. If response’s timing allow passed flag is not set, then set timingInfo to the result of creating an
  849. // opaque timing info for timingInfo and set cacheState to the empty string.
  850. if (!response.timingAllowPassed) {
  851. timingInfo = createOpaqueTimingInfo(timingInfo)
  852. cacheState = ''
  853. }
  854. // 6. Let responseStatus be 0.
  855. let responseStatus = 0
  856. // 7. If fetchParams’s request’s mode is not "navigate" or response’s has-cross-origin-redirects is false:
  857. if (fetchParams.request.mode !== 'navigator' || !response.hasCrossOriginRedirects) {
  858. // 1. Set responseStatus to response’s status.
  859. responseStatus = response.status
  860. // 2. Let mimeType be the result of extracting a MIME type from response’s header list.
  861. const mimeType = extractMimeType(response.headersList)
  862. // 3. If mimeType is not failure, then set bodyInfo’s content type to the result of minimizing a supported MIME type given mimeType.
  863. if (mimeType !== 'failure') {
  864. bodyInfo.contentType = minimizeSupportedMimeType(mimeType)
  865. }
  866. }
  867. // 8. If fetchParams’s request’s initiator type is non-null, then mark resource timing given timingInfo,
  868. // fetchParams’s request’s URL, fetchParams’s request’s initiator type, global, cacheState, bodyInfo,
  869. // and responseStatus.
  870. if (fetchParams.request.initiatorType != null) {
  871. markResourceTiming(timingInfo, fetchParams.request.url.href, fetchParams.request.initiatorType, globalThis, cacheState, bodyInfo, responseStatus)
  872. }
  873. }
  874. // 4. Let processResponseEndOfBodyTask be the following steps:
  875. const processResponseEndOfBodyTask = () => {
  876. // 1. Set fetchParams’s request’s done flag.
  877. fetchParams.request.done = true
  878. // 2. If fetchParams’s process response end-of-body is non-null, then run fetchParams’s process
  879. // response end-of-body given response.
  880. if (fetchParams.processResponseEndOfBody != null) {
  881. queueMicrotask(() => fetchParams.processResponseEndOfBody(response))
  882. }
  883. // 3. If fetchParams’s request’s initiator type is non-null and fetchParams’s request’s client’s
  884. // global object is fetchParams’s task destination, then run fetchParams’s controller’s report
  885. // timing steps given fetchParams’s request’s client’s global object.
  886. if (fetchParams.request.initiatorType != null) {
  887. fetchParams.controller.reportTimingSteps()
  888. }
  889. }
  890. // 5. Queue a fetch task to run processResponseEndOfBodyTask with fetchParams’s task destination
  891. queueMicrotask(() => processResponseEndOfBodyTask())
  892. }
  893. // 4. If fetchParams’s process response is non-null, then queue a fetch task to run fetchParams’s
  894. // process response given response, with fetchParams’s task destination.
  895. if (fetchParams.processResponse != null) {
  896. queueMicrotask(() => {
  897. fetchParams.processResponse(response)
  898. fetchParams.processResponse = null
  899. })
  900. }
  901. // 5. Let internalResponse be response, if response is a network error; otherwise response’s internal response.
  902. const internalResponse = response.type === 'error' ? response : (response.internalResponse ?? response)
  903. // 6. If internalResponse’s body is null, then run processResponseEndOfBody.
  904. // 7. Otherwise:
  905. if (internalResponse.body == null) {
  906. processResponseEndOfBody()
  907. } else {
  908. // mcollina: all the following steps of the specs are skipped.
  909. // The internal transform stream is not needed.
  910. // See https://github.com/nodejs/undici/pull/3093#issuecomment-2050198541
  911. // 1. Let transformStream be a new TransformStream.
  912. // 2. Let identityTransformAlgorithm be an algorithm which, given chunk, enqueues chunk in transformStream.
  913. // 3. Set up transformStream with transformAlgorithm set to identityTransformAlgorithm and flushAlgorithm
  914. // set to processResponseEndOfBody.
  915. // 4. Set internalResponse’s body’s stream to the result of internalResponse’s body’s stream piped through transformStream.
  916. finished(internalResponse.body.stream, () => {
  917. processResponseEndOfBody()
  918. })
  919. }
  920. }
  921. // https://fetch.spec.whatwg.org/#http-fetch
  922. async function httpFetch (fetchParams) {
  923. // 1. Let request be fetchParams’s request.
  924. const request = fetchParams.request
  925. // 2. Let response be null.
  926. let response = null
  927. // 3. Let actualResponse be null.
  928. let actualResponse = null
  929. // 4. Let timingInfo be fetchParams’s timing info.
  930. const timingInfo = fetchParams.timingInfo
  931. // 5. If request’s service-workers mode is "all", then:
  932. if (request.serviceWorkers === 'all') {
  933. // TODO
  934. }
  935. // 6. If response is null, then:
  936. if (response === null) {
  937. // 1. If makeCORSPreflight is true and one of these conditions is true:
  938. // TODO
  939. // 2. If request’s redirect mode is "follow", then set request’s
  940. // service-workers mode to "none".
  941. if (request.redirect === 'follow') {
  942. request.serviceWorkers = 'none'
  943. }
  944. // 3. Set response and actualResponse to the result of running
  945. // HTTP-network-or-cache fetch given fetchParams.
  946. actualResponse = response = await httpNetworkOrCacheFetch(fetchParams)
  947. // 4. If request’s response tainting is "cors" and a CORS check
  948. // for request and response returns failure, then return a network error.
  949. if (
  950. request.responseTainting === 'cors' &&
  951. corsCheck(request, response) === 'failure'
  952. ) {
  953. return makeNetworkError('cors failure')
  954. }
  955. // 5. If the TAO check for request and response returns failure, then set
  956. // request’s timing allow failed flag.
  957. if (TAOCheck(request, response) === 'failure') {
  958. request.timingAllowFailed = true
  959. }
  960. }
  961. // 7. If either request’s response tainting or response’s type
  962. // is "opaque", and the cross-origin resource policy check with
  963. // request’s origin, request’s client, request’s destination,
  964. // and actualResponse returns blocked, then return a network error.
  965. if (
  966. (request.responseTainting === 'opaque' || response.type === 'opaque') &&
  967. crossOriginResourcePolicyCheck(
  968. request.origin,
  969. request.client,
  970. request.destination,
  971. actualResponse
  972. ) === 'blocked'
  973. ) {
  974. return makeNetworkError('blocked')
  975. }
  976. // 8. If actualResponse’s status is a redirect status, then:
  977. if (redirectStatusSet.has(actualResponse.status)) {
  978. // 1. If actualResponse’s status is not 303, request’s body is not null,
  979. // and the connection uses HTTP/2, then user agents may, and are even
  980. // encouraged to, transmit an RST_STREAM frame.
  981. // See, https://github.com/whatwg/fetch/issues/1288
  982. if (request.redirect !== 'manual') {
  983. fetchParams.controller.connection.destroy(undefined, false)
  984. }
  985. // 2. Switch on request’s redirect mode:
  986. if (request.redirect === 'error') {
  987. // Set response to a network error.
  988. response = makeNetworkError('unexpected redirect')
  989. } else if (request.redirect === 'manual') {
  990. // Set response to an opaque-redirect filtered response whose internal
  991. // response is actualResponse.
  992. // NOTE(spec): On the web this would return an `opaqueredirect` response,
  993. // but that doesn't make sense server side.
  994. // See https://github.com/nodejs/undici/issues/1193.
  995. response = actualResponse
  996. } else if (request.redirect === 'follow') {
  997. // Set response to the result of running HTTP-redirect fetch given
  998. // fetchParams and response.
  999. response = await httpRedirectFetch(fetchParams, response)
  1000. } else {
  1001. assert(false)
  1002. }
  1003. }
  1004. // 9. Set response’s timing info to timingInfo.
  1005. response.timingInfo = timingInfo
  1006. // 10. Return response.
  1007. return response
  1008. }
  1009. // https://fetch.spec.whatwg.org/#http-redirect-fetch
  1010. function httpRedirectFetch (fetchParams, response) {
  1011. // 1. Let request be fetchParams’s request.
  1012. const request = fetchParams.request
  1013. // 2. Let actualResponse be response, if response is not a filtered response,
  1014. // and response’s internal response otherwise.
  1015. const actualResponse = response.internalResponse
  1016. ? response.internalResponse
  1017. : response
  1018. // 3. Let locationURL be actualResponse’s location URL given request’s current
  1019. // URL’s fragment.
  1020. let locationURL
  1021. try {
  1022. locationURL = responseLocationURL(
  1023. actualResponse,
  1024. requestCurrentURL(request).hash
  1025. )
  1026. // 4. If locationURL is null, then return response.
  1027. if (locationURL == null) {
  1028. return response
  1029. }
  1030. } catch (err) {
  1031. // 5. If locationURL is failure, then return a network error.
  1032. return Promise.resolve(makeNetworkError(err))
  1033. }
  1034. // 6. If locationURL’s scheme is not an HTTP(S) scheme, then return a network
  1035. // error.
  1036. if (!urlIsHttpHttpsScheme(locationURL)) {
  1037. return Promise.resolve(makeNetworkError('URL scheme must be a HTTP(S) scheme'))
  1038. }
  1039. // 7. If request’s redirect count is 20, then return a network error.
  1040. if (request.redirectCount === 20) {
  1041. return Promise.resolve(makeNetworkError('redirect count exceeded'))
  1042. }
  1043. // 8. Increase request’s redirect count by 1.
  1044. request.redirectCount += 1
  1045. // 9. If request’s mode is "cors", locationURL includes credentials, and
  1046. // request’s origin is not same origin with locationURL’s origin, then return
  1047. // a network error.
  1048. if (
  1049. request.mode === 'cors' &&
  1050. (locationURL.username || locationURL.password) &&
  1051. !sameOrigin(request, locationURL)
  1052. ) {
  1053. return Promise.resolve(makeNetworkError('cross origin not allowed for request mode "cors"'))
  1054. }
  1055. // 10. If request’s response tainting is "cors" and locationURL includes
  1056. // credentials, then return a network error.
  1057. if (
  1058. request.responseTainting === 'cors' &&
  1059. (locationURL.username || locationURL.password)
  1060. ) {
  1061. return Promise.resolve(makeNetworkError(
  1062. 'URL cannot contain credentials for request mode "cors"'
  1063. ))
  1064. }
  1065. // 11. If actualResponse’s status is not 303, request’s body is non-null,
  1066. // and request’s body’s source is null, then return a network error.
  1067. if (
  1068. actualResponse.status !== 303 &&
  1069. request.body != null &&
  1070. request.body.source == null
  1071. ) {
  1072. return Promise.resolve(makeNetworkError())
  1073. }
  1074. // 12. If one of the following is true
  1075. // - actualResponse’s status is 301 or 302 and request’s method is `POST`
  1076. // - actualResponse’s status is 303 and request’s method is not `GET` or `HEAD`
  1077. if (
  1078. ([301, 302].includes(actualResponse.status) && request.method === 'POST') ||
  1079. (actualResponse.status === 303 &&
  1080. !GET_OR_HEAD.includes(request.method))
  1081. ) {
  1082. // then:
  1083. // 1. Set request’s method to `GET` and request’s body to null.
  1084. request.method = 'GET'
  1085. request.body = null
  1086. // 2. For each headerName of request-body-header name, delete headerName from
  1087. // request’s header list.
  1088. for (const headerName of requestBodyHeader) {
  1089. request.headersList.delete(headerName)
  1090. }
  1091. }
  1092. // 13. If request’s current URL’s origin is not same origin with locationURL’s
  1093. // origin, then for each headerName of CORS non-wildcard request-header name,
  1094. // delete headerName from request’s header list.
  1095. if (!sameOrigin(requestCurrentURL(request), locationURL)) {
  1096. // https://fetch.spec.whatwg.org/#cors-non-wildcard-request-header-name
  1097. request.headersList.delete('authorization', true)
  1098. // https://fetch.spec.whatwg.org/#authentication-entries
  1099. request.headersList.delete('proxy-authorization', true)
  1100. // "Cookie" and "Host" are forbidden request-headers, which undici doesn't implement.
  1101. request.headersList.delete('cookie', true)
  1102. request.headersList.delete('host', true)
  1103. }
  1104. // 14. If request's body is non-null, then set request's body to the first return
  1105. // value of safely extracting request's body's source.
  1106. if (request.body != null) {
  1107. assert(request.body.source != null)
  1108. request.body = safelyExtractBody(request.body.source)[0]
  1109. }
  1110. // 15. Let timingInfo be fetchParams’s timing info.
  1111. const timingInfo = fetchParams.timingInfo
  1112. // 16. Set timingInfo’s redirect end time and post-redirect start time to the
  1113. // coarsened shared current time given fetchParams’s cross-origin isolated
  1114. // capability.
  1115. timingInfo.redirectEndTime = timingInfo.postRedirectStartTime =
  1116. coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability)
  1117. // 17. If timingInfo’s redirect start time is 0, then set timingInfo’s
  1118. // redirect start time to timingInfo’s start time.
  1119. if (timingInfo.redirectStartTime === 0) {
  1120. timingInfo.redirectStartTime = timingInfo.startTime
  1121. }
  1122. // 18. Append locationURL to request’s URL list.
  1123. request.urlList.push(locationURL)
  1124. // 19. Invoke set request’s referrer policy on redirect on request and
  1125. // actualResponse.
  1126. setRequestReferrerPolicyOnRedirect(request, actualResponse)
  1127. // 20. Return the result of running main fetch given fetchParams and true.
  1128. return mainFetch(fetchParams, true)
  1129. }
  1130. // https://fetch.spec.whatwg.org/#http-network-or-cache-fetch
  1131. async function httpNetworkOrCacheFetch (
  1132. fetchParams,
  1133. isAuthenticationFetch = false,
  1134. isNewConnectionFetch = false
  1135. ) {
  1136. // 1. Let request be fetchParams’s request.
  1137. const request = fetchParams.request
  1138. // 2. Let httpFetchParams be null.
  1139. let httpFetchParams = null
  1140. // 3. Let httpRequest be null.
  1141. let httpRequest = null
  1142. // 4. Let response be null.
  1143. let response = null
  1144. // 5. Let storedResponse be null.
  1145. // TODO: cache
  1146. // 6. Let httpCache be null.
  1147. const httpCache = null
  1148. // 7. Let the revalidatingFlag be unset.
  1149. const revalidatingFlag = false
  1150. // 8. Run these steps, but abort when the ongoing fetch is terminated:
  1151. // 1. If request’s window is "no-window" and request’s redirect mode is
  1152. // "error", then set httpFetchParams to fetchParams and httpRequest to
  1153. // request.
  1154. if (request.window === 'no-window' && request.redirect === 'error') {
  1155. httpFetchParams = fetchParams
  1156. httpRequest = request
  1157. } else {
  1158. // Otherwise:
  1159. // 1. Set httpRequest to a clone of request.
  1160. httpRequest = cloneRequest(request)
  1161. // 2. Set httpFetchParams to a copy of fetchParams.
  1162. httpFetchParams = { ...fetchParams }
  1163. // 3. Set httpFetchParams’s request to httpRequest.
  1164. httpFetchParams.request = httpRequest
  1165. }
  1166. // 3. Let includeCredentials be true if one of
  1167. const includeCredentials =
  1168. request.credentials === 'include' ||
  1169. (request.credentials === 'same-origin' &&
  1170. request.responseTainting === 'basic')
  1171. // 4. Let contentLength be httpRequest’s body’s length, if httpRequest’s
  1172. // body is non-null; otherwise null.
  1173. const contentLength = httpRequest.body ? httpRequest.body.length : null
  1174. // 5. Let contentLengthHeaderValue be null.
  1175. let contentLengthHeaderValue = null
  1176. // 6. If httpRequest’s body is null and httpRequest’s method is `POST` or
  1177. // `PUT`, then set contentLengthHeaderValue to `0`.
  1178. if (
  1179. httpRequest.body == null &&
  1180. ['POST', 'PUT'].includes(httpRequest.method)
  1181. ) {
  1182. contentLengthHeaderValue = '0'
  1183. }
  1184. // 7. If contentLength is non-null, then set contentLengthHeaderValue to
  1185. // contentLength, serialized and isomorphic encoded.
  1186. if (contentLength != null) {
  1187. contentLengthHeaderValue = isomorphicEncode(`${contentLength}`)
  1188. }
  1189. // 8. If contentLengthHeaderValue is non-null, then append
  1190. // `Content-Length`/contentLengthHeaderValue to httpRequest’s header
  1191. // list.
  1192. if (contentLengthHeaderValue != null) {
  1193. httpRequest.headersList.append('content-length', contentLengthHeaderValue, true)
  1194. }
  1195. // 9. If contentLengthHeaderValue is non-null, then append (`Content-Length`,
  1196. // contentLengthHeaderValue) to httpRequest’s header list.
  1197. // 10. If contentLength is non-null and httpRequest’s keepalive is true,
  1198. // then:
  1199. if (contentLength != null && httpRequest.keepalive) {
  1200. // NOTE: keepalive is a noop outside of browser context.
  1201. }
  1202. // 11. If httpRequest’s referrer is a URL, then append
  1203. // `Referer`/httpRequest’s referrer, serialized and isomorphic encoded,
  1204. // to httpRequest’s header list.
  1205. if (webidl.is.URL(httpRequest.referrer)) {
  1206. httpRequest.headersList.append('referer', isomorphicEncode(httpRequest.referrer.href), true)
  1207. }
  1208. // 12. Append a request `Origin` header for httpRequest.
  1209. appendRequestOriginHeader(httpRequest)
  1210. // 13. Append the Fetch metadata headers for httpRequest. [FETCH-METADATA]
  1211. appendFetchMetadata(httpRequest)
  1212. // 14. If httpRequest’s header list does not contain `User-Agent`, then
  1213. // user agents should append `User-Agent`/default `User-Agent` value to
  1214. // httpRequest’s header list.
  1215. if (!httpRequest.headersList.contains('user-agent', true)) {
  1216. httpRequest.headersList.append('user-agent', defaultUserAgent, true)
  1217. }
  1218. // 15. If httpRequest’s cache mode is "default" and httpRequest’s header
  1219. // list contains `If-Modified-Since`, `If-None-Match`,
  1220. // `If-Unmodified-Since`, `If-Match`, or `If-Range`, then set
  1221. // httpRequest’s cache mode to "no-store".
  1222. if (
  1223. httpRequest.cache === 'default' &&
  1224. (httpRequest.headersList.contains('if-modified-since', true) ||
  1225. httpRequest.headersList.contains('if-none-match', true) ||
  1226. httpRequest.headersList.contains('if-unmodified-since', true) ||
  1227. httpRequest.headersList.contains('if-match', true) ||
  1228. httpRequest.headersList.contains('if-range', true))
  1229. ) {
  1230. httpRequest.cache = 'no-store'
  1231. }
  1232. // 16. If httpRequest’s cache mode is "no-cache", httpRequest’s prevent
  1233. // no-cache cache-control header modification flag is unset, and
  1234. // httpRequest’s header list does not contain `Cache-Control`, then append
  1235. // `Cache-Control`/`max-age=0` to httpRequest’s header list.
  1236. if (
  1237. httpRequest.cache === 'no-cache' &&
  1238. !httpRequest.preventNoCacheCacheControlHeaderModification &&
  1239. !httpRequest.headersList.contains('cache-control', true)
  1240. ) {
  1241. httpRequest.headersList.append('cache-control', 'max-age=0', true)
  1242. }
  1243. // 17. If httpRequest’s cache mode is "no-store" or "reload", then:
  1244. if (httpRequest.cache === 'no-store' || httpRequest.cache === 'reload') {
  1245. // 1. If httpRequest’s header list does not contain `Pragma`, then append
  1246. // `Pragma`/`no-cache` to httpRequest’s header list.
  1247. if (!httpRequest.headersList.contains('pragma', true)) {
  1248. httpRequest.headersList.append('pragma', 'no-cache', true)
  1249. }
  1250. // 2. If httpRequest’s header list does not contain `Cache-Control`,
  1251. // then append `Cache-Control`/`no-cache` to httpRequest’s header list.
  1252. if (!httpRequest.headersList.contains('cache-control', true)) {
  1253. httpRequest.headersList.append('cache-control', 'no-cache', true)
  1254. }
  1255. }
  1256. // 18. If httpRequest’s header list contains `Range`, then append
  1257. // `Accept-Encoding`/`identity` to httpRequest’s header list.
  1258. if (httpRequest.headersList.contains('range', true)) {
  1259. httpRequest.headersList.append('accept-encoding', 'identity', true)
  1260. }
  1261. // 19. Modify httpRequest’s header list per HTTP. Do not append a given
  1262. // header if httpRequest’s header list contains that header’s name.
  1263. // TODO: https://github.com/whatwg/fetch/issues/1285#issuecomment-896560129
  1264. if (!httpRequest.headersList.contains('accept-encoding', true)) {
  1265. if (urlHasHttpsScheme(requestCurrentURL(httpRequest))) {
  1266. httpRequest.headersList.append('accept-encoding', 'br, gzip, deflate', true)
  1267. } else {
  1268. httpRequest.headersList.append('accept-encoding', 'gzip, deflate', true)
  1269. }
  1270. }
  1271. httpRequest.headersList.delete('host', true)
  1272. // 21. If includeCredentials is true, then:
  1273. if (includeCredentials) {
  1274. // 1. If the user agent is not configured to block cookies for httpRequest
  1275. // (see section 7 of [COOKIES]), then:
  1276. // TODO: credentials
  1277. // 2. If httpRequest’s header list does not contain `Authorization`, then:
  1278. if (!httpRequest.headersList.contains('authorization', true)) {
  1279. // 1. Let authorizationValue be null.
  1280. let authorizationValue = null
  1281. // 2. If there’s an authentication entry for httpRequest and either
  1282. // httpRequest’s use-URL-credentials flag is unset or httpRequest’s
  1283. // current URL does not include credentials, then set
  1284. // authorizationValue to authentication entry.
  1285. if (hasAuthenticationEntry(httpRequest) && (
  1286. httpRequest.useURLCredentials === undefined || !includesCredentials(requestCurrentURL(httpRequest))
  1287. )) {
  1288. // TODO
  1289. } else if (includesCredentials(requestCurrentURL(httpRequest)) && isAuthenticationFetch) {
  1290. // 3. Otherwise, if httpRequest’s current URL does include credentials
  1291. // and isAuthenticationFetch is true, set authorizationValue to
  1292. // httpRequest’s current URL, converted to an `Authorization` value
  1293. const { username, password } = requestCurrentURL(httpRequest)
  1294. authorizationValue = `Basic ${Buffer.from(`${username}:${password}`).toString('base64')}`
  1295. }
  1296. // 4. If authorizationValue is non-null, then append (`Authorization`,
  1297. // authorizationValue) to httpRequest’s header list.
  1298. if (authorizationValue !== null) {
  1299. httpRequest.headersList.append('Authorization', authorizationValue, false)
  1300. }
  1301. }
  1302. }
  1303. // 21. If there’s a proxy-authentication entry, use it as appropriate.
  1304. // TODO: proxy-authentication
  1305. // 22. Set httpCache to the result of determining the HTTP cache
  1306. // partition, given httpRequest.
  1307. // TODO: cache
  1308. // 23. If httpCache is null, then set httpRequest’s cache mode to
  1309. // "no-store".
  1310. if (httpCache == null) {
  1311. httpRequest.cache = 'no-store'
  1312. }
  1313. // 24. If httpRequest’s cache mode is neither "no-store" nor "reload",
  1314. // then:
  1315. if (httpRequest.cache !== 'no-store' && httpRequest.cache !== 'reload') {
  1316. // TODO: cache
  1317. }
  1318. // 9. If aborted, then return the appropriate network error for fetchParams.
  1319. // TODO
  1320. // 10. If response is null, then:
  1321. if (response == null) {
  1322. // 1. If httpRequest’s cache mode is "only-if-cached", then return a
  1323. // network error.
  1324. if (httpRequest.cache === 'only-if-cached') {
  1325. return makeNetworkError('only if cached')
  1326. }
  1327. // 2. Let forwardResponse be the result of running HTTP-network fetch
  1328. // given httpFetchParams, includeCredentials, and isNewConnectionFetch.
  1329. const forwardResponse = await httpNetworkFetch(
  1330. httpFetchParams,
  1331. includeCredentials,
  1332. isNewConnectionFetch
  1333. )
  1334. // 3. If httpRequest’s method is unsafe and forwardResponse’s status is
  1335. // in the range 200 to 399, inclusive, invalidate appropriate stored
  1336. // responses in httpCache, as per the "Invalidation" chapter of HTTP
  1337. // Caching, and set storedResponse to null. [HTTP-CACHING]
  1338. if (
  1339. !safeMethodsSet.has(httpRequest.method) &&
  1340. forwardResponse.status >= 200 &&
  1341. forwardResponse.status <= 399
  1342. ) {
  1343. // TODO: cache
  1344. }
  1345. // 4. If the revalidatingFlag is set and forwardResponse’s status is 304,
  1346. // then:
  1347. if (revalidatingFlag && forwardResponse.status === 304) {
  1348. // TODO: cache
  1349. }
  1350. // 5. If response is null, then:
  1351. if (response == null) {
  1352. // 1. Set response to forwardResponse.
  1353. response = forwardResponse
  1354. // 2. Store httpRequest and forwardResponse in httpCache, as per the
  1355. // "Storing Responses in Caches" chapter of HTTP Caching. [HTTP-CACHING]
  1356. // TODO: cache
  1357. }
  1358. }
  1359. // 11. Set response’s URL list to a clone of httpRequest’s URL list.
  1360. response.urlList = [...httpRequest.urlList]
  1361. // 12. If httpRequest’s header list contains `Range`, then set response’s
  1362. // range-requested flag.
  1363. if (httpRequest.headersList.contains('range', true)) {
  1364. response.rangeRequested = true
  1365. }
  1366. // 13. Set response’s request-includes-credentials to includeCredentials.
  1367. response.requestIncludesCredentials = includeCredentials
  1368. // 14. If response’s status is 401, httpRequest’s response tainting is not "cors",
  1369. // includeCredentials is true, and request’s traversable for user prompts is
  1370. // a traversable navigable:
  1371. if (response.status === 401 && httpRequest.responseTainting !== 'cors' && includeCredentials && isTraversableNavigable(request.traversableForUserPrompts)) {
  1372. // 2. If request’s body is non-null, then:
  1373. if (request.body != null) {
  1374. // 1. If request’s body’s source is null, then return a network error.
  1375. if (request.body.source == null) {
  1376. return makeNetworkError('expected non-null body source')
  1377. }
  1378. // 2. Set request’s body to the body of the result of safely extracting
  1379. // request’s body’s source.
  1380. request.body = safelyExtractBody(request.body.source)[0]
  1381. }
  1382. // 3. If request’s use-URL-credentials flag is unset or isAuthenticationFetch is
  1383. // true, then:
  1384. if (request.useURLCredentials === undefined || isAuthenticationFetch) {
  1385. // 1. If fetchParams is canceled, then return the appropriate network error
  1386. // for fetchParams.
  1387. if (isCancelled(fetchParams)) {
  1388. return makeAppropriateNetworkError(fetchParams)
  1389. }
  1390. // 2. Let username and password be the result of prompting the end user for a
  1391. // username and password, respectively, in request’s traversable for user prompts.
  1392. // TODO
  1393. // 3. Set the username given request’s current URL and username.
  1394. // requestCurrentURL(request).username = TODO
  1395. // 4. Set the password given request’s current URL and password.
  1396. // requestCurrentURL(request).password = TODO
  1397. // In browsers, the user will be prompted to enter a username/password before the request
  1398. // is re-sent. To prevent an infinite 401 loop, return the response for now.
  1399. // https://github.com/nodejs/undici/pull/4756
  1400. return response
  1401. }
  1402. // 4. Set response to the result of running HTTP-network-or-cache fetch given
  1403. // fetchParams and true.
  1404. fetchParams.controller.connection.destroy()
  1405. response = await httpNetworkOrCacheFetch(fetchParams, true)
  1406. }
  1407. // 15. If response’s status is 407, then:
  1408. if (response.status === 407) {
  1409. // 1. If request’s window is "no-window", then return a network error.
  1410. if (request.window === 'no-window') {
  1411. return makeNetworkError()
  1412. }
  1413. // 2. ???
  1414. // 3. If fetchParams is canceled, then return the appropriate network error for fetchParams.
  1415. if (isCancelled(fetchParams)) {
  1416. return makeAppropriateNetworkError(fetchParams)
  1417. }
  1418. // 4. Prompt the end user as appropriate in request’s window and store
  1419. // the result as a proxy-authentication entry. [HTTP-AUTH]
  1420. // TODO: Invoke some kind of callback?
  1421. // 5. Set response to the result of running HTTP-network-or-cache fetch given
  1422. // fetchParams.
  1423. // TODO
  1424. return makeNetworkError('proxy authentication required')
  1425. }
  1426. // 16. If all of the following are true
  1427. if (
  1428. // response’s status is 421
  1429. response.status === 421 &&
  1430. // isNewConnectionFetch is false
  1431. !isNewConnectionFetch &&
  1432. // request’s body is null, or request’s body is non-null and request’s body’s source is non-null
  1433. (request.body == null || request.body.source != null)
  1434. ) {
  1435. // then:
  1436. // 1. If fetchParams is canceled, then return the appropriate network error for fetchParams.
  1437. if (isCancelled(fetchParams)) {
  1438. return makeAppropriateNetworkError(fetchParams)
  1439. }
  1440. // 2. Set response to the result of running HTTP-network-or-cache
  1441. // fetch given fetchParams, isAuthenticationFetch, and true.
  1442. // TODO (spec): The spec doesn't specify this but we need to cancel
  1443. // the active response before we can start a new one.
  1444. // https://github.com/whatwg/fetch/issues/1293
  1445. fetchParams.controller.connection.destroy()
  1446. response = await httpNetworkOrCacheFetch(
  1447. fetchParams,
  1448. isAuthenticationFetch,
  1449. true
  1450. )
  1451. }
  1452. // 17. If isAuthenticationFetch is true, then create an authentication entry
  1453. if (isAuthenticationFetch) {
  1454. // TODO
  1455. }
  1456. // 18. Return response.
  1457. return response
  1458. }
  1459. // https://fetch.spec.whatwg.org/#http-network-fetch
  1460. async function httpNetworkFetch (
  1461. fetchParams,
  1462. includeCredentials = false,
  1463. forceNewConnection = false
  1464. ) {
  1465. assert(!fetchParams.controller.connection || fetchParams.controller.connection.destroyed)
  1466. fetchParams.controller.connection = {
  1467. abort: null,
  1468. destroyed: false,
  1469. destroy (err, abort = true) {
  1470. if (!this.destroyed) {
  1471. this.destroyed = true
  1472. if (abort) {
  1473. this.abort?.(err ?? new DOMException('The operation was aborted.', 'AbortError'))
  1474. }
  1475. }
  1476. }
  1477. }
  1478. // 1. Let request be fetchParams’s request.
  1479. const request = fetchParams.request
  1480. // 2. Let response be null.
  1481. let response = null
  1482. // 3. Let timingInfo be fetchParams’s timing info.
  1483. const timingInfo = fetchParams.timingInfo
  1484. // 4. Let httpCache be the result of determining the HTTP cache partition,
  1485. // given request.
  1486. // TODO: cache
  1487. const httpCache = null
  1488. // 5. If httpCache is null, then set request’s cache mode to "no-store".
  1489. if (httpCache == null) {
  1490. request.cache = 'no-store'
  1491. }
  1492. // 6. Let networkPartitionKey be the result of determining the network
  1493. // partition key given request.
  1494. // TODO
  1495. // 7. Let newConnection be "yes" if forceNewConnection is true; otherwise
  1496. // "no".
  1497. const newConnection = forceNewConnection ? 'yes' : 'no' // eslint-disable-line no-unused-vars
  1498. // 8. Switch on request’s mode:
  1499. if (request.mode === 'websocket') {
  1500. // Let connection be the result of obtaining a WebSocket connection,
  1501. // given request’s current URL.
  1502. // TODO
  1503. } else {
  1504. // Let connection be the result of obtaining a connection, given
  1505. // networkPartitionKey, request’s current URL’s origin,
  1506. // includeCredentials, and forceNewConnection.
  1507. // TODO
  1508. }
  1509. // 9. Run these steps, but abort when the ongoing fetch is terminated:
  1510. // 1. If connection is failure, then return a network error.
  1511. // 2. Set timingInfo’s final connection timing info to the result of
  1512. // calling clamp and coarsen connection timing info with connection’s
  1513. // timing info, timingInfo’s post-redirect start time, and fetchParams’s
  1514. // cross-origin isolated capability.
  1515. // 3. If connection is not an HTTP/2 connection, request’s body is non-null,
  1516. // and request’s body’s source is null, then append (`Transfer-Encoding`,
  1517. // `chunked`) to request’s header list.
  1518. // 4. Set timingInfo’s final network-request start time to the coarsened
  1519. // shared current time given fetchParams’s cross-origin isolated
  1520. // capability.
  1521. // 5. Set response to the result of making an HTTP request over connection
  1522. // using request with the following caveats:
  1523. // - Follow the relevant requirements from HTTP. [HTTP] [HTTP-SEMANTICS]
  1524. // [HTTP-COND] [HTTP-CACHING] [HTTP-AUTH]
  1525. // - If request’s body is non-null, and request’s body’s source is null,
  1526. // then the user agent may have a buffer of up to 64 kibibytes and store
  1527. // a part of request’s body in that buffer. If the user agent reads from
  1528. // request’s body beyond that buffer’s size and the user agent needs to
  1529. // resend request, then instead return a network error.
  1530. // - Set timingInfo’s final network-response start time to the coarsened
  1531. // shared current time given fetchParams’s cross-origin isolated capability,
  1532. // immediately after the user agent’s HTTP parser receives the first byte
  1533. // of the response (e.g., frame header bytes for HTTP/2 or response status
  1534. // line for HTTP/1.x).
  1535. // - Wait until all the headers are transmitted.
  1536. // - Any responses whose status is in the range 100 to 199, inclusive,
  1537. // and is not 101, are to be ignored, except for the purposes of setting
  1538. // timingInfo’s final network-response start time above.
  1539. // - If request’s header list contains `Transfer-Encoding`/`chunked` and
  1540. // response is transferred via HTTP/1.0 or older, then return a network
  1541. // error.
  1542. // - If the HTTP request results in a TLS client certificate dialog, then:
  1543. // 1. If request’s window is an environment settings object, make the
  1544. // dialog available in request’s window.
  1545. // 2. Otherwise, return a network error.
  1546. // To transmit request’s body body, run these steps:
  1547. let requestBody = null
  1548. // 1. If body is null and fetchParams’s process request end-of-body is
  1549. // non-null, then queue a fetch task given fetchParams’s process request
  1550. // end-of-body and fetchParams’s task destination.
  1551. if (request.body == null && fetchParams.processRequestEndOfBody) {
  1552. queueMicrotask(() => fetchParams.processRequestEndOfBody())
  1553. } else if (request.body != null) {
  1554. // 2. Otherwise, if body is non-null:
  1555. // 1. Let processBodyChunk given bytes be these steps:
  1556. const processBodyChunk = async function * (bytes) {
  1557. // 1. If the ongoing fetch is terminated, then abort these steps.
  1558. if (isCancelled(fetchParams)) {
  1559. return
  1560. }
  1561. // 2. Run this step in parallel: transmit bytes.
  1562. yield bytes
  1563. // 3. If fetchParams’s process request body is non-null, then run
  1564. // fetchParams’s process request body given bytes’s length.
  1565. fetchParams.processRequestBodyChunkLength?.(bytes.byteLength)
  1566. }
  1567. // 2. Let processEndOfBody be these steps:
  1568. const processEndOfBody = () => {
  1569. // 1. If fetchParams is canceled, then abort these steps.
  1570. if (isCancelled(fetchParams)) {
  1571. return
  1572. }
  1573. // 2. If fetchParams’s process request end-of-body is non-null,
  1574. // then run fetchParams’s process request end-of-body.
  1575. if (fetchParams.processRequestEndOfBody) {
  1576. fetchParams.processRequestEndOfBody()
  1577. }
  1578. }
  1579. // 3. Let processBodyError given e be these steps:
  1580. const processBodyError = (e) => {
  1581. // 1. If fetchParams is canceled, then abort these steps.
  1582. if (isCancelled(fetchParams)) {
  1583. return
  1584. }
  1585. // 2. If e is an "AbortError" DOMException, then abort fetchParams’s controller.
  1586. if (e.name === 'AbortError') {
  1587. fetchParams.controller.abort()
  1588. } else {
  1589. fetchParams.controller.terminate(e)
  1590. }
  1591. }
  1592. // 4. Incrementally read request’s body given processBodyChunk, processEndOfBody,
  1593. // processBodyError, and fetchParams’s task destination.
  1594. requestBody = (async function * () {
  1595. try {
  1596. for await (const bytes of request.body.stream) {
  1597. yield * processBodyChunk(bytes)
  1598. }
  1599. processEndOfBody()
  1600. } catch (err) {
  1601. processBodyError(err)
  1602. }
  1603. })()
  1604. }
  1605. try {
  1606. // socket is only provided for websockets
  1607. const { body, status, statusText, headersList, socket } = await dispatch({ body: requestBody })
  1608. if (socket) {
  1609. response = makeResponse({ status, statusText, headersList, socket })
  1610. } else {
  1611. const iterator = body[Symbol.asyncIterator]()
  1612. fetchParams.controller.next = () => iterator.next()
  1613. response = makeResponse({ status, statusText, headersList })
  1614. }
  1615. } catch (err) {
  1616. // 10. If aborted, then:
  1617. if (err.name === 'AbortError') {
  1618. // 1. If connection uses HTTP/2, then transmit an RST_STREAM frame.
  1619. fetchParams.controller.connection.destroy()
  1620. // 2. Return the appropriate network error for fetchParams.
  1621. return makeAppropriateNetworkError(fetchParams, err)
  1622. }
  1623. return makeNetworkError(err)
  1624. }
  1625. // 11. Let pullAlgorithm be an action that resumes the ongoing fetch
  1626. // if it is suspended.
  1627. const pullAlgorithm = () => {
  1628. return fetchParams.controller.resume()
  1629. }
  1630. // 12. Let cancelAlgorithm be an algorithm that aborts fetchParams’s
  1631. // controller with reason, given reason.
  1632. const cancelAlgorithm = (reason) => {
  1633. // If the aborted fetch was already terminated, then we do not
  1634. // need to do anything.
  1635. if (!isCancelled(fetchParams)) {
  1636. fetchParams.controller.abort(reason)
  1637. }
  1638. }
  1639. // 13. Let highWaterMark be a non-negative, non-NaN number, chosen by
  1640. // the user agent.
  1641. // TODO
  1642. // 14. Let sizeAlgorithm be an algorithm that accepts a chunk object
  1643. // and returns a non-negative, non-NaN, non-infinite number, chosen by the user agent.
  1644. // TODO
  1645. // 15. Let stream be a new ReadableStream.
  1646. // 16. Set up stream with byte reading support with pullAlgorithm set to pullAlgorithm,
  1647. // cancelAlgorithm set to cancelAlgorithm.
  1648. const stream = new ReadableStream(
  1649. {
  1650. start (controller) {
  1651. fetchParams.controller.controller = controller
  1652. },
  1653. pull: pullAlgorithm,
  1654. cancel: cancelAlgorithm,
  1655. type: 'bytes'
  1656. }
  1657. )
  1658. // 17. Run these steps, but abort when the ongoing fetch is terminated:
  1659. // 1. Set response’s body to a new body whose stream is stream.
  1660. response.body = { stream, source: null, length: null }
  1661. // 2. If response is not a network error and request’s cache mode is
  1662. // not "no-store", then update response in httpCache for request.
  1663. // TODO
  1664. // 3. If includeCredentials is true and the user agent is not configured
  1665. // to block cookies for request (see section 7 of [COOKIES]), then run the
  1666. // "set-cookie-string" parsing algorithm (see section 5.2 of [COOKIES]) on
  1667. // the value of each header whose name is a byte-case-insensitive match for
  1668. // `Set-Cookie` in response’s header list, if any, and request’s current URL.
  1669. // TODO
  1670. // 18. If aborted, then:
  1671. // TODO
  1672. // 19. Run these steps in parallel:
  1673. // 1. Run these steps, but abort when fetchParams is canceled:
  1674. if (!fetchParams.controller.resume) {
  1675. fetchParams.controller.on('terminated', onAborted)
  1676. }
  1677. fetchParams.controller.resume = async () => {
  1678. // 1. While true
  1679. while (true) {
  1680. // 1-3. See onData...
  1681. // 4. Set bytes to the result of handling content codings given
  1682. // codings and bytes.
  1683. let bytes
  1684. let isFailure
  1685. try {
  1686. const { done, value } = await fetchParams.controller.next()
  1687. if (isAborted(fetchParams)) {
  1688. break
  1689. }
  1690. bytes = done ? undefined : value
  1691. } catch (err) {
  1692. if (fetchParams.controller.ended && !timingInfo.encodedBodySize) {
  1693. // zlib doesn't like empty streams.
  1694. bytes = undefined
  1695. } else {
  1696. bytes = err
  1697. // err may be propagated from the result of calling readablestream.cancel,
  1698. // which might not be an error. https://github.com/nodejs/undici/issues/2009
  1699. isFailure = true
  1700. }
  1701. }
  1702. if (bytes === undefined) {
  1703. // 2. Otherwise, if the bytes transmission for response’s message
  1704. // body is done normally and stream is readable, then close
  1705. // stream, finalize response for fetchParams and response, and
  1706. // abort these in-parallel steps.
  1707. readableStreamClose(fetchParams.controller.controller)
  1708. finalizeResponse(fetchParams, response)
  1709. return
  1710. }
  1711. // 5. Increase timingInfo’s decoded body size by bytes’s length.
  1712. timingInfo.decodedBodySize += bytes?.byteLength ?? 0
  1713. // 6. If bytes is failure, then terminate fetchParams’s controller.
  1714. if (isFailure) {
  1715. fetchParams.controller.terminate(bytes)
  1716. return
  1717. }
  1718. // 7. Enqueue a Uint8Array wrapping an ArrayBuffer containing bytes
  1719. // into stream.
  1720. const buffer = new Uint8Array(bytes)
  1721. if (buffer.byteLength) {
  1722. fetchParams.controller.controller.enqueue(buffer)
  1723. }
  1724. // 8. If stream is errored, then terminate the ongoing fetch.
  1725. if (isErrored(stream)) {
  1726. fetchParams.controller.terminate()
  1727. return
  1728. }
  1729. // 9. If stream doesn’t need more data ask the user agent to suspend
  1730. // the ongoing fetch.
  1731. if (fetchParams.controller.controller.desiredSize <= 0) {
  1732. return
  1733. }
  1734. }
  1735. }
  1736. // 2. If aborted, then:
  1737. function onAborted (reason) {
  1738. // 2. If fetchParams is aborted, then:
  1739. if (isAborted(fetchParams)) {
  1740. // 1. Set response’s aborted flag.
  1741. response.aborted = true
  1742. // 2. If stream is readable, then error stream with the result of
  1743. // deserialize a serialized abort reason given fetchParams’s
  1744. // controller’s serialized abort reason and an
  1745. // implementation-defined realm.
  1746. if (isReadable(stream)) {
  1747. fetchParams.controller.controller.error(
  1748. fetchParams.controller.serializedAbortReason
  1749. )
  1750. }
  1751. } else {
  1752. // 3. Otherwise, if stream is readable, error stream with a TypeError.
  1753. if (isReadable(stream)) {
  1754. fetchParams.controller.controller.error(new TypeError('terminated', {
  1755. cause: isErrorLike(reason) ? reason : undefined
  1756. }))
  1757. }
  1758. }
  1759. // 4. If connection uses HTTP/2, then transmit an RST_STREAM frame.
  1760. // 5. Otherwise, the user agent should close connection unless it would be bad for performance to do so.
  1761. fetchParams.controller.connection.destroy()
  1762. }
  1763. // 20. Return response.
  1764. return response
  1765. function dispatch ({ body }) {
  1766. const url = requestCurrentURL(request)
  1767. /** @type {import('../../..').Agent} */
  1768. const agent = fetchParams.controller.dispatcher
  1769. return new Promise((resolve, reject) => agent.dispatch(
  1770. {
  1771. path: url.pathname + url.search,
  1772. origin: url.origin,
  1773. method: request.method,
  1774. body: agent.isMockActive ? request.body && (request.body.source || request.body.stream) : body,
  1775. headers: request.headersList.entries,
  1776. maxRedirections: 0,
  1777. upgrade: request.mode === 'websocket' ? 'websocket' : undefined
  1778. },
  1779. {
  1780. body: null,
  1781. abort: null,
  1782. onConnect (abort) {
  1783. // TODO (fix): Do we need connection here?
  1784. const { connection } = fetchParams.controller
  1785. // Set timingInfo’s final connection timing info to the result of calling clamp and coarsen
  1786. // connection timing info with connection’s timing info, timingInfo’s post-redirect start
  1787. // time, and fetchParams’s cross-origin isolated capability.
  1788. // TODO: implement connection timing
  1789. timingInfo.finalConnectionTimingInfo = clampAndCoarsenConnectionTimingInfo(undefined, timingInfo.postRedirectStartTime, fetchParams.crossOriginIsolatedCapability)
  1790. if (connection.destroyed) {
  1791. abort(new DOMException('The operation was aborted.', 'AbortError'))
  1792. } else {
  1793. fetchParams.controller.on('terminated', abort)
  1794. this.abort = connection.abort = abort
  1795. }
  1796. // Set timingInfo’s final network-request start time to the coarsened shared current time given
  1797. // fetchParams’s cross-origin isolated capability.
  1798. timingInfo.finalNetworkRequestStartTime = coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability)
  1799. },
  1800. onResponseStarted () {
  1801. // Set timingInfo’s final network-response start time to the coarsened shared current
  1802. // time given fetchParams’s cross-origin isolated capability, immediately after the
  1803. // user agent’s HTTP parser receives the first byte of the response (e.g., frame header
  1804. // bytes for HTTP/2 or response status line for HTTP/1.x).
  1805. timingInfo.finalNetworkResponseStartTime = coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability)
  1806. },
  1807. onHeaders (status, rawHeaders, resume, statusText) {
  1808. if (status < 200) {
  1809. return false
  1810. }
  1811. const headersList = new HeadersList()
  1812. for (let i = 0; i < rawHeaders.length; i += 2) {
  1813. headersList.append(bufferToLowerCasedHeaderName(rawHeaders[i]), rawHeaders[i + 1].toString('latin1'), true)
  1814. }
  1815. const location = headersList.get('location', true)
  1816. this.body = new Readable({ read: resume })
  1817. const willFollow = location && request.redirect === 'follow' &&
  1818. redirectStatusSet.has(status)
  1819. const decoders = []
  1820. // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding
  1821. if (request.method !== 'HEAD' && request.method !== 'CONNECT' && !nullBodyStatus.includes(status) && !willFollow) {
  1822. // https://www.rfc-editor.org/rfc/rfc7231#section-3.1.2.1
  1823. const contentEncoding = headersList.get('content-encoding', true)
  1824. // "All content-coding values are case-insensitive..."
  1825. /** @type {string[]} */
  1826. const codings = contentEncoding ? contentEncoding.toLowerCase().split(',') : []
  1827. // Limit the number of content-encodings to prevent resource exhaustion.
  1828. // CVE fix similar to urllib3 (GHSA-gm62-xv2j-4w53) and curl (CVE-2022-32206).
  1829. const maxContentEncodings = 5
  1830. if (codings.length > maxContentEncodings) {
  1831. reject(new Error(`too many content-encodings in response: ${codings.length}, maximum allowed is ${maxContentEncodings}`))
  1832. return true
  1833. }
  1834. for (let i = codings.length - 1; i >= 0; --i) {
  1835. const coding = codings[i].trim()
  1836. // https://www.rfc-editor.org/rfc/rfc9112.html#section-7.2
  1837. if (coding === 'x-gzip' || coding === 'gzip') {
  1838. decoders.push(zlib.createGunzip({
  1839. // Be less strict when decoding compressed responses, since sometimes
  1840. // servers send slightly invalid responses that are still accepted
  1841. // by common browsers.
  1842. // Always using Z_SYNC_FLUSH is what cURL does.
  1843. flush: zlib.constants.Z_SYNC_FLUSH,
  1844. finishFlush: zlib.constants.Z_SYNC_FLUSH
  1845. }))
  1846. } else if (coding === 'deflate') {
  1847. decoders.push(createInflate({
  1848. flush: zlib.constants.Z_SYNC_FLUSH,
  1849. finishFlush: zlib.constants.Z_SYNC_FLUSH
  1850. }))
  1851. } else if (coding === 'br') {
  1852. decoders.push(zlib.createBrotliDecompress({
  1853. flush: zlib.constants.BROTLI_OPERATION_FLUSH,
  1854. finishFlush: zlib.constants.BROTLI_OPERATION_FLUSH
  1855. }))
  1856. } else if (coding === 'zstd' && hasZstd) {
  1857. decoders.push(zlib.createZstdDecompress({
  1858. flush: zlib.constants.ZSTD_e_continue,
  1859. finishFlush: zlib.constants.ZSTD_e_end
  1860. }))
  1861. } else {
  1862. decoders.length = 0
  1863. break
  1864. }
  1865. }
  1866. }
  1867. const onError = this.onError.bind(this)
  1868. resolve({
  1869. status,
  1870. statusText,
  1871. headersList,
  1872. body: decoders.length
  1873. ? pipeline(this.body, ...decoders, (err) => {
  1874. if (err) {
  1875. this.onError(err)
  1876. }
  1877. }).on('error', onError)
  1878. : this.body.on('error', onError)
  1879. })
  1880. return true
  1881. },
  1882. onData (chunk) {
  1883. if (fetchParams.controller.dump) {
  1884. return
  1885. }
  1886. // 1. If one or more bytes have been transmitted from response’s
  1887. // message body, then:
  1888. // 1. Let bytes be the transmitted bytes.
  1889. const bytes = chunk
  1890. // 2. Let codings be the result of extracting header list values
  1891. // given `Content-Encoding` and response’s header list.
  1892. // See pullAlgorithm.
  1893. // 3. Increase timingInfo’s encoded body size by bytes’s length.
  1894. timingInfo.encodedBodySize += bytes.byteLength
  1895. // 4. See pullAlgorithm...
  1896. return this.body.push(bytes)
  1897. },
  1898. onComplete () {
  1899. if (this.abort) {
  1900. fetchParams.controller.off('terminated', this.abort)
  1901. }
  1902. fetchParams.controller.ended = true
  1903. this.body.push(null)
  1904. },
  1905. onError (error) {
  1906. if (this.abort) {
  1907. fetchParams.controller.off('terminated', this.abort)
  1908. }
  1909. this.body?.destroy(error)
  1910. fetchParams.controller.terminate(error)
  1911. reject(error)
  1912. },
  1913. onRequestUpgrade (_controller, status, headers, socket) {
  1914. // We need to support 200 for websocket over h2 as per RFC-8441
  1915. // Absence of session means H1
  1916. if ((socket.session != null && status !== 200) || (socket.session == null && status !== 101)) {
  1917. return false
  1918. }
  1919. const headersList = new HeadersList()
  1920. for (const [name, value] of Object.entries(headers)) {
  1921. if (value == null) {
  1922. continue
  1923. }
  1924. const headerName = name.toLowerCase()
  1925. if (Array.isArray(value)) {
  1926. for (const entry of value) {
  1927. headersList.append(headerName, String(entry), true)
  1928. }
  1929. } else {
  1930. headersList.append(headerName, String(value), true)
  1931. }
  1932. }
  1933. resolve({
  1934. status,
  1935. statusText: STATUS_CODES[status],
  1936. headersList,
  1937. socket
  1938. })
  1939. return true
  1940. },
  1941. onUpgrade (status, rawHeaders, socket) {
  1942. // We need to support 200 for websocket over h2 as per RFC-8441
  1943. // Absence of session means H1
  1944. if ((socket.session != null && status !== 200) || (socket.session == null && status !== 101)) {
  1945. return false
  1946. }
  1947. const headersList = new HeadersList()
  1948. for (let i = 0; i < rawHeaders.length; i += 2) {
  1949. headersList.append(bufferToLowerCasedHeaderName(rawHeaders[i]), rawHeaders[i + 1].toString('latin1'), true)
  1950. }
  1951. resolve({
  1952. status,
  1953. statusText: STATUS_CODES[status],
  1954. headersList,
  1955. socket
  1956. })
  1957. return true
  1958. }
  1959. }
  1960. ))
  1961. }
  1962. }
  1963. module.exports = {
  1964. fetch,
  1965. Fetch,
  1966. fetching,
  1967. finalizeAndReportTiming
  1968. }