index.js 81 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260
  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. bytesMatch,
  16. makePolicyContainer,
  17. clonePolicyContainer,
  18. requestBadPort,
  19. TAOCheck,
  20. appendRequestOriginHeader,
  21. responseLocationURL,
  22. requestCurrentURL,
  23. setRequestReferrerPolicyOnRedirect,
  24. tryUpgradeRequestToAPotentiallyTrustworthyURL,
  25. createOpaqueTimingInfo,
  26. appendFetchMetadata,
  27. corsCheck,
  28. crossOriginResourcePolicyCheck,
  29. determineRequestsReferrer,
  30. coarsenedSharedCurrentTime,
  31. sameOrigin,
  32. isCancelled,
  33. isAborted,
  34. isErrorLike,
  35. fullyReadBody,
  36. readableStreamClose,
  37. isomorphicEncode,
  38. urlIsLocal,
  39. urlIsHttpHttpsScheme,
  40. urlHasHttpsScheme,
  41. clampAndCoarsenConnectionTimingInfo,
  42. simpleRangeHeaderValue,
  43. buildContentRange,
  44. createInflate,
  45. extractMimeType
  46. } = require('./util')
  47. const assert = require('node:assert')
  48. const { safelyExtractBody, extractBody } = require('./body')
  49. const {
  50. redirectStatusSet,
  51. nullBodyStatus,
  52. safeMethodsSet,
  53. requestBodyHeader,
  54. subresourceSet
  55. } = require('./constants')
  56. const EE = require('node:events')
  57. const { Readable, pipeline, finished, isErrored, isReadable } = require('node:stream')
  58. const { addAbortListener, bufferToLowerCasedHeaderName } = require('../../core/util')
  59. const { dataURLProcessor, serializeAMimeType, minimizeSupportedMimeType } = require('./data-url')
  60. const { getGlobalDispatcher } = require('../../global')
  61. const { webidl } = require('../webidl')
  62. const { STATUS_CODES } = require('node:http')
  63. const { createDeferredPromise } = require('../../util/promise')
  64. const GET_OR_HEAD = ['GET', 'HEAD']
  65. const defaultUserAgent = typeof __UNDICI_IS_NODE__ !== 'undefined' || typeof esbuildDetection !== 'undefined'
  66. ? 'node'
  67. : 'undici'
  68. /** @type {import('buffer').resolveObjectURL} */
  69. let resolveObjectURL
  70. class Fetch extends EE {
  71. constructor (dispatcher) {
  72. super()
  73. this.dispatcher = dispatcher
  74. this.connection = null
  75. this.dump = false
  76. this.state = 'ongoing'
  77. }
  78. terminate (reason) {
  79. if (this.state !== 'ongoing') {
  80. return
  81. }
  82. this.state = 'terminated'
  83. this.connection?.destroy(reason)
  84. this.emit('terminated', reason)
  85. }
  86. // https://fetch.spec.whatwg.org/#fetch-controller-abort
  87. abort (error) {
  88. if (this.state !== 'ongoing') {
  89. return
  90. }
  91. // 1. Set controller’s state to "aborted".
  92. this.state = 'aborted'
  93. // 2. Let fallbackError be an "AbortError" DOMException.
  94. // 3. Set error to fallbackError if it is not given.
  95. if (!error) {
  96. error = new DOMException('The operation was aborted.', 'AbortError')
  97. }
  98. // 4. Let serializedError be StructuredSerialize(error).
  99. // If that threw an exception, catch it, and let
  100. // serializedError be StructuredSerialize(fallbackError).
  101. // 5. Set controller’s serialized abort reason to serializedError.
  102. this.serializedAbortReason = error
  103. this.connection?.destroy(error)
  104. this.emit('terminated', error)
  105. }
  106. }
  107. function handleFetchDone (response) {
  108. finalizeAndReportTiming(response, 'fetch')
  109. }
  110. // https://fetch.spec.whatwg.org/#fetch-method
  111. function fetch (input, init = undefined) {
  112. webidl.argumentLengthCheck(arguments, 1, 'globalThis.fetch')
  113. // 1. Let p be a new promise.
  114. let p = createDeferredPromise()
  115. // 2. Let requestObject be the result of invoking the initial value of
  116. // Request as constructor with input and init as arguments. If this throws
  117. // an exception, reject p with it and return p.
  118. let requestObject
  119. try {
  120. requestObject = new Request(input, init)
  121. } catch (e) {
  122. p.reject(e)
  123. return p.promise
  124. }
  125. // 3. Let request be requestObject’s request.
  126. const request = getRequestState(requestObject)
  127. // 4. If requestObject’s signal’s aborted flag is set, then:
  128. if (requestObject.signal.aborted) {
  129. // 1. Abort the fetch() call with p, request, null, and
  130. // requestObject’s signal’s abort reason.
  131. abortFetch(p, request, null, requestObject.signal.reason)
  132. // 2. Return p.
  133. return p.promise
  134. }
  135. // 5. Let globalObject be request’s client’s global object.
  136. const globalObject = request.client.globalObject
  137. // 6. If globalObject is a ServiceWorkerGlobalScope object, then set
  138. // request’s service-workers mode to "none".
  139. if (globalObject?.constructor?.name === 'ServiceWorkerGlobalScope') {
  140. request.serviceWorkers = 'none'
  141. }
  142. // 7. Let responseObject be null.
  143. let responseObject = null
  144. // 8. Let relevantRealm be this’s relevant Realm.
  145. // 9. Let locallyAborted be false.
  146. let locallyAborted = false
  147. // 10. Let controller be null.
  148. let controller = null
  149. // 11. Add the following abort steps to requestObject’s signal:
  150. addAbortListener(
  151. requestObject.signal,
  152. () => {
  153. // 1. Set locallyAborted to true.
  154. locallyAborted = true
  155. // 2. Assert: controller is non-null.
  156. assert(controller != null)
  157. // 3. Abort controller with requestObject’s signal’s abort reason.
  158. controller.abort(requestObject.signal.reason)
  159. const realResponse = responseObject?.deref()
  160. // 4. Abort the fetch() call with p, request, responseObject,
  161. // and requestObject’s signal’s abort reason.
  162. abortFetch(p, request, realResponse, requestObject.signal.reason)
  163. }
  164. )
  165. // 12. Let handleFetchDone given response response be to finalize and
  166. // report timing with response, globalObject, and "fetch".
  167. // see function handleFetchDone
  168. // 13. Set controller to the result of calling fetch given request,
  169. // with processResponseEndOfBody set to handleFetchDone, and processResponse
  170. // given response being these substeps:
  171. const processResponse = (response) => {
  172. // 1. If locallyAborted is true, terminate these substeps.
  173. if (locallyAborted) {
  174. return
  175. }
  176. // 2. If response’s aborted flag is set, then:
  177. if (response.aborted) {
  178. // 1. Let deserializedError be the result of deserialize a serialized
  179. // abort reason given controller’s serialized abort reason and
  180. // relevantRealm.
  181. // 2. Abort the fetch() call with p, request, responseObject, and
  182. // deserializedError.
  183. abortFetch(p, request, responseObject, controller.serializedAbortReason)
  184. return
  185. }
  186. // 3. If response is a network error, then reject p with a TypeError
  187. // and terminate these substeps.
  188. if (response.type === 'error') {
  189. p.reject(new TypeError('fetch failed', { cause: response.error }))
  190. return
  191. }
  192. // 4. Set responseObject to the result of creating a Response object,
  193. // given response, "immutable", and relevantRealm.
  194. responseObject = new WeakRef(fromInnerResponse(response, 'immutable'))
  195. // 5. Resolve p with responseObject.
  196. p.resolve(responseObject.deref())
  197. p = null
  198. }
  199. controller = fetching({
  200. request,
  201. processResponseEndOfBody: handleFetchDone,
  202. processResponse,
  203. dispatcher: getRequestDispatcher(requestObject) // undici
  204. })
  205. // 14. Return p.
  206. return p.promise
  207. }
  208. // https://fetch.spec.whatwg.org/#finalize-and-report-timing
  209. function finalizeAndReportTiming (response, initiatorType = 'other') {
  210. // 1. If response is an aborted network error, then return.
  211. if (response.type === 'error' && response.aborted) {
  212. return
  213. }
  214. // 2. If response’s URL list is null or empty, then return.
  215. if (!response.urlList?.length) {
  216. return
  217. }
  218. // 3. Let originalURL be response’s URL list[0].
  219. const originalURL = response.urlList[0]
  220. // 4. Let timingInfo be response’s timing info.
  221. let timingInfo = response.timingInfo
  222. // 5. Let cacheState be response’s cache state.
  223. let cacheState = response.cacheState
  224. // 6. If originalURL’s scheme is not an HTTP(S) scheme, then return.
  225. if (!urlIsHttpHttpsScheme(originalURL)) {
  226. return
  227. }
  228. // 7. If timingInfo is null, then return.
  229. if (timingInfo === null) {
  230. return
  231. }
  232. // 8. If response’s timing allow passed flag is not set, then:
  233. if (!response.timingAllowPassed) {
  234. // 1. Set timingInfo to a the result of creating an opaque timing info for timingInfo.
  235. timingInfo = createOpaqueTimingInfo({
  236. startTime: timingInfo.startTime
  237. })
  238. // 2. Set cacheState to the empty string.
  239. cacheState = ''
  240. }
  241. // 9. Set timingInfo’s end time to the coarsened shared current time
  242. // given global’s relevant settings object’s cross-origin isolated
  243. // capability.
  244. // TODO: given global’s relevant settings object’s cross-origin isolated
  245. // capability?
  246. timingInfo.endTime = coarsenedSharedCurrentTime()
  247. // 10. Set response’s timing info to timingInfo.
  248. response.timingInfo = timingInfo
  249. // 11. Mark resource timing for timingInfo, originalURL, initiatorType,
  250. // global, and cacheState.
  251. markResourceTiming(
  252. timingInfo,
  253. originalURL.href,
  254. initiatorType,
  255. globalThis,
  256. cacheState,
  257. '', // bodyType
  258. response.status
  259. )
  260. }
  261. // https://w3c.github.io/resource-timing/#dfn-mark-resource-timing
  262. const markResourceTiming = performance.markResourceTiming
  263. // https://fetch.spec.whatwg.org/#abort-fetch
  264. function abortFetch (p, request, responseObject, error) {
  265. // 1. Reject promise with error.
  266. if (p) {
  267. // We might have already resolved the promise at this stage
  268. p.reject(error)
  269. }
  270. // 2. If request’s body is not null and is readable, then cancel request’s
  271. // body with error.
  272. if (request.body?.stream != null && isReadable(request.body.stream)) {
  273. request.body.stream.cancel(error).catch((err) => {
  274. if (err.code === 'ERR_INVALID_STATE') {
  275. // Node bug?
  276. return
  277. }
  278. throw err
  279. })
  280. }
  281. // 3. If responseObject is null, then return.
  282. if (responseObject == null) {
  283. return
  284. }
  285. // 4. Let response be responseObject’s response.
  286. const response = getResponseState(responseObject)
  287. // 5. If response’s body is not null and is readable, then error response’s
  288. // body with error.
  289. if (response.body?.stream != null && isReadable(response.body.stream)) {
  290. response.body.stream.cancel(error).catch((err) => {
  291. if (err.code === 'ERR_INVALID_STATE') {
  292. // Node bug?
  293. return
  294. }
  295. throw err
  296. })
  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, 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. // 20. 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. // TODO: credentials
  1279. }
  1280. // 21. If there’s a proxy-authentication entry, use it as appropriate.
  1281. // TODO: proxy-authentication
  1282. // 22. Set httpCache to the result of determining the HTTP cache
  1283. // partition, given httpRequest.
  1284. // TODO: cache
  1285. // 23. If httpCache is null, then set httpRequest’s cache mode to
  1286. // "no-store".
  1287. if (httpCache == null) {
  1288. httpRequest.cache = 'no-store'
  1289. }
  1290. // 24. If httpRequest’s cache mode is neither "no-store" nor "reload",
  1291. // then:
  1292. if (httpRequest.cache !== 'no-store' && httpRequest.cache !== 'reload') {
  1293. // TODO: cache
  1294. }
  1295. // 9. If aborted, then return the appropriate network error for fetchParams.
  1296. // TODO
  1297. // 10. If response is null, then:
  1298. if (response == null) {
  1299. // 1. If httpRequest’s cache mode is "only-if-cached", then return a
  1300. // network error.
  1301. if (httpRequest.cache === 'only-if-cached') {
  1302. return makeNetworkError('only if cached')
  1303. }
  1304. // 2. Let forwardResponse be the result of running HTTP-network fetch
  1305. // given httpFetchParams, includeCredentials, and isNewConnectionFetch.
  1306. const forwardResponse = await httpNetworkFetch(
  1307. httpFetchParams,
  1308. includeCredentials,
  1309. isNewConnectionFetch
  1310. )
  1311. // 3. If httpRequest’s method is unsafe and forwardResponse’s status is
  1312. // in the range 200 to 399, inclusive, invalidate appropriate stored
  1313. // responses in httpCache, as per the "Invalidation" chapter of HTTP
  1314. // Caching, and set storedResponse to null. [HTTP-CACHING]
  1315. if (
  1316. !safeMethodsSet.has(httpRequest.method) &&
  1317. forwardResponse.status >= 200 &&
  1318. forwardResponse.status <= 399
  1319. ) {
  1320. // TODO: cache
  1321. }
  1322. // 4. If the revalidatingFlag is set and forwardResponse’s status is 304,
  1323. // then:
  1324. if (revalidatingFlag && forwardResponse.status === 304) {
  1325. // TODO: cache
  1326. }
  1327. // 5. If response is null, then:
  1328. if (response == null) {
  1329. // 1. Set response to forwardResponse.
  1330. response = forwardResponse
  1331. // 2. Store httpRequest and forwardResponse in httpCache, as per the
  1332. // "Storing Responses in Caches" chapter of HTTP Caching. [HTTP-CACHING]
  1333. // TODO: cache
  1334. }
  1335. }
  1336. // 11. Set response’s URL list to a clone of httpRequest’s URL list.
  1337. response.urlList = [...httpRequest.urlList]
  1338. // 12. If httpRequest’s header list contains `Range`, then set response’s
  1339. // range-requested flag.
  1340. if (httpRequest.headersList.contains('range', true)) {
  1341. response.rangeRequested = true
  1342. }
  1343. // 13. Set response’s request-includes-credentials to includeCredentials.
  1344. response.requestIncludesCredentials = includeCredentials
  1345. // 14. If response’s status is 401, httpRequest’s response tainting is not
  1346. // "cors", includeCredentials is true, and request’s window is an environment
  1347. // settings object, then:
  1348. // TODO
  1349. // 15. If response’s status is 407, then:
  1350. if (response.status === 407) {
  1351. // 1. If request’s window is "no-window", then return a network error.
  1352. if (request.window === 'no-window') {
  1353. return makeNetworkError()
  1354. }
  1355. // 2. ???
  1356. // 3. If fetchParams is canceled, then return the appropriate network error for fetchParams.
  1357. if (isCancelled(fetchParams)) {
  1358. return makeAppropriateNetworkError(fetchParams)
  1359. }
  1360. // 4. Prompt the end user as appropriate in request’s window and store
  1361. // the result as a proxy-authentication entry. [HTTP-AUTH]
  1362. // TODO: Invoke some kind of callback?
  1363. // 5. Set response to the result of running HTTP-network-or-cache fetch given
  1364. // fetchParams.
  1365. // TODO
  1366. return makeNetworkError('proxy authentication required')
  1367. }
  1368. // 16. If all of the following are true
  1369. if (
  1370. // response’s status is 421
  1371. response.status === 421 &&
  1372. // isNewConnectionFetch is false
  1373. !isNewConnectionFetch &&
  1374. // request’s body is null, or request’s body is non-null and request’s body’s source is non-null
  1375. (request.body == null || request.body.source != null)
  1376. ) {
  1377. // then:
  1378. // 1. If fetchParams is canceled, then return the appropriate network error for fetchParams.
  1379. if (isCancelled(fetchParams)) {
  1380. return makeAppropriateNetworkError(fetchParams)
  1381. }
  1382. // 2. Set response to the result of running HTTP-network-or-cache
  1383. // fetch given fetchParams, isAuthenticationFetch, and true.
  1384. // TODO (spec): The spec doesn't specify this but we need to cancel
  1385. // the active response before we can start a new one.
  1386. // https://github.com/whatwg/fetch/issues/1293
  1387. fetchParams.controller.connection.destroy()
  1388. response = await httpNetworkOrCacheFetch(
  1389. fetchParams,
  1390. isAuthenticationFetch,
  1391. true
  1392. )
  1393. }
  1394. // 17. If isAuthenticationFetch is true, then create an authentication entry
  1395. if (isAuthenticationFetch) {
  1396. // TODO
  1397. }
  1398. // 18. Return response.
  1399. return response
  1400. }
  1401. // https://fetch.spec.whatwg.org/#http-network-fetch
  1402. async function httpNetworkFetch (
  1403. fetchParams,
  1404. includeCredentials = false,
  1405. forceNewConnection = false
  1406. ) {
  1407. assert(!fetchParams.controller.connection || fetchParams.controller.connection.destroyed)
  1408. fetchParams.controller.connection = {
  1409. abort: null,
  1410. destroyed: false,
  1411. destroy (err, abort = true) {
  1412. if (!this.destroyed) {
  1413. this.destroyed = true
  1414. if (abort) {
  1415. this.abort?.(err ?? new DOMException('The operation was aborted.', 'AbortError'))
  1416. }
  1417. }
  1418. }
  1419. }
  1420. // 1. Let request be fetchParams’s request.
  1421. const request = fetchParams.request
  1422. // 2. Let response be null.
  1423. let response = null
  1424. // 3. Let timingInfo be fetchParams’s timing info.
  1425. const timingInfo = fetchParams.timingInfo
  1426. // 4. Let httpCache be the result of determining the HTTP cache partition,
  1427. // given request.
  1428. // TODO: cache
  1429. const httpCache = null
  1430. // 5. If httpCache is null, then set request’s cache mode to "no-store".
  1431. if (httpCache == null) {
  1432. request.cache = 'no-store'
  1433. }
  1434. // 6. Let networkPartitionKey be the result of determining the network
  1435. // partition key given request.
  1436. // TODO
  1437. // 7. Let newConnection be "yes" if forceNewConnection is true; otherwise
  1438. // "no".
  1439. const newConnection = forceNewConnection ? 'yes' : 'no' // eslint-disable-line no-unused-vars
  1440. // 8. Switch on request’s mode:
  1441. if (request.mode === 'websocket') {
  1442. // Let connection be the result of obtaining a WebSocket connection,
  1443. // given request’s current URL.
  1444. // TODO
  1445. } else {
  1446. // Let connection be the result of obtaining a connection, given
  1447. // networkPartitionKey, request’s current URL’s origin,
  1448. // includeCredentials, and forceNewConnection.
  1449. // TODO
  1450. }
  1451. // 9. Run these steps, but abort when the ongoing fetch is terminated:
  1452. // 1. If connection is failure, then return a network error.
  1453. // 2. Set timingInfo’s final connection timing info to the result of
  1454. // calling clamp and coarsen connection timing info with connection’s
  1455. // timing info, timingInfo’s post-redirect start time, and fetchParams’s
  1456. // cross-origin isolated capability.
  1457. // 3. If connection is not an HTTP/2 connection, request’s body is non-null,
  1458. // and request’s body’s source is null, then append (`Transfer-Encoding`,
  1459. // `chunked`) to request’s header list.
  1460. // 4. Set timingInfo’s final network-request start time to the coarsened
  1461. // shared current time given fetchParams’s cross-origin isolated
  1462. // capability.
  1463. // 5. Set response to the result of making an HTTP request over connection
  1464. // using request with the following caveats:
  1465. // - Follow the relevant requirements from HTTP. [HTTP] [HTTP-SEMANTICS]
  1466. // [HTTP-COND] [HTTP-CACHING] [HTTP-AUTH]
  1467. // - If request’s body is non-null, and request’s body’s source is null,
  1468. // then the user agent may have a buffer of up to 64 kibibytes and store
  1469. // a part of request’s body in that buffer. If the user agent reads from
  1470. // request’s body beyond that buffer’s size and the user agent needs to
  1471. // resend request, then instead return a network error.
  1472. // - Set timingInfo’s final network-response start time to the coarsened
  1473. // shared current time given fetchParams’s cross-origin isolated capability,
  1474. // immediately after the user agent’s HTTP parser receives the first byte
  1475. // of the response (e.g., frame header bytes for HTTP/2 or response status
  1476. // line for HTTP/1.x).
  1477. // - Wait until all the headers are transmitted.
  1478. // - Any responses whose status is in the range 100 to 199, inclusive,
  1479. // and is not 101, are to be ignored, except for the purposes of setting
  1480. // timingInfo’s final network-response start time above.
  1481. // - If request’s header list contains `Transfer-Encoding`/`chunked` and
  1482. // response is transferred via HTTP/1.0 or older, then return a network
  1483. // error.
  1484. // - If the HTTP request results in a TLS client certificate dialog, then:
  1485. // 1. If request’s window is an environment settings object, make the
  1486. // dialog available in request’s window.
  1487. // 2. Otherwise, return a network error.
  1488. // To transmit request’s body body, run these steps:
  1489. let requestBody = null
  1490. // 1. If body is null and fetchParams’s process request end-of-body is
  1491. // non-null, then queue a fetch task given fetchParams’s process request
  1492. // end-of-body and fetchParams’s task destination.
  1493. if (request.body == null && fetchParams.processRequestEndOfBody) {
  1494. queueMicrotask(() => fetchParams.processRequestEndOfBody())
  1495. } else if (request.body != null) {
  1496. // 2. Otherwise, if body is non-null:
  1497. // 1. Let processBodyChunk given bytes be these steps:
  1498. const processBodyChunk = async function * (bytes) {
  1499. // 1. If the ongoing fetch is terminated, then abort these steps.
  1500. if (isCancelled(fetchParams)) {
  1501. return
  1502. }
  1503. // 2. Run this step in parallel: transmit bytes.
  1504. yield bytes
  1505. // 3. If fetchParams’s process request body is non-null, then run
  1506. // fetchParams’s process request body given bytes’s length.
  1507. fetchParams.processRequestBodyChunkLength?.(bytes.byteLength)
  1508. }
  1509. // 2. Let processEndOfBody be these steps:
  1510. const processEndOfBody = () => {
  1511. // 1. If fetchParams is canceled, then abort these steps.
  1512. if (isCancelled(fetchParams)) {
  1513. return
  1514. }
  1515. // 2. If fetchParams’s process request end-of-body is non-null,
  1516. // then run fetchParams’s process request end-of-body.
  1517. if (fetchParams.processRequestEndOfBody) {
  1518. fetchParams.processRequestEndOfBody()
  1519. }
  1520. }
  1521. // 3. Let processBodyError given e be these steps:
  1522. const processBodyError = (e) => {
  1523. // 1. If fetchParams is canceled, then abort these steps.
  1524. if (isCancelled(fetchParams)) {
  1525. return
  1526. }
  1527. // 2. If e is an "AbortError" DOMException, then abort fetchParams’s controller.
  1528. if (e.name === 'AbortError') {
  1529. fetchParams.controller.abort()
  1530. } else {
  1531. fetchParams.controller.terminate(e)
  1532. }
  1533. }
  1534. // 4. Incrementally read request’s body given processBodyChunk, processEndOfBody,
  1535. // processBodyError, and fetchParams’s task destination.
  1536. requestBody = (async function * () {
  1537. try {
  1538. for await (const bytes of request.body.stream) {
  1539. yield * processBodyChunk(bytes)
  1540. }
  1541. processEndOfBody()
  1542. } catch (err) {
  1543. processBodyError(err)
  1544. }
  1545. })()
  1546. }
  1547. try {
  1548. // socket is only provided for websockets
  1549. const { body, status, statusText, headersList, socket } = await dispatch({ body: requestBody })
  1550. if (socket) {
  1551. response = makeResponse({ status, statusText, headersList, socket })
  1552. } else {
  1553. const iterator = body[Symbol.asyncIterator]()
  1554. fetchParams.controller.next = () => iterator.next()
  1555. response = makeResponse({ status, statusText, headersList })
  1556. }
  1557. } catch (err) {
  1558. // 10. If aborted, then:
  1559. if (err.name === 'AbortError') {
  1560. // 1. If connection uses HTTP/2, then transmit an RST_STREAM frame.
  1561. fetchParams.controller.connection.destroy()
  1562. // 2. Return the appropriate network error for fetchParams.
  1563. return makeAppropriateNetworkError(fetchParams, err)
  1564. }
  1565. return makeNetworkError(err)
  1566. }
  1567. // 11. Let pullAlgorithm be an action that resumes the ongoing fetch
  1568. // if it is suspended.
  1569. const pullAlgorithm = () => {
  1570. return fetchParams.controller.resume()
  1571. }
  1572. // 12. Let cancelAlgorithm be an algorithm that aborts fetchParams’s
  1573. // controller with reason, given reason.
  1574. const cancelAlgorithm = (reason) => {
  1575. // If the aborted fetch was already terminated, then we do not
  1576. // need to do anything.
  1577. if (!isCancelled(fetchParams)) {
  1578. fetchParams.controller.abort(reason)
  1579. }
  1580. }
  1581. // 13. Let highWaterMark be a non-negative, non-NaN number, chosen by
  1582. // the user agent.
  1583. // TODO
  1584. // 14. Let sizeAlgorithm be an algorithm that accepts a chunk object
  1585. // and returns a non-negative, non-NaN, non-infinite number, chosen by the user agent.
  1586. // TODO
  1587. // 15. Let stream be a new ReadableStream.
  1588. // 16. Set up stream with byte reading support with pullAlgorithm set to pullAlgorithm,
  1589. // cancelAlgorithm set to cancelAlgorithm.
  1590. const stream = new ReadableStream(
  1591. {
  1592. start (controller) {
  1593. fetchParams.controller.controller = controller
  1594. },
  1595. pull: pullAlgorithm,
  1596. cancel: cancelAlgorithm,
  1597. type: 'bytes'
  1598. }
  1599. )
  1600. // 17. Run these steps, but abort when the ongoing fetch is terminated:
  1601. // 1. Set response’s body to a new body whose stream is stream.
  1602. response.body = { stream, source: null, length: null }
  1603. // 2. If response is not a network error and request’s cache mode is
  1604. // not "no-store", then update response in httpCache for request.
  1605. // TODO
  1606. // 3. If includeCredentials is true and the user agent is not configured
  1607. // to block cookies for request (see section 7 of [COOKIES]), then run the
  1608. // "set-cookie-string" parsing algorithm (see section 5.2 of [COOKIES]) on
  1609. // the value of each header whose name is a byte-case-insensitive match for
  1610. // `Set-Cookie` in response’s header list, if any, and request’s current URL.
  1611. // TODO
  1612. // 18. If aborted, then:
  1613. // TODO
  1614. // 19. Run these steps in parallel:
  1615. // 1. Run these steps, but abort when fetchParams is canceled:
  1616. if (!fetchParams.controller.resume) {
  1617. fetchParams.controller.on('terminated', onAborted)
  1618. }
  1619. fetchParams.controller.resume = async () => {
  1620. // 1. While true
  1621. while (true) {
  1622. // 1-3. See onData...
  1623. // 4. Set bytes to the result of handling content codings given
  1624. // codings and bytes.
  1625. let bytes
  1626. let isFailure
  1627. try {
  1628. const { done, value } = await fetchParams.controller.next()
  1629. if (isAborted(fetchParams)) {
  1630. break
  1631. }
  1632. bytes = done ? undefined : value
  1633. } catch (err) {
  1634. if (fetchParams.controller.ended && !timingInfo.encodedBodySize) {
  1635. // zlib doesn't like empty streams.
  1636. bytes = undefined
  1637. } else {
  1638. bytes = err
  1639. // err may be propagated from the result of calling readablestream.cancel,
  1640. // which might not be an error. https://github.com/nodejs/undici/issues/2009
  1641. isFailure = true
  1642. }
  1643. }
  1644. if (bytes === undefined) {
  1645. // 2. Otherwise, if the bytes transmission for response’s message
  1646. // body is done normally and stream is readable, then close
  1647. // stream, finalize response for fetchParams and response, and
  1648. // abort these in-parallel steps.
  1649. readableStreamClose(fetchParams.controller.controller)
  1650. finalizeResponse(fetchParams, response)
  1651. return
  1652. }
  1653. // 5. Increase timingInfo’s decoded body size by bytes’s length.
  1654. timingInfo.decodedBodySize += bytes?.byteLength ?? 0
  1655. // 6. If bytes is failure, then terminate fetchParams’s controller.
  1656. if (isFailure) {
  1657. fetchParams.controller.terminate(bytes)
  1658. return
  1659. }
  1660. // 7. Enqueue a Uint8Array wrapping an ArrayBuffer containing bytes
  1661. // into stream.
  1662. const buffer = new Uint8Array(bytes)
  1663. if (buffer.byteLength) {
  1664. fetchParams.controller.controller.enqueue(buffer)
  1665. }
  1666. // 8. If stream is errored, then terminate the ongoing fetch.
  1667. if (isErrored(stream)) {
  1668. fetchParams.controller.terminate()
  1669. return
  1670. }
  1671. // 9. If stream doesn’t need more data ask the user agent to suspend
  1672. // the ongoing fetch.
  1673. if (fetchParams.controller.controller.desiredSize <= 0) {
  1674. return
  1675. }
  1676. }
  1677. }
  1678. // 2. If aborted, then:
  1679. function onAborted (reason) {
  1680. // 2. If fetchParams is aborted, then:
  1681. if (isAborted(fetchParams)) {
  1682. // 1. Set response’s aborted flag.
  1683. response.aborted = true
  1684. // 2. If stream is readable, then error stream with the result of
  1685. // deserialize a serialized abort reason given fetchParams’s
  1686. // controller’s serialized abort reason and an
  1687. // implementation-defined realm.
  1688. if (isReadable(stream)) {
  1689. fetchParams.controller.controller.error(
  1690. fetchParams.controller.serializedAbortReason
  1691. )
  1692. }
  1693. } else {
  1694. // 3. Otherwise, if stream is readable, error stream with a TypeError.
  1695. if (isReadable(stream)) {
  1696. fetchParams.controller.controller.error(new TypeError('terminated', {
  1697. cause: isErrorLike(reason) ? reason : undefined
  1698. }))
  1699. }
  1700. }
  1701. // 4. If connection uses HTTP/2, then transmit an RST_STREAM frame.
  1702. // 5. Otherwise, the user agent should close connection unless it would be bad for performance to do so.
  1703. fetchParams.controller.connection.destroy()
  1704. }
  1705. // 20. Return response.
  1706. return response
  1707. function dispatch ({ body }) {
  1708. const url = requestCurrentURL(request)
  1709. /** @type {import('../../..').Agent} */
  1710. const agent = fetchParams.controller.dispatcher
  1711. return new Promise((resolve, reject) => agent.dispatch(
  1712. {
  1713. path: url.pathname + url.search,
  1714. origin: url.origin,
  1715. method: request.method,
  1716. body: agent.isMockActive ? request.body && (request.body.source || request.body.stream) : body,
  1717. headers: request.headersList.entries,
  1718. maxRedirections: 0,
  1719. upgrade: request.mode === 'websocket' ? 'websocket' : undefined
  1720. },
  1721. {
  1722. body: null,
  1723. abort: null,
  1724. onConnect (abort) {
  1725. // TODO (fix): Do we need connection here?
  1726. const { connection } = fetchParams.controller
  1727. // Set timingInfo’s final connection timing info to the result of calling clamp and coarsen
  1728. // connection timing info with connection’s timing info, timingInfo’s post-redirect start
  1729. // time, and fetchParams’s cross-origin isolated capability.
  1730. // TODO: implement connection timing
  1731. timingInfo.finalConnectionTimingInfo = clampAndCoarsenConnectionTimingInfo(undefined, timingInfo.postRedirectStartTime, fetchParams.crossOriginIsolatedCapability)
  1732. if (connection.destroyed) {
  1733. abort(new DOMException('The operation was aborted.', 'AbortError'))
  1734. } else {
  1735. fetchParams.controller.on('terminated', abort)
  1736. this.abort = connection.abort = abort
  1737. }
  1738. // Set timingInfo’s final network-request start time to the coarsened shared current time given
  1739. // fetchParams’s cross-origin isolated capability.
  1740. timingInfo.finalNetworkRequestStartTime = coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability)
  1741. },
  1742. onResponseStarted () {
  1743. // Set timingInfo’s final network-response start time to the coarsened shared current
  1744. // time given fetchParams’s cross-origin isolated capability, immediately after the
  1745. // user agent’s HTTP parser receives the first byte of the response (e.g., frame header
  1746. // bytes for HTTP/2 or response status line for HTTP/1.x).
  1747. timingInfo.finalNetworkResponseStartTime = coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability)
  1748. },
  1749. onHeaders (status, rawHeaders, resume, statusText) {
  1750. if (status < 200) {
  1751. return false
  1752. }
  1753. /** @type {string[]} */
  1754. let codings = []
  1755. const headersList = new HeadersList()
  1756. for (let i = 0; i < rawHeaders.length; i += 2) {
  1757. headersList.append(bufferToLowerCasedHeaderName(rawHeaders[i]), rawHeaders[i + 1].toString('latin1'), true)
  1758. }
  1759. const contentEncoding = headersList.get('content-encoding', true)
  1760. if (contentEncoding) {
  1761. // https://www.rfc-editor.org/rfc/rfc7231#section-3.1.2.1
  1762. // "All content-coding values are case-insensitive..."
  1763. codings = contentEncoding.toLowerCase().split(',').map((x) => x.trim())
  1764. }
  1765. const location = headersList.get('location', true)
  1766. this.body = new Readable({ read: resume })
  1767. const decoders = []
  1768. const willFollow = location && request.redirect === 'follow' &&
  1769. redirectStatusSet.has(status)
  1770. // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding
  1771. if (codings.length !== 0 && request.method !== 'HEAD' && request.method !== 'CONNECT' && !nullBodyStatus.includes(status) && !willFollow) {
  1772. for (let i = codings.length - 1; i >= 0; --i) {
  1773. const coding = codings[i]
  1774. // https://www.rfc-editor.org/rfc/rfc9112.html#section-7.2
  1775. if (coding === 'x-gzip' || coding === 'gzip') {
  1776. decoders.push(zlib.createGunzip({
  1777. // Be less strict when decoding compressed responses, since sometimes
  1778. // servers send slightly invalid responses that are still accepted
  1779. // by common browsers.
  1780. // Always using Z_SYNC_FLUSH is what cURL does.
  1781. flush: zlib.constants.Z_SYNC_FLUSH,
  1782. finishFlush: zlib.constants.Z_SYNC_FLUSH
  1783. }))
  1784. } else if (coding === 'deflate') {
  1785. decoders.push(createInflate({
  1786. flush: zlib.constants.Z_SYNC_FLUSH,
  1787. finishFlush: zlib.constants.Z_SYNC_FLUSH
  1788. }))
  1789. } else if (coding === 'br') {
  1790. decoders.push(zlib.createBrotliDecompress({
  1791. flush: zlib.constants.BROTLI_OPERATION_FLUSH,
  1792. finishFlush: zlib.constants.BROTLI_OPERATION_FLUSH
  1793. }))
  1794. } else if (coding === 'zstd' && typeof zlib.createZstdDecompress === 'function') {
  1795. // Node.js v23.8.0+ and v22.15.0+ supports Zstandard
  1796. decoders.push(zlib.createZstdDecompress({
  1797. flush: zlib.constants.ZSTD_e_continue,
  1798. finishFlush: zlib.constants.ZSTD_e_end
  1799. }))
  1800. } else {
  1801. decoders.length = 0
  1802. break
  1803. }
  1804. }
  1805. }
  1806. const onError = this.onError.bind(this)
  1807. resolve({
  1808. status,
  1809. statusText,
  1810. headersList,
  1811. body: decoders.length
  1812. ? pipeline(this.body, ...decoders, (err) => {
  1813. if (err) {
  1814. this.onError(err)
  1815. }
  1816. }).on('error', onError)
  1817. : this.body.on('error', onError)
  1818. })
  1819. return true
  1820. },
  1821. onData (chunk) {
  1822. if (fetchParams.controller.dump) {
  1823. return
  1824. }
  1825. // 1. If one or more bytes have been transmitted from response’s
  1826. // message body, then:
  1827. // 1. Let bytes be the transmitted bytes.
  1828. const bytes = chunk
  1829. // 2. Let codings be the result of extracting header list values
  1830. // given `Content-Encoding` and response’s header list.
  1831. // See pullAlgorithm.
  1832. // 3. Increase timingInfo’s encoded body size by bytes’s length.
  1833. timingInfo.encodedBodySize += bytes.byteLength
  1834. // 4. See pullAlgorithm...
  1835. return this.body.push(bytes)
  1836. },
  1837. onComplete () {
  1838. if (this.abort) {
  1839. fetchParams.controller.off('terminated', this.abort)
  1840. }
  1841. fetchParams.controller.ended = true
  1842. this.body.push(null)
  1843. },
  1844. onError (error) {
  1845. if (this.abort) {
  1846. fetchParams.controller.off('terminated', this.abort)
  1847. }
  1848. this.body?.destroy(error)
  1849. fetchParams.controller.terminate(error)
  1850. reject(error)
  1851. },
  1852. onUpgrade (status, rawHeaders, socket) {
  1853. if (status !== 101) {
  1854. return
  1855. }
  1856. const headersList = new HeadersList()
  1857. for (let i = 0; i < rawHeaders.length; i += 2) {
  1858. headersList.append(bufferToLowerCasedHeaderName(rawHeaders[i]), rawHeaders[i + 1].toString('latin1'), true)
  1859. }
  1860. resolve({
  1861. status,
  1862. statusText: STATUS_CODES[status],
  1863. headersList,
  1864. socket
  1865. })
  1866. return true
  1867. }
  1868. }
  1869. ))
  1870. }
  1871. }
  1872. module.exports = {
  1873. fetch,
  1874. Fetch,
  1875. fetching,
  1876. finalizeAndReportTiming
  1877. }