api-session-spec.ts 44 KB

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