api-session-spec.ts 36 KB

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