api-session-spec.ts 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189
  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<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 () => {
  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<void>(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<void>(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<void>(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<void>(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. let validate: () => void;
  487. ses.setCertificateVerifyProc(({ hostname, verificationResult, errorCode }, callback) => {
  488. if (hostname !== '127.0.0.1') return callback(-3);
  489. validate = () => {
  490. expect(verificationResult).to.be.oneOf(['net::ERR_CERT_AUTHORITY_INVALID', 'net::ERR_CERT_COMMON_NAME_INVALID']);
  491. expect(errorCode).to.be.oneOf([-202, -200]);
  492. };
  493. callback(0);
  494. });
  495. const w = new BrowserWindow({ show: false, webPreferences: { session: ses } });
  496. await w.loadURL(`https://127.0.0.1:${(server.address() as AddressInfo).port}`);
  497. expect(w.webContents.getTitle()).to.equal('hello');
  498. expect(validate!).not.to.be.undefined();
  499. validate!();
  500. });
  501. it('rejects the request when the callback is called with -2', async () => {
  502. const ses = session.fromPartition(`${Math.random()}`);
  503. let validate: () => void;
  504. ses.setCertificateVerifyProc(({ hostname, certificate, verificationResult, isIssuedByKnownRoot }, callback) => {
  505. if (hostname !== '127.0.0.1') return callback(-3);
  506. validate = () => {
  507. expect(certificate.issuerName).to.equal('Intermediate CA');
  508. expect(certificate.subjectName).to.equal('localhost');
  509. expect(certificate.issuer.commonName).to.equal('Intermediate CA');
  510. expect(certificate.subject.commonName).to.equal('localhost');
  511. expect(certificate.issuerCert.issuer.commonName).to.equal('Root CA');
  512. expect(certificate.issuerCert.subject.commonName).to.equal('Intermediate CA');
  513. expect(certificate.issuerCert.issuerCert.issuer.commonName).to.equal('Root CA');
  514. expect(certificate.issuerCert.issuerCert.subject.commonName).to.equal('Root CA');
  515. expect(certificate.issuerCert.issuerCert.issuerCert).to.equal(undefined);
  516. expect(verificationResult).to.be.oneOf(['net::ERR_CERT_AUTHORITY_INVALID', 'net::ERR_CERT_COMMON_NAME_INVALID']);
  517. expect(isIssuedByKnownRoot).to.be.false();
  518. };
  519. callback(-2);
  520. });
  521. const url = `https://127.0.0.1:${(server.address() as AddressInfo).port}`;
  522. const w = new BrowserWindow({ show: false, webPreferences: { session: ses } });
  523. await expect(w.loadURL(url)).to.eventually.be.rejectedWith(/ERR_FAILED/);
  524. expect(w.webContents.getTitle()).to.equal(url);
  525. expect(validate!).not.to.be.undefined();
  526. validate!();
  527. });
  528. it('saves cached results', async () => {
  529. const ses = session.fromPartition(`${Math.random()}`);
  530. let numVerificationRequests = 0;
  531. ses.setCertificateVerifyProc((e, callback) => {
  532. if (e.hostname !== '127.0.0.1') return callback(-3);
  533. numVerificationRequests++;
  534. callback(-2);
  535. });
  536. const url = `https://127.0.0.1:${(server.address() as AddressInfo).port}`;
  537. const w = new BrowserWindow({ show: false, webPreferences: { session: ses } });
  538. await expect(w.loadURL(url), 'first load').to.eventually.be.rejectedWith(/ERR_FAILED/);
  539. await emittedOnce(w.webContents, 'did-stop-loading');
  540. await expect(w.loadURL(url + '/test'), 'second load').to.eventually.be.rejectedWith(/ERR_FAILED/);
  541. expect(w.webContents.getTitle()).to.equal(url + '/test');
  542. expect(numVerificationRequests).to.equal(1);
  543. });
  544. it('does not cancel requests in other sessions', async () => {
  545. const ses1 = session.fromPartition(`${Math.random()}`);
  546. ses1.setCertificateVerifyProc((opts, cb) => cb(0));
  547. const ses2 = session.fromPartition(`${Math.random()}`);
  548. const url = `https://127.0.0.1:${(server.address() as AddressInfo).port}`;
  549. const req = net.request({ url, session: ses1, credentials: 'include' });
  550. req.end();
  551. setTimeout(() => {
  552. ses2.setCertificateVerifyProc((opts, callback) => callback(0));
  553. });
  554. await expect(new Promise<void>((resolve, reject) => {
  555. req.on('error', (err) => {
  556. reject(err);
  557. });
  558. req.on('response', () => {
  559. resolve();
  560. });
  561. })).to.eventually.be.fulfilled();
  562. });
  563. });
  564. describe('ses.clearAuthCache()', () => {
  565. it('can clear http auth info from cache', async () => {
  566. const ses = session.fromPartition('auth-cache');
  567. const server = http.createServer((req, res) => {
  568. const credentials = auth(req);
  569. if (!credentials || credentials.name !== 'test' || credentials.pass !== 'test') {
  570. res.statusCode = 401;
  571. res.setHeader('WWW-Authenticate', 'Basic realm="Restricted"');
  572. res.end();
  573. } else {
  574. res.end('authenticated');
  575. }
  576. });
  577. await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
  578. const port = (server.address() as AddressInfo).port;
  579. const fetch = (url: string) => new Promise((resolve, reject) => {
  580. const request = net.request({ url, session: ses });
  581. request.on('response', (response) => {
  582. let data: string | null = null;
  583. response.on('data', (chunk) => {
  584. if (!data) {
  585. data = '';
  586. }
  587. data += chunk;
  588. });
  589. response.on('end', () => {
  590. if (!data) {
  591. reject(new Error('Empty response'));
  592. } else {
  593. resolve(data);
  594. }
  595. });
  596. response.on('error', (error: any) => { reject(new Error(error)); });
  597. });
  598. request.on('error', (error: any) => { reject(new Error(error)); });
  599. request.end();
  600. });
  601. // the first time should throw due to unauthenticated
  602. await expect(fetch(`http://127.0.0.1:${port}`)).to.eventually.be.rejected();
  603. // passing the password should let us in
  604. expect(await fetch(`http://test:[email protected]:${port}`)).to.equal('authenticated');
  605. // subsequently, the credentials are cached
  606. expect(await fetch(`http://127.0.0.1:${port}`)).to.equal('authenticated');
  607. await ses.clearAuthCache();
  608. // once the cache is cleared, we should get an error again
  609. await expect(fetch(`http://127.0.0.1:${port}`)).to.eventually.be.rejected();
  610. });
  611. });
  612. describe('DownloadItem', () => {
  613. const mockPDF = Buffer.alloc(1024 * 1024 * 5);
  614. const downloadFilePath = path.join(__dirname, '..', 'fixtures', 'mock.pdf');
  615. const protocolName = 'custom-dl';
  616. const contentDisposition = 'inline; filename="mock.pdf"';
  617. let address: AddressInfo;
  618. let downloadServer: http.Server;
  619. before(async () => {
  620. downloadServer = http.createServer((req, res) => {
  621. res.writeHead(200, {
  622. 'Content-Length': mockPDF.length,
  623. 'Content-Type': 'application/pdf',
  624. 'Content-Disposition': req.url === '/?testFilename' ? 'inline' : contentDisposition
  625. });
  626. res.end(mockPDF);
  627. });
  628. await new Promise<void>(resolve => downloadServer.listen(0, '127.0.0.1', resolve));
  629. address = downloadServer.address() as AddressInfo;
  630. });
  631. after(async () => {
  632. await new Promise(resolve => downloadServer.close(resolve));
  633. });
  634. afterEach(closeAllWindows);
  635. const isPathEqual = (path1: string, path2: string) => {
  636. return path.relative(path1, path2) === '';
  637. };
  638. const assertDownload = (state: string, item: Electron.DownloadItem, isCustom = false) => {
  639. expect(state).to.equal('completed');
  640. expect(item.getFilename()).to.equal('mock.pdf');
  641. expect(path.isAbsolute(item.savePath)).to.equal(true);
  642. expect(isPathEqual(item.savePath, downloadFilePath)).to.equal(true);
  643. if (isCustom) {
  644. expect(item.getURL()).to.equal(`${protocolName}://item`);
  645. } else {
  646. expect(item.getURL()).to.be.equal(`${url}:${address.port}/`);
  647. }
  648. expect(item.getMimeType()).to.equal('application/pdf');
  649. expect(item.getReceivedBytes()).to.equal(mockPDF.length);
  650. expect(item.getTotalBytes()).to.equal(mockPDF.length);
  651. expect(item.getContentDisposition()).to.equal(contentDisposition);
  652. expect(fs.existsSync(downloadFilePath)).to.equal(true);
  653. fs.unlinkSync(downloadFilePath);
  654. };
  655. it('can download using session.downloadURL', (done) => {
  656. const port = address.port;
  657. session.defaultSession.once('will-download', function (e, item) {
  658. item.savePath = downloadFilePath;
  659. item.on('done', function (e, state) {
  660. try {
  661. assertDownload(state, item);
  662. done();
  663. } catch (e) {
  664. done(e);
  665. }
  666. });
  667. });
  668. session.defaultSession.downloadURL(`${url}:${port}`);
  669. });
  670. it('can download using WebContents.downloadURL', (done) => {
  671. const port = address.port;
  672. const w = new BrowserWindow({ show: false });
  673. w.webContents.session.once('will-download', function (e, item) {
  674. item.savePath = downloadFilePath;
  675. item.on('done', function (e, state) {
  676. try {
  677. assertDownload(state, item);
  678. done();
  679. } catch (e) {
  680. done(e);
  681. }
  682. });
  683. });
  684. w.webContents.downloadURL(`${url}:${port}`);
  685. });
  686. it('can download from custom protocols using WebContents.downloadURL', (done) => {
  687. const protocol = session.defaultSession.protocol;
  688. const port = address.port;
  689. const handler = (ignoredError: any, callback: Function) => {
  690. callback({ url: `${url}:${port}` });
  691. };
  692. protocol.registerHttpProtocol(protocolName, handler);
  693. const w = new BrowserWindow({ show: false });
  694. w.webContents.session.once('will-download', function (e, item) {
  695. item.savePath = downloadFilePath;
  696. item.on('done', function (e, state) {
  697. try {
  698. assertDownload(state, item, true);
  699. done();
  700. } catch (e) {
  701. done(e);
  702. }
  703. });
  704. });
  705. w.webContents.downloadURL(`${protocolName}://item`);
  706. });
  707. it('can download using WebView.downloadURL', async () => {
  708. const port = address.port;
  709. const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true } });
  710. await w.loadURL('about:blank');
  711. function webviewDownload ({ fixtures, url, port }: {fixtures: string, url: string, port: string}) {
  712. const webview = new (window as any).WebView();
  713. webview.addEventListener('did-finish-load', () => {
  714. webview.downloadURL(`${url}:${port}/`);
  715. });
  716. webview.src = `file://${fixtures}/api/blank.html`;
  717. document.body.appendChild(webview);
  718. }
  719. const done: Promise<[string, Electron.DownloadItem]> = new Promise(resolve => {
  720. w.webContents.session.once('will-download', function (e, item) {
  721. item.savePath = downloadFilePath;
  722. item.on('done', function (e, state) {
  723. resolve([state, item]);
  724. });
  725. });
  726. });
  727. await w.webContents.executeJavaScript(`(${webviewDownload})(${JSON.stringify({ fixtures, url, port })})`);
  728. const [state, item] = await done;
  729. assertDownload(state, item);
  730. });
  731. it('can cancel download', (done) => {
  732. const port = address.port;
  733. const w = new BrowserWindow({ show: false });
  734. w.webContents.session.once('will-download', function (e, item) {
  735. item.savePath = downloadFilePath;
  736. item.on('done', function (e, state) {
  737. try {
  738. expect(state).to.equal('cancelled');
  739. expect(item.getFilename()).to.equal('mock.pdf');
  740. expect(item.getMimeType()).to.equal('application/pdf');
  741. expect(item.getReceivedBytes()).to.equal(0);
  742. expect(item.getTotalBytes()).to.equal(mockPDF.length);
  743. expect(item.getContentDisposition()).to.equal(contentDisposition);
  744. done();
  745. } catch (e) {
  746. done(e);
  747. }
  748. });
  749. item.cancel();
  750. });
  751. w.webContents.downloadURL(`${url}:${port}/`);
  752. });
  753. it('can generate a default filename', function (done) {
  754. if (process.env.APPVEYOR === 'True') {
  755. // FIXME(alexeykuzmin): Skip the test.
  756. // this.skip()
  757. return done();
  758. }
  759. const port = address.port;
  760. const w = new BrowserWindow({ show: false });
  761. w.webContents.session.once('will-download', function (e, item) {
  762. item.savePath = downloadFilePath;
  763. item.on('done', function () {
  764. try {
  765. expect(item.getFilename()).to.equal('download.pdf');
  766. done();
  767. } catch (e) {
  768. done(e);
  769. }
  770. });
  771. item.cancel();
  772. });
  773. w.webContents.downloadURL(`${url}:${port}/?testFilename`);
  774. });
  775. it('can set options for the save dialog', (done) => {
  776. const filePath = path.join(__dirname, 'fixtures', 'mock.pdf');
  777. const port = address.port;
  778. const options = {
  779. window: null,
  780. title: 'title',
  781. message: 'message',
  782. buttonLabel: 'buttonLabel',
  783. nameFieldLabel: 'nameFieldLabel',
  784. defaultPath: '/',
  785. filters: [{
  786. name: '1', extensions: ['.1', '.2']
  787. }, {
  788. name: '2', extensions: ['.3', '.4', '.5']
  789. }],
  790. showsTagField: true,
  791. securityScopedBookmarks: true
  792. };
  793. const w = new BrowserWindow({ show: false });
  794. w.webContents.session.once('will-download', function (e, item) {
  795. item.setSavePath(filePath);
  796. item.setSaveDialogOptions(options);
  797. item.on('done', function () {
  798. try {
  799. expect(item.getSaveDialogOptions()).to.deep.equal(options);
  800. done();
  801. } catch (e) {
  802. done(e);
  803. }
  804. });
  805. item.cancel();
  806. });
  807. w.webContents.downloadURL(`${url}:${port}`);
  808. });
  809. describe('when a save path is specified and the URL is unavailable', () => {
  810. it('does not display a save dialog and reports the done state as interrupted', (done) => {
  811. const w = new BrowserWindow({ show: false });
  812. w.webContents.session.once('will-download', function (e, item) {
  813. item.savePath = downloadFilePath;
  814. if (item.getState() === 'interrupted') {
  815. item.resume();
  816. }
  817. item.on('done', function (e, state) {
  818. try {
  819. expect(state).to.equal('interrupted');
  820. done();
  821. } catch (e) {
  822. done(e);
  823. }
  824. });
  825. });
  826. w.webContents.downloadURL(`file://${path.join(__dirname, 'does-not-exist.txt')}`);
  827. });
  828. });
  829. });
  830. describe('ses.createInterruptedDownload(options)', () => {
  831. afterEach(closeAllWindows);
  832. it('can create an interrupted download item', async () => {
  833. const downloadFilePath = path.join(__dirname, '..', 'fixtures', 'mock.pdf');
  834. const options = {
  835. path: downloadFilePath,
  836. urlChain: ['http://127.0.0.1/'],
  837. mimeType: 'application/pdf',
  838. offset: 0,
  839. length: 5242880
  840. };
  841. const w = new BrowserWindow({ show: false });
  842. const p = emittedOnce(w.webContents.session, 'will-download');
  843. w.webContents.session.createInterruptedDownload(options);
  844. const [, item] = await p;
  845. expect(item.getState()).to.equal('interrupted');
  846. item.cancel();
  847. expect(item.getURLChain()).to.deep.equal(options.urlChain);
  848. expect(item.getMimeType()).to.equal(options.mimeType);
  849. expect(item.getReceivedBytes()).to.equal(options.offset);
  850. expect(item.getTotalBytes()).to.equal(options.length);
  851. expect(item.savePath).to.equal(downloadFilePath);
  852. });
  853. it('can be resumed', async () => {
  854. const downloadFilePath = path.join(fixtures, 'logo.png');
  855. const rangeServer = http.createServer((req, res) => {
  856. const options = { root: fixtures };
  857. send(req, req.url!, options)
  858. .on('error', (error: any) => { throw error; }).pipe(res);
  859. });
  860. try {
  861. await new Promise<void>(resolve => rangeServer.listen(0, '127.0.0.1', resolve));
  862. const port = (rangeServer.address() as AddressInfo).port;
  863. const w = new BrowserWindow({ show: false });
  864. const downloadCancelled: Promise<Electron.DownloadItem> = new Promise((resolve) => {
  865. w.webContents.session.once('will-download', function (e, item) {
  866. item.setSavePath(downloadFilePath);
  867. item.on('done', function () {
  868. resolve(item);
  869. });
  870. item.cancel();
  871. });
  872. });
  873. const downloadUrl = `http://127.0.0.1:${port}/assets/logo.png`;
  874. w.webContents.downloadURL(downloadUrl);
  875. const item = await downloadCancelled;
  876. expect(item.getState()).to.equal('cancelled');
  877. const options = {
  878. path: item.savePath,
  879. urlChain: item.getURLChain(),
  880. mimeType: item.getMimeType(),
  881. offset: item.getReceivedBytes(),
  882. length: item.getTotalBytes(),
  883. lastModified: item.getLastModifiedTime(),
  884. eTag: item.getETag()
  885. };
  886. const downloadResumed: Promise<Electron.DownloadItem> = new Promise((resolve) => {
  887. w.webContents.session.once('will-download', function (e, item) {
  888. expect(item.getState()).to.equal('interrupted');
  889. item.setSavePath(downloadFilePath);
  890. item.resume();
  891. item.on('done', function () {
  892. resolve(item);
  893. });
  894. });
  895. });
  896. w.webContents.session.createInterruptedDownload(options);
  897. const completedItem = await downloadResumed;
  898. expect(completedItem.getState()).to.equal('completed');
  899. expect(completedItem.getFilename()).to.equal('logo.png');
  900. expect(completedItem.savePath).to.equal(downloadFilePath);
  901. expect(completedItem.getURL()).to.equal(downloadUrl);
  902. expect(completedItem.getMimeType()).to.equal('image/png');
  903. expect(completedItem.getReceivedBytes()).to.equal(14022);
  904. expect(completedItem.getTotalBytes()).to.equal(14022);
  905. expect(fs.existsSync(downloadFilePath)).to.equal(true);
  906. } finally {
  907. rangeServer.close();
  908. }
  909. });
  910. });
  911. describe('ses.setPermissionRequestHandler(handler)', () => {
  912. afterEach(closeAllWindows);
  913. it('cancels any pending requests when cleared', async () => {
  914. const w = new BrowserWindow({
  915. show: false,
  916. webPreferences: {
  917. partition: 'very-temp-permision-handler',
  918. nodeIntegration: true,
  919. contextIsolation: false
  920. }
  921. });
  922. const ses = w.webContents.session;
  923. ses.setPermissionRequestHandler(() => {
  924. ses.setPermissionRequestHandler(null);
  925. });
  926. ses.protocol.interceptStringProtocol('https', (req, cb) => {
  927. cb(`<html><script>(${remote})()</script></html>`);
  928. });
  929. const result = emittedOnce(require('electron').ipcMain, 'message');
  930. function remote () {
  931. (navigator as any).requestMIDIAccess({ sysex: true }).then(() => {}, (err: any) => {
  932. require('electron').ipcRenderer.send('message', err.name);
  933. });
  934. }
  935. await w.loadURL('https://myfakesite');
  936. const [, name] = await result;
  937. expect(name).to.deep.equal('SecurityError');
  938. });
  939. });
  940. describe('ses.isPersistent()', () => {
  941. afterEach(closeAllWindows);
  942. it('returns default session as persistent', () => {
  943. const w = new BrowserWindow({
  944. show: false
  945. });
  946. const ses = w.webContents.session;
  947. expect(ses.isPersistent()).to.be.true();
  948. });
  949. it('returns persist: session as persistent', () => {
  950. const ses = session.fromPartition(`persist:${Math.random()}`);
  951. expect(ses.isPersistent()).to.be.true();
  952. });
  953. it('returns temporary session as not persistent', () => {
  954. const ses = session.fromPartition(`${Math.random()}`);
  955. expect(ses.isPersistent()).to.be.false();
  956. });
  957. });
  958. describe('ses.setUserAgent()', () => {
  959. afterEach(closeAllWindows);
  960. it('can be retrieved with getUserAgent()', () => {
  961. const userAgent = 'test-agent';
  962. const ses = session.fromPartition('' + Math.random());
  963. ses.setUserAgent(userAgent);
  964. expect(ses.getUserAgent()).to.equal(userAgent);
  965. });
  966. it('sets the User-Agent header for web requests made from renderers', async () => {
  967. const userAgent = 'test-agent';
  968. const ses = session.fromPartition('' + Math.random());
  969. ses.setUserAgent(userAgent, 'en-US,fr,de');
  970. const w = new BrowserWindow({ show: false, webPreferences: { session: ses } });
  971. let headers: http.IncomingHttpHeaders | null = null;
  972. const server = http.createServer((req, res) => {
  973. headers = req.headers;
  974. res.end();
  975. server.close();
  976. });
  977. await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
  978. await w.loadURL(`http://127.0.0.1:${(server.address() as AddressInfo).port}`);
  979. expect(headers!['user-agent']).to.equal(userAgent);
  980. expect(headers!['accept-language']).to.equal('en-US,fr;q=0.9,de;q=0.8');
  981. });
  982. });
  983. describe('session-created event', () => {
  984. it('is emitted when a session is created', async () => {
  985. const sessionCreated = emittedOnce(app, 'session-created');
  986. const session1 = session.fromPartition('' + Math.random());
  987. const [session2] = await sessionCreated;
  988. expect(session1).to.equal(session2);
  989. });
  990. });
  991. describe('session.storagePage', () => {
  992. it('returns a string', () => {
  993. expect(session.defaultSession.storagePath).to.be.a('string');
  994. });
  995. it('returns null for in memory sessions', () => {
  996. expect(session.fromPartition('in-memory').storagePath).to.equal(null);
  997. });
  998. it('returns different paths for partitions and the default session', () => {
  999. expect(session.defaultSession.storagePath).to.not.equal(session.fromPartition('persist:two').storagePath);
  1000. });
  1001. it('returns different paths for different partitions', () => {
  1002. expect(session.fromPartition('persist:one').storagePath).to.not.equal(session.fromPartition('persist:two').storagePath);
  1003. });
  1004. });
  1005. describe('session.setCodeCachePath()', () => {
  1006. it('throws when relative or empty path is provided', () => {
  1007. expect(() => {
  1008. session.defaultSession.setCodeCachePath('../fixtures');
  1009. }).to.throw('Absolute path must be provided to store code cache.');
  1010. expect(() => {
  1011. session.defaultSession.setCodeCachePath('');
  1012. }).to.throw('Absolute path must be provided to store code cache.');
  1013. expect(() => {
  1014. session.defaultSession.setCodeCachePath(path.join(app.getPath('userData'), 'electron-test-code-cache'));
  1015. }).to.not.throw();
  1016. });
  1017. });
  1018. describe('ses.setSSLConfig()', () => {
  1019. it('can disable cipher suites', async () => {
  1020. const ses = session.fromPartition('' + Math.random());
  1021. const fixturesPath = path.resolve(__dirname, '..', 'spec', 'fixtures');
  1022. const certPath = path.join(fixturesPath, 'certificates');
  1023. const server = https.createServer({
  1024. key: fs.readFileSync(path.join(certPath, 'server.key')),
  1025. cert: fs.readFileSync(path.join(certPath, 'server.pem')),
  1026. ca: [
  1027. fs.readFileSync(path.join(certPath, 'rootCA.pem')),
  1028. fs.readFileSync(path.join(certPath, 'intermediateCA.pem'))
  1029. ],
  1030. minVersion: 'TLSv1.2',
  1031. maxVersion: 'TLSv1.2',
  1032. ciphers: 'AES128-GCM-SHA256'
  1033. }, (req, res) => {
  1034. res.end('hi');
  1035. });
  1036. await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
  1037. defer(() => server.close());
  1038. const { port } = server.address() as AddressInfo;
  1039. function request () {
  1040. return new Promise((resolve, reject) => {
  1041. const r = net.request({
  1042. url: `https://127.0.0.1:${port}`,
  1043. session: ses
  1044. });
  1045. r.on('response', (res) => {
  1046. let data = '';
  1047. res.on('data', (chunk) => {
  1048. data += chunk.toString('utf8');
  1049. });
  1050. res.on('end', () => {
  1051. resolve(data);
  1052. });
  1053. });
  1054. r.on('error', (err) => {
  1055. reject(err);
  1056. });
  1057. r.end();
  1058. });
  1059. }
  1060. await expect(request()).to.be.rejectedWith(/ERR_CERT_AUTHORITY_INVALID/);
  1061. ses.setSSLConfig({
  1062. disabledCipherSuites: [0x009C]
  1063. });
  1064. await expect(request()).to.be.rejectedWith(/ERR_SSL_VERSION_OR_CIPHER_MISMATCH/);
  1065. });
  1066. });
  1067. });