api-net-spec.ts 91 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342
  1. import { expect } from 'chai';
  2. import * as dns from 'node:dns';
  3. import { net, session, ClientRequest, BrowserWindow, ClientRequestConstructorOptions, protocol } from 'electron/main';
  4. import * as http from 'node:http';
  5. import * as url from 'node:url';
  6. import * as path from 'node:path';
  7. import { Socket } from 'node:net';
  8. import { defer, listen } from './lib/spec-helpers';
  9. import { once } from 'node:events';
  10. import { setTimeout } from 'node:timers/promises';
  11. // See https://github.com/nodejs/node/issues/40702.
  12. dns.setDefaultResultOrder('ipv4first');
  13. const kOneKiloByte = 1024;
  14. const kOneMegaByte = kOneKiloByte * kOneKiloByte;
  15. function randomBuffer (size: number, start: number = 0, end: number = 255) {
  16. const range = 1 + end - start;
  17. const buffer = Buffer.allocUnsafe(size);
  18. for (let i = 0; i < size; ++i) {
  19. buffer[i] = start + Math.floor(Math.random() * range);
  20. }
  21. return buffer;
  22. }
  23. function randomString (length: number) {
  24. const buffer = randomBuffer(length, '0'.charCodeAt(0), 'z'.charCodeAt(0));
  25. return buffer.toString();
  26. }
  27. async function getResponse (urlRequest: Electron.ClientRequest) {
  28. return new Promise<Electron.IncomingMessage>((resolve, reject) => {
  29. urlRequest.on('error', reject);
  30. urlRequest.on('abort', reject);
  31. urlRequest.on('response', (response) => resolve(response));
  32. urlRequest.end();
  33. });
  34. }
  35. async function collectStreamBody (response: Electron.IncomingMessage | http.IncomingMessage) {
  36. return (await collectStreamBodyBuffer(response)).toString();
  37. }
  38. function collectStreamBodyBuffer (response: Electron.IncomingMessage | http.IncomingMessage) {
  39. return new Promise<Buffer>((resolve, reject) => {
  40. response.on('error', reject);
  41. (response as NodeJS.EventEmitter).on('aborted', reject);
  42. const data: Buffer[] = [];
  43. response.on('data', (chunk) => data.push(chunk));
  44. response.on('end', (chunk?: Buffer) => {
  45. if (chunk) data.push(chunk);
  46. resolve(Buffer.concat(data));
  47. });
  48. });
  49. }
  50. async function respondNTimes (fn: http.RequestListener, n: number): Promise<string> {
  51. const server = http.createServer((request, response) => {
  52. fn(request, response);
  53. // don't close if a redirect was returned
  54. if ((response.statusCode < 300 || response.statusCode >= 399) && n <= 0) {
  55. n--;
  56. server.close();
  57. }
  58. });
  59. const sockets: Socket[] = [];
  60. server.on('connection', s => sockets.push(s));
  61. defer(() => {
  62. server.close();
  63. sockets.forEach(s => s.destroy());
  64. });
  65. return (await listen(server)).url;
  66. }
  67. function respondOnce (fn: http.RequestListener) {
  68. return respondNTimes(fn, 1);
  69. }
  70. let routeFailure = false;
  71. respondNTimes.toRoutes = (routes: Record<string, http.RequestListener>, n: number) => {
  72. return respondNTimes((request, response) => {
  73. if (Object.hasOwn(routes, request.url || '')) {
  74. (async () => {
  75. await Promise.resolve(routes[request.url || ''](request, response));
  76. })().catch((err) => {
  77. routeFailure = true;
  78. console.error('Route handler failed, this is probably why your test failed', err);
  79. response.statusCode = 500;
  80. response.end();
  81. });
  82. } else {
  83. response.statusCode = 500;
  84. response.end();
  85. expect.fail(`Unexpected URL: ${request.url}`);
  86. }
  87. }, n);
  88. };
  89. respondOnce.toRoutes = (routes: Record<string, http.RequestListener>) => respondNTimes.toRoutes(routes, 1);
  90. respondNTimes.toURL = (url: string, fn: http.RequestListener, n: number) => {
  91. return respondNTimes.toRoutes({ [url]: fn }, n);
  92. };
  93. respondOnce.toURL = (url: string, fn: http.RequestListener) => respondNTimes.toURL(url, fn, 1);
  94. respondNTimes.toSingleURL = (fn: http.RequestListener, n: number) => {
  95. const requestUrl = '/requestUrl';
  96. return respondNTimes.toURL(requestUrl, fn, n).then(url => `${url}${requestUrl}`);
  97. };
  98. respondOnce.toSingleURL = (fn: http.RequestListener) => respondNTimes.toSingleURL(fn, 1);
  99. describe('net module', () => {
  100. beforeEach(() => {
  101. routeFailure = false;
  102. });
  103. afterEach(async function () {
  104. await session.defaultSession.clearCache();
  105. if (routeFailure && this.test) {
  106. if (!this.test.isFailed()) {
  107. throw new Error('Failing this test due an unhandled error in the respondOnce route handler, check the logs above for the actual error');
  108. }
  109. }
  110. });
  111. describe('HTTP basics', () => {
  112. it('should be able to issue a basic GET request', async () => {
  113. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  114. expect(request.method).to.equal('GET');
  115. response.end();
  116. });
  117. const urlRequest = net.request(serverUrl);
  118. const response = await getResponse(urlRequest);
  119. expect(response.statusCode).to.equal(200);
  120. await collectStreamBody(response);
  121. });
  122. it('should be able to issue a basic POST request', async () => {
  123. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  124. expect(request.method).to.equal('POST');
  125. response.end();
  126. });
  127. const urlRequest = net.request({
  128. method: 'POST',
  129. url: serverUrl
  130. });
  131. const response = await getResponse(urlRequest);
  132. expect(response.statusCode).to.equal(200);
  133. await collectStreamBody(response);
  134. });
  135. it('should fetch correct data in a GET request', async () => {
  136. const expectedBodyData = 'Hello World!';
  137. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  138. expect(request.method).to.equal('GET');
  139. response.end(expectedBodyData);
  140. });
  141. const urlRequest = net.request(serverUrl);
  142. const response = await getResponse(urlRequest);
  143. expect(response.statusCode).to.equal(200);
  144. const body = await collectStreamBody(response);
  145. expect(body).to.equal(expectedBodyData);
  146. });
  147. it('should post the correct data in a POST request', async () => {
  148. const bodyData = 'Hello World!';
  149. let postedBodyData: string = '';
  150. const serverUrl = await respondOnce.toSingleURL(async (request, response) => {
  151. postedBodyData = await collectStreamBody(request);
  152. response.end();
  153. });
  154. const urlRequest = net.request({
  155. method: 'POST',
  156. url: serverUrl
  157. });
  158. urlRequest.write(bodyData);
  159. const response = await getResponse(urlRequest);
  160. expect(response.statusCode).to.equal(200);
  161. expect(postedBodyData).to.equal(bodyData);
  162. });
  163. it('a 307 redirected POST request preserves the body', async () => {
  164. const bodyData = 'Hello World!';
  165. let postedBodyData: string = '';
  166. let methodAfterRedirect: string | undefined;
  167. const serverUrl = await respondNTimes.toRoutes({
  168. '/redirect': (req, res) => {
  169. res.statusCode = 307;
  170. res.setHeader('location', serverUrl);
  171. return res.end();
  172. },
  173. '/': async (req, res) => {
  174. methodAfterRedirect = req.method;
  175. postedBodyData = await collectStreamBody(req);
  176. res.end();
  177. }
  178. }, 2);
  179. const urlRequest = net.request({
  180. method: 'POST',
  181. url: serverUrl + '/redirect'
  182. });
  183. urlRequest.write(bodyData);
  184. const response = await getResponse(urlRequest);
  185. expect(response.statusCode).to.equal(200);
  186. await collectStreamBody(response);
  187. expect(methodAfterRedirect).to.equal('POST');
  188. expect(postedBodyData).to.equal(bodyData);
  189. });
  190. it('a 302 redirected POST request DOES NOT preserve the body', async () => {
  191. const bodyData = 'Hello World!';
  192. let postedBodyData: string = '';
  193. let methodAfterRedirect: string | undefined;
  194. const serverUrl = await respondNTimes.toRoutes({
  195. '/redirect': (req, res) => {
  196. res.statusCode = 302;
  197. res.setHeader('location', serverUrl);
  198. return res.end();
  199. },
  200. '/': async (req, res) => {
  201. methodAfterRedirect = req.method;
  202. postedBodyData = await collectStreamBody(req);
  203. res.end();
  204. }
  205. }, 2);
  206. const urlRequest = net.request({
  207. method: 'POST',
  208. url: serverUrl + '/redirect'
  209. });
  210. urlRequest.write(bodyData);
  211. const response = await getResponse(urlRequest);
  212. expect(response.statusCode).to.equal(200);
  213. await collectStreamBody(response);
  214. expect(methodAfterRedirect).to.equal('GET');
  215. expect(postedBodyData).to.equal('');
  216. });
  217. it('should support chunked encoding', async () => {
  218. let receivedRequest: http.IncomingMessage = null as any;
  219. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  220. response.statusCode = 200;
  221. response.statusMessage = 'OK';
  222. response.chunkedEncoding = true;
  223. receivedRequest = request;
  224. request.on('data', (chunk: Buffer) => {
  225. response.write(chunk);
  226. });
  227. request.on('end', (chunk: Buffer) => {
  228. response.end(chunk);
  229. });
  230. });
  231. const urlRequest = net.request({
  232. method: 'POST',
  233. url: serverUrl
  234. });
  235. let chunkIndex = 0;
  236. const chunkCount = 100;
  237. let sent = Buffer.alloc(0);
  238. urlRequest.chunkedEncoding = true;
  239. while (chunkIndex < chunkCount) {
  240. chunkIndex += 1;
  241. const chunk = randomBuffer(kOneKiloByte);
  242. sent = Buffer.concat([sent, chunk]);
  243. urlRequest.write(chunk);
  244. }
  245. const response = await getResponse(urlRequest);
  246. expect(receivedRequest.method).to.equal('POST');
  247. expect(receivedRequest.headers['transfer-encoding']).to.equal('chunked');
  248. expect(receivedRequest.headers['content-length']).to.equal(undefined);
  249. expect(response.statusCode).to.equal(200);
  250. const received = await collectStreamBodyBuffer(response);
  251. expect(sent.equals(received)).to.be.true();
  252. expect(chunkIndex).to.be.equal(chunkCount);
  253. });
  254. for (const extraOptions of [{}, { credentials: 'include' }, { useSessionCookies: false, credentials: 'include' }] as ClientRequestConstructorOptions[]) {
  255. describe(`authentication when ${JSON.stringify(extraOptions)}`, () => {
  256. it('should emit the login event when 401', async () => {
  257. const [user, pass] = ['user', 'pass'];
  258. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  259. if (!request.headers.authorization) {
  260. return response.writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' }).end();
  261. }
  262. response.writeHead(200).end('ok');
  263. });
  264. let loginAuthInfo: Electron.AuthInfo;
  265. const request = net.request({ method: 'GET', url: serverUrl, ...extraOptions });
  266. request.on('login', (authInfo, cb) => {
  267. loginAuthInfo = authInfo;
  268. cb(user, pass);
  269. });
  270. const response = await getResponse(request);
  271. expect(response.statusCode).to.equal(200);
  272. expect(loginAuthInfo!.realm).to.equal('Foo');
  273. expect(loginAuthInfo!.scheme).to.equal('basic');
  274. });
  275. it('should receive 401 response when cancelling authentication', async () => {
  276. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  277. if (!request.headers.authorization) {
  278. response.writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' });
  279. response.end('unauthenticated');
  280. } else {
  281. response.writeHead(200).end('ok');
  282. }
  283. });
  284. const request = net.request({ method: 'GET', url: serverUrl, ...extraOptions });
  285. request.on('login', (authInfo, cb) => {
  286. cb();
  287. });
  288. const response = await getResponse(request);
  289. const body = await collectStreamBody(response);
  290. expect(response.statusCode).to.equal(401);
  291. expect(body).to.equal('unauthenticated');
  292. });
  293. it('should share credentials with WebContents', async () => {
  294. const [user, pass] = ['user', 'pass'];
  295. const serverUrl = await respondNTimes.toSingleURL((request, response) => {
  296. if (!request.headers.authorization) {
  297. return response.writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' }).end();
  298. }
  299. return response.writeHead(200).end('ok');
  300. }, 2);
  301. const bw = new BrowserWindow({ show: false });
  302. bw.webContents.on('login', (event, details, authInfo, cb) => {
  303. event.preventDefault();
  304. cb(user, pass);
  305. });
  306. await bw.loadURL(serverUrl);
  307. bw.close();
  308. const request = net.request({ method: 'GET', url: serverUrl, ...extraOptions });
  309. let logInCount = 0;
  310. request.on('login', () => {
  311. logInCount++;
  312. });
  313. const response = await getResponse(request);
  314. await collectStreamBody(response);
  315. expect(logInCount).to.equal(0, 'should not receive a login event, credentials should be cached');
  316. });
  317. it('should share proxy credentials with WebContents', async () => {
  318. const [user, pass] = ['user', 'pass'];
  319. const proxyUrl = await respondNTimes((request, response) => {
  320. if (!request.headers['proxy-authorization']) {
  321. return response.writeHead(407, { 'Proxy-Authenticate': 'Basic realm="Foo"' }).end();
  322. }
  323. return response.writeHead(200).end('ok');
  324. }, 2);
  325. const customSession = session.fromPartition(`net-proxy-test-${Math.random()}`);
  326. await customSession.setProxy({ proxyRules: proxyUrl.replace('http://', ''), proxyBypassRules: '<-loopback>' });
  327. const bw = new BrowserWindow({ show: false, webPreferences: { session: customSession } });
  328. bw.webContents.on('login', (event, details, authInfo, cb) => {
  329. event.preventDefault();
  330. cb(user, pass);
  331. });
  332. await bw.loadURL('http://127.0.0.1:9999');
  333. bw.close();
  334. const request = net.request({ method: 'GET', url: 'http://127.0.0.1:9999', session: customSession, ...extraOptions });
  335. let logInCount = 0;
  336. request.on('login', () => {
  337. logInCount++;
  338. });
  339. const response = await getResponse(request);
  340. const body = await collectStreamBody(response);
  341. expect(response.statusCode).to.equal(200);
  342. expect(body).to.equal('ok');
  343. expect(logInCount).to.equal(0, 'should not receive a login event, credentials should be cached');
  344. });
  345. it('should upload body when 401', async () => {
  346. const [user, pass] = ['user', 'pass'];
  347. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  348. if (!request.headers.authorization) {
  349. return response.writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' }).end();
  350. }
  351. response.writeHead(200);
  352. request.on('data', (chunk) => response.write(chunk));
  353. request.on('end', () => response.end());
  354. });
  355. const requestData = randomString(kOneKiloByte);
  356. const request = net.request({ method: 'GET', url: serverUrl, ...extraOptions });
  357. request.on('login', (authInfo, cb) => {
  358. cb(user, pass);
  359. });
  360. request.write(requestData);
  361. const response = await getResponse(request);
  362. const responseData = await collectStreamBody(response);
  363. expect(responseData).to.equal(requestData);
  364. });
  365. });
  366. }
  367. describe('authentication when {"credentials":"omit"}', () => {
  368. it('should not emit the login event when 401', async () => {
  369. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  370. if (!request.headers.authorization) {
  371. return response.writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' }).end();
  372. }
  373. response.writeHead(200).end('ok');
  374. });
  375. const request = net.request({ method: 'GET', url: serverUrl, credentials: 'omit' });
  376. request.on('login', () => {
  377. expect.fail('unexpected login event');
  378. });
  379. const response = await getResponse(request);
  380. expect(response.statusCode).to.equal(401);
  381. expect(response.headers['www-authenticate']).to.equal('Basic realm="Foo"');
  382. });
  383. it('should not share credentials with WebContents', async () => {
  384. const [user, pass] = ['user', 'pass'];
  385. const serverUrl = await respondNTimes.toSingleURL((request, response) => {
  386. if (!request.headers.authorization) {
  387. return response.writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' }).end();
  388. }
  389. return response.writeHead(200).end('ok');
  390. }, 2);
  391. const bw = new BrowserWindow({ show: false });
  392. bw.webContents.on('login', (event, details, authInfo, cb) => {
  393. event.preventDefault();
  394. cb(user, pass);
  395. });
  396. await bw.loadURL(serverUrl);
  397. bw.close();
  398. const request = net.request({ method: 'GET', url: serverUrl, credentials: 'omit' });
  399. request.on('login', () => {
  400. expect.fail();
  401. });
  402. const response = await getResponse(request);
  403. expect(response.statusCode).to.equal(401);
  404. expect(response.headers['www-authenticate']).to.equal('Basic realm="Foo"');
  405. });
  406. it('should share proxy credentials with WebContents', async () => {
  407. const [user, pass] = ['user', 'pass'];
  408. const proxyUrl = await respondNTimes((request, response) => {
  409. if (!request.headers['proxy-authorization']) {
  410. return response.writeHead(407, { 'Proxy-Authenticate': 'Basic realm="Foo"' }).end();
  411. }
  412. return response.writeHead(200).end('ok');
  413. }, 2);
  414. const customSession = session.fromPartition(`net-proxy-test-${Math.random()}`);
  415. await customSession.setProxy({ proxyRules: proxyUrl.replace('http://', ''), proxyBypassRules: '<-loopback>' });
  416. const bw = new BrowserWindow({ show: false, webPreferences: { session: customSession } });
  417. bw.webContents.on('login', (event, details, authInfo, cb) => {
  418. event.preventDefault();
  419. cb(user, pass);
  420. });
  421. await bw.loadURL('http://127.0.0.1:9999');
  422. bw.close();
  423. const request = net.request({ method: 'GET', url: 'http://127.0.0.1:9999', session: customSession, credentials: 'omit' });
  424. request.on('login', () => {
  425. expect.fail();
  426. });
  427. const response = await getResponse(request);
  428. const body = await collectStreamBody(response);
  429. expect(response.statusCode).to.equal(200);
  430. expect(body).to.equal('ok');
  431. });
  432. });
  433. });
  434. describe('ClientRequest API', () => {
  435. it('request/response objects should emit expected events', async () => {
  436. const bodyData = randomString(kOneKiloByte);
  437. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  438. response.end(bodyData);
  439. });
  440. const urlRequest = net.request(serverUrl);
  441. // request close event
  442. const closePromise = once(urlRequest, 'close');
  443. // request finish event
  444. const finishPromise = once(urlRequest, 'close');
  445. // request "response" event
  446. const response = await getResponse(urlRequest);
  447. response.on('error', (error: Error) => {
  448. expect(error).to.be.an('Error');
  449. });
  450. const statusCode = response.statusCode;
  451. expect(statusCode).to.equal(200);
  452. // response data event
  453. // respond end event
  454. const body = await collectStreamBody(response);
  455. expect(body).to.equal(bodyData);
  456. urlRequest.on('error', (error) => {
  457. expect(error).to.be.an('Error');
  458. });
  459. await Promise.all([closePromise, finishPromise]);
  460. });
  461. it('should be able to set a custom HTTP request header before first write', async () => {
  462. const customHeaderName = 'Some-Custom-Header-Name';
  463. const customHeaderValue = 'Some-Customer-Header-Value';
  464. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  465. expect(request.headers[customHeaderName.toLowerCase()]).to.equal(customHeaderValue);
  466. response.statusCode = 200;
  467. response.statusMessage = 'OK';
  468. response.end();
  469. });
  470. const urlRequest = net.request(serverUrl);
  471. urlRequest.setHeader(customHeaderName, customHeaderValue);
  472. expect(urlRequest.getHeader(customHeaderName)).to.equal(customHeaderValue);
  473. expect(urlRequest.getHeader(customHeaderName.toLowerCase())).to.equal(customHeaderValue);
  474. urlRequest.write('');
  475. expect(urlRequest.getHeader(customHeaderName)).to.equal(customHeaderValue);
  476. expect(urlRequest.getHeader(customHeaderName.toLowerCase())).to.equal(customHeaderValue);
  477. const response = await getResponse(urlRequest);
  478. expect(response.statusCode).to.equal(200);
  479. await collectStreamBody(response);
  480. });
  481. it('should be able to set a non-string object as a header value', async () => {
  482. const customHeaderName = 'Some-Integer-Value';
  483. const customHeaderValue = 900;
  484. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  485. expect(request.headers[customHeaderName.toLowerCase()]).to.equal(customHeaderValue.toString());
  486. response.statusCode = 200;
  487. response.statusMessage = 'OK';
  488. response.end();
  489. });
  490. const urlRequest = net.request(serverUrl);
  491. urlRequest.setHeader(customHeaderName, customHeaderValue as any);
  492. expect(urlRequest.getHeader(customHeaderName)).to.equal(customHeaderValue);
  493. expect(urlRequest.getHeader(customHeaderName.toLowerCase())).to.equal(customHeaderValue);
  494. urlRequest.write('');
  495. expect(urlRequest.getHeader(customHeaderName)).to.equal(customHeaderValue);
  496. expect(urlRequest.getHeader(customHeaderName.toLowerCase())).to.equal(customHeaderValue);
  497. const response = await getResponse(urlRequest);
  498. expect(response.statusCode).to.equal(200);
  499. await collectStreamBody(response);
  500. });
  501. it('should not change the case of header name', async () => {
  502. const customHeaderName = 'X-Header-Name';
  503. const customHeaderValue = 'value';
  504. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  505. expect(request.headers[customHeaderName.toLowerCase()]).to.equal(customHeaderValue.toString());
  506. expect(request.rawHeaders.includes(customHeaderName)).to.equal(true);
  507. response.statusCode = 200;
  508. response.statusMessage = 'OK';
  509. response.end();
  510. });
  511. const urlRequest = net.request(serverUrl);
  512. urlRequest.setHeader(customHeaderName, customHeaderValue);
  513. expect(urlRequest.getHeader(customHeaderName)).to.equal(customHeaderValue);
  514. urlRequest.write('');
  515. const response = await getResponse(urlRequest);
  516. expect(response.statusCode).to.equal(200);
  517. await collectStreamBody(response);
  518. });
  519. it('should not be able to set a custom HTTP request header after first write', async () => {
  520. const customHeaderName = 'Some-Custom-Header-Name';
  521. const customHeaderValue = 'Some-Customer-Header-Value';
  522. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  523. expect(request.headers[customHeaderName.toLowerCase()]).to.equal(undefined);
  524. response.statusCode = 200;
  525. response.statusMessage = 'OK';
  526. response.end();
  527. });
  528. const urlRequest = net.request(serverUrl);
  529. urlRequest.write('');
  530. expect(() => {
  531. urlRequest.setHeader(customHeaderName, customHeaderValue);
  532. }).to.throw();
  533. expect(urlRequest.getHeader(customHeaderName)).to.equal(undefined);
  534. const response = await getResponse(urlRequest);
  535. expect(response.statusCode).to.equal(200);
  536. await collectStreamBody(response);
  537. });
  538. it('should be able to remove a custom HTTP request header before first write', async () => {
  539. const customHeaderName = 'Some-Custom-Header-Name';
  540. const customHeaderValue = 'Some-Customer-Header-Value';
  541. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  542. expect(request.headers[customHeaderName.toLowerCase()]).to.equal(undefined);
  543. response.statusCode = 200;
  544. response.statusMessage = 'OK';
  545. response.end();
  546. });
  547. const urlRequest = net.request(serverUrl);
  548. urlRequest.setHeader(customHeaderName, customHeaderValue);
  549. expect(urlRequest.getHeader(customHeaderName)).to.equal(customHeaderValue);
  550. urlRequest.removeHeader(customHeaderName);
  551. expect(urlRequest.getHeader(customHeaderName)).to.equal(undefined);
  552. urlRequest.write('');
  553. const response = await getResponse(urlRequest);
  554. expect(response.statusCode).to.equal(200);
  555. await collectStreamBody(response);
  556. });
  557. it('should not be able to remove a custom HTTP request header after first write', async () => {
  558. const customHeaderName = 'Some-Custom-Header-Name';
  559. const customHeaderValue = 'Some-Customer-Header-Value';
  560. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  561. expect(request.headers[customHeaderName.toLowerCase()]).to.equal(customHeaderValue);
  562. response.statusCode = 200;
  563. response.statusMessage = 'OK';
  564. response.end();
  565. });
  566. const urlRequest = net.request(serverUrl);
  567. urlRequest.setHeader(customHeaderName, customHeaderValue);
  568. expect(urlRequest.getHeader(customHeaderName)).to.equal(customHeaderValue);
  569. urlRequest.write('');
  570. expect(() => {
  571. urlRequest.removeHeader(customHeaderName);
  572. }).to.throw();
  573. expect(urlRequest.getHeader(customHeaderName)).to.equal(customHeaderValue);
  574. const response = await getResponse(urlRequest);
  575. expect(response.statusCode).to.equal(200);
  576. await collectStreamBody(response);
  577. });
  578. it('should keep the order of headers', async () => {
  579. const customHeaderNameA = 'X-Header-100';
  580. const customHeaderNameB = 'X-Header-200';
  581. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  582. const headerNames = Array.from(Object.keys(request.headers));
  583. const headerAIndex = headerNames.indexOf(customHeaderNameA.toLowerCase());
  584. const headerBIndex = headerNames.indexOf(customHeaderNameB.toLowerCase());
  585. expect(headerBIndex).to.be.below(headerAIndex);
  586. response.statusCode = 200;
  587. response.statusMessage = 'OK';
  588. response.end();
  589. });
  590. const urlRequest = net.request(serverUrl);
  591. urlRequest.setHeader(customHeaderNameB, 'b');
  592. urlRequest.setHeader(customHeaderNameA, 'a');
  593. const response = await getResponse(urlRequest);
  594. expect(response.statusCode).to.equal(200);
  595. await collectStreamBody(response);
  596. });
  597. it('should be able to set cookie header line', async () => {
  598. const cookieHeaderName = 'Cookie';
  599. const cookieHeaderValue = 'test=12345';
  600. const customSession = session.fromPartition(`test-cookie-header-${Math.random()}`);
  601. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  602. expect(request.headers[cookieHeaderName.toLowerCase()]).to.equal(cookieHeaderValue);
  603. response.statusCode = 200;
  604. response.statusMessage = 'OK';
  605. response.end();
  606. });
  607. await customSession.cookies.set({
  608. url: `${serverUrl}`,
  609. name: 'test',
  610. value: '11111',
  611. expirationDate: 0
  612. });
  613. const urlRequest = net.request({
  614. method: 'GET',
  615. url: serverUrl,
  616. session: customSession
  617. });
  618. urlRequest.setHeader(cookieHeaderName, cookieHeaderValue);
  619. expect(urlRequest.getHeader(cookieHeaderName)).to.equal(cookieHeaderValue);
  620. const response = await getResponse(urlRequest);
  621. expect(response.statusCode).to.equal(200);
  622. await collectStreamBody(response);
  623. });
  624. it('should be able to receive cookies', async () => {
  625. const cookie = ['cookie1', 'cookie2'];
  626. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  627. response.statusCode = 200;
  628. response.statusMessage = 'OK';
  629. response.setHeader('set-cookie', cookie);
  630. response.end();
  631. });
  632. const urlRequest = net.request(serverUrl);
  633. const response = await getResponse(urlRequest);
  634. expect(response.headers['set-cookie']).to.have.same.members(cookie);
  635. });
  636. it('should be able to receive content-type', async () => {
  637. const contentType = 'mime/test; charset=test';
  638. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  639. response.statusCode = 200;
  640. response.statusMessage = 'OK';
  641. response.setHeader('content-type', contentType);
  642. response.end();
  643. });
  644. const urlRequest = net.request(serverUrl);
  645. const response = await getResponse(urlRequest);
  646. expect(response.headers['content-type']).to.equal(contentType);
  647. });
  648. it('should not use the sessions cookie store by default', async () => {
  649. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  650. response.statusCode = 200;
  651. response.statusMessage = 'OK';
  652. response.setHeader('x-cookie', `${request.headers.cookie!}`);
  653. response.end();
  654. });
  655. const sess = session.fromPartition(`cookie-tests-${Math.random()}`);
  656. const cookieVal = `${Date.now()}`;
  657. await sess.cookies.set({
  658. url: serverUrl,
  659. name: 'wild_cookie',
  660. value: cookieVal
  661. });
  662. const urlRequest = net.request({
  663. url: serverUrl,
  664. session: sess
  665. });
  666. const response = await getResponse(urlRequest);
  667. expect(response.headers['x-cookie']).to.equal('undefined');
  668. });
  669. for (const extraOptions of [{ useSessionCookies: true }, { credentials: 'include' }] as ClientRequestConstructorOptions[]) {
  670. describe(`when ${JSON.stringify(extraOptions)}`, () => {
  671. it('should be able to use the sessions cookie store', async () => {
  672. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  673. response.statusCode = 200;
  674. response.statusMessage = 'OK';
  675. response.setHeader('x-cookie', request.headers.cookie!);
  676. response.end();
  677. });
  678. const sess = session.fromPartition(`cookie-tests-${Math.random()}`);
  679. const cookieVal = `${Date.now()}`;
  680. await sess.cookies.set({
  681. url: serverUrl,
  682. name: 'wild_cookie',
  683. value: cookieVal
  684. });
  685. const urlRequest = net.request({
  686. url: serverUrl,
  687. session: sess,
  688. ...extraOptions
  689. });
  690. const response = await getResponse(urlRequest);
  691. expect(response.headers['x-cookie']).to.equal(`wild_cookie=${cookieVal}`);
  692. });
  693. it('should be able to use the sessions cookie store with set-cookie', async () => {
  694. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  695. response.statusCode = 200;
  696. response.statusMessage = 'OK';
  697. response.setHeader('set-cookie', 'foo=bar');
  698. response.end();
  699. });
  700. const sess = session.fromPartition(`cookie-tests-${Math.random()}`);
  701. let cookies = await sess.cookies.get({});
  702. expect(cookies).to.have.lengthOf(0);
  703. const urlRequest = net.request({
  704. url: serverUrl,
  705. session: sess,
  706. ...extraOptions
  707. });
  708. await collectStreamBody(await getResponse(urlRequest));
  709. cookies = await sess.cookies.get({});
  710. expect(cookies).to.have.lengthOf(1);
  711. expect(cookies[0]).to.deep.equal({
  712. name: 'foo',
  713. value: 'bar',
  714. domain: '127.0.0.1',
  715. hostOnly: true,
  716. path: '/',
  717. secure: false,
  718. httpOnly: false,
  719. session: true,
  720. sameSite: 'unspecified'
  721. });
  722. });
  723. ['Lax', 'Strict'].forEach((mode) => {
  724. it(`should be able to use the sessions cookie store with same-site ${mode} cookies`, async () => {
  725. const serverUrl = await respondNTimes.toSingleURL((request, response) => {
  726. response.statusCode = 200;
  727. response.statusMessage = 'OK';
  728. response.setHeader('set-cookie', `same=site; SameSite=${mode}`);
  729. response.setHeader('x-cookie', `${request.headers.cookie}`);
  730. response.end();
  731. }, 2);
  732. const sess = session.fromPartition(`cookie-tests-${Math.random()}`);
  733. let cookies = await sess.cookies.get({});
  734. expect(cookies).to.have.lengthOf(0);
  735. const urlRequest = net.request({
  736. url: serverUrl,
  737. session: sess,
  738. ...extraOptions
  739. });
  740. const response = await getResponse(urlRequest);
  741. expect(response.headers['x-cookie']).to.equal('undefined');
  742. await collectStreamBody(response);
  743. cookies = await sess.cookies.get({});
  744. expect(cookies).to.have.lengthOf(1);
  745. expect(cookies[0]).to.deep.equal({
  746. name: 'same',
  747. value: 'site',
  748. domain: '127.0.0.1',
  749. hostOnly: true,
  750. path: '/',
  751. secure: false,
  752. httpOnly: false,
  753. session: true,
  754. sameSite: mode.toLowerCase()
  755. });
  756. const urlRequest2 = net.request({
  757. url: serverUrl,
  758. session: sess,
  759. ...extraOptions
  760. });
  761. const response2 = await getResponse(urlRequest2);
  762. expect(response2.headers['x-cookie']).to.equal('same=site');
  763. });
  764. });
  765. it('should be able to use the sessions cookie store safely across redirects', async () => {
  766. const serverUrl = await respondOnce.toSingleURL(async (request, response) => {
  767. response.statusCode = 302;
  768. response.statusMessage = 'Moved';
  769. const newUrl = await respondOnce.toSingleURL((req, res) => {
  770. res.statusCode = 200;
  771. res.statusMessage = 'OK';
  772. res.setHeader('x-cookie', req.headers.cookie!);
  773. res.end();
  774. });
  775. response.setHeader('x-cookie', request.headers.cookie!);
  776. response.setHeader('location', newUrl.replace('127.0.0.1', 'localhost'));
  777. response.end();
  778. });
  779. const sess = session.fromPartition(`cookie-tests-${Math.random()}`);
  780. const cookie127Val = `${Date.now()}-127`;
  781. const cookieLocalVal = `${Date.now()}-local`;
  782. const localhostUrl = serverUrl.replace('127.0.0.1', 'localhost');
  783. expect(localhostUrl).to.not.equal(serverUrl);
  784. // cookies with lax or strict same-site settings will not
  785. // persist after redirects. no_restriction must be used
  786. await Promise.all([
  787. sess.cookies.set({
  788. url: serverUrl,
  789. name: 'wild_cookie',
  790. sameSite: 'no_restriction',
  791. value: cookie127Val
  792. }), sess.cookies.set({
  793. url: localhostUrl,
  794. name: 'wild_cookie',
  795. sameSite: 'no_restriction',
  796. value: cookieLocalVal
  797. })
  798. ]);
  799. const urlRequest = net.request({
  800. url: serverUrl,
  801. session: sess,
  802. ...extraOptions
  803. });
  804. urlRequest.on('redirect', (status, method, url, headers) => {
  805. // The initial redirect response should have received the 127 value here
  806. expect(headers['x-cookie'][0]).to.equal(`wild_cookie=${cookie127Val}`);
  807. urlRequest.followRedirect();
  808. });
  809. const response = await getResponse(urlRequest);
  810. // We expect the server to have received the localhost value here
  811. // The original request was to a 127.0.0.1 URL
  812. // That request would have the cookie127Val cookie attached
  813. // The request is then redirect to a localhost URL (different site)
  814. // Because we are using the session cookie store it should do the safe / secure thing
  815. // and attach the cookies for the new target domain
  816. expect(response.headers['x-cookie']).to.equal(`wild_cookie=${cookieLocalVal}`);
  817. });
  818. });
  819. }
  820. it('should be able correctly filter out cookies that are secure', async () => {
  821. const sess = session.fromPartition(`cookie-tests-${Math.random()}`);
  822. await Promise.all([
  823. sess.cookies.set({
  824. url: 'https://electronjs.org',
  825. domain: 'electronjs.org',
  826. name: 'cookie1',
  827. value: '1',
  828. secure: true
  829. }),
  830. sess.cookies.set({
  831. url: 'https://electronjs.org',
  832. domain: 'electronjs.org',
  833. name: 'cookie2',
  834. value: '2',
  835. secure: false
  836. })
  837. ]);
  838. const secureCookies = await sess.cookies.get({
  839. secure: true
  840. });
  841. expect(secureCookies).to.have.lengthOf(1);
  842. expect(secureCookies[0].name).to.equal('cookie1');
  843. const cookies = await sess.cookies.get({
  844. secure: false
  845. });
  846. expect(cookies).to.have.lengthOf(1);
  847. expect(cookies[0].name).to.equal('cookie2');
  848. });
  849. it('throws when an invalid domain is passed', async () => {
  850. const sess = session.fromPartition(`cookie-tests-${Math.random()}`);
  851. await expect(sess.cookies.set({
  852. url: 'https://electronjs.org',
  853. domain: 'wssss.iamabaddomain.fun',
  854. name: 'cookie1'
  855. })).to.eventually.be.rejectedWith(/Failed to set cookie with an invalid domain attribute/);
  856. });
  857. it('should be able correctly filter out cookies that are session', async () => {
  858. const sess = session.fromPartition(`cookie-tests-${Math.random()}`);
  859. await Promise.all([
  860. sess.cookies.set({
  861. url: 'https://electronjs.org',
  862. domain: 'electronjs.org',
  863. name: 'cookie1',
  864. value: '1'
  865. }),
  866. sess.cookies.set({
  867. url: 'https://electronjs.org',
  868. domain: 'electronjs.org',
  869. name: 'cookie2',
  870. value: '2',
  871. expirationDate: Math.round(Date.now() / 1000) + 10000
  872. })
  873. ]);
  874. const sessionCookies = await sess.cookies.get({
  875. session: true
  876. });
  877. expect(sessionCookies).to.have.lengthOf(1);
  878. expect(sessionCookies[0].name).to.equal('cookie1');
  879. const cookies = await sess.cookies.get({
  880. session: false
  881. });
  882. expect(cookies).to.have.lengthOf(1);
  883. expect(cookies[0].name).to.equal('cookie2');
  884. });
  885. it('should be able correctly filter out cookies that are httpOnly', async () => {
  886. const sess = session.fromPartition(`cookie-tests-${Math.random()}`);
  887. await Promise.all([
  888. sess.cookies.set({
  889. url: 'https://electronjs.org',
  890. domain: 'electronjs.org',
  891. name: 'cookie1',
  892. value: '1',
  893. httpOnly: true
  894. }),
  895. sess.cookies.set({
  896. url: 'https://electronjs.org',
  897. domain: 'electronjs.org',
  898. name: 'cookie2',
  899. value: '2',
  900. httpOnly: false
  901. })
  902. ]);
  903. const httpOnlyCookies = await sess.cookies.get({
  904. httpOnly: true
  905. });
  906. expect(httpOnlyCookies).to.have.lengthOf(1);
  907. expect(httpOnlyCookies[0].name).to.equal('cookie1');
  908. const cookies = await sess.cookies.get({
  909. httpOnly: false
  910. });
  911. expect(cookies).to.have.lengthOf(1);
  912. expect(cookies[0].name).to.equal('cookie2');
  913. });
  914. describe('when {"credentials":"omit"}', () => {
  915. it('should not send cookies');
  916. it('should not store cookies');
  917. });
  918. it('should set sec-fetch-site to same-origin for request from same origin', async () => {
  919. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  920. expect(request.headers['sec-fetch-site']).to.equal('same-origin');
  921. response.statusCode = 200;
  922. response.statusMessage = 'OK';
  923. response.end();
  924. });
  925. const urlRequest = net.request({
  926. url: serverUrl,
  927. origin: serverUrl
  928. });
  929. await collectStreamBody(await getResponse(urlRequest));
  930. });
  931. it('should set sec-fetch-site to same-origin for request with the same origin header', async () => {
  932. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  933. expect(request.headers['sec-fetch-site']).to.equal('same-origin');
  934. response.statusCode = 200;
  935. response.statusMessage = 'OK';
  936. response.end();
  937. });
  938. const urlRequest = net.request({
  939. url: serverUrl
  940. });
  941. urlRequest.setHeader('Origin', serverUrl);
  942. await collectStreamBody(await getResponse(urlRequest));
  943. });
  944. it('should set sec-fetch-site to cross-site for request from other origin', async () => {
  945. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  946. expect(request.headers['sec-fetch-site']).to.equal('cross-site');
  947. response.statusCode = 200;
  948. response.statusMessage = 'OK';
  949. response.end();
  950. });
  951. const urlRequest = net.request({
  952. url: serverUrl,
  953. origin: 'https://not-exists.com'
  954. });
  955. await collectStreamBody(await getResponse(urlRequest));
  956. });
  957. it('should not send sec-fetch-user header by default', async () => {
  958. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  959. expect(request.headers).not.to.have.property('sec-fetch-user');
  960. response.statusCode = 200;
  961. response.statusMessage = 'OK';
  962. response.end();
  963. });
  964. const urlRequest = net.request({
  965. url: serverUrl
  966. });
  967. await collectStreamBody(await getResponse(urlRequest));
  968. });
  969. it('should set sec-fetch-user to ?1 if requested', async () => {
  970. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  971. expect(request.headers['sec-fetch-user']).to.equal('?1');
  972. response.statusCode = 200;
  973. response.statusMessage = 'OK';
  974. response.end();
  975. });
  976. const urlRequest = net.request({
  977. url: serverUrl
  978. });
  979. urlRequest.setHeader('sec-fetch-user', '?1');
  980. await collectStreamBody(await getResponse(urlRequest));
  981. });
  982. it('should set sec-fetch-mode to no-cors by default', async () => {
  983. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  984. expect(request.headers['sec-fetch-mode']).to.equal('no-cors');
  985. response.statusCode = 200;
  986. response.statusMessage = 'OK';
  987. response.end();
  988. });
  989. const urlRequest = net.request({
  990. url: serverUrl
  991. });
  992. await collectStreamBody(await getResponse(urlRequest));
  993. });
  994. ['navigate', 'cors', 'no-cors', 'same-origin'].forEach((mode) => {
  995. it(`should set sec-fetch-mode to ${mode} if requested`, async () => {
  996. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  997. expect(request.headers['sec-fetch-mode']).to.equal(mode);
  998. response.statusCode = 200;
  999. response.statusMessage = 'OK';
  1000. response.end();
  1001. });
  1002. const urlRequest = net.request({
  1003. url: serverUrl,
  1004. origin: serverUrl
  1005. });
  1006. urlRequest.setHeader('sec-fetch-mode', mode);
  1007. await collectStreamBody(await getResponse(urlRequest));
  1008. });
  1009. });
  1010. it('should set sec-fetch-dest to empty by default', async () => {
  1011. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1012. expect(request.headers['sec-fetch-dest']).to.equal('empty');
  1013. response.statusCode = 200;
  1014. response.statusMessage = 'OK';
  1015. response.end();
  1016. });
  1017. const urlRequest = net.request({
  1018. url: serverUrl
  1019. });
  1020. await collectStreamBody(await getResponse(urlRequest));
  1021. });
  1022. [
  1023. 'empty', 'audio', 'audioworklet', 'document', 'embed', 'font',
  1024. 'frame', 'iframe', 'image', 'manifest', 'object', 'paintworklet',
  1025. 'report', 'script', 'serviceworker', 'style', 'track', 'video',
  1026. 'worker', 'xslt'
  1027. ].forEach((dest) => {
  1028. it(`should set sec-fetch-dest to ${dest} if requested`, async () => {
  1029. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1030. expect(request.headers['sec-fetch-dest']).to.equal(dest);
  1031. response.statusCode = 200;
  1032. response.statusMessage = 'OK';
  1033. response.end();
  1034. });
  1035. const urlRequest = net.request({
  1036. url: serverUrl,
  1037. origin: serverUrl
  1038. });
  1039. urlRequest.setHeader('sec-fetch-dest', dest);
  1040. await collectStreamBody(await getResponse(urlRequest));
  1041. });
  1042. });
  1043. it('should be able to abort an HTTP request before first write', async () => {
  1044. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1045. response.end();
  1046. expect.fail('Unexpected request event');
  1047. });
  1048. const urlRequest = net.request(serverUrl);
  1049. urlRequest.on('response', () => {
  1050. expect.fail('unexpected response event');
  1051. });
  1052. const aborted = once(urlRequest, 'abort');
  1053. urlRequest.abort();
  1054. urlRequest.write('');
  1055. urlRequest.end();
  1056. await aborted;
  1057. });
  1058. it('it should be able to abort an HTTP request before request end', async () => {
  1059. let requestReceivedByServer = false;
  1060. let urlRequest: ClientRequest | null = null;
  1061. const serverUrl = await respondOnce.toSingleURL(() => {
  1062. requestReceivedByServer = true;
  1063. urlRequest!.abort();
  1064. });
  1065. let requestAbortEventEmitted = false;
  1066. urlRequest = net.request(serverUrl);
  1067. urlRequest.on('response', () => {
  1068. expect.fail('Unexpected response event');
  1069. });
  1070. urlRequest.on('finish', () => {
  1071. expect.fail('Unexpected finish event');
  1072. });
  1073. urlRequest.on('error', () => {
  1074. expect.fail('Unexpected error event');
  1075. });
  1076. urlRequest.on('abort', () => {
  1077. requestAbortEventEmitted = true;
  1078. });
  1079. const p = once(urlRequest, 'close');
  1080. urlRequest.chunkedEncoding = true;
  1081. urlRequest.write(randomString(kOneKiloByte));
  1082. await p;
  1083. expect(requestReceivedByServer).to.equal(true);
  1084. expect(requestAbortEventEmitted).to.equal(true);
  1085. });
  1086. it('it should be able to abort an HTTP request after request end and before response', async () => {
  1087. let requestReceivedByServer = false;
  1088. let urlRequest: ClientRequest | null = null;
  1089. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1090. requestReceivedByServer = true;
  1091. urlRequest!.abort();
  1092. process.nextTick(() => {
  1093. response.statusCode = 200;
  1094. response.statusMessage = 'OK';
  1095. response.end();
  1096. });
  1097. });
  1098. let requestFinishEventEmitted = false;
  1099. urlRequest = net.request(serverUrl);
  1100. urlRequest.on('response', () => {
  1101. expect.fail('Unexpected response event');
  1102. });
  1103. urlRequest.on('finish', () => {
  1104. requestFinishEventEmitted = true;
  1105. });
  1106. urlRequest.on('error', () => {
  1107. expect.fail('Unexpected error event');
  1108. });
  1109. urlRequest.end(randomString(kOneKiloByte));
  1110. await once(urlRequest, 'abort');
  1111. expect(requestFinishEventEmitted).to.equal(true);
  1112. expect(requestReceivedByServer).to.equal(true);
  1113. });
  1114. it('it should be able to abort an HTTP request after response start', async () => {
  1115. let requestReceivedByServer = false;
  1116. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1117. requestReceivedByServer = true;
  1118. response.statusCode = 200;
  1119. response.statusMessage = 'OK';
  1120. response.write(randomString(kOneKiloByte));
  1121. });
  1122. let requestFinishEventEmitted = false;
  1123. let requestResponseEventEmitted = false;
  1124. let responseCloseEventEmitted = false;
  1125. const urlRequest = net.request(serverUrl);
  1126. urlRequest.on('response', (response) => {
  1127. requestResponseEventEmitted = true;
  1128. const statusCode = response.statusCode;
  1129. expect(statusCode).to.equal(200);
  1130. response.on('data', () => {});
  1131. response.on('end', () => {
  1132. expect.fail('Unexpected end event');
  1133. });
  1134. response.on('error', () => {
  1135. expect.fail('Unexpected error event');
  1136. });
  1137. response.on('close' as any, () => {
  1138. responseCloseEventEmitted = true;
  1139. });
  1140. urlRequest.abort();
  1141. });
  1142. urlRequest.on('finish', () => {
  1143. requestFinishEventEmitted = true;
  1144. });
  1145. urlRequest.on('error', () => {
  1146. expect.fail('Unexpected error event');
  1147. });
  1148. urlRequest.end(randomString(kOneKiloByte));
  1149. await once(urlRequest, 'abort');
  1150. expect(requestFinishEventEmitted).to.be.true('request should emit "finish" event');
  1151. expect(requestReceivedByServer).to.be.true('request should be received by the server');
  1152. expect(requestResponseEventEmitted).to.be.true('"response" event should be emitted');
  1153. expect(responseCloseEventEmitted).to.be.true('response should emit "close" event');
  1154. });
  1155. it('abort event should be emitted at most once', async () => {
  1156. let requestReceivedByServer = false;
  1157. let urlRequest: ClientRequest | null = null;
  1158. const serverUrl = await respondOnce.toSingleURL(() => {
  1159. requestReceivedByServer = true;
  1160. urlRequest!.abort();
  1161. urlRequest!.abort();
  1162. });
  1163. let requestFinishEventEmitted = false;
  1164. let abortsEmitted = 0;
  1165. urlRequest = net.request(serverUrl);
  1166. urlRequest.on('response', () => {
  1167. expect.fail('Unexpected response event');
  1168. });
  1169. urlRequest.on('finish', () => {
  1170. requestFinishEventEmitted = true;
  1171. });
  1172. urlRequest.on('error', () => {
  1173. expect.fail('Unexpected error event');
  1174. });
  1175. urlRequest.on('abort', () => {
  1176. abortsEmitted++;
  1177. });
  1178. urlRequest.end(randomString(kOneKiloByte));
  1179. await once(urlRequest, 'abort');
  1180. expect(requestFinishEventEmitted).to.be.true('request should emit "finish" event');
  1181. expect(requestReceivedByServer).to.be.true('request should be received by server');
  1182. expect(abortsEmitted).to.equal(1, 'request should emit exactly 1 "abort" event');
  1183. });
  1184. it('should allow to read response body from non-2xx response', async () => {
  1185. const bodyData = randomString(kOneKiloByte);
  1186. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1187. response.statusCode = 404;
  1188. response.end(bodyData);
  1189. });
  1190. const urlRequest = net.request(serverUrl);
  1191. const bodyCheckPromise = getResponse(urlRequest).then(r => {
  1192. expect(r.statusCode).to.equal(404);
  1193. return r;
  1194. }).then(collectStreamBody).then(receivedBodyData => {
  1195. expect(receivedBodyData.toString()).to.equal(bodyData);
  1196. });
  1197. const eventHandlers = Promise.all([
  1198. bodyCheckPromise,
  1199. once(urlRequest, 'close')
  1200. ]);
  1201. urlRequest.end();
  1202. await eventHandlers;
  1203. });
  1204. describe('webRequest', () => {
  1205. afterEach(() => {
  1206. session.defaultSession.webRequest.onBeforeRequest(null);
  1207. });
  1208. it('Should throw when invalid filters are passed', () => {
  1209. expect(() => {
  1210. session.defaultSession.webRequest.onBeforeRequest(
  1211. { urls: ['*://www.googleapis.com'] },
  1212. (details, callback) => { callback({ cancel: false }); }
  1213. );
  1214. }).to.throw('Invalid url pattern *://www.googleapis.com: Empty path.');
  1215. expect(() => {
  1216. session.defaultSession.webRequest.onBeforeRequest(
  1217. { urls: ['*://www.googleapis.com/', '*://blahblah.dev'] },
  1218. (details, callback) => { callback({ cancel: false }); }
  1219. );
  1220. }).to.throw('Invalid url pattern *://blahblah.dev: Empty path.');
  1221. });
  1222. it('Should not throw when valid filters are passed', () => {
  1223. expect(() => {
  1224. session.defaultSession.webRequest.onBeforeRequest(
  1225. { urls: ['*://www.googleapis.com/'] },
  1226. (details, callback) => { callback({ cancel: false }); }
  1227. );
  1228. }).to.not.throw();
  1229. });
  1230. it('Requests should be intercepted by webRequest module', async () => {
  1231. const requestUrl = '/requestUrl';
  1232. const redirectUrl = '/redirectUrl';
  1233. let requestIsRedirected = false;
  1234. const serverUrl = await respondOnce.toURL(redirectUrl, (request, response) => {
  1235. requestIsRedirected = true;
  1236. response.end();
  1237. });
  1238. let requestIsIntercepted = false;
  1239. session.defaultSession.webRequest.onBeforeRequest(
  1240. (details, callback) => {
  1241. if (details.url === `${serverUrl}${requestUrl}`) {
  1242. requestIsIntercepted = true;
  1243. callback({
  1244. redirectURL: `${serverUrl}${redirectUrl}`
  1245. });
  1246. } else {
  1247. callback({
  1248. cancel: false
  1249. });
  1250. }
  1251. });
  1252. const urlRequest = net.request(`${serverUrl}${requestUrl}`);
  1253. const response = await getResponse(urlRequest);
  1254. expect(response.statusCode).to.equal(200);
  1255. await collectStreamBody(response);
  1256. expect(requestIsRedirected).to.be.true('The server should receive a request to the forward URL');
  1257. expect(requestIsIntercepted).to.be.true('The request should be intercepted by the webRequest module');
  1258. });
  1259. it('should to able to create and intercept a request using a custom session object', async () => {
  1260. const requestUrl = '/requestUrl';
  1261. const redirectUrl = '/redirectUrl';
  1262. const customPartitionName = `custom-partition-${Math.random()}`;
  1263. let requestIsRedirected = false;
  1264. const serverUrl = await respondOnce.toURL(redirectUrl, (request, response) => {
  1265. requestIsRedirected = true;
  1266. response.end();
  1267. });
  1268. session.defaultSession.webRequest.onBeforeRequest(() => {
  1269. expect.fail('Request should not be intercepted by the default session');
  1270. });
  1271. const customSession = session.fromPartition(customPartitionName, { cache: false });
  1272. let requestIsIntercepted = false;
  1273. customSession.webRequest.onBeforeRequest((details, callback) => {
  1274. if (details.url === `${serverUrl}${requestUrl}`) {
  1275. requestIsIntercepted = true;
  1276. callback({
  1277. redirectURL: `${serverUrl}${redirectUrl}`
  1278. });
  1279. } else {
  1280. callback({
  1281. cancel: false
  1282. });
  1283. }
  1284. });
  1285. const urlRequest = net.request({
  1286. url: `${serverUrl}${requestUrl}`,
  1287. session: customSession
  1288. });
  1289. const response = await getResponse(urlRequest);
  1290. expect(response.statusCode).to.equal(200);
  1291. await collectStreamBody(response);
  1292. expect(requestIsRedirected).to.be.true('The server should receive a request to the forward URL');
  1293. expect(requestIsIntercepted).to.be.true('The request should be intercepted by the webRequest module');
  1294. });
  1295. it('should to able to create and intercept a request using a custom partition name', async () => {
  1296. const requestUrl = '/requestUrl';
  1297. const redirectUrl = '/redirectUrl';
  1298. const customPartitionName = `custom-partition-${Math.random()}`;
  1299. let requestIsRedirected = false;
  1300. const serverUrl = await respondOnce.toURL(redirectUrl, (request, response) => {
  1301. requestIsRedirected = true;
  1302. response.end();
  1303. });
  1304. session.defaultSession.webRequest.onBeforeRequest(() => {
  1305. expect.fail('Request should not be intercepted by the default session');
  1306. });
  1307. const customSession = session.fromPartition(customPartitionName, { cache: false });
  1308. let requestIsIntercepted = false;
  1309. customSession.webRequest.onBeforeRequest((details, callback) => {
  1310. if (details.url === `${serverUrl}${requestUrl}`) {
  1311. requestIsIntercepted = true;
  1312. callback({
  1313. redirectURL: `${serverUrl}${redirectUrl}`
  1314. });
  1315. } else {
  1316. callback({
  1317. cancel: false
  1318. });
  1319. }
  1320. });
  1321. const urlRequest = net.request({
  1322. url: `${serverUrl}${requestUrl}`,
  1323. partition: customPartitionName
  1324. });
  1325. const response = await getResponse(urlRequest);
  1326. expect(response.statusCode).to.equal(200);
  1327. await collectStreamBody(response);
  1328. expect(requestIsRedirected).to.be.true('The server should receive a request to the forward URL');
  1329. expect(requestIsIntercepted).to.be.true('The request should be intercepted by the webRequest module');
  1330. });
  1331. it('triggers webRequest handlers when bypassCustomProtocolHandlers', async () => {
  1332. let webRequestDetails: Electron.OnBeforeRequestListenerDetails | null = null;
  1333. const serverUrl = await respondOnce.toSingleURL((req, res) => res.end('hi'));
  1334. session.defaultSession.webRequest.onBeforeRequest((details, cb) => {
  1335. webRequestDetails = details;
  1336. cb({});
  1337. });
  1338. const body = await net.fetch(serverUrl, { bypassCustomProtocolHandlers: true }).then(r => r.text());
  1339. expect(body).to.equal('hi');
  1340. expect(webRequestDetails).to.have.property('url', serverUrl);
  1341. });
  1342. });
  1343. it('should throw when calling getHeader without a name', () => {
  1344. expect(() => {
  1345. (net.request({ url: 'https://test' }).getHeader as any)();
  1346. }).to.throw(/`name` is required for getHeader\(name\)/);
  1347. expect(() => {
  1348. net.request({ url: 'https://test' }).getHeader(null as any);
  1349. }).to.throw(/`name` is required for getHeader\(name\)/);
  1350. });
  1351. it('should throw when calling removeHeader without a name', () => {
  1352. expect(() => {
  1353. (net.request({ url: 'https://test' }).removeHeader as any)();
  1354. }).to.throw(/`name` is required for removeHeader\(name\)/);
  1355. expect(() => {
  1356. net.request({ url: 'https://test' }).removeHeader(null as any);
  1357. }).to.throw(/`name` is required for removeHeader\(name\)/);
  1358. });
  1359. it('should follow redirect when no redirect handler is provided', async () => {
  1360. const requestUrl = '/302';
  1361. const serverUrl = await respondOnce.toRoutes({
  1362. '/302': (request, response) => {
  1363. response.statusCode = 302;
  1364. response.setHeader('Location', '/200');
  1365. response.end();
  1366. },
  1367. '/200': (request, response) => {
  1368. response.statusCode = 200;
  1369. response.end();
  1370. }
  1371. });
  1372. const urlRequest = net.request({
  1373. url: `${serverUrl}${requestUrl}`
  1374. });
  1375. const response = await getResponse(urlRequest);
  1376. expect(response.statusCode).to.equal(200);
  1377. });
  1378. it('should follow redirect chain when no redirect handler is provided', async () => {
  1379. const serverUrl = await respondOnce.toRoutes({
  1380. '/redirectChain': (request, response) => {
  1381. response.statusCode = 302;
  1382. response.setHeader('Location', '/302');
  1383. response.end();
  1384. },
  1385. '/302': (request, response) => {
  1386. response.statusCode = 302;
  1387. response.setHeader('Location', '/200');
  1388. response.end();
  1389. },
  1390. '/200': (request, response) => {
  1391. response.statusCode = 200;
  1392. response.end();
  1393. }
  1394. });
  1395. const urlRequest = net.request({
  1396. url: `${serverUrl}/redirectChain`
  1397. });
  1398. const response = await getResponse(urlRequest);
  1399. expect(response.statusCode).to.equal(200);
  1400. });
  1401. it('should not follow redirect when request is canceled in redirect handler', async () => {
  1402. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1403. response.statusCode = 302;
  1404. response.setHeader('Location', '/200');
  1405. response.end();
  1406. });
  1407. const urlRequest = net.request({
  1408. url: serverUrl
  1409. });
  1410. urlRequest.end();
  1411. urlRequest.on('redirect', () => { urlRequest.abort(); });
  1412. urlRequest.on('error', () => {});
  1413. urlRequest.on('response', () => {
  1414. expect.fail('Unexpected response');
  1415. });
  1416. await once(urlRequest, 'abort');
  1417. });
  1418. it('should not follow redirect when mode is error', async () => {
  1419. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1420. response.statusCode = 302;
  1421. response.setHeader('Location', '/200');
  1422. response.end();
  1423. });
  1424. const urlRequest = net.request({
  1425. url: serverUrl,
  1426. redirect: 'error'
  1427. });
  1428. urlRequest.end();
  1429. await once(urlRequest, 'error');
  1430. });
  1431. it('should follow redirect when handler calls callback', async () => {
  1432. const serverUrl = await respondOnce.toRoutes({
  1433. '/redirectChain': (request, response) => {
  1434. response.statusCode = 302;
  1435. response.setHeader('Location', '/302');
  1436. response.end();
  1437. },
  1438. '/302': (request, response) => {
  1439. response.statusCode = 302;
  1440. response.setHeader('Location', '/200');
  1441. response.end();
  1442. },
  1443. '/200': (request, response) => {
  1444. response.statusCode = 200;
  1445. response.end();
  1446. }
  1447. });
  1448. const urlRequest = net.request({ url: `${serverUrl}/redirectChain`, redirect: 'manual' });
  1449. const redirects: string[] = [];
  1450. urlRequest.on('redirect', (status, method, url) => {
  1451. redirects.push(url);
  1452. urlRequest.followRedirect();
  1453. });
  1454. const response = await getResponse(urlRequest);
  1455. expect(response.statusCode).to.equal(200);
  1456. expect(redirects).to.deep.equal([
  1457. `${serverUrl}/302`,
  1458. `${serverUrl}/200`
  1459. ]);
  1460. });
  1461. it('should throw if given an invalid session option', () => {
  1462. expect(() => {
  1463. net.request({
  1464. url: 'https://foo',
  1465. session: 1 as any
  1466. });
  1467. }).to.throw('`session` should be an instance of the Session class');
  1468. });
  1469. it('should throw if given an invalid partition option', () => {
  1470. expect(() => {
  1471. net.request({
  1472. url: 'https://foo',
  1473. partition: 1 as any
  1474. });
  1475. }).to.throw('`partition` should be a string');
  1476. });
  1477. it('should be able to create a request with options', async () => {
  1478. const customHeaderName = 'Some-Custom-Header-Name';
  1479. const customHeaderValue = 'Some-Customer-Header-Value';
  1480. const serverUrlUnparsed = await respondOnce.toURL('/', (request, response) => {
  1481. expect(request.method).to.equal('GET');
  1482. expect(request.headers[customHeaderName.toLowerCase()]).to.equal(customHeaderValue);
  1483. response.statusCode = 200;
  1484. response.statusMessage = 'OK';
  1485. response.end();
  1486. });
  1487. const serverUrl = url.parse(serverUrlUnparsed);
  1488. const options = {
  1489. port: serverUrl.port ? parseInt(serverUrl.port, 10) : undefined,
  1490. hostname: '127.0.0.1',
  1491. headers: { [customHeaderName]: customHeaderValue }
  1492. };
  1493. const urlRequest = net.request(options);
  1494. const response = await getResponse(urlRequest);
  1495. expect(response.statusCode).to.be.equal(200);
  1496. await collectStreamBody(response);
  1497. });
  1498. it('should be able to pipe a readable stream into a net request', async () => {
  1499. const bodyData = randomString(kOneMegaByte);
  1500. let netRequestReceived = false;
  1501. let netRequestEnded = false;
  1502. const [nodeServerUrl, netServerUrl] = await Promise.all([
  1503. respondOnce.toSingleURL((request, response) => response.end(bodyData)),
  1504. respondOnce.toSingleURL((request, response) => {
  1505. netRequestReceived = true;
  1506. let receivedBodyData = '';
  1507. request.on('data', (chunk) => {
  1508. receivedBodyData += chunk.toString();
  1509. });
  1510. request.on('end', (chunk: Buffer | undefined) => {
  1511. netRequestEnded = true;
  1512. if (chunk) {
  1513. receivedBodyData += chunk.toString();
  1514. }
  1515. expect(receivedBodyData).to.be.equal(bodyData);
  1516. response.end();
  1517. });
  1518. })
  1519. ]);
  1520. const nodeRequest = http.request(nodeServerUrl);
  1521. const nodeResponse = await getResponse(nodeRequest as any) as any as http.ServerResponse;
  1522. const netRequest = net.request(netServerUrl);
  1523. const responsePromise = once(netRequest, 'response');
  1524. // TODO(@MarshallOfSound) - FIXME with #22730
  1525. nodeResponse.pipe(netRequest as any);
  1526. const [netResponse] = await responsePromise;
  1527. expect(netResponse.statusCode).to.equal(200);
  1528. await collectStreamBody(netResponse);
  1529. expect(netRequestReceived).to.be.true('net request received');
  1530. expect(netRequestEnded).to.be.true('net request ended');
  1531. });
  1532. it('should report upload progress', async () => {
  1533. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1534. response.end();
  1535. });
  1536. const netRequest = net.request({ url: serverUrl, method: 'POST' });
  1537. expect(netRequest.getUploadProgress()).to.have.property('active', false);
  1538. netRequest.end(Buffer.from('hello'));
  1539. const [position, total] = await once(netRequest, 'upload-progress');
  1540. expect(netRequest.getUploadProgress()).to.deep.equal({ active: true, started: true, current: position, total });
  1541. });
  1542. it('should emit error event on server socket destroy', async () => {
  1543. const serverUrl = await respondOnce.toSingleURL((request) => {
  1544. request.socket.destroy();
  1545. });
  1546. const urlRequest = net.request(serverUrl);
  1547. urlRequest.end();
  1548. const [error] = await once(urlRequest, 'error');
  1549. expect(error.message).to.equal('net::ERR_EMPTY_RESPONSE');
  1550. });
  1551. it('should emit error event on server request destroy', async () => {
  1552. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1553. request.destroy();
  1554. response.end();
  1555. });
  1556. const urlRequest = net.request(serverUrl);
  1557. urlRequest.end(randomBuffer(kOneMegaByte));
  1558. const [error] = await once(urlRequest, 'error');
  1559. expect(error.message).to.be.oneOf(['net::ERR_FAILED', 'net::ERR_CONNECTION_RESET', 'net::ERR_CONNECTION_ABORTED']);
  1560. });
  1561. it('should not emit any event after close', async () => {
  1562. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1563. response.end();
  1564. });
  1565. const urlRequest = net.request(serverUrl);
  1566. urlRequest.end();
  1567. await once(urlRequest, 'close');
  1568. await new Promise((resolve, reject) => {
  1569. ['finish', 'abort', 'close', 'error'].forEach(evName => {
  1570. urlRequest.on(evName as any, () => {
  1571. reject(new Error(`Unexpected ${evName} event`));
  1572. });
  1573. });
  1574. setTimeout(50).then(resolve);
  1575. });
  1576. });
  1577. it('should remove the referer header when no referrer url specified', async () => {
  1578. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1579. expect(request.headers.referer).to.equal(undefined);
  1580. response.statusCode = 200;
  1581. response.statusMessage = 'OK';
  1582. response.end();
  1583. });
  1584. const urlRequest = net.request(serverUrl);
  1585. urlRequest.end();
  1586. const response = await getResponse(urlRequest);
  1587. expect(response.statusCode).to.equal(200);
  1588. await collectStreamBody(response);
  1589. });
  1590. it('should set the referer header when a referrer url specified', async () => {
  1591. const referrerURL = 'https://www.electronjs.org/';
  1592. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1593. expect(request.headers.referer).to.equal(referrerURL);
  1594. response.statusCode = 200;
  1595. response.statusMessage = 'OK';
  1596. response.end();
  1597. });
  1598. // The referrerPolicy must be unsafe-url because the referrer's origin
  1599. // doesn't match the loaded page. With the default referrer policy
  1600. // (strict-origin-when-cross-origin), the request will be canceled by the
  1601. // network service when the referrer header is invalid.
  1602. // See:
  1603. // - https://source.chromium.org/chromium/chromium/src/+/main:net/url_request/url_request.cc;l=682-683;drc=ae587fa7cd2e5cc308ce69353ee9ce86437e5d41
  1604. // - https://source.chromium.org/chromium/chromium/src/+/main:services/network/public/mojom/network_context.mojom;l=316-318;drc=ae5c7fcf09509843c1145f544cce3a61874b9698
  1605. // - https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer
  1606. const urlRequest = net.request({ url: serverUrl, referrerPolicy: 'unsafe-url' });
  1607. urlRequest.setHeader('referer', referrerURL);
  1608. urlRequest.end();
  1609. const response = await getResponse(urlRequest);
  1610. expect(response.statusCode).to.equal(200);
  1611. await collectStreamBody(response);
  1612. });
  1613. });
  1614. describe('IncomingMessage API', () => {
  1615. it('response object should implement the IncomingMessage API', async () => {
  1616. const customHeaderName = 'Some-Custom-Header-Name';
  1617. const customHeaderValue = 'Some-Customer-Header-Value';
  1618. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1619. response.statusCode = 200;
  1620. response.statusMessage = 'OK';
  1621. response.setHeader(customHeaderName, customHeaderValue);
  1622. response.end();
  1623. });
  1624. const urlRequest = net.request(serverUrl);
  1625. const response = await getResponse(urlRequest);
  1626. expect(response.statusCode).to.equal(200);
  1627. expect(response.statusMessage).to.equal('OK');
  1628. const headers = response.headers;
  1629. expect(headers).to.be.an('object');
  1630. const headerValue = headers[customHeaderName.toLowerCase()];
  1631. expect(headerValue).to.equal(customHeaderValue);
  1632. const rawHeaders = response.rawHeaders;
  1633. expect(rawHeaders).to.be.an('array');
  1634. expect(rawHeaders[0]).to.equal(customHeaderName);
  1635. expect(rawHeaders[1]).to.equal(customHeaderValue);
  1636. const httpVersion = response.httpVersion;
  1637. expect(httpVersion).to.be.a('string').and.to.have.lengthOf.at.least(1);
  1638. const httpVersionMajor = response.httpVersionMajor;
  1639. expect(httpVersionMajor).to.be.a('number').and.to.be.at.least(1);
  1640. const httpVersionMinor = response.httpVersionMinor;
  1641. expect(httpVersionMinor).to.be.a('number').and.to.be.at.least(0);
  1642. await collectStreamBody(response);
  1643. });
  1644. it('should discard duplicate headers', async () => {
  1645. const includedHeader = 'max-forwards';
  1646. const discardableHeader = 'Max-Forwards';
  1647. const includedHeaderValue = 'max-fwds-val';
  1648. const discardableHeaderValue = 'max-fwds-val-two';
  1649. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1650. response.statusCode = 200;
  1651. response.statusMessage = 'OK';
  1652. response.setHeader(discardableHeader, discardableHeaderValue);
  1653. response.setHeader(includedHeader, includedHeaderValue);
  1654. response.end();
  1655. });
  1656. const urlRequest = net.request(serverUrl);
  1657. const response = await getResponse(urlRequest);
  1658. expect(response.statusCode).to.equal(200);
  1659. expect(response.statusMessage).to.equal('OK');
  1660. const headers = response.headers;
  1661. expect(headers).to.be.an('object');
  1662. expect(headers).to.have.property(includedHeader);
  1663. expect(headers).to.not.have.property(discardableHeader);
  1664. expect(headers[includedHeader]).to.equal(includedHeaderValue);
  1665. await collectStreamBody(response);
  1666. });
  1667. it('should join repeated non-discardable header values with ,', async () => {
  1668. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1669. response.statusCode = 200;
  1670. response.statusMessage = 'OK';
  1671. response.setHeader('referrer-policy', ['first-text', 'second-text']);
  1672. response.end();
  1673. });
  1674. const urlRequest = net.request(serverUrl);
  1675. const response = await getResponse(urlRequest);
  1676. expect(response.statusCode).to.equal(200);
  1677. expect(response.statusMessage).to.equal('OK');
  1678. const headers = response.headers;
  1679. expect(headers).to.be.an('object');
  1680. expect(headers).to.have.property('referrer-policy');
  1681. expect(headers['referrer-policy']).to.equal('first-text, second-text');
  1682. await collectStreamBody(response);
  1683. });
  1684. it('should not join repeated discardable header values with ,', async () => {
  1685. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1686. response.statusCode = 200;
  1687. response.statusMessage = 'OK';
  1688. response.setHeader('last-modified', ['yesterday', 'today']);
  1689. response.end();
  1690. });
  1691. const urlRequest = net.request(serverUrl);
  1692. const response = await getResponse(urlRequest);
  1693. expect(response.statusCode).to.equal(200);
  1694. expect(response.statusMessage).to.equal('OK');
  1695. const headers = response.headers;
  1696. expect(headers).to.be.an('object');
  1697. expect(headers).to.have.property('last-modified');
  1698. expect(headers['last-modified']).to.equal('yesterday');
  1699. await collectStreamBody(response);
  1700. });
  1701. it('should make set-cookie header an array even if single value', async () => {
  1702. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1703. response.statusCode = 200;
  1704. response.statusMessage = 'OK';
  1705. response.setHeader('set-cookie', 'chocolate-chip');
  1706. response.end();
  1707. });
  1708. const urlRequest = net.request(serverUrl);
  1709. const response = await getResponse(urlRequest);
  1710. expect(response.statusCode).to.equal(200);
  1711. expect(response.statusMessage).to.equal('OK');
  1712. const headers = response.headers;
  1713. expect(headers).to.be.an('object');
  1714. expect(headers).to.have.property('set-cookie');
  1715. expect(headers['set-cookie']).to.be.an('array');
  1716. expect(headers['set-cookie'][0]).to.equal('chocolate-chip');
  1717. await collectStreamBody(response);
  1718. });
  1719. it('should keep set-cookie header an array when an array', async () => {
  1720. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1721. response.statusCode = 200;
  1722. response.statusMessage = 'OK';
  1723. response.setHeader('set-cookie', ['chocolate-chip', 'oatmeal']);
  1724. response.end();
  1725. });
  1726. const urlRequest = net.request(serverUrl);
  1727. const response = await getResponse(urlRequest);
  1728. expect(response.statusCode).to.equal(200);
  1729. expect(response.statusMessage).to.equal('OK');
  1730. const headers = response.headers;
  1731. expect(headers).to.be.an('object');
  1732. expect(headers).to.have.property('set-cookie');
  1733. expect(headers['set-cookie']).to.be.an('array');
  1734. expect(headers['set-cookie'][0]).to.equal('chocolate-chip');
  1735. expect(headers['set-cookie'][1]).to.equal('oatmeal');
  1736. await collectStreamBody(response);
  1737. });
  1738. it('should lowercase header keys', async () => {
  1739. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1740. response.statusCode = 200;
  1741. response.statusMessage = 'OK';
  1742. response.setHeader('HEADER-KEY', ['header-value']);
  1743. response.setHeader('SeT-CookiE', ['chocolate-chip', 'oatmeal']);
  1744. response.setHeader('rEFERREr-pOLICy', ['first-text', 'second-text']);
  1745. response.setHeader('LAST-modified', 'yesterday');
  1746. response.end();
  1747. });
  1748. const urlRequest = net.request(serverUrl);
  1749. const response = await getResponse(urlRequest);
  1750. expect(response.statusCode).to.equal(200);
  1751. expect(response.statusMessage).to.equal('OK');
  1752. const headers = response.headers;
  1753. expect(headers).to.be.an('object');
  1754. expect(headers).to.have.property('header-key');
  1755. expect(headers).to.have.property('set-cookie');
  1756. expect(headers).to.have.property('referrer-policy');
  1757. expect(headers).to.have.property('last-modified');
  1758. await collectStreamBody(response);
  1759. });
  1760. it('should return correct raw headers', async () => {
  1761. const customHeaders: [string, string|string[]][] = [
  1762. ['HEADER-KEY-ONE', 'header-value-one'],
  1763. ['set-cookie', 'chocolate-chip'],
  1764. ['header-key-two', 'header-value-two'],
  1765. ['referrer-policy', ['first-text', 'second-text']],
  1766. ['HEADER-KEY-THREE', 'header-value-three'],
  1767. ['last-modified', ['first-text', 'second-text']],
  1768. ['header-key-four', 'header-value-four']
  1769. ];
  1770. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1771. response.statusCode = 200;
  1772. response.statusMessage = 'OK';
  1773. customHeaders.forEach((headerTuple) => {
  1774. response.setHeader(headerTuple[0], headerTuple[1]);
  1775. });
  1776. response.end();
  1777. });
  1778. const urlRequest = net.request(serverUrl);
  1779. const response = await getResponse(urlRequest);
  1780. expect(response.statusCode).to.equal(200);
  1781. expect(response.statusMessage).to.equal('OK');
  1782. const rawHeaders = response.rawHeaders;
  1783. expect(rawHeaders).to.be.an('array');
  1784. let rawHeadersIdx = 0;
  1785. customHeaders.forEach((headerTuple) => {
  1786. const headerKey = headerTuple[0];
  1787. const headerValues = Array.isArray(headerTuple[1]) ? headerTuple[1] : [headerTuple[1]];
  1788. headerValues.forEach((headerValue) => {
  1789. expect(rawHeaders[rawHeadersIdx]).to.equal(headerKey);
  1790. expect(rawHeaders[rawHeadersIdx + 1]).to.equal(headerValue);
  1791. rawHeadersIdx += 2;
  1792. });
  1793. });
  1794. await collectStreamBody(response);
  1795. });
  1796. it('should be able to pipe a net response into a writable stream', async () => {
  1797. const bodyData = randomString(kOneKiloByte);
  1798. let nodeRequestProcessed = false;
  1799. const [netServerUrl, nodeServerUrl] = await Promise.all([
  1800. respondOnce.toSingleURL((request, response) => response.end(bodyData)),
  1801. respondOnce.toSingleURL(async (request, response) => {
  1802. const receivedBodyData = await collectStreamBody(request);
  1803. expect(receivedBodyData).to.be.equal(bodyData);
  1804. nodeRequestProcessed = true;
  1805. response.end();
  1806. })
  1807. ]);
  1808. const netRequest = net.request(netServerUrl);
  1809. const netResponse = await getResponse(netRequest);
  1810. const serverUrl = url.parse(nodeServerUrl);
  1811. const nodeOptions = {
  1812. method: 'POST',
  1813. path: serverUrl.path,
  1814. port: serverUrl.port
  1815. };
  1816. const nodeRequest = http.request(nodeOptions);
  1817. const nodeResponsePromise = once(nodeRequest, 'response');
  1818. // TODO(@MarshallOfSound) - FIXME with #22730
  1819. (netResponse as any).pipe(nodeRequest);
  1820. const [nodeResponse] = await nodeResponsePromise;
  1821. netRequest.end();
  1822. await collectStreamBody(nodeResponse);
  1823. expect(nodeRequestProcessed).to.equal(true);
  1824. });
  1825. it('should correctly throttle an incoming stream', async () => {
  1826. let numChunksSent = 0;
  1827. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1828. const data = randomString(kOneMegaByte);
  1829. const write = () => {
  1830. let ok = true;
  1831. do {
  1832. numChunksSent++;
  1833. if (numChunksSent > 30) return;
  1834. ok = response.write(data);
  1835. } while (ok);
  1836. response.once('drain', write);
  1837. };
  1838. write();
  1839. });
  1840. const urlRequest = net.request(serverUrl);
  1841. urlRequest.on('response', () => {});
  1842. urlRequest.end();
  1843. await setTimeout(2000);
  1844. // TODO(nornagon): I think this ought to max out at 20, but in practice
  1845. // it seems to exceed that sometimes. This is at 25 to avoid test flakes,
  1846. // but we should investigate if there's actually something broken here and
  1847. // if so fix it and reset this to max at 20, and if not then delete this
  1848. // comment.
  1849. expect(numChunksSent).to.be.at.most(25);
  1850. });
  1851. });
  1852. describe('net.isOnline', () => {
  1853. it('getter returns boolean', () => {
  1854. expect(net.isOnline()).to.be.a('boolean');
  1855. });
  1856. it('property returns boolean', () => {
  1857. expect(net.online).to.be.a('boolean');
  1858. });
  1859. });
  1860. describe('Stability and performance', () => {
  1861. it('should free unreferenced, never-started request objects without crash', (done) => {
  1862. net.request('https://test');
  1863. process.nextTick(() => {
  1864. const v8Util = process._linkedBinding('electron_common_v8_util');
  1865. v8Util.requestGarbageCollectionForTesting();
  1866. done();
  1867. });
  1868. });
  1869. it('should collect on-going requests without crash', async () => {
  1870. let finishResponse: (() => void) | null = null;
  1871. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1872. response.write(randomString(kOneKiloByte));
  1873. finishResponse = () => {
  1874. response.write(randomString(kOneKiloByte));
  1875. response.end();
  1876. };
  1877. });
  1878. const urlRequest = net.request(serverUrl);
  1879. const response = await getResponse(urlRequest);
  1880. process.nextTick(() => {
  1881. // Trigger a garbage collection.
  1882. const v8Util = process._linkedBinding('electron_common_v8_util');
  1883. v8Util.requestGarbageCollectionForTesting();
  1884. finishResponse!();
  1885. });
  1886. await collectStreamBody(response);
  1887. });
  1888. it('should collect unreferenced, ended requests without crash', async () => {
  1889. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1890. response.end();
  1891. });
  1892. const urlRequest = net.request(serverUrl);
  1893. process.nextTick(() => {
  1894. const v8Util = process._linkedBinding('electron_common_v8_util');
  1895. v8Util.requestGarbageCollectionForTesting();
  1896. });
  1897. const response = await getResponse(urlRequest);
  1898. await collectStreamBody(response);
  1899. });
  1900. it('should finish sending data when urlRequest is unreferenced', async () => {
  1901. const serverUrl = await respondOnce.toSingleURL(async (request, response) => {
  1902. const received = await collectStreamBodyBuffer(request);
  1903. expect(received.length).to.equal(kOneMegaByte);
  1904. response.end();
  1905. });
  1906. const urlRequest = net.request(serverUrl);
  1907. urlRequest.on('close', () => {
  1908. process.nextTick(() => {
  1909. const v8Util = process._linkedBinding('electron_common_v8_util');
  1910. v8Util.requestGarbageCollectionForTesting();
  1911. });
  1912. });
  1913. urlRequest.write(randomBuffer(kOneMegaByte));
  1914. const response = await getResponse(urlRequest);
  1915. await collectStreamBody(response);
  1916. });
  1917. it('should finish sending data when urlRequest is unreferenced for chunked encoding', async () => {
  1918. const serverUrl = await respondOnce.toSingleURL(async (request, response) => {
  1919. const received = await collectStreamBodyBuffer(request);
  1920. response.end();
  1921. expect(received.length).to.equal(kOneMegaByte);
  1922. });
  1923. const urlRequest = net.request(serverUrl);
  1924. urlRequest.chunkedEncoding = true;
  1925. urlRequest.write(randomBuffer(kOneMegaByte));
  1926. const response = await getResponse(urlRequest);
  1927. await collectStreamBody(response);
  1928. process.nextTick(() => {
  1929. const v8Util = process._linkedBinding('electron_common_v8_util');
  1930. v8Util.requestGarbageCollectionForTesting();
  1931. });
  1932. });
  1933. it('should finish sending data when urlRequest is unreferenced before close event for chunked encoding', async () => {
  1934. const serverUrl = await respondOnce.toSingleURL(async (request, response) => {
  1935. const received = await collectStreamBodyBuffer(request);
  1936. response.end();
  1937. expect(received.length).to.equal(kOneMegaByte);
  1938. });
  1939. const urlRequest = net.request(serverUrl);
  1940. urlRequest.chunkedEncoding = true;
  1941. urlRequest.write(randomBuffer(kOneMegaByte));
  1942. const v8Util = process._linkedBinding('electron_common_v8_util');
  1943. v8Util.requestGarbageCollectionForTesting();
  1944. await collectStreamBody(await getResponse(urlRequest));
  1945. });
  1946. it('should finish sending data when urlRequest is unreferenced', async () => {
  1947. const serverUrl = await respondOnce.toSingleURL(async (request, response) => {
  1948. const received = await collectStreamBodyBuffer(request);
  1949. response.end();
  1950. expect(received.length).to.equal(kOneMegaByte);
  1951. });
  1952. const urlRequest = net.request(serverUrl);
  1953. urlRequest.on('close', () => {
  1954. process.nextTick(() => {
  1955. const v8Util = process._linkedBinding('electron_common_v8_util');
  1956. v8Util.requestGarbageCollectionForTesting();
  1957. });
  1958. });
  1959. urlRequest.write(randomBuffer(kOneMegaByte));
  1960. await collectStreamBody(await getResponse(urlRequest));
  1961. });
  1962. it('should finish sending data when urlRequest is unreferenced for chunked encoding', async () => {
  1963. const serverUrl = await respondOnce.toSingleURL(async (request, response) => {
  1964. const received = await collectStreamBodyBuffer(request);
  1965. response.end();
  1966. expect(received.length).to.equal(kOneMegaByte);
  1967. });
  1968. const urlRequest = net.request(serverUrl);
  1969. urlRequest.on('close', () => {
  1970. process.nextTick(() => {
  1971. const v8Util = process._linkedBinding('electron_common_v8_util');
  1972. v8Util.requestGarbageCollectionForTesting();
  1973. });
  1974. });
  1975. urlRequest.chunkedEncoding = true;
  1976. urlRequest.write(randomBuffer(kOneMegaByte));
  1977. await collectStreamBody(await getResponse(urlRequest));
  1978. });
  1979. });
  1980. describe('non-http schemes', () => {
  1981. it('should be rejected by net.request', async () => {
  1982. expect(() => {
  1983. net.request('file://bar');
  1984. }).to.throw('ClientRequest only supports http: and https: protocols');
  1985. });
  1986. it('should be rejected by net.request when passed in url:', async () => {
  1987. expect(() => {
  1988. net.request({ url: 'file://bar' });
  1989. }).to.throw('ClientRequest only supports http: and https: protocols');
  1990. });
  1991. });
  1992. describe('net.fetch', () => {
  1993. // NB. there exist much more comprehensive tests for fetch() in the form of
  1994. // the WPT: https://github.com/web-platform-tests/wpt/tree/master/fetch
  1995. // It's possible to run these tests against net.fetch(), but the test
  1996. // harness to do so is quite complex and hasn't been munged to smoothly run
  1997. // inside the Electron test runner yet.
  1998. //
  1999. // In the meantime, here are some tests for basic functionality and
  2000. // Electron-specific behavior.
  2001. describe('basic', () => {
  2002. it('can fetch http urls', async () => {
  2003. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  2004. response.end('test');
  2005. });
  2006. const resp = await net.fetch(serverUrl);
  2007. expect(resp.ok).to.be.true();
  2008. expect(await resp.text()).to.equal('test');
  2009. });
  2010. it('can upload a string body', async () => {
  2011. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  2012. request.on('data', chunk => response.write(chunk));
  2013. request.on('end', () => response.end());
  2014. });
  2015. const resp = await net.fetch(serverUrl, {
  2016. method: 'POST',
  2017. body: 'anchovies'
  2018. });
  2019. expect(await resp.text()).to.equal('anchovies');
  2020. });
  2021. it('can read response as an array buffer', async () => {
  2022. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  2023. request.on('data', chunk => response.write(chunk));
  2024. request.on('end', () => response.end());
  2025. });
  2026. const resp = await net.fetch(serverUrl, {
  2027. method: 'POST',
  2028. body: 'anchovies'
  2029. });
  2030. expect(new TextDecoder().decode(new Uint8Array(await resp.arrayBuffer()))).to.equal('anchovies');
  2031. });
  2032. it('can read response as form data', async () => {
  2033. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  2034. response.setHeader('content-type', 'application/x-www-form-urlencoded');
  2035. response.end('foo=bar');
  2036. });
  2037. const resp = await net.fetch(serverUrl);
  2038. const result = await resp.formData();
  2039. expect(result.get('foo')).to.equal('bar');
  2040. });
  2041. it('should be able to use a session cookie store', async () => {
  2042. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  2043. response.statusCode = 200;
  2044. response.statusMessage = 'OK';
  2045. response.setHeader('x-cookie', request.headers.cookie!);
  2046. response.end();
  2047. });
  2048. const sess = session.fromPartition(`cookie-tests-${Math.random()}`);
  2049. const cookieVal = `${Date.now()}`;
  2050. await sess.cookies.set({
  2051. url: serverUrl,
  2052. name: 'wild_cookie',
  2053. value: cookieVal
  2054. });
  2055. const response = await sess.fetch(serverUrl, {
  2056. credentials: 'include'
  2057. });
  2058. expect(response.headers.get('x-cookie')).to.equal(`wild_cookie=${cookieVal}`);
  2059. });
  2060. it('should reject promise on DNS failure', async () => {
  2061. const r = net.fetch('https://i.do.not.exist');
  2062. await expect(r).to.be.rejectedWith(/ERR_NAME_NOT_RESOLVED/);
  2063. });
  2064. it('should reject body promise when stream fails', async () => {
  2065. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  2066. response.write('first chunk');
  2067. setTimeout().then(() => response.destroy());
  2068. });
  2069. const r = await net.fetch(serverUrl);
  2070. expect(r.status).to.equal(200);
  2071. await expect(r.text()).to.be.rejectedWith(/ERR_INCOMPLETE_CHUNKED_ENCODING/);
  2072. });
  2073. });
  2074. it('can request file:// URLs', async () => {
  2075. const resp = await net.fetch(url.pathToFileURL(path.join(__dirname, 'fixtures', 'hello.txt')).toString());
  2076. expect(resp.ok).to.be.true();
  2077. // trimRight instead of asserting the whole string to avoid line ending shenanigans on WOA
  2078. expect((await resp.text()).trimRight()).to.equal('hello world');
  2079. });
  2080. it('can make requests to custom protocols', async () => {
  2081. protocol.registerStringProtocol('electron-test', (req, cb) => { cb('hello ' + req.url); });
  2082. defer(() => {
  2083. protocol.unregisterProtocol('electron-test');
  2084. });
  2085. const body = await net.fetch('electron-test://foo').then(r => r.text());
  2086. expect(body).to.equal('hello electron-test://foo');
  2087. });
  2088. it('runs through intercept handlers', async () => {
  2089. protocol.interceptStringProtocol('http', (req, cb) => { cb('hello ' + req.url); });
  2090. defer(() => {
  2091. protocol.uninterceptProtocol('http');
  2092. });
  2093. const body = await net.fetch('http://foo').then(r => r.text());
  2094. expect(body).to.equal('hello http://foo/');
  2095. });
  2096. it('file: runs through intercept handlers', async () => {
  2097. protocol.interceptStringProtocol('file', (req, cb) => { cb('hello ' + req.url); });
  2098. defer(() => {
  2099. protocol.uninterceptProtocol('file');
  2100. });
  2101. const body = await net.fetch('file://foo').then(r => r.text());
  2102. expect(body).to.equal('hello file://foo/');
  2103. });
  2104. it('can be redirected', async () => {
  2105. protocol.interceptStringProtocol('file', (req, cb) => { cb({ statusCode: 302, headers: { location: 'electron-test://bar' } }); });
  2106. defer(() => {
  2107. protocol.uninterceptProtocol('file');
  2108. });
  2109. protocol.registerStringProtocol('electron-test', (req, cb) => { cb('hello ' + req.url); });
  2110. defer(() => {
  2111. protocol.unregisterProtocol('electron-test');
  2112. });
  2113. const body = await net.fetch('file://foo').then(r => r.text());
  2114. expect(body).to.equal('hello electron-test://bar');
  2115. });
  2116. it('should not follow redirect when redirect: error', async () => {
  2117. protocol.registerStringProtocol('electron-test', (req, cb) => {
  2118. if (/redirect/.test(req.url)) return cb({ statusCode: 302, headers: { location: 'electron-test://bar' } });
  2119. cb('hello ' + req.url);
  2120. });
  2121. defer(() => {
  2122. protocol.unregisterProtocol('electron-test');
  2123. });
  2124. await expect(net.fetch('electron-test://redirect', { redirect: 'error' })).to.eventually.be.rejectedWith('Attempted to redirect, but redirect policy was \'error\'');
  2125. });
  2126. it('a 307 redirected POST request preserves the body', async () => {
  2127. const bodyData = 'Hello World!';
  2128. let postedBodyData: any;
  2129. protocol.registerStringProtocol('electron-test', async (req, cb) => {
  2130. if (/redirect/.test(req.url)) return cb({ statusCode: 307, headers: { location: 'electron-test://bar' } });
  2131. postedBodyData = req.uploadData![0].bytes.toString();
  2132. cb('hello ' + req.url);
  2133. });
  2134. defer(() => {
  2135. protocol.unregisterProtocol('electron-test');
  2136. });
  2137. const response = await net.fetch('electron-test://redirect', {
  2138. method: 'POST',
  2139. body: bodyData
  2140. });
  2141. expect(response.status).to.equal(200);
  2142. await response.text();
  2143. expect(postedBodyData).to.equal(bodyData);
  2144. });
  2145. });
  2146. });