api-session-spec.ts 43 KB

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