api-net-spec.ts 59 KB

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