api-session-spec.ts 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318
  1. import { expect } from 'chai';
  2. import * as http from 'http';
  3. import * as https from 'https';
  4. import * as path from 'path';
  5. import * as fs from 'fs';
  6. import * as ChildProcess from 'child_process';
  7. import { app, session, BrowserWindow, net, ipcMain, Session, webFrameMain, WebFrameMain } from 'electron/main';
  8. import * as send from 'send';
  9. import * as auth from 'basic-auth';
  10. import { closeAllWindows } from './window-helpers';
  11. import { emittedOnce } from './events-helpers';
  12. import { defer, delay } from './spec-helpers';
  13. import { AddressInfo } from 'net';
  14. /* The whole session API doesn't use standard callbacks */
  15. /* eslint-disable standard/no-callback-literal */
  16. describe('session module', () => {
  17. const fixtures = path.resolve(__dirname, '..', 'spec', 'fixtures');
  18. const url = 'http://127.0.0.1';
  19. describe('session.defaultSession', () => {
  20. it('returns the default session', () => {
  21. expect(session.defaultSession).to.equal(session.fromPartition(''));
  22. });
  23. });
  24. describe('session.fromPartition(partition, options)', () => {
  25. it('returns existing session with same partition', () => {
  26. expect(session.fromPartition('test')).to.equal(session.fromPartition('test'));
  27. });
  28. });
  29. describe('ses.cookies', () => {
  30. const name = '0';
  31. const value = '0';
  32. afterEach(closeAllWindows);
  33. // Clear cookie of defaultSession after each test.
  34. afterEach(async () => {
  35. const { cookies } = session.defaultSession;
  36. const cs = await cookies.get({ url });
  37. for (const c of cs) {
  38. await cookies.remove(url, c.name);
  39. }
  40. });
  41. it('should get cookies', async () => {
  42. const server = http.createServer((req, res) => {
  43. res.setHeader('Set-Cookie', [`${name}=${value}`]);
  44. res.end('finished');
  45. server.close();
  46. });
  47. await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
  48. const { port } = server.address() as AddressInfo;
  49. const w = new BrowserWindow({ show: false });
  50. await w.loadURL(`${url}:${port}`);
  51. const list = await w.webContents.session.cookies.get({ url });
  52. const cookie = list.find(cookie => cookie.name === name);
  53. expect(cookie).to.exist.and.to.have.property('value', value);
  54. });
  55. it('sets cookies', async () => {
  56. const { cookies } = session.defaultSession;
  57. const name = '1';
  58. const value = '1';
  59. await cookies.set({ url, name, value, expirationDate: (+new Date()) / 1000 + 120 });
  60. const c = (await cookies.get({ url }))[0];
  61. expect(c.name).to.equal(name);
  62. expect(c.value).to.equal(value);
  63. expect(c.session).to.equal(false);
  64. });
  65. it('sets session cookies', async () => {
  66. const { cookies } = session.defaultSession;
  67. const name = '2';
  68. const value = '1';
  69. await cookies.set({ url, name, value });
  70. const c = (await cookies.get({ url }))[0];
  71. expect(c.name).to.equal(name);
  72. expect(c.value).to.equal(value);
  73. expect(c.session).to.equal(true);
  74. });
  75. it('sets cookies without name', async () => {
  76. const { cookies } = session.defaultSession;
  77. const value = '3';
  78. await cookies.set({ url, value });
  79. const c = (await cookies.get({ url }))[0];
  80. expect(c.name).to.be.empty();
  81. expect(c.value).to.equal(value);
  82. });
  83. for (const sameSite of <const>['unspecified', 'no_restriction', 'lax', 'strict']) {
  84. it(`sets cookies with samesite=${sameSite}`, async () => {
  85. const { cookies } = session.defaultSession;
  86. const value = 'hithere';
  87. await cookies.set({ url, value, sameSite });
  88. const c = (await cookies.get({ url }))[0];
  89. expect(c.name).to.be.empty();
  90. expect(c.value).to.equal(value);
  91. expect(c.sameSite).to.equal(sameSite);
  92. });
  93. }
  94. it('fails to set cookies with samesite=garbage', async () => {
  95. const { cookies } = session.defaultSession;
  96. const value = 'hithere';
  97. await expect(cookies.set({ url, value, sameSite: 'garbage' as any })).to.eventually.be.rejectedWith('Failed to convert \'garbage\' to an appropriate cookie same site value');
  98. });
  99. it('gets cookies without url', async () => {
  100. const { cookies } = session.defaultSession;
  101. const name = '1';
  102. const value = '1';
  103. await cookies.set({ url, name, value, expirationDate: (+new Date()) / 1000 + 120 });
  104. const cs = await cookies.get({ domain: '127.0.0.1' });
  105. expect(cs.some(c => c.name === name && c.value === value)).to.equal(true);
  106. });
  107. it('yields an error when setting a cookie with missing required fields', async () => {
  108. const { cookies } = session.defaultSession;
  109. const name = '1';
  110. const value = '1';
  111. await expect(
  112. cookies.set({ url: '', name, value })
  113. ).to.eventually.be.rejectedWith('Failed to get cookie domain');
  114. });
  115. it('yields an error when setting a cookie with an invalid URL', async () => {
  116. const { cookies } = session.defaultSession;
  117. const name = '1';
  118. const value = '1';
  119. await expect(
  120. cookies.set({ url: 'asdf', name, value })
  121. ).to.eventually.be.rejectedWith('Failed to get cookie domain');
  122. });
  123. it('should overwrite previous cookies', async () => {
  124. const { cookies } = session.defaultSession;
  125. const name = 'DidOverwrite';
  126. for (const value of ['No', 'Yes']) {
  127. await cookies.set({ url, name, value, expirationDate: (+new Date()) / 1000 + 120 });
  128. const list = await cookies.get({ url });
  129. expect(list.some(cookie => cookie.name === name && cookie.value === value)).to.equal(true);
  130. }
  131. });
  132. it('should remove cookies', async () => {
  133. const { cookies } = session.defaultSession;
  134. const name = '2';
  135. const value = '2';
  136. await cookies.set({ url, name, value, expirationDate: (+new Date()) / 1000 + 120 });
  137. await cookies.remove(url, name);
  138. const list = await cookies.get({ url });
  139. expect(list.some(cookie => cookie.name === name && cookie.value === value)).to.equal(false);
  140. });
  141. it.skip('should set cookie for standard scheme', async () => {
  142. const { cookies } = session.defaultSession;
  143. const domain = 'fake-host';
  144. const url = `${standardScheme}://${domain}`;
  145. const name = 'custom';
  146. const value = '1';
  147. await cookies.set({ url, name, value, expirationDate: (+new Date()) / 1000 + 120 });
  148. const list = await cookies.get({ url });
  149. expect(list).to.have.lengthOf(1);
  150. expect(list[0]).to.have.property('name', name);
  151. expect(list[0]).to.have.property('value', value);
  152. expect(list[0]).to.have.property('domain', domain);
  153. });
  154. it('emits a changed event when a cookie is added or removed', async () => {
  155. const { cookies } = session.fromPartition('cookies-changed');
  156. const name = 'foo';
  157. const value = 'bar';
  158. const a = emittedOnce(cookies, 'changed');
  159. await cookies.set({ url, name, value, expirationDate: (+new Date()) / 1000 + 120 });
  160. const [, setEventCookie, setEventCause, setEventRemoved] = await a;
  161. const b = emittedOnce(cookies, 'changed');
  162. await cookies.remove(url, name);
  163. const [, removeEventCookie, removeEventCause, removeEventRemoved] = await b;
  164. expect(setEventCookie.name).to.equal(name);
  165. expect(setEventCookie.value).to.equal(value);
  166. expect(setEventCause).to.equal('explicit');
  167. expect(setEventRemoved).to.equal(false);
  168. expect(removeEventCookie.name).to.equal(name);
  169. expect(removeEventCookie.value).to.equal(value);
  170. expect(removeEventCause).to.equal('explicit');
  171. expect(removeEventRemoved).to.equal(true);
  172. });
  173. describe('ses.cookies.flushStore()', async () => {
  174. it('flushes the cookies to disk', async () => {
  175. const name = 'foo';
  176. const value = 'bar';
  177. const { cookies } = session.defaultSession;
  178. await cookies.set({ url, name, value });
  179. await cookies.flushStore();
  180. });
  181. });
  182. it('should survive an app restart for persistent partition', async function () {
  183. this.timeout(60000);
  184. const appPath = path.join(fixtures, 'api', 'cookie-app');
  185. const runAppWithPhase = (phase: string) => {
  186. return new Promise((resolve) => {
  187. let output = '';
  188. const appProcess = ChildProcess.spawn(
  189. process.execPath,
  190. [appPath],
  191. { env: { PHASE: phase, ...process.env } }
  192. );
  193. appProcess.stdout.on('data', data => { output += data; });
  194. appProcess.on('exit', () => {
  195. resolve(output.replace(/(\r\n|\n|\r)/gm, ''));
  196. });
  197. });
  198. };
  199. expect(await runAppWithPhase('one')).to.equal('011');
  200. expect(await runAppWithPhase('two')).to.equal('110');
  201. });
  202. });
  203. describe('ses.clearStorageData(options)', () => {
  204. afterEach(closeAllWindows);
  205. it('clears localstorage data', async () => {
  206. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
  207. await w.loadFile(path.join(fixtures, 'api', 'localstorage.html'));
  208. const options = {
  209. origin: 'file://',
  210. storages: ['localstorage'],
  211. quotas: ['persistent']
  212. };
  213. await w.webContents.session.clearStorageData(options);
  214. while (await w.webContents.executeJavaScript('localStorage.length') !== 0) {
  215. // The storage clear isn't instantly visible to the renderer, so keep
  216. // trying until it is.
  217. }
  218. });
  219. });
  220. describe('will-download event', () => {
  221. afterEach(closeAllWindows);
  222. it('can cancel default download behavior', async () => {
  223. const w = new BrowserWindow({ show: false });
  224. const mockFile = Buffer.alloc(1024);
  225. const contentDisposition = 'inline; filename="mockFile.txt"';
  226. const downloadServer = http.createServer((req, res) => {
  227. res.writeHead(200, {
  228. 'Content-Length': mockFile.length,
  229. 'Content-Type': 'application/plain',
  230. 'Content-Disposition': contentDisposition
  231. });
  232. res.end(mockFile);
  233. downloadServer.close();
  234. });
  235. await new Promise<void>(resolve => downloadServer.listen(0, '127.0.0.1', resolve));
  236. const port = (downloadServer.address() as AddressInfo).port;
  237. const url = `http://127.0.0.1:${port}/`;
  238. const downloadPrevented: Promise<{itemUrl: string, itemFilename: string, item: Electron.DownloadItem}> = new Promise(resolve => {
  239. w.webContents.session.once('will-download', function (e, item) {
  240. e.preventDefault();
  241. resolve({ itemUrl: item.getURL(), itemFilename: item.getFilename(), item });
  242. });
  243. });
  244. w.loadURL(url);
  245. const { item, itemUrl, itemFilename } = await downloadPrevented;
  246. expect(itemUrl).to.equal(url);
  247. expect(itemFilename).to.equal('mockFile.txt');
  248. // Delay till the next tick.
  249. await new Promise<void>(resolve => setImmediate(() => resolve()));
  250. expect(() => item.getURL()).to.throw('DownloadItem used after being destroyed');
  251. });
  252. });
  253. describe('ses.protocol', () => {
  254. const partitionName = 'temp';
  255. const protocolName = 'sp';
  256. let customSession: Session;
  257. const protocol = session.defaultSession.protocol;
  258. const handler = (ignoredError: any, callback: Function) => {
  259. callback({ data: '<script>require(\'electron\').ipcRenderer.send(\'hello\')</script>', mimeType: 'text/html' });
  260. };
  261. beforeEach(async () => {
  262. customSession = session.fromPartition(partitionName);
  263. await customSession.protocol.registerStringProtocol(protocolName, handler);
  264. });
  265. afterEach(async () => {
  266. await customSession.protocol.unregisterProtocol(protocolName);
  267. customSession = null as any;
  268. });
  269. afterEach(closeAllWindows);
  270. it('does not affect defaultSession', () => {
  271. const result1 = protocol.isProtocolRegistered(protocolName);
  272. expect(result1).to.equal(false);
  273. const result2 = customSession.protocol.isProtocolRegistered(protocolName);
  274. expect(result2).to.equal(true);
  275. });
  276. it('handles requests from partition', async () => {
  277. const w = new BrowserWindow({
  278. show: false,
  279. webPreferences: {
  280. partition: partitionName,
  281. nodeIntegration: true,
  282. contextIsolation: false
  283. }
  284. });
  285. customSession = session.fromPartition(partitionName);
  286. await customSession.protocol.registerStringProtocol(protocolName, handler);
  287. w.loadURL(`${protocolName}://fake-host`);
  288. await emittedOnce(ipcMain, 'hello');
  289. });
  290. });
  291. describe('ses.setProxy(options)', () => {
  292. let server: http.Server;
  293. let customSession: Electron.Session;
  294. let created = false;
  295. beforeEach(async () => {
  296. customSession = session.fromPartition('proxyconfig');
  297. if (!created) {
  298. // Work around for https://github.com/electron/electron/issues/26166 to
  299. // reduce flake
  300. await delay(100);
  301. created = true;
  302. }
  303. });
  304. afterEach(() => {
  305. if (server) {
  306. server.close();
  307. }
  308. customSession = null as any;
  309. });
  310. it('allows configuring proxy settings', async () => {
  311. const config = { proxyRules: 'http=myproxy:80' };
  312. await customSession.setProxy(config);
  313. const proxy = await customSession.resolveProxy('http://example.com/');
  314. expect(proxy).to.equal('PROXY myproxy:80');
  315. });
  316. it('allows removing the implicit bypass rules for localhost', async () => {
  317. const config = {
  318. proxyRules: 'http=myproxy:80',
  319. proxyBypassRules: '<-loopback>'
  320. };
  321. await customSession.setProxy(config);
  322. const proxy = await customSession.resolveProxy('http://localhost');
  323. expect(proxy).to.equal('PROXY myproxy:80');
  324. });
  325. it('allows configuring proxy settings with pacScript', async () => {
  326. server = http.createServer((req, res) => {
  327. const pac = `
  328. function FindProxyForURL(url, host) {
  329. return "PROXY myproxy:8132";
  330. }
  331. `;
  332. res.writeHead(200, {
  333. 'Content-Type': 'application/x-ns-proxy-autoconfig'
  334. });
  335. res.end(pac);
  336. });
  337. await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
  338. {
  339. const config = { pacScript: `http://127.0.0.1:${(server.address() as AddressInfo).port}` };
  340. await customSession.setProxy(config);
  341. const proxy = await customSession.resolveProxy('https://google.com');
  342. expect(proxy).to.equal('PROXY myproxy:8132');
  343. }
  344. {
  345. const config = { mode: 'pac_script' as any, pacScript: `http://127.0.0.1:${(server.address() as AddressInfo).port}` };
  346. await customSession.setProxy(config);
  347. const proxy = await customSession.resolveProxy('https://google.com');
  348. expect(proxy).to.equal('PROXY myproxy:8132');
  349. }
  350. });
  351. it('allows bypassing proxy settings', async () => {
  352. const config = {
  353. proxyRules: 'http=myproxy:80',
  354. proxyBypassRules: '<local>'
  355. };
  356. await customSession.setProxy(config);
  357. const proxy = await customSession.resolveProxy('http://example/');
  358. expect(proxy).to.equal('DIRECT');
  359. });
  360. it('allows configuring proxy settings with mode `direct`', async () => {
  361. const config = { mode: 'direct' as any, proxyRules: 'http=myproxy:80' };
  362. await customSession.setProxy(config);
  363. const proxy = await customSession.resolveProxy('http://example.com/');
  364. expect(proxy).to.equal('DIRECT');
  365. });
  366. it('allows configuring proxy settings with mode `auto_detect`', async () => {
  367. const config = { mode: 'auto_detect' as any };
  368. await customSession.setProxy(config);
  369. });
  370. it('allows configuring proxy settings with mode `pac_script`', async () => {
  371. const config = { mode: 'pac_script' as any };
  372. await customSession.setProxy(config);
  373. const proxy = await customSession.resolveProxy('http://example.com/');
  374. expect(proxy).to.equal('DIRECT');
  375. });
  376. it('allows configuring proxy settings with mode `fixed_servers`', async () => {
  377. const config = { mode: 'fixed_servers' as any, proxyRules: 'http=myproxy:80' };
  378. await customSession.setProxy(config);
  379. const proxy = await customSession.resolveProxy('http://example.com/');
  380. expect(proxy).to.equal('PROXY myproxy:80');
  381. });
  382. it('allows configuring proxy settings with mode `system`', async () => {
  383. const config = { mode: 'system' as any };
  384. await customSession.setProxy(config);
  385. });
  386. it('disallows configuring proxy settings with mode `invalid`', async () => {
  387. const config = { mode: 'invalid' as any };
  388. await expect(customSession.setProxy(config)).to.eventually.be.rejectedWith(/Invalid mode/);
  389. });
  390. it('reload proxy configuration', async () => {
  391. let proxyPort = 8132;
  392. server = http.createServer((req, res) => {
  393. const pac = `
  394. function FindProxyForURL(url, host) {
  395. return "PROXY myproxy:${proxyPort}";
  396. }
  397. `;
  398. res.writeHead(200, {
  399. 'Content-Type': 'application/x-ns-proxy-autoconfig'
  400. });
  401. res.end(pac);
  402. });
  403. await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
  404. const config = { mode: 'pac_script' as any, pacScript: `http://127.0.0.1:${(server.address() as AddressInfo).port}` };
  405. await customSession.setProxy(config);
  406. {
  407. const proxy = await customSession.resolveProxy('https://google.com');
  408. expect(proxy).to.equal(`PROXY myproxy:${proxyPort}`);
  409. }
  410. {
  411. proxyPort = 8133;
  412. await customSession.forceReloadProxyConfig();
  413. const proxy = await customSession.resolveProxy('https://google.com');
  414. expect(proxy).to.equal(`PROXY myproxy:${proxyPort}`);
  415. }
  416. });
  417. });
  418. describe('ses.getBlobData()', () => {
  419. const scheme = 'cors-blob';
  420. const protocol = session.defaultSession.protocol;
  421. const url = `${scheme}://host`;
  422. after(async () => {
  423. await protocol.unregisterProtocol(scheme);
  424. });
  425. afterEach(closeAllWindows);
  426. it('returns blob data for uuid', (done) => {
  427. const postData = JSON.stringify({
  428. type: 'blob',
  429. value: 'hello'
  430. });
  431. const content = `<html>
  432. <script>
  433. let fd = new FormData();
  434. fd.append('file', new Blob(['${postData}'], {type:'application/json'}));
  435. fetch('${url}', {method:'POST', body: fd });
  436. </script>
  437. </html>`;
  438. protocol.registerStringProtocol(scheme, (request, callback) => {
  439. try {
  440. if (request.method === 'GET') {
  441. callback({ data: content, mimeType: 'text/html' });
  442. } else if (request.method === 'POST') {
  443. const uuid = request.uploadData![1].blobUUID;
  444. expect(uuid).to.be.a('string');
  445. session.defaultSession.getBlobData(uuid!).then(result => {
  446. try {
  447. expect(result.toString()).to.equal(postData);
  448. done();
  449. } catch (e) {
  450. done(e);
  451. }
  452. });
  453. }
  454. } catch (e) {
  455. done(e);
  456. }
  457. });
  458. const w = new BrowserWindow({ show: false });
  459. w.loadURL(url);
  460. });
  461. });
  462. describe('ses.getBlobData2()', () => {
  463. const scheme = 'cors-blob';
  464. const protocol = session.defaultSession.protocol;
  465. const url = `${scheme}://host`;
  466. after(async () => {
  467. await protocol.unregisterProtocol(scheme);
  468. });
  469. afterEach(closeAllWindows);
  470. it('returns blob data for uuid', (done) => {
  471. const content = `<html>
  472. <script>
  473. let fd = new FormData();
  474. fd.append("data", new Blob(new Array(65_537).fill('a')));
  475. fetch('${url}', {method:'POST', body: fd });
  476. </script>
  477. </html>`;
  478. protocol.registerStringProtocol(scheme, (request, callback) => {
  479. try {
  480. if (request.method === 'GET') {
  481. callback({ data: content, mimeType: 'text/html' });
  482. } else if (request.method === 'POST') {
  483. const uuid = request.uploadData![1].blobUUID;
  484. expect(uuid).to.be.a('string');
  485. session.defaultSession.getBlobData(uuid!).then(result => {
  486. try {
  487. const data = new Array(65_537).fill('a');
  488. expect(result.toString()).to.equal(data.join(''));
  489. done();
  490. } catch (e) {
  491. done(e);
  492. }
  493. });
  494. }
  495. } catch (e) {
  496. done(e);
  497. }
  498. });
  499. const w = new BrowserWindow({ show: false });
  500. w.loadURL(url);
  501. });
  502. });
  503. describe('ses.setCertificateVerifyProc(callback)', () => {
  504. let server: http.Server;
  505. beforeEach((done) => {
  506. const certPath = path.join(fixtures, 'certificates');
  507. const options = {
  508. key: fs.readFileSync(path.join(certPath, 'server.key')),
  509. cert: fs.readFileSync(path.join(certPath, 'server.pem')),
  510. ca: [
  511. fs.readFileSync(path.join(certPath, 'rootCA.pem')),
  512. fs.readFileSync(path.join(certPath, 'intermediateCA.pem'))
  513. ],
  514. rejectUnauthorized: false
  515. };
  516. server = https.createServer(options, (req, res) => {
  517. res.writeHead(200);
  518. res.end('<title>hello</title>');
  519. });
  520. server.listen(0, '127.0.0.1', done);
  521. });
  522. afterEach((done) => {
  523. server.close(done);
  524. });
  525. afterEach(closeAllWindows);
  526. it('accepts the request when the callback is called with 0', async () => {
  527. const ses = session.fromPartition(`${Math.random()}`);
  528. let validate: () => void;
  529. ses.setCertificateVerifyProc(({ hostname, verificationResult, errorCode }, callback) => {
  530. if (hostname !== '127.0.0.1') return callback(-3);
  531. validate = () => {
  532. expect(verificationResult).to.be.oneOf(['net::ERR_CERT_AUTHORITY_INVALID', 'net::ERR_CERT_COMMON_NAME_INVALID']);
  533. expect(errorCode).to.be.oneOf([-202, -200]);
  534. };
  535. callback(0);
  536. });
  537. const w = new BrowserWindow({ show: false, webPreferences: { session: ses } });
  538. await w.loadURL(`https://127.0.0.1:${(server.address() as AddressInfo).port}`);
  539. expect(w.webContents.getTitle()).to.equal('hello');
  540. expect(validate!).not.to.be.undefined();
  541. validate!();
  542. });
  543. it('rejects the request when the callback is called with -2', async () => {
  544. const ses = session.fromPartition(`${Math.random()}`);
  545. let validate: () => void;
  546. ses.setCertificateVerifyProc(({ hostname, certificate, verificationResult, isIssuedByKnownRoot }, callback) => {
  547. if (hostname !== '127.0.0.1') return callback(-3);
  548. validate = () => {
  549. expect(certificate.issuerName).to.equal('Intermediate CA');
  550. expect(certificate.subjectName).to.equal('localhost');
  551. expect(certificate.issuer.commonName).to.equal('Intermediate CA');
  552. expect(certificate.subject.commonName).to.equal('localhost');
  553. expect(certificate.issuerCert.issuer.commonName).to.equal('Root CA');
  554. expect(certificate.issuerCert.subject.commonName).to.equal('Intermediate CA');
  555. expect(certificate.issuerCert.issuerCert.issuer.commonName).to.equal('Root CA');
  556. expect(certificate.issuerCert.issuerCert.subject.commonName).to.equal('Root CA');
  557. expect(certificate.issuerCert.issuerCert.issuerCert).to.equal(undefined);
  558. expect(verificationResult).to.be.oneOf(['net::ERR_CERT_AUTHORITY_INVALID', 'net::ERR_CERT_COMMON_NAME_INVALID']);
  559. expect(isIssuedByKnownRoot).to.be.false();
  560. };
  561. callback(-2);
  562. });
  563. const url = `https://127.0.0.1:${(server.address() as AddressInfo).port}`;
  564. const w = new BrowserWindow({ show: false, webPreferences: { session: ses } });
  565. await expect(w.loadURL(url)).to.eventually.be.rejectedWith(/ERR_FAILED/);
  566. expect(w.webContents.getTitle()).to.equal(url);
  567. expect(validate!).not.to.be.undefined();
  568. validate!();
  569. });
  570. it('saves cached results', async () => {
  571. const ses = session.fromPartition(`${Math.random()}`);
  572. let numVerificationRequests = 0;
  573. ses.setCertificateVerifyProc((e, callback) => {
  574. if (e.hostname !== '127.0.0.1') return callback(-3);
  575. numVerificationRequests++;
  576. callback(-2);
  577. });
  578. const url = `https://127.0.0.1:${(server.address() as AddressInfo).port}`;
  579. const w = new BrowserWindow({ show: false, webPreferences: { session: ses } });
  580. await expect(w.loadURL(url), 'first load').to.eventually.be.rejectedWith(/ERR_FAILED/);
  581. await emittedOnce(w.webContents, 'did-stop-loading');
  582. await expect(w.loadURL(url + '/test'), 'second load').to.eventually.be.rejectedWith(/ERR_FAILED/);
  583. expect(w.webContents.getTitle()).to.equal(url + '/test');
  584. expect(numVerificationRequests).to.equal(1);
  585. });
  586. it('does not cancel requests in other sessions', async () => {
  587. const ses1 = session.fromPartition(`${Math.random()}`);
  588. ses1.setCertificateVerifyProc((opts, cb) => cb(0));
  589. const ses2 = session.fromPartition(`${Math.random()}`);
  590. const url = `https://127.0.0.1:${(server.address() as AddressInfo).port}`;
  591. const req = net.request({ url, session: ses1, credentials: 'include' });
  592. req.end();
  593. setTimeout(() => {
  594. ses2.setCertificateVerifyProc((opts, callback) => callback(0));
  595. });
  596. await expect(new Promise<void>((resolve, reject) => {
  597. req.on('error', (err) => {
  598. reject(err);
  599. });
  600. req.on('response', () => {
  601. resolve();
  602. });
  603. })).to.eventually.be.fulfilled();
  604. });
  605. });
  606. describe('ses.clearAuthCache()', () => {
  607. it('can clear http auth info from cache', async () => {
  608. const ses = session.fromPartition('auth-cache');
  609. const server = http.createServer((req, res) => {
  610. const credentials = auth(req);
  611. if (!credentials || credentials.name !== 'test' || credentials.pass !== 'test') {
  612. res.statusCode = 401;
  613. res.setHeader('WWW-Authenticate', 'Basic realm="Restricted"');
  614. res.end();
  615. } else {
  616. res.end('authenticated');
  617. }
  618. });
  619. await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
  620. const port = (server.address() as AddressInfo).port;
  621. const fetch = (url: string) => new Promise((resolve, reject) => {
  622. const request = net.request({ url, session: ses });
  623. request.on('response', (response) => {
  624. let data: string | null = null;
  625. response.on('data', (chunk) => {
  626. if (!data) {
  627. data = '';
  628. }
  629. data += chunk;
  630. });
  631. response.on('end', () => {
  632. if (!data) {
  633. reject(new Error('Empty response'));
  634. } else {
  635. resolve(data);
  636. }
  637. });
  638. response.on('error', (error: any) => { reject(new Error(error)); });
  639. });
  640. request.on('error', (error: any) => { reject(new Error(error)); });
  641. request.end();
  642. });
  643. // the first time should throw due to unauthenticated
  644. await expect(fetch(`http://127.0.0.1:${port}`)).to.eventually.be.rejected();
  645. // passing the password should let us in
  646. expect(await fetch(`http://test:[email protected]:${port}`)).to.equal('authenticated');
  647. // subsequently, the credentials are cached
  648. expect(await fetch(`http://127.0.0.1:${port}`)).to.equal('authenticated');
  649. await ses.clearAuthCache();
  650. // once the cache is cleared, we should get an error again
  651. await expect(fetch(`http://127.0.0.1:${port}`)).to.eventually.be.rejected();
  652. });
  653. });
  654. describe('DownloadItem', () => {
  655. const mockPDF = Buffer.alloc(1024 * 1024 * 5);
  656. const downloadFilePath = path.join(__dirname, '..', 'fixtures', 'mock.pdf');
  657. const protocolName = 'custom-dl';
  658. const contentDisposition = 'inline; filename="mock.pdf"';
  659. let address: AddressInfo;
  660. let downloadServer: http.Server;
  661. before(async () => {
  662. downloadServer = http.createServer((req, res) => {
  663. res.writeHead(200, {
  664. 'Content-Length': mockPDF.length,
  665. 'Content-Type': 'application/pdf',
  666. 'Content-Disposition': req.url === '/?testFilename' ? 'inline' : contentDisposition
  667. });
  668. res.end(mockPDF);
  669. });
  670. await new Promise<void>(resolve => downloadServer.listen(0, '127.0.0.1', resolve));
  671. address = downloadServer.address() as AddressInfo;
  672. });
  673. after(async () => {
  674. await new Promise(resolve => downloadServer.close(resolve));
  675. });
  676. afterEach(closeAllWindows);
  677. const isPathEqual = (path1: string, path2: string) => {
  678. return path.relative(path1, path2) === '';
  679. };
  680. const assertDownload = (state: string, item: Electron.DownloadItem, isCustom = false) => {
  681. expect(state).to.equal('completed');
  682. expect(item.getFilename()).to.equal('mock.pdf');
  683. expect(path.isAbsolute(item.savePath)).to.equal(true);
  684. expect(isPathEqual(item.savePath, downloadFilePath)).to.equal(true);
  685. if (isCustom) {
  686. expect(item.getURL()).to.equal(`${protocolName}://item`);
  687. } else {
  688. expect(item.getURL()).to.be.equal(`${url}:${address.port}/`);
  689. }
  690. expect(item.getMimeType()).to.equal('application/pdf');
  691. expect(item.getReceivedBytes()).to.equal(mockPDF.length);
  692. expect(item.getTotalBytes()).to.equal(mockPDF.length);
  693. expect(item.getContentDisposition()).to.equal(contentDisposition);
  694. expect(fs.existsSync(downloadFilePath)).to.equal(true);
  695. fs.unlinkSync(downloadFilePath);
  696. };
  697. it('can download using session.downloadURL', (done) => {
  698. const port = address.port;
  699. session.defaultSession.once('will-download', function (e, item) {
  700. item.savePath = downloadFilePath;
  701. item.on('done', function (e, state) {
  702. try {
  703. assertDownload(state, item);
  704. done();
  705. } catch (e) {
  706. done(e);
  707. }
  708. });
  709. });
  710. session.defaultSession.downloadURL(`${url}:${port}`);
  711. });
  712. it('can download using WebContents.downloadURL', (done) => {
  713. const port = address.port;
  714. const w = new BrowserWindow({ show: false });
  715. w.webContents.session.once('will-download', function (e, item) {
  716. item.savePath = downloadFilePath;
  717. item.on('done', function (e, state) {
  718. try {
  719. assertDownload(state, item);
  720. done();
  721. } catch (e) {
  722. done(e);
  723. }
  724. });
  725. });
  726. w.webContents.downloadURL(`${url}:${port}`);
  727. });
  728. it('can download from custom protocols using WebContents.downloadURL', (done) => {
  729. const protocol = session.defaultSession.protocol;
  730. const port = address.port;
  731. const handler = (ignoredError: any, callback: Function) => {
  732. callback({ url: `${url}:${port}` });
  733. };
  734. protocol.registerHttpProtocol(protocolName, handler);
  735. const w = new BrowserWindow({ show: false });
  736. w.webContents.session.once('will-download', function (e, item) {
  737. item.savePath = downloadFilePath;
  738. item.on('done', function (e, state) {
  739. try {
  740. assertDownload(state, item, true);
  741. done();
  742. } catch (e) {
  743. done(e);
  744. }
  745. });
  746. });
  747. w.webContents.downloadURL(`${protocolName}://item`);
  748. });
  749. it('can download using WebView.downloadURL', async () => {
  750. const port = address.port;
  751. const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true } });
  752. await w.loadURL('about:blank');
  753. function webviewDownload ({ fixtures, url, port }: {fixtures: string, url: string, port: string}) {
  754. const webview = new (window as any).WebView();
  755. webview.addEventListener('did-finish-load', () => {
  756. webview.downloadURL(`${url}:${port}/`);
  757. });
  758. webview.src = `file://${fixtures}/api/blank.html`;
  759. document.body.appendChild(webview);
  760. }
  761. const done: Promise<[string, Electron.DownloadItem]> = new Promise(resolve => {
  762. w.webContents.session.once('will-download', function (e, item) {
  763. item.savePath = downloadFilePath;
  764. item.on('done', function (e, state) {
  765. resolve([state, item]);
  766. });
  767. });
  768. });
  769. await w.webContents.executeJavaScript(`(${webviewDownload})(${JSON.stringify({ fixtures, url, port })})`);
  770. const [state, item] = await done;
  771. assertDownload(state, item);
  772. });
  773. it('can cancel download', (done) => {
  774. const port = address.port;
  775. const w = new BrowserWindow({ show: false });
  776. w.webContents.session.once('will-download', function (e, item) {
  777. item.savePath = downloadFilePath;
  778. item.on('done', function (e, state) {
  779. try {
  780. expect(state).to.equal('cancelled');
  781. expect(item.getFilename()).to.equal('mock.pdf');
  782. expect(item.getMimeType()).to.equal('application/pdf');
  783. expect(item.getReceivedBytes()).to.equal(0);
  784. expect(item.getTotalBytes()).to.equal(mockPDF.length);
  785. expect(item.getContentDisposition()).to.equal(contentDisposition);
  786. done();
  787. } catch (e) {
  788. done(e);
  789. }
  790. });
  791. item.cancel();
  792. });
  793. w.webContents.downloadURL(`${url}:${port}/`);
  794. });
  795. it('can generate a default filename', function (done) {
  796. if (process.env.APPVEYOR === 'True') {
  797. // FIXME(alexeykuzmin): Skip the test.
  798. // this.skip()
  799. return done();
  800. }
  801. const port = address.port;
  802. const w = new BrowserWindow({ show: false });
  803. w.webContents.session.once('will-download', function (e, item) {
  804. item.savePath = downloadFilePath;
  805. item.on('done', function () {
  806. try {
  807. expect(item.getFilename()).to.equal('download.pdf');
  808. done();
  809. } catch (e) {
  810. done(e);
  811. }
  812. });
  813. item.cancel();
  814. });
  815. w.webContents.downloadURL(`${url}:${port}/?testFilename`);
  816. });
  817. it('can set options for the save dialog', (done) => {
  818. const filePath = path.join(__dirname, 'fixtures', 'mock.pdf');
  819. const port = address.port;
  820. const options = {
  821. window: null,
  822. title: 'title',
  823. message: 'message',
  824. buttonLabel: 'buttonLabel',
  825. nameFieldLabel: 'nameFieldLabel',
  826. defaultPath: '/',
  827. filters: [{
  828. name: '1', extensions: ['.1', '.2']
  829. }, {
  830. name: '2', extensions: ['.3', '.4', '.5']
  831. }],
  832. showsTagField: true,
  833. securityScopedBookmarks: true
  834. };
  835. const w = new BrowserWindow({ show: false });
  836. w.webContents.session.once('will-download', function (e, item) {
  837. item.setSavePath(filePath);
  838. item.setSaveDialogOptions(options);
  839. item.on('done', function () {
  840. try {
  841. expect(item.getSaveDialogOptions()).to.deep.equal(options);
  842. done();
  843. } catch (e) {
  844. done(e);
  845. }
  846. });
  847. item.cancel();
  848. });
  849. w.webContents.downloadURL(`${url}:${port}`);
  850. });
  851. describe('when a save path is specified and the URL is unavailable', () => {
  852. it('does not display a save dialog and reports the done state as interrupted', (done) => {
  853. const w = new BrowserWindow({ show: false });
  854. w.webContents.session.once('will-download', function (e, item) {
  855. item.savePath = downloadFilePath;
  856. if (item.getState() === 'interrupted') {
  857. item.resume();
  858. }
  859. item.on('done', function (e, state) {
  860. try {
  861. expect(state).to.equal('interrupted');
  862. done();
  863. } catch (e) {
  864. done(e);
  865. }
  866. });
  867. });
  868. w.webContents.downloadURL(`file://${path.join(__dirname, 'does-not-exist.txt')}`);
  869. });
  870. });
  871. });
  872. describe('ses.createInterruptedDownload(options)', () => {
  873. afterEach(closeAllWindows);
  874. it('can create an interrupted download item', async () => {
  875. const downloadFilePath = path.join(__dirname, '..', 'fixtures', 'mock.pdf');
  876. const options = {
  877. path: downloadFilePath,
  878. urlChain: ['http://127.0.0.1/'],
  879. mimeType: 'application/pdf',
  880. offset: 0,
  881. length: 5242880
  882. };
  883. const w = new BrowserWindow({ show: false });
  884. const p = emittedOnce(w.webContents.session, 'will-download');
  885. w.webContents.session.createInterruptedDownload(options);
  886. const [, item] = await p;
  887. expect(item.getState()).to.equal('interrupted');
  888. item.cancel();
  889. expect(item.getURLChain()).to.deep.equal(options.urlChain);
  890. expect(item.getMimeType()).to.equal(options.mimeType);
  891. expect(item.getReceivedBytes()).to.equal(options.offset);
  892. expect(item.getTotalBytes()).to.equal(options.length);
  893. expect(item.savePath).to.equal(downloadFilePath);
  894. });
  895. it('can be resumed', async () => {
  896. const downloadFilePath = path.join(fixtures, 'logo.png');
  897. const rangeServer = http.createServer((req, res) => {
  898. const options = { root: fixtures };
  899. send(req, req.url!, options)
  900. .on('error', (error: any) => { throw error; }).pipe(res);
  901. });
  902. try {
  903. await new Promise<void>(resolve => rangeServer.listen(0, '127.0.0.1', resolve));
  904. const port = (rangeServer.address() as AddressInfo).port;
  905. const w = new BrowserWindow({ show: false });
  906. const downloadCancelled: Promise<Electron.DownloadItem> = new Promise((resolve) => {
  907. w.webContents.session.once('will-download', function (e, item) {
  908. item.setSavePath(downloadFilePath);
  909. item.on('done', function () {
  910. resolve(item);
  911. });
  912. item.cancel();
  913. });
  914. });
  915. const downloadUrl = `http://127.0.0.1:${port}/assets/logo.png`;
  916. w.webContents.downloadURL(downloadUrl);
  917. const item = await downloadCancelled;
  918. expect(item.getState()).to.equal('cancelled');
  919. const options = {
  920. path: item.savePath,
  921. urlChain: item.getURLChain(),
  922. mimeType: item.getMimeType(),
  923. offset: item.getReceivedBytes(),
  924. length: item.getTotalBytes(),
  925. lastModified: item.getLastModifiedTime(),
  926. eTag: item.getETag()
  927. };
  928. const downloadResumed: Promise<Electron.DownloadItem> = new Promise((resolve) => {
  929. w.webContents.session.once('will-download', function (e, item) {
  930. expect(item.getState()).to.equal('interrupted');
  931. item.setSavePath(downloadFilePath);
  932. item.resume();
  933. item.on('done', function () {
  934. resolve(item);
  935. });
  936. });
  937. });
  938. w.webContents.session.createInterruptedDownload(options);
  939. const completedItem = await downloadResumed;
  940. expect(completedItem.getState()).to.equal('completed');
  941. expect(completedItem.getFilename()).to.equal('logo.png');
  942. expect(completedItem.savePath).to.equal(downloadFilePath);
  943. expect(completedItem.getURL()).to.equal(downloadUrl);
  944. expect(completedItem.getMimeType()).to.equal('image/png');
  945. expect(completedItem.getReceivedBytes()).to.equal(14022);
  946. expect(completedItem.getTotalBytes()).to.equal(14022);
  947. expect(fs.existsSync(downloadFilePath)).to.equal(true);
  948. } finally {
  949. rangeServer.close();
  950. }
  951. });
  952. });
  953. describe('ses.setPermissionRequestHandler(handler)', () => {
  954. afterEach(closeAllWindows);
  955. it('cancels any pending requests when cleared', async () => {
  956. const w = new BrowserWindow({
  957. show: false,
  958. webPreferences: {
  959. partition: 'very-temp-permission-handler',
  960. nodeIntegration: true,
  961. contextIsolation: false
  962. }
  963. });
  964. const ses = w.webContents.session;
  965. ses.setPermissionRequestHandler(() => {
  966. ses.setPermissionRequestHandler(null);
  967. });
  968. ses.protocol.interceptStringProtocol('https', (req, cb) => {
  969. cb(`<html><script>(${remote})()</script></html>`);
  970. });
  971. const result = emittedOnce(require('electron').ipcMain, 'message');
  972. function remote () {
  973. (navigator as any).requestMIDIAccess({ sysex: true }).then(() => {}, (err: any) => {
  974. require('electron').ipcRenderer.send('message', err.name);
  975. });
  976. }
  977. await w.loadURL('https://myfakesite');
  978. const [, name] = await result;
  979. expect(name).to.deep.equal('SecurityError');
  980. });
  981. });
  982. describe('ses.setPermissionCheckHandler(handler)', () => {
  983. afterEach(closeAllWindows);
  984. it('details provides requestingURL for mainFrame', async () => {
  985. const w = new BrowserWindow({
  986. show: false,
  987. webPreferences: {
  988. partition: 'very-temp-permission-handler'
  989. }
  990. });
  991. const ses = w.webContents.session;
  992. const loadUrl = 'https://myfakesite/';
  993. let handlerDetails : Electron.PermissionCheckHandlerHandlerDetails;
  994. ses.protocol.interceptStringProtocol('https', (req, cb) => {
  995. cb('<html><script>console.log(\'test\');</script></html>');
  996. });
  997. ses.setPermissionCheckHandler((wc, permission, requestingOrigin, details) => {
  998. if (permission === 'clipboard-read') {
  999. handlerDetails = details;
  1000. return true;
  1001. }
  1002. return false;
  1003. });
  1004. const readClipboardPermission: any = () => {
  1005. return w.webContents.executeJavaScript(`
  1006. navigator.permissions.query({name: 'clipboard-read'})
  1007. .then(permission => permission.state).catch(err => err.message);
  1008. `, true);
  1009. };
  1010. await w.loadURL(loadUrl);
  1011. const state = await readClipboardPermission();
  1012. expect(state).to.equal('granted');
  1013. expect(handlerDetails!.requestingUrl).to.equal(loadUrl);
  1014. });
  1015. it('details provides requestingURL for cross origin subFrame', async () => {
  1016. const w = new BrowserWindow({
  1017. show: false,
  1018. webPreferences: {
  1019. partition: 'very-temp-permission-handler'
  1020. }
  1021. });
  1022. const ses = w.webContents.session;
  1023. const loadUrl = 'https://myfakesite/';
  1024. let handlerDetails : Electron.PermissionCheckHandlerHandlerDetails;
  1025. ses.protocol.interceptStringProtocol('https', (req, cb) => {
  1026. cb('<html><script>console.log(\'test\');</script></html>');
  1027. });
  1028. ses.setPermissionCheckHandler((wc, permission, requestingOrigin, details) => {
  1029. if (permission === 'clipboard-read') {
  1030. handlerDetails = details;
  1031. return true;
  1032. }
  1033. return false;
  1034. });
  1035. const readClipboardPermission: any = (frame: WebFrameMain) => {
  1036. return frame.executeJavaScript(`
  1037. navigator.permissions.query({name: 'clipboard-read'})
  1038. .then(permission => permission.state).catch(err => err.message);
  1039. `, true);
  1040. };
  1041. await w.loadFile(path.join(fixtures, 'api', 'blank.html'));
  1042. w.webContents.executeJavaScript(`
  1043. var iframe = document.createElement('iframe');
  1044. iframe.src = '${loadUrl}';
  1045. document.body.appendChild(iframe);
  1046. null;
  1047. `);
  1048. const [,, frameProcessId, frameRoutingId] = await emittedOnce(w.webContents, 'did-frame-finish-load');
  1049. const state = await readClipboardPermission(webFrameMain.fromId(frameProcessId, frameRoutingId));
  1050. expect(state).to.equal('granted');
  1051. expect(handlerDetails!.requestingUrl).to.equal(loadUrl);
  1052. expect(handlerDetails!.isMainFrame).to.be.false();
  1053. expect(handlerDetails!.embeddingOrigin).to.equal('file:///');
  1054. });
  1055. });
  1056. describe('ses.isPersistent()', () => {
  1057. afterEach(closeAllWindows);
  1058. it('returns default session as persistent', () => {
  1059. const w = new BrowserWindow({
  1060. show: false
  1061. });
  1062. const ses = w.webContents.session;
  1063. expect(ses.isPersistent()).to.be.true();
  1064. });
  1065. it('returns persist: session as persistent', () => {
  1066. const ses = session.fromPartition(`persist:${Math.random()}`);
  1067. expect(ses.isPersistent()).to.be.true();
  1068. });
  1069. it('returns temporary session as not persistent', () => {
  1070. const ses = session.fromPartition(`${Math.random()}`);
  1071. expect(ses.isPersistent()).to.be.false();
  1072. });
  1073. });
  1074. describe('ses.setUserAgent()', () => {
  1075. afterEach(closeAllWindows);
  1076. it('can be retrieved with getUserAgent()', () => {
  1077. const userAgent = 'test-agent';
  1078. const ses = session.fromPartition('' + Math.random());
  1079. ses.setUserAgent(userAgent);
  1080. expect(ses.getUserAgent()).to.equal(userAgent);
  1081. });
  1082. it('sets the User-Agent header for web requests made from renderers', async () => {
  1083. const userAgent = 'test-agent';
  1084. const ses = session.fromPartition('' + Math.random());
  1085. ses.setUserAgent(userAgent, 'en-US,fr,de');
  1086. const w = new BrowserWindow({ show: false, webPreferences: { session: ses } });
  1087. let headers: http.IncomingHttpHeaders | null = null;
  1088. const server = http.createServer((req, res) => {
  1089. headers = req.headers;
  1090. res.end();
  1091. server.close();
  1092. });
  1093. await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
  1094. await w.loadURL(`http://127.0.0.1:${(server.address() as AddressInfo).port}`);
  1095. expect(headers!['user-agent']).to.equal(userAgent);
  1096. expect(headers!['accept-language']).to.equal('en-US,fr;q=0.9,de;q=0.8');
  1097. });
  1098. });
  1099. describe('session-created event', () => {
  1100. it('is emitted when a session is created', async () => {
  1101. const sessionCreated = emittedOnce(app, 'session-created');
  1102. const session1 = session.fromPartition('' + Math.random());
  1103. const [session2] = await sessionCreated;
  1104. expect(session1).to.equal(session2);
  1105. });
  1106. });
  1107. describe('session.storagePage', () => {
  1108. it('returns a string', () => {
  1109. expect(session.defaultSession.storagePath).to.be.a('string');
  1110. });
  1111. it('returns null for in memory sessions', () => {
  1112. expect(session.fromPartition('in-memory').storagePath).to.equal(null);
  1113. });
  1114. it('returns different paths for partitions and the default session', () => {
  1115. expect(session.defaultSession.storagePath).to.not.equal(session.fromPartition('persist:two').storagePath);
  1116. });
  1117. it('returns different paths for different partitions', () => {
  1118. expect(session.fromPartition('persist:one').storagePath).to.not.equal(session.fromPartition('persist:two').storagePath);
  1119. });
  1120. });
  1121. describe('session.setCodeCachePath()', () => {
  1122. it('throws when relative or empty path is provided', () => {
  1123. expect(() => {
  1124. session.defaultSession.setCodeCachePath('../fixtures');
  1125. }).to.throw('Absolute path must be provided to store code cache.');
  1126. expect(() => {
  1127. session.defaultSession.setCodeCachePath('');
  1128. }).to.throw('Absolute path must be provided to store code cache.');
  1129. expect(() => {
  1130. session.defaultSession.setCodeCachePath(path.join(app.getPath('userData'), 'electron-test-code-cache'));
  1131. }).to.not.throw();
  1132. });
  1133. });
  1134. describe('ses.setSSLConfig()', () => {
  1135. it('can disable cipher suites', async () => {
  1136. const ses = session.fromPartition('' + Math.random());
  1137. const fixturesPath = path.resolve(__dirname, '..', 'spec', 'fixtures');
  1138. const certPath = path.join(fixturesPath, 'certificates');
  1139. const server = https.createServer({
  1140. key: fs.readFileSync(path.join(certPath, 'server.key')),
  1141. cert: fs.readFileSync(path.join(certPath, 'server.pem')),
  1142. ca: [
  1143. fs.readFileSync(path.join(certPath, 'rootCA.pem')),
  1144. fs.readFileSync(path.join(certPath, 'intermediateCA.pem'))
  1145. ],
  1146. minVersion: 'TLSv1.2',
  1147. maxVersion: 'TLSv1.2',
  1148. ciphers: 'AES128-GCM-SHA256'
  1149. }, (req, res) => {
  1150. res.end('hi');
  1151. });
  1152. await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
  1153. defer(() => server.close());
  1154. const { port } = server.address() as AddressInfo;
  1155. function request () {
  1156. return new Promise((resolve, reject) => {
  1157. const r = net.request({
  1158. url: `https://127.0.0.1:${port}`,
  1159. session: ses
  1160. });
  1161. r.on('response', (res) => {
  1162. let data = '';
  1163. res.on('data', (chunk) => {
  1164. data += chunk.toString('utf8');
  1165. });
  1166. res.on('end', () => {
  1167. resolve(data);
  1168. });
  1169. });
  1170. r.on('error', (err) => {
  1171. reject(err);
  1172. });
  1173. r.end();
  1174. });
  1175. }
  1176. await expect(request()).to.be.rejectedWith(/ERR_CERT_AUTHORITY_INVALID/);
  1177. ses.setSSLConfig({
  1178. disabledCipherSuites: [0x009C]
  1179. });
  1180. await expect(request()).to.be.rejectedWith(/ERR_SSL_VERSION_OR_CIPHER_MISMATCH/);
  1181. });
  1182. });
  1183. });