api-net-spec.ts 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525
  1. import { expect } from 'chai';
  2. import { net, session, ClientRequest, BrowserWindow } from 'electron/main';
  3. import * as http from 'http';
  4. import * as url from 'url';
  5. import { AddressInfo, Socket } from 'net';
  6. import { emittedOnce } from './events-helpers';
  7. import { defer } from './spec-helpers';
  8. const kOneKiloByte = 1024;
  9. const kOneMegaByte = kOneKiloByte * kOneKiloByte;
  10. function randomBuffer (size: number, start: number = 0, end: number = 255) {
  11. const range = 1 + end - start;
  12. const buffer = Buffer.allocUnsafe(size);
  13. for (let i = 0; i < size; ++i) {
  14. buffer[i] = start + Math.floor(Math.random() * range);
  15. }
  16. return buffer;
  17. }
  18. function randomString (length: number) {
  19. const buffer = randomBuffer(length, '0'.charCodeAt(0), 'z'.charCodeAt(0));
  20. return buffer.toString();
  21. }
  22. async function getResponse (urlRequest: Electron.ClientRequest) {
  23. return new Promise<Electron.IncomingMessage>((resolve, reject) => {
  24. urlRequest.on('error', reject);
  25. urlRequest.on('abort', reject);
  26. urlRequest.on('response', (response) => resolve(response));
  27. urlRequest.end();
  28. });
  29. }
  30. async function collectStreamBody (response: Electron.IncomingMessage | http.IncomingMessage) {
  31. return (await collectStreamBodyBuffer(response)).toString();
  32. }
  33. function collectStreamBodyBuffer (response: Electron.IncomingMessage | http.IncomingMessage) {
  34. return new Promise<Buffer>((resolve, reject) => {
  35. response.on('error', reject);
  36. (response as NodeJS.EventEmitter).on('aborted', reject);
  37. const data: Buffer[] = [];
  38. response.on('data', (chunk) => data.push(chunk));
  39. response.on('end', (chunk?: Buffer) => {
  40. if (chunk) data.push(chunk);
  41. resolve(Buffer.concat(data));
  42. });
  43. });
  44. }
  45. function respondNTimes (fn: http.RequestListener, n: number): Promise<string> {
  46. return new Promise((resolve) => {
  47. const server = http.createServer((request, response) => {
  48. fn(request, response);
  49. // don't close if a redirect was returned
  50. if ((response.statusCode < 300 || response.statusCode >= 399) && n <= 0) {
  51. n--;
  52. server.close();
  53. }
  54. });
  55. server.listen(0, '127.0.0.1', () => {
  56. resolve(`http://127.0.0.1:${(server.address() as AddressInfo).port}`);
  57. });
  58. const sockets: Socket[] = [];
  59. server.on('connection', s => sockets.push(s));
  60. defer(() => {
  61. server.close();
  62. sockets.forEach(s => s.destroy());
  63. });
  64. });
  65. }
  66. function respondOnce (fn: http.RequestListener) {
  67. return respondNTimes(fn, 1);
  68. }
  69. let routeFailure = false;
  70. respondNTimes.toRoutes = (routes: Record<string, http.RequestListener>, n: number) => {
  71. return respondNTimes((request, response) => {
  72. if (Object.prototype.hasOwnProperty.call(routes, request.url || '')) {
  73. (async () => {
  74. await Promise.resolve(routes[request.url || ''](request, response));
  75. })().catch((err) => {
  76. routeFailure = true;
  77. console.error('Route handler failed, this is probably why your test failed', err);
  78. response.statusCode = 500;
  79. response.end();
  80. });
  81. } else {
  82. response.statusCode = 500;
  83. response.end();
  84. expect.fail(`Unexpected URL: ${request.url}`);
  85. }
  86. }, n);
  87. };
  88. respondOnce.toRoutes = (routes: Record<string, http.RequestListener>) => respondNTimes.toRoutes(routes, 1);
  89. respondNTimes.toURL = (url: string, fn: http.RequestListener, n: number) => {
  90. return respondNTimes.toRoutes({ [url]: fn }, n);
  91. };
  92. respondOnce.toURL = (url: string, fn: http.RequestListener) => respondNTimes.toURL(url, fn, 1);
  93. respondNTimes.toSingleURL = (fn: http.RequestListener, n: number) => {
  94. const requestUrl = '/requestUrl';
  95. return respondNTimes.toURL(requestUrl, fn, n).then(url => `${url}${requestUrl}`);
  96. };
  97. respondOnce.toSingleURL = (fn: http.RequestListener) => respondNTimes.toSingleURL(fn, 1);
  98. describe('net module', () => {
  99. beforeEach(() => {
  100. routeFailure = false;
  101. });
  102. afterEach(async function () {
  103. await session.defaultSession.clearCache();
  104. if (routeFailure && this.test) {
  105. if (!this.test.isFailed()) {
  106. throw new Error('Failing this test due an unhandled error in the respondOnce route handler, check the logs above for the actual error');
  107. }
  108. }
  109. });
  110. describe('HTTP basics', () => {
  111. it('should be able to issue a basic GET request', async () => {
  112. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  113. expect(request.method).to.equal('GET');
  114. response.end();
  115. });
  116. const urlRequest = net.request(serverUrl);
  117. const response = await getResponse(urlRequest);
  118. expect(response.statusCode).to.equal(200);
  119. await collectStreamBody(response);
  120. });
  121. it('should be able to issue a basic POST request', async () => {
  122. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  123. expect(request.method).to.equal('POST');
  124. response.end();
  125. });
  126. const urlRequest = net.request({
  127. method: 'POST',
  128. url: serverUrl
  129. });
  130. const response = await getResponse(urlRequest);
  131. expect(response.statusCode).to.equal(200);
  132. await collectStreamBody(response);
  133. });
  134. it('should fetch correct data in a GET request', async () => {
  135. const expectedBodyData = 'Hello World!';
  136. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  137. expect(request.method).to.equal('GET');
  138. response.end(expectedBodyData);
  139. });
  140. const urlRequest = net.request(serverUrl);
  141. const response = await getResponse(urlRequest);
  142. expect(response.statusCode).to.equal(200);
  143. const body = await collectStreamBody(response);
  144. expect(body).to.equal(expectedBodyData);
  145. });
  146. it('should post the correct data in a POST request', async () => {
  147. const bodyData = 'Hello World!';
  148. const serverUrl = await respondOnce.toSingleURL(async (request, response) => {
  149. const postedBodyData = await collectStreamBody(request);
  150. expect(postedBodyData).to.equal(bodyData);
  151. response.end();
  152. });
  153. const urlRequest = net.request({
  154. method: 'POST',
  155. url: serverUrl
  156. });
  157. urlRequest.write(bodyData);
  158. const response = await getResponse(urlRequest);
  159. expect(response.statusCode).to.equal(200);
  160. });
  161. it('should support chunked encoding', async () => {
  162. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  163. response.statusCode = 200;
  164. response.statusMessage = 'OK';
  165. response.chunkedEncoding = true;
  166. expect(request.method).to.equal('POST');
  167. expect(request.headers['transfer-encoding']).to.equal('chunked');
  168. expect(request.headers['content-length']).to.equal(undefined);
  169. request.on('data', (chunk: Buffer) => {
  170. response.write(chunk);
  171. });
  172. request.on('end', (chunk: Buffer) => {
  173. response.end(chunk);
  174. });
  175. });
  176. const urlRequest = net.request({
  177. method: 'POST',
  178. url: serverUrl
  179. });
  180. let chunkIndex = 0;
  181. const chunkCount = 100;
  182. let sent = Buffer.alloc(0);
  183. urlRequest.chunkedEncoding = true;
  184. while (chunkIndex < chunkCount) {
  185. chunkIndex += 1;
  186. const chunk = randomBuffer(kOneKiloByte);
  187. sent = Buffer.concat([sent, chunk]);
  188. urlRequest.write(chunk);
  189. }
  190. const response = await getResponse(urlRequest);
  191. expect(response.statusCode).to.equal(200);
  192. const received = await collectStreamBodyBuffer(response);
  193. expect(sent.equals(received)).to.be.true();
  194. expect(chunkIndex).to.be.equal(chunkCount);
  195. });
  196. it('should emit the login event when 401', async () => {
  197. const [user, pass] = ['user', 'pass'];
  198. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  199. if (!request.headers.authorization) {
  200. return response.writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' }).end();
  201. }
  202. response.writeHead(200).end('ok');
  203. });
  204. let loginAuthInfo: Electron.AuthInfo;
  205. const request = net.request({ method: 'GET', url: serverUrl });
  206. request.on('login', (authInfo, cb) => {
  207. loginAuthInfo = authInfo;
  208. cb(user, pass);
  209. });
  210. const response = await getResponse(request);
  211. expect(response.statusCode).to.equal(200);
  212. expect(loginAuthInfo!.realm).to.equal('Foo');
  213. expect(loginAuthInfo!.scheme).to.equal('basic');
  214. });
  215. it('should response when cancelling authentication', async () => {
  216. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  217. if (!request.headers.authorization) {
  218. response.writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' });
  219. response.end('unauthenticated');
  220. } else {
  221. response.writeHead(200).end('ok');
  222. }
  223. });
  224. const request = net.request({ method: 'GET', url: serverUrl });
  225. request.on('login', (authInfo, cb) => {
  226. cb();
  227. });
  228. const response = await getResponse(request);
  229. const body = await collectStreamBody(response);
  230. expect(body).to.equal('unauthenticated');
  231. });
  232. it('should share credentials with WebContents', async () => {
  233. const [user, pass] = ['user', 'pass'];
  234. const serverUrl = await respondNTimes.toSingleURL((request, response) => {
  235. if (!request.headers.authorization) {
  236. return response.writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' }).end();
  237. }
  238. return response.writeHead(200).end('ok');
  239. }, 2);
  240. const bw = new BrowserWindow({ show: false });
  241. bw.webContents.on('login', (event, details, authInfo, cb) => {
  242. event.preventDefault();
  243. cb(user, pass);
  244. });
  245. await bw.loadURL(serverUrl);
  246. bw.close();
  247. const request = net.request({ method: 'GET', url: serverUrl });
  248. let logInCount = 0;
  249. request.on('login', () => {
  250. logInCount++;
  251. });
  252. const response = await getResponse(request);
  253. await collectStreamBody(response);
  254. expect(logInCount).to.equal(0, 'should not receive a login event, credentials should be cached');
  255. });
  256. it('should share proxy credentials with WebContents', async () => {
  257. const [user, pass] = ['user', 'pass'];
  258. const proxyUrl = await respondNTimes((request, response) => {
  259. if (!request.headers['proxy-authorization']) {
  260. return response.writeHead(407, { 'Proxy-Authenticate': 'Basic realm="Foo"' }).end();
  261. }
  262. return response.writeHead(200).end('ok');
  263. }, 2);
  264. const customSession = session.fromPartition(`net-proxy-test-${Math.random()}`);
  265. await customSession.setProxy({ proxyRules: proxyUrl.replace('http://', ''), proxyBypassRules: '<-loopback>' });
  266. const bw = new BrowserWindow({ show: false, webPreferences: { session: customSession } });
  267. bw.webContents.on('login', (event, details, authInfo, cb) => {
  268. event.preventDefault();
  269. cb(user, pass);
  270. });
  271. await bw.loadURL('http://127.0.0.1:9999');
  272. bw.close();
  273. const request = net.request({ method: 'GET', url: 'http://127.0.0.1:9999', session: customSession });
  274. let logInCount = 0;
  275. request.on('login', () => {
  276. logInCount++;
  277. });
  278. const response = await getResponse(request);
  279. const body = await collectStreamBody(response);
  280. expect(response.statusCode).to.equal(200);
  281. expect(body).to.equal('ok');
  282. expect(logInCount).to.equal(0, 'should not receive a login event, credentials should be cached');
  283. });
  284. it('should upload body when 401', async () => {
  285. const [user, pass] = ['user', 'pass'];
  286. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  287. if (!request.headers.authorization) {
  288. return response.writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' }).end();
  289. }
  290. response.writeHead(200);
  291. request.on('data', (chunk) => response.write(chunk));
  292. request.on('end', () => response.end());
  293. });
  294. const requestData = randomString(kOneKiloByte);
  295. const request = net.request({ method: 'GET', url: serverUrl });
  296. request.on('login', (authInfo, cb) => {
  297. cb(user, pass);
  298. });
  299. request.write(requestData);
  300. const response = await getResponse(request);
  301. const responseData = await collectStreamBody(response);
  302. expect(responseData).to.equal(requestData);
  303. });
  304. });
  305. describe('ClientRequest API', () => {
  306. it('request/response objects should emit expected events', async () => {
  307. const bodyData = randomString(kOneKiloByte);
  308. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  309. response.end(bodyData);
  310. });
  311. const urlRequest = net.request(serverUrl);
  312. // request close event
  313. const closePromise = emittedOnce(urlRequest, 'close');
  314. // request finish event
  315. const finishPromise = emittedOnce(urlRequest, 'close');
  316. // request "response" event
  317. const response = await getResponse(urlRequest);
  318. response.on('error', (error: Error) => {
  319. expect(error).to.be.an('Error');
  320. });
  321. const statusCode = response.statusCode;
  322. expect(statusCode).to.equal(200);
  323. // response data event
  324. // respond end event
  325. const body = await collectStreamBody(response);
  326. expect(body).to.equal(bodyData);
  327. urlRequest.on('error', (error) => {
  328. expect(error).to.be.an('Error');
  329. });
  330. await Promise.all([closePromise, finishPromise]);
  331. });
  332. it('should be able to set a custom HTTP request header before first write', async () => {
  333. const customHeaderName = 'Some-Custom-Header-Name';
  334. const customHeaderValue = 'Some-Customer-Header-Value';
  335. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  336. expect(request.headers[customHeaderName.toLowerCase()]).to.equal(customHeaderValue);
  337. response.statusCode = 200;
  338. response.statusMessage = 'OK';
  339. response.end();
  340. });
  341. const urlRequest = net.request(serverUrl);
  342. urlRequest.setHeader(customHeaderName, customHeaderValue);
  343. expect(urlRequest.getHeader(customHeaderName)).to.equal(customHeaderValue);
  344. expect(urlRequest.getHeader(customHeaderName.toLowerCase())).to.equal(customHeaderValue);
  345. urlRequest.write('');
  346. expect(urlRequest.getHeader(customHeaderName)).to.equal(customHeaderValue);
  347. expect(urlRequest.getHeader(customHeaderName.toLowerCase())).to.equal(customHeaderValue);
  348. const response = await getResponse(urlRequest);
  349. expect(response.statusCode).to.equal(200);
  350. await collectStreamBody(response);
  351. });
  352. it('should be able to set a non-string object as a header value', async () => {
  353. const customHeaderName = 'Some-Integer-Value';
  354. const customHeaderValue = 900;
  355. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  356. expect(request.headers[customHeaderName.toLowerCase()]).to.equal(customHeaderValue.toString());
  357. response.statusCode = 200;
  358. response.statusMessage = 'OK';
  359. response.end();
  360. });
  361. const urlRequest = net.request(serverUrl);
  362. urlRequest.setHeader(customHeaderName, customHeaderValue as any);
  363. expect(urlRequest.getHeader(customHeaderName)).to.equal(customHeaderValue);
  364. expect(urlRequest.getHeader(customHeaderName.toLowerCase())).to.equal(customHeaderValue);
  365. urlRequest.write('');
  366. expect(urlRequest.getHeader(customHeaderName)).to.equal(customHeaderValue);
  367. expect(urlRequest.getHeader(customHeaderName.toLowerCase())).to.equal(customHeaderValue);
  368. const response = await getResponse(urlRequest);
  369. expect(response.statusCode).to.equal(200);
  370. await collectStreamBody(response);
  371. });
  372. it('should not be able to set a custom HTTP request header after first write', async () => {
  373. const customHeaderName = 'Some-Custom-Header-Name';
  374. const customHeaderValue = 'Some-Customer-Header-Value';
  375. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  376. expect(request.headers[customHeaderName.toLowerCase()]).to.equal(undefined);
  377. response.statusCode = 200;
  378. response.statusMessage = 'OK';
  379. response.end();
  380. });
  381. const urlRequest = net.request(serverUrl);
  382. urlRequest.write('');
  383. expect(() => {
  384. urlRequest.setHeader(customHeaderName, customHeaderValue);
  385. }).to.throw();
  386. expect(urlRequest.getHeader(customHeaderName)).to.equal(undefined);
  387. const response = await getResponse(urlRequest);
  388. expect(response.statusCode).to.equal(200);
  389. await collectStreamBody(response);
  390. });
  391. it('should be able to remove a custom HTTP request header before first write', async () => {
  392. const customHeaderName = 'Some-Custom-Header-Name';
  393. const customHeaderValue = 'Some-Customer-Header-Value';
  394. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  395. expect(request.headers[customHeaderName.toLowerCase()]).to.equal(undefined);
  396. response.statusCode = 200;
  397. response.statusMessage = 'OK';
  398. response.end();
  399. });
  400. const urlRequest = net.request(serverUrl);
  401. urlRequest.setHeader(customHeaderName, customHeaderValue);
  402. expect(urlRequest.getHeader(customHeaderName)).to.equal(customHeaderValue);
  403. urlRequest.removeHeader(customHeaderName);
  404. expect(urlRequest.getHeader(customHeaderName)).to.equal(undefined);
  405. urlRequest.write('');
  406. const response = await getResponse(urlRequest);
  407. expect(response.statusCode).to.equal(200);
  408. await collectStreamBody(response);
  409. });
  410. it('should not be able to remove a custom HTTP request header after first write', async () => {
  411. const customHeaderName = 'Some-Custom-Header-Name';
  412. const customHeaderValue = 'Some-Customer-Header-Value';
  413. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  414. expect(request.headers[customHeaderName.toLowerCase()]).to.equal(customHeaderValue);
  415. response.statusCode = 200;
  416. response.statusMessage = 'OK';
  417. response.end();
  418. });
  419. const urlRequest = net.request(serverUrl);
  420. urlRequest.setHeader(customHeaderName, customHeaderValue);
  421. expect(urlRequest.getHeader(customHeaderName)).to.equal(customHeaderValue);
  422. urlRequest.write('');
  423. expect(() => {
  424. urlRequest.removeHeader(customHeaderName);
  425. }).to.throw();
  426. expect(urlRequest.getHeader(customHeaderName)).to.equal(customHeaderValue);
  427. const response = await getResponse(urlRequest);
  428. expect(response.statusCode).to.equal(200);
  429. await collectStreamBody(response);
  430. });
  431. it('should be able to set cookie header line', async () => {
  432. const cookieHeaderName = 'Cookie';
  433. const cookieHeaderValue = 'test=12345';
  434. const customSession = session.fromPartition('test-cookie-header');
  435. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  436. expect(request.headers[cookieHeaderName.toLowerCase()]).to.equal(cookieHeaderValue);
  437. response.statusCode = 200;
  438. response.statusMessage = 'OK';
  439. response.end();
  440. });
  441. await customSession.cookies.set({
  442. url: `${serverUrl}`,
  443. name: 'test',
  444. value: '11111',
  445. expirationDate: 0
  446. });
  447. const urlRequest = net.request({
  448. method: 'GET',
  449. url: serverUrl,
  450. session: customSession
  451. });
  452. urlRequest.setHeader(cookieHeaderName, cookieHeaderValue);
  453. expect(urlRequest.getHeader(cookieHeaderName)).to.equal(cookieHeaderValue);
  454. const response = await getResponse(urlRequest);
  455. expect(response.statusCode).to.equal(200);
  456. await collectStreamBody(response);
  457. });
  458. it('should be able to receive cookies', async () => {
  459. const cookie = ['cookie1', 'cookie2'];
  460. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  461. response.statusCode = 200;
  462. response.statusMessage = 'OK';
  463. response.setHeader('set-cookie', cookie);
  464. response.end();
  465. });
  466. const urlRequest = net.request(serverUrl);
  467. const response = await getResponse(urlRequest);
  468. expect(response.headers['set-cookie']).to.have.same.members(cookie);
  469. });
  470. it('should not use the sessions cookie store by default', async () => {
  471. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  472. response.statusCode = 200;
  473. response.statusMessage = 'OK';
  474. response.setHeader('x-cookie', `${request.headers.cookie!}`);
  475. response.end();
  476. });
  477. const sess = session.fromPartition('cookie-tests-1');
  478. const cookieVal = `${Date.now()}`;
  479. await sess.cookies.set({
  480. url: serverUrl,
  481. name: 'wild_cookie',
  482. value: cookieVal
  483. });
  484. const urlRequest = net.request({
  485. url: serverUrl,
  486. session: sess
  487. });
  488. const response = await getResponse(urlRequest);
  489. expect(response.headers['x-cookie']).to.equal('undefined');
  490. });
  491. it('should be able to use the sessions cookie store', async () => {
  492. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  493. response.statusCode = 200;
  494. response.statusMessage = 'OK';
  495. response.setHeader('x-cookie', request.headers.cookie!);
  496. response.end();
  497. });
  498. const sess = session.fromPartition('cookie-tests-2');
  499. const cookieVal = `${Date.now()}`;
  500. await sess.cookies.set({
  501. url: serverUrl,
  502. name: 'wild_cookie',
  503. value: cookieVal
  504. });
  505. const urlRequest = net.request({
  506. url: serverUrl,
  507. session: sess,
  508. useSessionCookies: true
  509. });
  510. const response = await getResponse(urlRequest);
  511. expect(response.headers['x-cookie']).to.equal(`wild_cookie=${cookieVal}`);
  512. });
  513. it('should be able to use the sessions cookie store with set-cookie', async () => {
  514. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  515. response.statusCode = 200;
  516. response.statusMessage = 'OK';
  517. response.setHeader('set-cookie', 'foo=bar');
  518. response.end();
  519. });
  520. const sess = session.fromPartition('cookie-tests-3');
  521. let cookies = await sess.cookies.get({});
  522. expect(cookies).to.have.lengthOf(0);
  523. const urlRequest = net.request({
  524. url: serverUrl,
  525. session: sess,
  526. useSessionCookies: true
  527. });
  528. await collectStreamBody(await getResponse(urlRequest));
  529. cookies = await sess.cookies.get({});
  530. expect(cookies).to.have.lengthOf(1);
  531. expect(cookies[0]).to.deep.equal({
  532. name: 'foo',
  533. value: 'bar',
  534. domain: '127.0.0.1',
  535. hostOnly: true,
  536. path: '/',
  537. secure: false,
  538. httpOnly: false,
  539. session: true,
  540. sameSite: 'unspecified'
  541. });
  542. });
  543. ['Lax', 'Strict'].forEach((mode) => {
  544. it(`should be able to use the sessions cookie store with same-site ${mode} cookies`, async () => {
  545. const serverUrl = await respondNTimes.toSingleURL((request, response) => {
  546. response.statusCode = 200;
  547. response.statusMessage = 'OK';
  548. response.setHeader('set-cookie', `same=site; SameSite=${mode}`);
  549. response.setHeader('x-cookie', `${request.headers.cookie}`);
  550. response.end();
  551. }, 2);
  552. const sess = session.fromPartition(`cookie-tests-same-site-${mode}`);
  553. let cookies = await sess.cookies.get({});
  554. expect(cookies).to.have.lengthOf(0);
  555. const urlRequest = net.request({
  556. url: serverUrl,
  557. session: sess,
  558. useSessionCookies: true
  559. });
  560. const response = await getResponse(urlRequest);
  561. expect(response.headers['x-cookie']).to.equal('undefined');
  562. await collectStreamBody(response);
  563. cookies = await sess.cookies.get({});
  564. expect(cookies).to.have.lengthOf(1);
  565. expect(cookies[0]).to.deep.equal({
  566. name: 'same',
  567. value: 'site',
  568. domain: '127.0.0.1',
  569. hostOnly: true,
  570. path: '/',
  571. secure: false,
  572. httpOnly: false,
  573. session: true,
  574. sameSite: mode.toLowerCase()
  575. });
  576. const urlRequest2 = net.request({
  577. url: serverUrl,
  578. session: sess,
  579. useSessionCookies: true
  580. });
  581. const response2 = await getResponse(urlRequest2);
  582. expect(response2.headers['x-cookie']).to.equal('same=site');
  583. });
  584. });
  585. it('should be able to use the sessions cookie store safely across redirects', async () => {
  586. const serverUrl = await respondOnce.toSingleURL(async (request, response) => {
  587. response.statusCode = 302;
  588. response.statusMessage = 'Moved';
  589. const newUrl = await respondOnce.toSingleURL((req, res) => {
  590. res.statusCode = 200;
  591. res.statusMessage = 'OK';
  592. res.setHeader('x-cookie', req.headers.cookie!);
  593. res.end();
  594. });
  595. response.setHeader('x-cookie', request.headers.cookie!);
  596. response.setHeader('location', newUrl.replace('127.0.0.1', 'localhost'));
  597. response.end();
  598. });
  599. const sess = session.fromPartition('cookie-tests-4');
  600. const cookie127Val = `${Date.now()}-127`;
  601. const cookieLocalVal = `${Date.now()}-local`;
  602. const localhostUrl = serverUrl.replace('127.0.0.1', 'localhost');
  603. expect(localhostUrl).to.not.equal(serverUrl);
  604. await Promise.all([
  605. sess.cookies.set({
  606. url: serverUrl,
  607. name: 'wild_cookie',
  608. value: cookie127Val
  609. }), sess.cookies.set({
  610. url: localhostUrl,
  611. name: 'wild_cookie',
  612. value: cookieLocalVal
  613. })
  614. ]);
  615. const urlRequest = net.request({
  616. url: serverUrl,
  617. session: sess,
  618. useSessionCookies: true
  619. });
  620. urlRequest.on('redirect', (status, method, url, headers) => {
  621. // The initial redirect response should have received the 127 value here
  622. expect(headers['x-cookie'][0]).to.equal(`wild_cookie=${cookie127Val}`);
  623. urlRequest.followRedirect();
  624. });
  625. const response = await getResponse(urlRequest);
  626. // We expect the server to have received the localhost value here
  627. // The original request was to a 127.0.0.1 URL
  628. // That request would have the cookie127Val cookie attached
  629. // The request is then redirect to a localhost URL (different site)
  630. // Because we are using the session cookie store it should do the safe / secure thing
  631. // and attach the cookies for the new target domain
  632. expect(response.headers['x-cookie']).to.equal(`wild_cookie=${cookieLocalVal}`);
  633. });
  634. it('should be able to abort an HTTP request before first write', async () => {
  635. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  636. response.end();
  637. expect.fail('Unexpected request event');
  638. });
  639. const urlRequest = net.request(serverUrl);
  640. urlRequest.on('response', () => {
  641. expect.fail('unexpected response event');
  642. });
  643. const aborted = emittedOnce(urlRequest, 'abort');
  644. urlRequest.abort();
  645. urlRequest.write('');
  646. urlRequest.end();
  647. await aborted;
  648. });
  649. it('it should be able to abort an HTTP request before request end', async () => {
  650. let requestReceivedByServer = false;
  651. let urlRequest: ClientRequest | null = null;
  652. const serverUrl = await respondOnce.toSingleURL(() => {
  653. requestReceivedByServer = true;
  654. urlRequest!.abort();
  655. });
  656. let requestAbortEventEmitted = false;
  657. urlRequest = net.request(serverUrl);
  658. urlRequest.on('response', () => {
  659. expect.fail('Unexpected response event');
  660. });
  661. urlRequest.on('finish', () => {
  662. expect.fail('Unexpected finish event');
  663. });
  664. urlRequest.on('error', () => {
  665. expect.fail('Unexpected error event');
  666. });
  667. urlRequest.on('abort', () => {
  668. requestAbortEventEmitted = true;
  669. });
  670. await emittedOnce(urlRequest, 'close', () => {
  671. urlRequest!.chunkedEncoding = true;
  672. urlRequest!.write(randomString(kOneKiloByte));
  673. });
  674. expect(requestReceivedByServer).to.equal(true);
  675. expect(requestAbortEventEmitted).to.equal(true);
  676. });
  677. it('it should be able to abort an HTTP request after request end and before response', async () => {
  678. let requestReceivedByServer = false;
  679. let urlRequest: ClientRequest | null = null;
  680. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  681. requestReceivedByServer = true;
  682. urlRequest!.abort();
  683. process.nextTick(() => {
  684. response.statusCode = 200;
  685. response.statusMessage = 'OK';
  686. response.end();
  687. });
  688. });
  689. let requestFinishEventEmitted = false;
  690. urlRequest = net.request(serverUrl);
  691. urlRequest.on('response', () => {
  692. expect.fail('Unexpected response event');
  693. });
  694. urlRequest.on('finish', () => {
  695. requestFinishEventEmitted = true;
  696. });
  697. urlRequest.on('error', () => {
  698. expect.fail('Unexpected error event');
  699. });
  700. urlRequest.end(randomString(kOneKiloByte));
  701. await emittedOnce(urlRequest, 'abort');
  702. expect(requestFinishEventEmitted).to.equal(true);
  703. expect(requestReceivedByServer).to.equal(true);
  704. });
  705. it('it should be able to abort an HTTP request after response start', async () => {
  706. let requestReceivedByServer = false;
  707. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  708. requestReceivedByServer = true;
  709. response.statusCode = 200;
  710. response.statusMessage = 'OK';
  711. response.write(randomString(kOneKiloByte));
  712. });
  713. let requestFinishEventEmitted = false;
  714. let requestResponseEventEmitted = false;
  715. let responseCloseEventEmitted = false;
  716. const urlRequest = net.request(serverUrl);
  717. urlRequest.on('response', (response) => {
  718. requestResponseEventEmitted = true;
  719. const statusCode = response.statusCode;
  720. expect(statusCode).to.equal(200);
  721. response.on('data', () => {});
  722. response.on('end', () => {
  723. expect.fail('Unexpected end event');
  724. });
  725. response.on('error', () => {
  726. expect.fail('Unexpected error event');
  727. });
  728. response.on('close' as any, () => {
  729. responseCloseEventEmitted = true;
  730. });
  731. urlRequest.abort();
  732. });
  733. urlRequest.on('finish', () => {
  734. requestFinishEventEmitted = true;
  735. });
  736. urlRequest.on('error', () => {
  737. expect.fail('Unexpected error event');
  738. });
  739. urlRequest.end(randomString(kOneKiloByte));
  740. await emittedOnce(urlRequest, 'abort');
  741. expect(requestFinishEventEmitted).to.be.true('request should emit "finish" event');
  742. expect(requestReceivedByServer).to.be.true('request should be received by the server');
  743. expect(requestResponseEventEmitted).to.be.true('"response" event should be emitted');
  744. expect(responseCloseEventEmitted).to.be.true('response should emit "close" event');
  745. });
  746. it('abort event should be emitted at most once', async () => {
  747. let requestReceivedByServer = false;
  748. let urlRequest: ClientRequest | null = null;
  749. const serverUrl = await respondOnce.toSingleURL(() => {
  750. requestReceivedByServer = true;
  751. urlRequest!.abort();
  752. urlRequest!.abort();
  753. });
  754. let requestFinishEventEmitted = false;
  755. let abortsEmitted = 0;
  756. urlRequest = net.request(serverUrl);
  757. urlRequest.on('response', () => {
  758. expect.fail('Unexpected response event');
  759. });
  760. urlRequest.on('finish', () => {
  761. requestFinishEventEmitted = true;
  762. });
  763. urlRequest.on('error', () => {
  764. expect.fail('Unexpected error event');
  765. });
  766. urlRequest.on('abort', () => {
  767. abortsEmitted++;
  768. });
  769. urlRequest.end(randomString(kOneKiloByte));
  770. await emittedOnce(urlRequest, 'abort');
  771. expect(requestFinishEventEmitted).to.be.true('request should emit "finish" event');
  772. expect(requestReceivedByServer).to.be.true('request should be received by server');
  773. expect(abortsEmitted).to.equal(1, 'request should emit exactly 1 "abort" event');
  774. });
  775. it('should allow to read response body from non-2xx response', async () => {
  776. const bodyData = randomString(kOneKiloByte);
  777. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  778. response.statusCode = 404;
  779. response.end(bodyData);
  780. });
  781. const urlRequest = net.request(serverUrl);
  782. const bodyCheckPromise = getResponse(urlRequest).then(r => {
  783. expect(r.statusCode).to.equal(404);
  784. return r;
  785. }).then(collectStreamBody).then(receivedBodyData => {
  786. expect(receivedBodyData.toString()).to.equal(bodyData);
  787. });
  788. const eventHandlers = Promise.all([
  789. bodyCheckPromise,
  790. emittedOnce(urlRequest, 'close')
  791. ]);
  792. urlRequest.end();
  793. await eventHandlers;
  794. });
  795. describe('webRequest', () => {
  796. afterEach(() => {
  797. session.defaultSession.webRequest.onBeforeRequest(null);
  798. });
  799. it('Should throw when invalid filters are passed', () => {
  800. expect(() => {
  801. session.defaultSession.webRequest.onBeforeRequest(
  802. { urls: ['*://www.googleapis.com'] },
  803. (details, callback) => { callback({ cancel: false }); }
  804. );
  805. }).to.throw('Invalid url pattern *://www.googleapis.com: Empty path.');
  806. expect(() => {
  807. session.defaultSession.webRequest.onBeforeRequest(
  808. { urls: ['*://www.googleapis.com/', '*://blahblah.dev'] },
  809. (details, callback) => { callback({ cancel: false }); }
  810. );
  811. }).to.throw('Invalid url pattern *://blahblah.dev: Empty path.');
  812. });
  813. it('Should not throw when valid filters are passed', () => {
  814. expect(() => {
  815. session.defaultSession.webRequest.onBeforeRequest(
  816. { urls: ['*://www.googleapis.com/'] },
  817. (details, callback) => { callback({ cancel: false }); }
  818. );
  819. }).to.not.throw();
  820. });
  821. it('Requests should be intercepted by webRequest module', async () => {
  822. const requestUrl = '/requestUrl';
  823. const redirectUrl = '/redirectUrl';
  824. let requestIsRedirected = false;
  825. const serverUrl = await respondOnce.toURL(redirectUrl, (request, response) => {
  826. requestIsRedirected = true;
  827. response.end();
  828. });
  829. let requestIsIntercepted = false;
  830. session.defaultSession.webRequest.onBeforeRequest(
  831. (details, callback) => {
  832. if (details.url === `${serverUrl}${requestUrl}`) {
  833. requestIsIntercepted = true;
  834. // Disabled due to false positive in StandardJS
  835. // eslint-disable-next-line standard/no-callback-literal
  836. callback({
  837. redirectURL: `${serverUrl}${redirectUrl}`
  838. });
  839. } else {
  840. callback({
  841. cancel: false
  842. });
  843. }
  844. });
  845. const urlRequest = net.request(`${serverUrl}${requestUrl}`);
  846. const response = await getResponse(urlRequest);
  847. expect(response.statusCode).to.equal(200);
  848. await collectStreamBody(response);
  849. expect(requestIsRedirected).to.be.true('The server should receive a request to the forward URL');
  850. expect(requestIsIntercepted).to.be.true('The request should be intercepted by the webRequest module');
  851. });
  852. it('should to able to create and intercept a request using a custom session object', async () => {
  853. const requestUrl = '/requestUrl';
  854. const redirectUrl = '/redirectUrl';
  855. const customPartitionName = 'custom-partition';
  856. let requestIsRedirected = false;
  857. const serverUrl = await respondOnce.toURL(redirectUrl, (request, response) => {
  858. requestIsRedirected = true;
  859. response.end();
  860. });
  861. session.defaultSession.webRequest.onBeforeRequest(() => {
  862. expect.fail('Request should not be intercepted by the default session');
  863. });
  864. const customSession = session.fromPartition(customPartitionName, { cache: false });
  865. let requestIsIntercepted = false;
  866. customSession.webRequest.onBeforeRequest((details, callback) => {
  867. if (details.url === `${serverUrl}${requestUrl}`) {
  868. requestIsIntercepted = true;
  869. // Disabled due to false positive in StandardJS
  870. // eslint-disable-next-line standard/no-callback-literal
  871. callback({
  872. redirectURL: `${serverUrl}${redirectUrl}`
  873. });
  874. } else {
  875. callback({
  876. cancel: false
  877. });
  878. }
  879. });
  880. const urlRequest = net.request({
  881. url: `${serverUrl}${requestUrl}`,
  882. session: customSession
  883. });
  884. const response = await getResponse(urlRequest);
  885. expect(response.statusCode).to.equal(200);
  886. await collectStreamBody(response);
  887. expect(requestIsRedirected).to.be.true('The server should receive a request to the forward URL');
  888. expect(requestIsIntercepted).to.be.true('The request should be intercepted by the webRequest module');
  889. });
  890. it('should to able to create and intercept a request using a custom partition name', async () => {
  891. const requestUrl = '/requestUrl';
  892. const redirectUrl = '/redirectUrl';
  893. const customPartitionName = 'custom-partition';
  894. let requestIsRedirected = false;
  895. const serverUrl = await respondOnce.toURL(redirectUrl, (request, response) => {
  896. requestIsRedirected = true;
  897. response.end();
  898. });
  899. session.defaultSession.webRequest.onBeforeRequest(() => {
  900. expect.fail('Request should not be intercepted by the default session');
  901. });
  902. const customSession = session.fromPartition(customPartitionName, { cache: false });
  903. let requestIsIntercepted = false;
  904. customSession.webRequest.onBeforeRequest((details, callback) => {
  905. if (details.url === `${serverUrl}${requestUrl}`) {
  906. requestIsIntercepted = true;
  907. // Disabled due to false positive in StandardJS
  908. // eslint-disable-next-line standard/no-callback-literal
  909. callback({
  910. redirectURL: `${serverUrl}${redirectUrl}`
  911. });
  912. } else {
  913. callback({
  914. cancel: false
  915. });
  916. }
  917. });
  918. const urlRequest = net.request({
  919. url: `${serverUrl}${requestUrl}`,
  920. partition: customPartitionName
  921. });
  922. const response = await getResponse(urlRequest);
  923. expect(response.statusCode).to.equal(200);
  924. await collectStreamBody(response);
  925. expect(requestIsRedirected).to.be.true('The server should receive a request to the forward URL');
  926. expect(requestIsIntercepted).to.be.true('The request should be intercepted by the webRequest module');
  927. });
  928. });
  929. it('should throw when calling getHeader without a name', () => {
  930. expect(() => {
  931. (net.request({ url: 'https://test' }).getHeader as any)();
  932. }).to.throw(/`name` is required for getHeader\(name\)/);
  933. expect(() => {
  934. net.request({ url: 'https://test' }).getHeader(null as any);
  935. }).to.throw(/`name` is required for getHeader\(name\)/);
  936. });
  937. it('should throw when calling removeHeader without a name', () => {
  938. expect(() => {
  939. (net.request({ url: 'https://test' }).removeHeader as any)();
  940. }).to.throw(/`name` is required for removeHeader\(name\)/);
  941. expect(() => {
  942. net.request({ url: 'https://test' }).removeHeader(null as any);
  943. }).to.throw(/`name` is required for removeHeader\(name\)/);
  944. });
  945. it('should follow redirect when no redirect handler is provided', async () => {
  946. const requestUrl = '/302';
  947. const serverUrl = await respondOnce.toRoutes({
  948. '/302': (request, response) => {
  949. response.statusCode = 302;
  950. response.setHeader('Location', '/200');
  951. response.end();
  952. },
  953. '/200': (request, response) => {
  954. response.statusCode = 200;
  955. response.end();
  956. }
  957. });
  958. const urlRequest = net.request({
  959. url: `${serverUrl}${requestUrl}`
  960. });
  961. const response = await getResponse(urlRequest);
  962. expect(response.statusCode).to.equal(200);
  963. });
  964. it('should follow redirect chain when no redirect handler is provided', async () => {
  965. const serverUrl = await respondOnce.toRoutes({
  966. '/redirectChain': (request, response) => {
  967. response.statusCode = 302;
  968. response.setHeader('Location', '/302');
  969. response.end();
  970. },
  971. '/302': (request, response) => {
  972. response.statusCode = 302;
  973. response.setHeader('Location', '/200');
  974. response.end();
  975. },
  976. '/200': (request, response) => {
  977. response.statusCode = 200;
  978. response.end();
  979. }
  980. });
  981. const urlRequest = net.request({
  982. url: `${serverUrl}/redirectChain`
  983. });
  984. const response = await getResponse(urlRequest);
  985. expect(response.statusCode).to.equal(200);
  986. });
  987. it('should not follow redirect when request is canceled in redirect handler', async () => {
  988. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  989. response.statusCode = 302;
  990. response.setHeader('Location', '/200');
  991. response.end();
  992. });
  993. const urlRequest = net.request({
  994. url: serverUrl
  995. });
  996. urlRequest.end();
  997. urlRequest.on('redirect', () => { urlRequest.abort(); });
  998. urlRequest.on('error', () => {});
  999. await emittedOnce(urlRequest, 'abort');
  1000. });
  1001. it('should not follow redirect when mode is error', async () => {
  1002. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1003. response.statusCode = 302;
  1004. response.setHeader('Location', '/200');
  1005. response.end();
  1006. });
  1007. const urlRequest = net.request({
  1008. url: serverUrl,
  1009. redirect: 'error'
  1010. });
  1011. urlRequest.end();
  1012. await emittedOnce(urlRequest, 'error');
  1013. });
  1014. it('should follow redirect when handler calls callback', async () => {
  1015. const serverUrl = await respondOnce.toRoutes({
  1016. '/redirectChain': (request, response) => {
  1017. response.statusCode = 302;
  1018. response.setHeader('Location', '/302');
  1019. response.end();
  1020. },
  1021. '/302': (request, response) => {
  1022. response.statusCode = 302;
  1023. response.setHeader('Location', '/200');
  1024. response.end();
  1025. },
  1026. '/200': (request, response) => {
  1027. response.statusCode = 200;
  1028. response.end();
  1029. }
  1030. });
  1031. const urlRequest = net.request({ url: `${serverUrl}/redirectChain`, redirect: 'manual' });
  1032. const redirects: string[] = [];
  1033. urlRequest.on('redirect', (status, method, url) => {
  1034. redirects.push(url);
  1035. urlRequest.followRedirect();
  1036. });
  1037. const response = await getResponse(urlRequest);
  1038. expect(response.statusCode).to.equal(200);
  1039. expect(redirects).to.deep.equal([
  1040. `${serverUrl}/302`,
  1041. `${serverUrl}/200`
  1042. ]);
  1043. });
  1044. it('should throw if given an invalid session option', () => {
  1045. expect(() => {
  1046. net.request({
  1047. url: 'https://foo',
  1048. session: 1 as any
  1049. });
  1050. }).to.throw('`session` should be an instance of the Session class');
  1051. });
  1052. it('should throw if given an invalid partition option', () => {
  1053. expect(() => {
  1054. net.request({
  1055. url: 'https://foo',
  1056. partition: 1 as any
  1057. });
  1058. }).to.throw('`partition` should be a string');
  1059. });
  1060. it('should be able to create a request with options', async () => {
  1061. const customHeaderName = 'Some-Custom-Header-Name';
  1062. const customHeaderValue = 'Some-Customer-Header-Value';
  1063. const serverUrlUnparsed = await respondOnce.toURL('/', (request, response) => {
  1064. expect(request.method).to.equal('GET');
  1065. expect(request.headers[customHeaderName.toLowerCase()]).to.equal(customHeaderValue);
  1066. response.statusCode = 200;
  1067. response.statusMessage = 'OK';
  1068. response.end();
  1069. });
  1070. const serverUrl = url.parse(serverUrlUnparsed);
  1071. const options = {
  1072. port: serverUrl.port ? parseInt(serverUrl.port, 10) : undefined,
  1073. hostname: '127.0.0.1',
  1074. headers: { [customHeaderName]: customHeaderValue }
  1075. };
  1076. const urlRequest = net.request(options);
  1077. const response = await getResponse(urlRequest);
  1078. expect(response.statusCode).to.be.equal(200);
  1079. await collectStreamBody(response);
  1080. });
  1081. it('should be able to pipe a readable stream into a net request', async () => {
  1082. const bodyData = randomString(kOneMegaByte);
  1083. let netRequestReceived = false;
  1084. let netRequestEnded = false;
  1085. const [nodeServerUrl, netServerUrl] = await Promise.all([
  1086. respondOnce.toSingleURL((request, response) => response.end(bodyData)),
  1087. respondOnce.toSingleURL((request, response) => {
  1088. netRequestReceived = true;
  1089. let receivedBodyData = '';
  1090. request.on('data', (chunk) => {
  1091. receivedBodyData += chunk.toString();
  1092. });
  1093. request.on('end', (chunk: Buffer | undefined) => {
  1094. netRequestEnded = true;
  1095. if (chunk) {
  1096. receivedBodyData += chunk.toString();
  1097. }
  1098. expect(receivedBodyData).to.be.equal(bodyData);
  1099. response.end();
  1100. });
  1101. })
  1102. ]);
  1103. const nodeRequest = http.request(nodeServerUrl);
  1104. const nodeResponse = await getResponse(nodeRequest as any) as any as http.ServerResponse;
  1105. const netRequest = net.request(netServerUrl);
  1106. const responsePromise = emittedOnce(netRequest, 'response');
  1107. // TODO(@MarshallOfSound) - FIXME with #22730
  1108. nodeResponse.pipe(netRequest as any);
  1109. const [netResponse] = await responsePromise;
  1110. expect(netResponse.statusCode).to.equal(200);
  1111. await collectStreamBody(netResponse);
  1112. expect(netRequestReceived).to.be.true('net request received');
  1113. expect(netRequestEnded).to.be.true('net request ended');
  1114. });
  1115. it('should report upload progress', async () => {
  1116. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1117. response.end();
  1118. });
  1119. const netRequest = net.request({ url: serverUrl, method: 'POST' });
  1120. expect(netRequest.getUploadProgress()).to.have.property('active', false);
  1121. netRequest.end(Buffer.from('hello'));
  1122. const [position, total] = await emittedOnce(netRequest, 'upload-progress');
  1123. expect(netRequest.getUploadProgress()).to.deep.equal({ active: true, started: true, current: position, total });
  1124. });
  1125. it('should emit error event on server socket destroy', async () => {
  1126. const serverUrl = await respondOnce.toSingleURL((request) => {
  1127. request.socket.destroy();
  1128. });
  1129. const urlRequest = net.request(serverUrl);
  1130. urlRequest.end();
  1131. const [error] = await emittedOnce(urlRequest, 'error');
  1132. expect(error.message).to.equal('net::ERR_EMPTY_RESPONSE');
  1133. });
  1134. it('should emit error event on server request destroy', async () => {
  1135. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1136. request.destroy();
  1137. response.end();
  1138. });
  1139. const urlRequest = net.request(serverUrl);
  1140. urlRequest.end(randomBuffer(kOneMegaByte));
  1141. const [error] = await emittedOnce(urlRequest, 'error');
  1142. expect(error.message).to.be.oneOf(['net::ERR_CONNECTION_RESET', 'net::ERR_CONNECTION_ABORTED']);
  1143. });
  1144. it('should not emit any event after close', async () => {
  1145. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1146. response.end();
  1147. });
  1148. const urlRequest = net.request(serverUrl);
  1149. urlRequest.end();
  1150. await emittedOnce(urlRequest, 'close');
  1151. await new Promise((resolve, reject) => {
  1152. ['finish', 'abort', 'close', 'error'].forEach(evName => {
  1153. urlRequest.on(evName as any, () => {
  1154. reject(new Error(`Unexpected ${evName} event`));
  1155. });
  1156. });
  1157. setTimeout(resolve, 50);
  1158. });
  1159. });
  1160. it('should remove the referer header when no referrer url specified', async () => {
  1161. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1162. expect(request.headers.referer).to.equal(undefined);
  1163. response.statusCode = 200;
  1164. response.statusMessage = 'OK';
  1165. response.end();
  1166. });
  1167. const urlRequest = net.request(serverUrl);
  1168. urlRequest.end();
  1169. const response = await getResponse(urlRequest);
  1170. expect(response.statusCode).to.equal(200);
  1171. await collectStreamBody(response);
  1172. });
  1173. it('should set the referer header when a referrer url specified', async () => {
  1174. const referrerURL = 'https://www.electronjs.org/';
  1175. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1176. expect(request.headers.referer).to.equal(referrerURL);
  1177. response.statusCode = 200;
  1178. response.statusMessage = 'OK';
  1179. response.end();
  1180. });
  1181. const urlRequest = net.request(serverUrl);
  1182. urlRequest.setHeader('referer', referrerURL);
  1183. urlRequest.end();
  1184. const response = await getResponse(urlRequest);
  1185. expect(response.statusCode).to.equal(200);
  1186. await collectStreamBody(response);
  1187. });
  1188. });
  1189. describe('IncomingMessage API', () => {
  1190. it('response object should implement the IncomingMessage API', async () => {
  1191. const customHeaderName = 'Some-Custom-Header-Name';
  1192. const customHeaderValue = 'Some-Customer-Header-Value';
  1193. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1194. response.statusCode = 200;
  1195. response.statusMessage = 'OK';
  1196. response.setHeader(customHeaderName, customHeaderValue);
  1197. response.end();
  1198. });
  1199. const urlRequest = net.request(serverUrl);
  1200. const response = await getResponse(urlRequest);
  1201. expect(response.statusCode).to.equal(200);
  1202. expect(response.statusMessage).to.equal('OK');
  1203. const headers = response.headers;
  1204. expect(headers).to.be.an('object');
  1205. const headerValue = headers[customHeaderName.toLowerCase()];
  1206. expect(headerValue).to.equal(customHeaderValue);
  1207. const httpVersion = response.httpVersion;
  1208. expect(httpVersion).to.be.a('string').and.to.have.lengthOf.at.least(1);
  1209. const httpVersionMajor = response.httpVersionMajor;
  1210. expect(httpVersionMajor).to.be.a('number').and.to.be.at.least(1);
  1211. const httpVersionMinor = response.httpVersionMinor;
  1212. expect(httpVersionMinor).to.be.a('number').and.to.be.at.least(0);
  1213. await collectStreamBody(response);
  1214. });
  1215. it('should discard duplicate headers', async () => {
  1216. const includedHeader = 'max-forwards';
  1217. const discardableHeader = 'Max-Forwards';
  1218. const includedHeaderValue = 'max-fwds-val';
  1219. const discardableHeaderValue = 'max-fwds-val-two';
  1220. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1221. response.statusCode = 200;
  1222. response.statusMessage = 'OK';
  1223. response.setHeader(discardableHeader, discardableHeaderValue);
  1224. response.setHeader(includedHeader, includedHeaderValue);
  1225. response.end();
  1226. });
  1227. const urlRequest = net.request(serverUrl);
  1228. const response = await getResponse(urlRequest);
  1229. expect(response.statusCode).to.equal(200);
  1230. expect(response.statusMessage).to.equal('OK');
  1231. const headers = response.headers;
  1232. expect(headers).to.be.an('object');
  1233. expect(headers).to.have.property(includedHeader);
  1234. expect(headers).to.not.have.property(discardableHeader);
  1235. expect(headers[includedHeader]).to.equal(includedHeaderValue);
  1236. await collectStreamBody(response);
  1237. });
  1238. it('should join repeated non-discardable value with ,', async () => {
  1239. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1240. response.statusCode = 200;
  1241. response.statusMessage = 'OK';
  1242. response.setHeader('referrer-policy', ['first-text', 'second-text']);
  1243. response.end();
  1244. });
  1245. const urlRequest = net.request(serverUrl);
  1246. const response = await getResponse(urlRequest);
  1247. expect(response.statusCode).to.equal(200);
  1248. expect(response.statusMessage).to.equal('OK');
  1249. const headers = response.headers;
  1250. expect(headers).to.be.an('object');
  1251. expect(headers).to.have.property('referrer-policy');
  1252. expect(headers['referrer-policy']).to.equal('first-text, second-text');
  1253. await collectStreamBody(response);
  1254. });
  1255. it('should be able to pipe a net response into a writable stream', async () => {
  1256. const bodyData = randomString(kOneKiloByte);
  1257. let nodeRequestProcessed = false;
  1258. const [netServerUrl, nodeServerUrl] = await Promise.all([
  1259. respondOnce.toSingleURL((request, response) => response.end(bodyData)),
  1260. respondOnce.toSingleURL(async (request, response) => {
  1261. const receivedBodyData = await collectStreamBody(request);
  1262. expect(receivedBodyData).to.be.equal(bodyData);
  1263. nodeRequestProcessed = true;
  1264. response.end();
  1265. })
  1266. ]);
  1267. const netRequest = net.request(netServerUrl);
  1268. const netResponse = await getResponse(netRequest);
  1269. const serverUrl = url.parse(nodeServerUrl);
  1270. const nodeOptions = {
  1271. method: 'POST',
  1272. path: serverUrl.path,
  1273. port: serverUrl.port
  1274. };
  1275. const nodeRequest = http.request(nodeOptions);
  1276. const nodeResponsePromise = emittedOnce(nodeRequest, 'response');
  1277. // TODO(@MarshallOfSound) - FIXME with #22730
  1278. (netResponse as any).pipe(nodeRequest);
  1279. const [nodeResponse] = await nodeResponsePromise;
  1280. netRequest.end();
  1281. await collectStreamBody(nodeResponse);
  1282. expect(nodeRequestProcessed).to.equal(true);
  1283. });
  1284. });
  1285. describe('Stability and performance', () => {
  1286. it('should free unreferenced, never-started request objects without crash', (done) => {
  1287. net.request('https://test');
  1288. process.nextTick(() => {
  1289. const v8Util = process._linkedBinding('electron_common_v8_util');
  1290. v8Util.requestGarbageCollectionForTesting();
  1291. done();
  1292. });
  1293. });
  1294. it('should collect on-going requests without crash', async () => {
  1295. let finishResponse: (() => void) | null = null;
  1296. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1297. response.write(randomString(kOneKiloByte));
  1298. finishResponse = () => {
  1299. response.write(randomString(kOneKiloByte));
  1300. response.end();
  1301. };
  1302. });
  1303. const urlRequest = net.request(serverUrl);
  1304. const response = await getResponse(urlRequest);
  1305. process.nextTick(() => {
  1306. // Trigger a garbage collection.
  1307. const v8Util = process._linkedBinding('electron_common_v8_util');
  1308. v8Util.requestGarbageCollectionForTesting();
  1309. finishResponse!();
  1310. });
  1311. await collectStreamBody(response);
  1312. });
  1313. it('should collect unreferenced, ended requests without crash', async () => {
  1314. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1315. response.end();
  1316. });
  1317. const urlRequest = net.request(serverUrl);
  1318. process.nextTick(() => {
  1319. const v8Util = process._linkedBinding('electron_common_v8_util');
  1320. v8Util.requestGarbageCollectionForTesting();
  1321. });
  1322. const response = await getResponse(urlRequest);
  1323. await collectStreamBody(response);
  1324. });
  1325. it('should finish sending data when urlRequest is unreferenced', async () => {
  1326. const serverUrl = await respondOnce.toSingleURL(async (request, response) => {
  1327. const received = await collectStreamBodyBuffer(request);
  1328. expect(received.length).to.equal(kOneMegaByte);
  1329. response.end();
  1330. });
  1331. const urlRequest = net.request(serverUrl);
  1332. urlRequest.on('close', () => {
  1333. process.nextTick(() => {
  1334. const v8Util = process._linkedBinding('electron_common_v8_util');
  1335. v8Util.requestGarbageCollectionForTesting();
  1336. });
  1337. });
  1338. urlRequest.write(randomBuffer(kOneMegaByte));
  1339. const response = await getResponse(urlRequest);
  1340. await collectStreamBody(response);
  1341. });
  1342. it('should finish sending data when urlRequest is unreferenced for chunked encoding', async () => {
  1343. const serverUrl = await respondOnce.toSingleURL(async (request, response) => {
  1344. const received = await collectStreamBodyBuffer(request);
  1345. response.end();
  1346. expect(received.length).to.equal(kOneMegaByte);
  1347. });
  1348. const urlRequest = net.request(serverUrl);
  1349. urlRequest.chunkedEncoding = true;
  1350. urlRequest.write(randomBuffer(kOneMegaByte));
  1351. const response = await getResponse(urlRequest);
  1352. await collectStreamBody(response);
  1353. process.nextTick(() => {
  1354. const v8Util = process._linkedBinding('electron_common_v8_util');
  1355. v8Util.requestGarbageCollectionForTesting();
  1356. });
  1357. });
  1358. it('should finish sending data when urlRequest is unreferenced before close event for chunked encoding', async () => {
  1359. const serverUrl = await respondOnce.toSingleURL(async (request, response) => {
  1360. const received = await collectStreamBodyBuffer(request);
  1361. response.end();
  1362. expect(received.length).to.equal(kOneMegaByte);
  1363. });
  1364. const urlRequest = net.request(serverUrl);
  1365. urlRequest.chunkedEncoding = true;
  1366. urlRequest.write(randomBuffer(kOneMegaByte));
  1367. const v8Util = process._linkedBinding('electron_common_v8_util');
  1368. v8Util.requestGarbageCollectionForTesting();
  1369. await collectStreamBody(await getResponse(urlRequest));
  1370. });
  1371. it('should finish sending data when urlRequest is unreferenced', async () => {
  1372. const serverUrl = await respondOnce.toSingleURL(async (request, response) => {
  1373. const received = await collectStreamBodyBuffer(request);
  1374. response.end();
  1375. expect(received.length).to.equal(kOneMegaByte);
  1376. });
  1377. const urlRequest = net.request(serverUrl);
  1378. urlRequest.on('close', () => {
  1379. process.nextTick(() => {
  1380. const v8Util = process._linkedBinding('electron_common_v8_util');
  1381. v8Util.requestGarbageCollectionForTesting();
  1382. });
  1383. });
  1384. urlRequest.write(randomBuffer(kOneMegaByte));
  1385. await collectStreamBody(await getResponse(urlRequest));
  1386. });
  1387. it('should finish sending data when urlRequest is unreferenced for chunked encoding', async () => {
  1388. const serverUrl = await respondOnce.toSingleURL(async (request, response) => {
  1389. const received = await collectStreamBodyBuffer(request);
  1390. response.end();
  1391. expect(received.length).to.equal(kOneMegaByte);
  1392. });
  1393. const urlRequest = net.request(serverUrl);
  1394. urlRequest.on('close', () => {
  1395. process.nextTick(() => {
  1396. const v8Util = process._linkedBinding('electron_common_v8_util');
  1397. v8Util.requestGarbageCollectionForTesting();
  1398. });
  1399. });
  1400. urlRequest.chunkedEncoding = true;
  1401. urlRequest.write(randomBuffer(kOneMegaByte));
  1402. await collectStreamBody(await getResponse(urlRequest));
  1403. });
  1404. });
  1405. });