api-session-spec.ts 35 KB

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