api-session-spec.ts 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144
  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 } 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(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 () => {
  183. const appPath = path.join(fixtures, 'api', 'cookie-app');
  184. const runAppWithPhase = (phase: string) => {
  185. return new Promise((resolve) => {
  186. let output = '';
  187. const appProcess = ChildProcess.spawn(
  188. process.execPath,
  189. [appPath],
  190. { env: { PHASE: phase, ...process.env } }
  191. );
  192. appProcess.stdout.on('data', data => { output += data; });
  193. appProcess.on('exit', () => {
  194. resolve(output.replace(/(\r\n|\n|\r)/gm, ''));
  195. });
  196. });
  197. };
  198. expect(await runAppWithPhase('one')).to.equal('011');
  199. expect(await runAppWithPhase('two')).to.equal('110');
  200. });
  201. });
  202. describe('ses.clearStorageData(options)', () => {
  203. afterEach(closeAllWindows);
  204. it('clears localstorage data', async () => {
  205. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
  206. await w.loadFile(path.join(fixtures, 'api', 'localstorage.html'));
  207. const options = {
  208. origin: 'file://',
  209. storages: ['localstorage'],
  210. quotas: ['persistent']
  211. };
  212. await w.webContents.session.clearStorageData(options);
  213. while (await w.webContents.executeJavaScript('localStorage.length') !== 0) {
  214. // The storage clear isn't instantly visible to the renderer, so keep
  215. // trying until it is.
  216. }
  217. });
  218. });
  219. describe('will-download event', () => {
  220. afterEach(closeAllWindows);
  221. it('can cancel default download behavior', async () => {
  222. const w = new BrowserWindow({ show: false });
  223. const mockFile = Buffer.alloc(1024);
  224. const contentDisposition = 'inline; filename="mockFile.txt"';
  225. const downloadServer = http.createServer((req, res) => {
  226. res.writeHead(200, {
  227. 'Content-Length': mockFile.length,
  228. 'Content-Type': 'application/plain',
  229. 'Content-Disposition': contentDisposition
  230. });
  231. res.end(mockFile);
  232. downloadServer.close();
  233. });
  234. await new Promise(resolve => downloadServer.listen(0, '127.0.0.1', resolve));
  235. const port = (downloadServer.address() as AddressInfo).port;
  236. const url = `http://127.0.0.1:${port}/`;
  237. const downloadPrevented: Promise<{itemUrl: string, itemFilename: string, item: Electron.DownloadItem}> = new Promise(resolve => {
  238. w.webContents.session.once('will-download', function (e, item) {
  239. e.preventDefault();
  240. resolve({ itemUrl: item.getURL(), itemFilename: item.getFilename(), item });
  241. });
  242. });
  243. w.loadURL(url);
  244. const { item, itemUrl, itemFilename } = await downloadPrevented;
  245. expect(itemUrl).to.equal(url);
  246. expect(itemFilename).to.equal('mockFile.txt');
  247. // Delay till the next tick.
  248. await new Promise(resolve => setImmediate(() => resolve()));
  249. expect(() => item.getURL()).to.throw('DownloadItem used after being destroyed');
  250. });
  251. });
  252. describe('ses.protocol', () => {
  253. const partitionName = 'temp';
  254. const protocolName = 'sp';
  255. let customSession: Session;
  256. const protocol = session.defaultSession.protocol;
  257. const handler = (ignoredError: any, callback: Function) => {
  258. callback({ data: '<script>require(\'electron\').ipcRenderer.send(\'hello\')</script>', mimeType: 'text/html' });
  259. };
  260. beforeEach(async () => {
  261. customSession = session.fromPartition(partitionName);
  262. await customSession.protocol.registerStringProtocol(protocolName, handler);
  263. });
  264. afterEach(async () => {
  265. await customSession.protocol.unregisterProtocol(protocolName);
  266. customSession = null as any;
  267. });
  268. afterEach(closeAllWindows);
  269. it('does not affect defaultSession', () => {
  270. const result1 = protocol.isProtocolRegistered(protocolName);
  271. expect(result1).to.equal(false);
  272. const result2 = customSession.protocol.isProtocolRegistered(protocolName);
  273. expect(result2).to.equal(true);
  274. });
  275. it('handles requests from partition', async () => {
  276. const w = new BrowserWindow({
  277. show: false,
  278. webPreferences: {
  279. partition: partitionName,
  280. nodeIntegration: true,
  281. contextIsolation: false
  282. }
  283. });
  284. customSession = session.fromPartition(partitionName);
  285. await customSession.protocol.registerStringProtocol(protocolName, handler);
  286. w.loadURL(`${protocolName}://fake-host`);
  287. await emittedOnce(ipcMain, 'hello');
  288. });
  289. });
  290. describe('ses.setProxy(options)', () => {
  291. let server: http.Server;
  292. let customSession: Electron.Session;
  293. let created = false;
  294. beforeEach(async () => {
  295. customSession = session.fromPartition('proxyconfig');
  296. if (!created) {
  297. // Work around for https://github.com/electron/electron/issues/26166 to
  298. // reduce flake
  299. await delay(100);
  300. created = true;
  301. }
  302. });
  303. afterEach(() => {
  304. if (server) {
  305. server.close();
  306. }
  307. customSession = null as any;
  308. });
  309. it('allows configuring proxy settings', async () => {
  310. const config = { proxyRules: 'http=myproxy:80' };
  311. await customSession.setProxy(config);
  312. const proxy = await customSession.resolveProxy('http://example.com/');
  313. expect(proxy).to.equal('PROXY myproxy:80');
  314. });
  315. it('allows removing the implicit bypass rules for localhost', async () => {
  316. const config = {
  317. proxyRules: 'http=myproxy:80',
  318. proxyBypassRules: '<-loopback>'
  319. };
  320. await customSession.setProxy(config);
  321. const proxy = await customSession.resolveProxy('http://localhost');
  322. expect(proxy).to.equal('PROXY myproxy:80');
  323. });
  324. it('allows configuring proxy settings with pacScript', async () => {
  325. server = http.createServer((req, res) => {
  326. const pac = `
  327. function FindProxyForURL(url, host) {
  328. return "PROXY myproxy:8132";
  329. }
  330. `;
  331. res.writeHead(200, {
  332. 'Content-Type': 'application/x-ns-proxy-autoconfig'
  333. });
  334. res.end(pac);
  335. });
  336. await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
  337. {
  338. const config = { pacScript: `http://127.0.0.1:${(server.address() as AddressInfo).port}` };
  339. await customSession.setProxy(config);
  340. const proxy = await customSession.resolveProxy('https://google.com');
  341. expect(proxy).to.equal('PROXY myproxy:8132');
  342. }
  343. {
  344. const config = { mode: 'pac_script' as any, pacScript: `http://127.0.0.1:${(server.address() as AddressInfo).port}` };
  345. await customSession.setProxy(config);
  346. const proxy = await customSession.resolveProxy('https://google.com');
  347. expect(proxy).to.equal('PROXY myproxy:8132');
  348. }
  349. });
  350. it('allows bypassing proxy settings', async () => {
  351. const config = {
  352. proxyRules: 'http=myproxy:80',
  353. proxyBypassRules: '<local>'
  354. };
  355. await customSession.setProxy(config);
  356. const proxy = await customSession.resolveProxy('http://example/');
  357. expect(proxy).to.equal('DIRECT');
  358. });
  359. it('allows configuring proxy settings with mode `direct`', async () => {
  360. const config = { mode: 'direct' as any, proxyRules: 'http=myproxy:80' };
  361. await customSession.setProxy(config);
  362. const proxy = await customSession.resolveProxy('http://example.com/');
  363. expect(proxy).to.equal('DIRECT');
  364. });
  365. it('allows configuring proxy settings with mode `auto_detect`', async () => {
  366. const config = { mode: 'auto_detect' as any };
  367. await customSession.setProxy(config);
  368. });
  369. it('allows configuring proxy settings with mode `pac_script`', async () => {
  370. const config = { mode: 'pac_script' as any };
  371. await customSession.setProxy(config);
  372. const proxy = await customSession.resolveProxy('http://example.com/');
  373. expect(proxy).to.equal('DIRECT');
  374. });
  375. it('allows configuring proxy settings with mode `fixed_servers`', async () => {
  376. const config = { mode: 'fixed_servers' as any, proxyRules: 'http=myproxy:80' };
  377. await customSession.setProxy(config);
  378. const proxy = await customSession.resolveProxy('http://example.com/');
  379. expect(proxy).to.equal('PROXY myproxy:80');
  380. });
  381. it('allows configuring proxy settings with mode `system`', async () => {
  382. const config = { mode: 'system' as any };
  383. await customSession.setProxy(config);
  384. });
  385. it('disallows configuring proxy settings with mode `invalid`', async () => {
  386. const config = { mode: 'invalid' as any };
  387. await expect(customSession.setProxy(config)).to.eventually.be.rejectedWith(/Invalid mode/);
  388. });
  389. it('reload proxy configuration', async () => {
  390. let proxyPort = 8132;
  391. server = http.createServer((req, res) => {
  392. const pac = `
  393. function FindProxyForURL(url, host) {
  394. return "PROXY myproxy:${proxyPort}";
  395. }
  396. `;
  397. res.writeHead(200, {
  398. 'Content-Type': 'application/x-ns-proxy-autoconfig'
  399. });
  400. res.end(pac);
  401. });
  402. await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
  403. const config = { mode: 'pac_script' as any, pacScript: `http://127.0.0.1:${(server.address() as AddressInfo).port}` };
  404. await customSession.setProxy(config);
  405. {
  406. const proxy = await customSession.resolveProxy('https://google.com');
  407. expect(proxy).to.equal(`PROXY myproxy:${proxyPort}`);
  408. }
  409. {
  410. proxyPort = 8133;
  411. await customSession.forceReloadProxyConfig();
  412. const proxy = await customSession.resolveProxy('https://google.com');
  413. expect(proxy).to.equal(`PROXY myproxy:${proxyPort}`);
  414. }
  415. });
  416. });
  417. describe('ses.getBlobData()', () => {
  418. const scheme = 'cors-blob';
  419. const protocol = session.defaultSession.protocol;
  420. const url = `${scheme}://host`;
  421. after(async () => {
  422. await protocol.unregisterProtocol(scheme);
  423. });
  424. afterEach(closeAllWindows);
  425. it('returns blob data for uuid', (done) => {
  426. const postData = JSON.stringify({
  427. type: 'blob',
  428. value: 'hello'
  429. });
  430. const content = `<html>
  431. <script>
  432. let fd = new FormData();
  433. fd.append('file', new Blob(['${postData}'], {type:'application/json'}));
  434. fetch('${url}', {method:'POST', body: fd });
  435. </script>
  436. </html>`;
  437. protocol.registerStringProtocol(scheme, (request, callback) => {
  438. try {
  439. if (request.method === 'GET') {
  440. callback({ data: content, mimeType: 'text/html' });
  441. } else if (request.method === 'POST') {
  442. const uuid = request.uploadData![1].blobUUID;
  443. expect(uuid).to.be.a('string');
  444. session.defaultSession.getBlobData(uuid!).then(result => {
  445. try {
  446. expect(result.toString()).to.equal(postData);
  447. done();
  448. } catch (e) {
  449. done(e);
  450. }
  451. });
  452. }
  453. } catch (e) {
  454. done(e);
  455. }
  456. });
  457. const w = new BrowserWindow({ show: false });
  458. w.loadURL(url);
  459. });
  460. });
  461. describe('ses.setCertificateVerifyProc(callback)', () => {
  462. let server: http.Server;
  463. beforeEach((done) => {
  464. const certPath = path.join(fixtures, 'certificates');
  465. const options = {
  466. key: fs.readFileSync(path.join(certPath, 'server.key')),
  467. cert: fs.readFileSync(path.join(certPath, 'server.pem')),
  468. ca: [
  469. fs.readFileSync(path.join(certPath, 'rootCA.pem')),
  470. fs.readFileSync(path.join(certPath, 'intermediateCA.pem'))
  471. ],
  472. rejectUnauthorized: false
  473. };
  474. server = https.createServer(options, (req, res) => {
  475. res.writeHead(200);
  476. res.end('<title>hello</title>');
  477. });
  478. server.listen(0, '127.0.0.1', done);
  479. });
  480. afterEach((done) => {
  481. server.close(done);
  482. });
  483. afterEach(closeAllWindows);
  484. it('accepts the request when the callback is called with 0', async () => {
  485. const ses = session.fromPartition(`${Math.random()}`);
  486. ses.setCertificateVerifyProc(({ verificationResult, errorCode }, callback) => {
  487. expect(['net::ERR_CERT_AUTHORITY_INVALID', 'net::ERR_CERT_COMMON_NAME_INVALID'].includes(verificationResult)).to.be.true();
  488. expect([-202, -200].includes(errorCode)).to.be.true();
  489. callback(0);
  490. });
  491. const w = new BrowserWindow({ show: false, webPreferences: { session: ses } });
  492. await w.loadURL(`https://127.0.0.1:${(server.address() as AddressInfo).port}`);
  493. expect(w.webContents.getTitle()).to.equal('hello');
  494. });
  495. it('rejects the request when the callback is called with -2', async () => {
  496. const ses = session.fromPartition(`${Math.random()}`);
  497. ses.setCertificateVerifyProc(({ hostname, certificate, verificationResult }, callback) => {
  498. expect(hostname).to.equal('127.0.0.1');
  499. expect(certificate.issuerName).to.equal('Intermediate CA');
  500. expect(certificate.subjectName).to.equal('localhost');
  501. expect(certificate.issuer.commonName).to.equal('Intermediate CA');
  502. expect(certificate.subject.commonName).to.equal('localhost');
  503. expect(certificate.issuerCert.issuer.commonName).to.equal('Root CA');
  504. expect(certificate.issuerCert.subject.commonName).to.equal('Intermediate CA');
  505. expect(certificate.issuerCert.issuerCert.issuer.commonName).to.equal('Root CA');
  506. expect(certificate.issuerCert.issuerCert.subject.commonName).to.equal('Root CA');
  507. expect(certificate.issuerCert.issuerCert.issuerCert).to.equal(undefined);
  508. expect(['net::ERR_CERT_AUTHORITY_INVALID', 'net::ERR_CERT_COMMON_NAME_INVALID'].includes(verificationResult)).to.be.true();
  509. callback(-2);
  510. });
  511. const url = `https://127.0.0.1:${(server.address() as AddressInfo).port}`;
  512. const w = new BrowserWindow({ show: false, webPreferences: { session: ses } });
  513. await expect(w.loadURL(url)).to.eventually.be.rejectedWith(/ERR_FAILED/);
  514. expect(w.webContents.getTitle()).to.equal(url);
  515. });
  516. it('saves cached results', async () => {
  517. const ses = session.fromPartition(`${Math.random()}`);
  518. let numVerificationRequests = 0;
  519. ses.setCertificateVerifyProc((e, callback) => {
  520. numVerificationRequests++;
  521. callback(-2);
  522. });
  523. const url = `https://127.0.0.1:${(server.address() as AddressInfo).port}`;
  524. const w = new BrowserWindow({ show: false, webPreferences: { session: ses } });
  525. await expect(w.loadURL(url), 'first load').to.eventually.be.rejectedWith(/ERR_FAILED/);
  526. await emittedOnce(w.webContents, 'did-stop-loading');
  527. await expect(w.loadURL(url + '/test'), 'second load').to.eventually.be.rejectedWith(/ERR_FAILED/);
  528. expect(w.webContents.getTitle()).to.equal(url + '/test');
  529. expect(numVerificationRequests).to.equal(1);
  530. });
  531. it('does not cancel requests in other sessions', async () => {
  532. const ses1 = session.fromPartition(`${Math.random()}`);
  533. ses1.setCertificateVerifyProc((opts, cb) => cb(0));
  534. const ses2 = session.fromPartition(`${Math.random()}`);
  535. const url = `https://127.0.0.1:${(server.address() as AddressInfo).port}`;
  536. const req = net.request({ url, session: ses1, credentials: 'include' });
  537. req.end();
  538. setTimeout(() => {
  539. ses2.setCertificateVerifyProc((opts, callback) => callback(0));
  540. });
  541. await expect(new Promise((resolve, reject) => {
  542. req.on('error', (err) => {
  543. reject(err);
  544. });
  545. req.on('response', () => {
  546. resolve();
  547. });
  548. })).to.eventually.be.fulfilled();
  549. });
  550. });
  551. describe('ses.clearAuthCache()', () => {
  552. it('can clear http auth info from cache', async () => {
  553. const ses = session.fromPartition('auth-cache');
  554. const server = http.createServer((req, res) => {
  555. const credentials = auth(req);
  556. if (!credentials || credentials.name !== 'test' || credentials.pass !== 'test') {
  557. res.statusCode = 401;
  558. res.setHeader('WWW-Authenticate', 'Basic realm="Restricted"');
  559. res.end();
  560. } else {
  561. res.end('authenticated');
  562. }
  563. });
  564. await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
  565. const port = (server.address() as AddressInfo).port;
  566. const fetch = (url: string) => new Promise((resolve, reject) => {
  567. const request = net.request({ url, session: ses });
  568. request.on('response', (response) => {
  569. let data: string | null = null;
  570. response.on('data', (chunk) => {
  571. if (!data) {
  572. data = '';
  573. }
  574. data += chunk;
  575. });
  576. response.on('end', () => {
  577. if (!data) {
  578. reject(new Error('Empty response'));
  579. } else {
  580. resolve(data);
  581. }
  582. });
  583. response.on('error', (error: any) => { reject(new Error(error)); });
  584. });
  585. request.on('error', (error: any) => { reject(new Error(error)); });
  586. request.end();
  587. });
  588. // the first time should throw due to unauthenticated
  589. await expect(fetch(`http://127.0.0.1:${port}`)).to.eventually.be.rejected();
  590. // passing the password should let us in
  591. expect(await fetch(`http://test:[email protected]:${port}`)).to.equal('authenticated');
  592. // subsequently, the credentials are cached
  593. expect(await fetch(`http://127.0.0.1:${port}`)).to.equal('authenticated');
  594. await ses.clearAuthCache();
  595. // once the cache is cleared, we should get an error again
  596. await expect(fetch(`http://127.0.0.1:${port}`)).to.eventually.be.rejected();
  597. });
  598. });
  599. describe('DownloadItem', () => {
  600. const mockPDF = Buffer.alloc(1024 * 1024 * 5);
  601. const downloadFilePath = path.join(__dirname, '..', 'fixtures', 'mock.pdf');
  602. const protocolName = 'custom-dl';
  603. const contentDisposition = 'inline; filename="mock.pdf"';
  604. let address: AddressInfo;
  605. let downloadServer: http.Server;
  606. before(async () => {
  607. downloadServer = http.createServer((req, res) => {
  608. res.writeHead(200, {
  609. 'Content-Length': mockPDF.length,
  610. 'Content-Type': 'application/pdf',
  611. 'Content-Disposition': req.url === '/?testFilename' ? 'inline' : contentDisposition
  612. });
  613. res.end(mockPDF);
  614. });
  615. await new Promise(resolve => downloadServer.listen(0, '127.0.0.1', resolve));
  616. address = downloadServer.address() as AddressInfo;
  617. });
  618. after(async () => {
  619. await new Promise(resolve => downloadServer.close(resolve));
  620. });
  621. afterEach(closeAllWindows);
  622. const isPathEqual = (path1: string, path2: string) => {
  623. return path.relative(path1, path2) === '';
  624. };
  625. const assertDownload = (state: string, item: Electron.DownloadItem, isCustom = false) => {
  626. expect(state).to.equal('completed');
  627. expect(item.getFilename()).to.equal('mock.pdf');
  628. expect(path.isAbsolute(item.savePath)).to.equal(true);
  629. expect(isPathEqual(item.savePath, downloadFilePath)).to.equal(true);
  630. if (isCustom) {
  631. expect(item.getURL()).to.equal(`${protocolName}://item`);
  632. } else {
  633. expect(item.getURL()).to.be.equal(`${url}:${address.port}/`);
  634. }
  635. expect(item.getMimeType()).to.equal('application/pdf');
  636. expect(item.getReceivedBytes()).to.equal(mockPDF.length);
  637. expect(item.getTotalBytes()).to.equal(mockPDF.length);
  638. expect(item.getContentDisposition()).to.equal(contentDisposition);
  639. expect(fs.existsSync(downloadFilePath)).to.equal(true);
  640. fs.unlinkSync(downloadFilePath);
  641. };
  642. it('can download using session.downloadURL', (done) => {
  643. const port = address.port;
  644. session.defaultSession.once('will-download', function (e, item) {
  645. item.savePath = downloadFilePath;
  646. item.on('done', function (e, state) {
  647. try {
  648. assertDownload(state, item);
  649. done();
  650. } catch (e) {
  651. done(e);
  652. }
  653. });
  654. });
  655. session.defaultSession.downloadURL(`${url}:${port}`);
  656. });
  657. it('can download using WebContents.downloadURL', (done) => {
  658. const port = address.port;
  659. const w = new BrowserWindow({ show: false });
  660. w.webContents.session.once('will-download', function (e, item) {
  661. item.savePath = downloadFilePath;
  662. item.on('done', function (e, state) {
  663. try {
  664. assertDownload(state, item);
  665. done();
  666. } catch (e) {
  667. done(e);
  668. }
  669. });
  670. });
  671. w.webContents.downloadURL(`${url}:${port}`);
  672. });
  673. it('can download from custom protocols using WebContents.downloadURL', (done) => {
  674. const protocol = session.defaultSession.protocol;
  675. const port = address.port;
  676. const handler = (ignoredError: any, callback: Function) => {
  677. callback({ url: `${url}:${port}` });
  678. };
  679. protocol.registerHttpProtocol(protocolName, handler);
  680. const w = new BrowserWindow({ show: false });
  681. w.webContents.session.once('will-download', function (e, item) {
  682. item.savePath = downloadFilePath;
  683. item.on('done', function (e, state) {
  684. try {
  685. assertDownload(state, item, true);
  686. done();
  687. } catch (e) {
  688. done(e);
  689. }
  690. });
  691. });
  692. w.webContents.downloadURL(`${protocolName}://item`);
  693. });
  694. it('can download using WebView.downloadURL', async () => {
  695. const port = address.port;
  696. const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true } });
  697. await w.loadURL('about:blank');
  698. function webviewDownload ({ fixtures, url, port }: {fixtures: string, url: string, port: string}) {
  699. const webview = new (window as any).WebView();
  700. webview.addEventListener('did-finish-load', () => {
  701. webview.downloadURL(`${url}:${port}/`);
  702. });
  703. webview.src = `file://${fixtures}/api/blank.html`;
  704. document.body.appendChild(webview);
  705. }
  706. const done: Promise<[string, Electron.DownloadItem]> = new Promise(resolve => {
  707. w.webContents.session.once('will-download', function (e, item) {
  708. item.savePath = downloadFilePath;
  709. item.on('done', function (e, state) {
  710. resolve([state, item]);
  711. });
  712. });
  713. });
  714. await w.webContents.executeJavaScript(`(${webviewDownload})(${JSON.stringify({ fixtures, url, port })})`);
  715. const [state, item] = await done;
  716. assertDownload(state, item);
  717. });
  718. it('can cancel download', (done) => {
  719. const port = address.port;
  720. const w = new BrowserWindow({ show: false });
  721. w.webContents.session.once('will-download', function (e, item) {
  722. item.savePath = downloadFilePath;
  723. item.on('done', function (e, state) {
  724. try {
  725. expect(state).to.equal('cancelled');
  726. expect(item.getFilename()).to.equal('mock.pdf');
  727. expect(item.getMimeType()).to.equal('application/pdf');
  728. expect(item.getReceivedBytes()).to.equal(0);
  729. expect(item.getTotalBytes()).to.equal(mockPDF.length);
  730. expect(item.getContentDisposition()).to.equal(contentDisposition);
  731. done();
  732. } catch (e) {
  733. done(e);
  734. }
  735. });
  736. item.cancel();
  737. });
  738. w.webContents.downloadURL(`${url}:${port}/`);
  739. });
  740. it('can generate a default filename', function (done) {
  741. if (process.env.APPVEYOR === 'True') {
  742. // FIXME(alexeykuzmin): Skip the test.
  743. // this.skip()
  744. return done();
  745. }
  746. const port = address.port;
  747. const w = new BrowserWindow({ show: false });
  748. w.webContents.session.once('will-download', function (e, item) {
  749. item.savePath = downloadFilePath;
  750. item.on('done', function () {
  751. try {
  752. expect(item.getFilename()).to.equal('download.pdf');
  753. done();
  754. } catch (e) {
  755. done(e);
  756. }
  757. });
  758. item.cancel();
  759. });
  760. w.webContents.downloadURL(`${url}:${port}/?testFilename`);
  761. });
  762. it('can set options for the save dialog', (done) => {
  763. const filePath = path.join(__dirname, 'fixtures', 'mock.pdf');
  764. const port = address.port;
  765. const options = {
  766. window: null,
  767. title: 'title',
  768. message: 'message',
  769. buttonLabel: 'buttonLabel',
  770. nameFieldLabel: 'nameFieldLabel',
  771. defaultPath: '/',
  772. filters: [{
  773. name: '1', extensions: ['.1', '.2']
  774. }, {
  775. name: '2', extensions: ['.3', '.4', '.5']
  776. }],
  777. showsTagField: true,
  778. securityScopedBookmarks: true
  779. };
  780. const w = new BrowserWindow({ show: false });
  781. w.webContents.session.once('will-download', function (e, item) {
  782. item.setSavePath(filePath);
  783. item.setSaveDialogOptions(options);
  784. item.on('done', function () {
  785. try {
  786. expect(item.getSaveDialogOptions()).to.deep.equal(options);
  787. done();
  788. } catch (e) {
  789. done(e);
  790. }
  791. });
  792. item.cancel();
  793. });
  794. w.webContents.downloadURL(`${url}:${port}`);
  795. });
  796. describe('when a save path is specified and the URL is unavailable', () => {
  797. it('does not display a save dialog and reports the done state as interrupted', (done) => {
  798. const w = new BrowserWindow({ show: false });
  799. w.webContents.session.once('will-download', function (e, item) {
  800. item.savePath = downloadFilePath;
  801. if (item.getState() === 'interrupted') {
  802. item.resume();
  803. }
  804. item.on('done', function (e, state) {
  805. try {
  806. expect(state).to.equal('interrupted');
  807. done();
  808. } catch (e) {
  809. done(e);
  810. }
  811. });
  812. });
  813. w.webContents.downloadURL(`file://${path.join(__dirname, 'does-not-exist.txt')}`);
  814. });
  815. });
  816. });
  817. describe('ses.createInterruptedDownload(options)', () => {
  818. afterEach(closeAllWindows);
  819. it('can create an interrupted download item', async () => {
  820. const downloadFilePath = path.join(__dirname, '..', 'fixtures', 'mock.pdf');
  821. const options = {
  822. path: downloadFilePath,
  823. urlChain: ['http://127.0.0.1/'],
  824. mimeType: 'application/pdf',
  825. offset: 0,
  826. length: 5242880
  827. };
  828. const w = new BrowserWindow({ show: false });
  829. const p = emittedOnce(w.webContents.session, 'will-download');
  830. w.webContents.session.createInterruptedDownload(options);
  831. const [, item] = await p;
  832. expect(item.getState()).to.equal('interrupted');
  833. item.cancel();
  834. expect(item.getURLChain()).to.deep.equal(options.urlChain);
  835. expect(item.getMimeType()).to.equal(options.mimeType);
  836. expect(item.getReceivedBytes()).to.equal(options.offset);
  837. expect(item.getTotalBytes()).to.equal(options.length);
  838. expect(item.savePath).to.equal(downloadFilePath);
  839. });
  840. it('can be resumed', async () => {
  841. const downloadFilePath = path.join(fixtures, 'logo.png');
  842. const rangeServer = http.createServer((req, res) => {
  843. const options = { root: fixtures };
  844. send(req, req.url!, options)
  845. .on('error', (error: any) => { throw error; }).pipe(res);
  846. });
  847. try {
  848. await new Promise(resolve => rangeServer.listen(0, '127.0.0.1', resolve));
  849. const port = (rangeServer.address() as AddressInfo).port;
  850. const w = new BrowserWindow({ show: false });
  851. const downloadCancelled: Promise<Electron.DownloadItem> = new Promise((resolve) => {
  852. w.webContents.session.once('will-download', function (e, item) {
  853. item.setSavePath(downloadFilePath);
  854. item.on('done', function () {
  855. resolve(item);
  856. });
  857. item.cancel();
  858. });
  859. });
  860. const downloadUrl = `http://127.0.0.1:${port}/assets/logo.png`;
  861. w.webContents.downloadURL(downloadUrl);
  862. const item = await downloadCancelled;
  863. expect(item.getState()).to.equal('cancelled');
  864. const options = {
  865. path: item.savePath,
  866. urlChain: item.getURLChain(),
  867. mimeType: item.getMimeType(),
  868. offset: item.getReceivedBytes(),
  869. length: item.getTotalBytes(),
  870. lastModified: item.getLastModifiedTime(),
  871. eTag: item.getETag()
  872. };
  873. const downloadResumed: Promise<Electron.DownloadItem> = new Promise((resolve) => {
  874. w.webContents.session.once('will-download', function (e, item) {
  875. expect(item.getState()).to.equal('interrupted');
  876. item.setSavePath(downloadFilePath);
  877. item.resume();
  878. item.on('done', function () {
  879. resolve(item);
  880. });
  881. });
  882. });
  883. w.webContents.session.createInterruptedDownload(options);
  884. const completedItem = await downloadResumed;
  885. expect(completedItem.getState()).to.equal('completed');
  886. expect(completedItem.getFilename()).to.equal('logo.png');
  887. expect(completedItem.savePath).to.equal(downloadFilePath);
  888. expect(completedItem.getURL()).to.equal(downloadUrl);
  889. expect(completedItem.getMimeType()).to.equal('image/png');
  890. expect(completedItem.getReceivedBytes()).to.equal(14022);
  891. expect(completedItem.getTotalBytes()).to.equal(14022);
  892. expect(fs.existsSync(downloadFilePath)).to.equal(true);
  893. } finally {
  894. rangeServer.close();
  895. }
  896. });
  897. });
  898. describe('ses.setPermissionRequestHandler(handler)', () => {
  899. afterEach(closeAllWindows);
  900. it('cancels any pending requests when cleared', async () => {
  901. const w = new BrowserWindow({
  902. show: false,
  903. webPreferences: {
  904. partition: 'very-temp-permision-handler',
  905. nodeIntegration: true,
  906. contextIsolation: false
  907. }
  908. });
  909. const ses = w.webContents.session;
  910. ses.setPermissionRequestHandler(() => {
  911. ses.setPermissionRequestHandler(null);
  912. });
  913. ses.protocol.interceptStringProtocol('https', (req, cb) => {
  914. cb(`<html><script>(${remote})()</script></html>`);
  915. });
  916. const result = emittedOnce(require('electron').ipcMain, 'message');
  917. function remote () {
  918. (navigator as any).requestMIDIAccess({ sysex: true }).then(() => {}, (err: any) => {
  919. require('electron').ipcRenderer.send('message', err.name);
  920. });
  921. }
  922. await w.loadURL('https://myfakesite');
  923. const [, name] = await result;
  924. expect(name).to.deep.equal('SecurityError');
  925. });
  926. });
  927. describe('ses.isPersistent()', () => {
  928. afterEach(closeAllWindows);
  929. it('returns default session as persistent', () => {
  930. const w = new BrowserWindow({
  931. show: false
  932. });
  933. const ses = w.webContents.session;
  934. expect(ses.isPersistent()).to.be.true();
  935. });
  936. it('returns persist: session as persistent', () => {
  937. const ses = session.fromPartition(`persist:${Math.random()}`);
  938. expect(ses.isPersistent()).to.be.true();
  939. });
  940. it('returns temporary session as not persistent', () => {
  941. const ses = session.fromPartition(`${Math.random()}`);
  942. expect(ses.isPersistent()).to.be.false();
  943. });
  944. });
  945. describe('ses.setUserAgent()', () => {
  946. afterEach(closeAllWindows);
  947. it('can be retrieved with getUserAgent()', () => {
  948. const userAgent = 'test-agent';
  949. const ses = session.fromPartition('' + Math.random());
  950. ses.setUserAgent(userAgent);
  951. expect(ses.getUserAgent()).to.equal(userAgent);
  952. });
  953. it('sets the User-Agent header for web requests made from renderers', async () => {
  954. const userAgent = 'test-agent';
  955. const ses = session.fromPartition('' + Math.random());
  956. ses.setUserAgent(userAgent, 'en-US,fr,de');
  957. const w = new BrowserWindow({ show: false, webPreferences: { session: ses } });
  958. let headers: http.IncomingHttpHeaders | null = null;
  959. const server = http.createServer((req, res) => {
  960. headers = req.headers;
  961. res.end();
  962. server.close();
  963. });
  964. await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
  965. await w.loadURL(`http://127.0.0.1:${(server.address() as AddressInfo).port}`);
  966. expect(headers!['user-agent']).to.equal(userAgent);
  967. expect(headers!['accept-language']).to.equal('en-US,fr;q=0.9,de;q=0.8');
  968. });
  969. });
  970. describe('session-created event', () => {
  971. it('is emitted when a session is created', async () => {
  972. const sessionCreated = emittedOnce(app, 'session-created');
  973. const session1 = session.fromPartition('' + Math.random());
  974. const [session2] = await sessionCreated;
  975. expect(session1).to.equal(session2);
  976. });
  977. });
  978. describe('ses.setSSLConfig()', () => {
  979. it('can disable cipher suites', async () => {
  980. const ses = session.fromPartition('' + Math.random());
  981. const fixturesPath = path.resolve(__dirname, '..', 'spec', 'fixtures');
  982. const certPath = path.join(fixturesPath, 'certificates');
  983. const server = https.createServer({
  984. key: fs.readFileSync(path.join(certPath, 'server.key')),
  985. cert: fs.readFileSync(path.join(certPath, 'server.pem')),
  986. ca: [
  987. fs.readFileSync(path.join(certPath, 'rootCA.pem')),
  988. fs.readFileSync(path.join(certPath, 'intermediateCA.pem'))
  989. ],
  990. minVersion: 'TLSv1.2',
  991. maxVersion: 'TLSv1.2',
  992. ciphers: 'AES128-GCM-SHA256'
  993. }, (req, res) => {
  994. res.end('hi');
  995. });
  996. await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
  997. defer(() => server.close());
  998. const { port } = server.address() as AddressInfo;
  999. function request () {
  1000. return new Promise((resolve, reject) => {
  1001. const r = net.request({
  1002. url: `https://127.0.0.1:${port}`,
  1003. session: ses
  1004. });
  1005. r.on('response', (res) => {
  1006. let data = '';
  1007. res.on('data', (chunk) => {
  1008. data += chunk.toString('utf8');
  1009. });
  1010. res.on('end', () => {
  1011. resolve(data);
  1012. });
  1013. });
  1014. r.on('error', (err) => {
  1015. reject(err);
  1016. });
  1017. r.end();
  1018. });
  1019. }
  1020. await expect(request()).to.be.rejectedWith(/ERR_CERT_AUTHORITY_INVALID/);
  1021. ses.setSSLConfig({
  1022. disabledCipherSuites: [0x009C]
  1023. });
  1024. await expect(request()).to.be.rejectedWith(/ERR_SSL_VERSION_OR_CIPHER_MISMATCH/);
  1025. });
  1026. });
  1027. });