api-session-spec.ts 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609
  1. import { expect } from 'chai';
  2. import * as http from 'node:http';
  3. import * as https from 'node:https';
  4. import * as path from 'node:path';
  5. import * as fs from 'node:fs';
  6. import * as ChildProcess from 'node:child_process';
  7. import { app, session, BrowserWindow, net, ipcMain, Session, webFrameMain, WebFrameMain } from 'electron/main';
  8. import * as send from 'send';
  9. import * as auth from 'basic-auth';
  10. import { closeAllWindows } from './lib/window-helpers';
  11. import { defer, listen } from './lib/spec-helpers';
  12. import { once } from 'node:events';
  13. import { setTimeout } from 'node:timers/promises';
  14. describe('session module', () => {
  15. const fixtures = path.resolve(__dirname, 'fixtures');
  16. const url = 'http://127.0.0.1';
  17. describe('session.defaultSession', () => {
  18. it('returns the default session', () => {
  19. expect(session.defaultSession).to.equal(session.fromPartition(''));
  20. });
  21. });
  22. describe('session.fromPartition(partition, options)', () => {
  23. it('returns existing session with same partition', () => {
  24. expect(session.fromPartition('test')).to.equal(session.fromPartition('test'));
  25. });
  26. });
  27. describe('session.fromPath(path)', () => {
  28. it('returns storage path of a session which was created with an absolute path', () => {
  29. const tmppath = require('electron').app.getPath('temp');
  30. const ses = session.fromPath(tmppath);
  31. expect(ses.storagePath).to.equal(tmppath);
  32. });
  33. });
  34. describe('ses.cookies', () => {
  35. const name = '0';
  36. const value = '0';
  37. afterEach(closeAllWindows);
  38. // Clear cookie of defaultSession after each test.
  39. afterEach(async () => {
  40. const { cookies } = session.defaultSession;
  41. const cs = await cookies.get({ url });
  42. for (const c of cs) {
  43. await cookies.remove(url, c.name);
  44. }
  45. });
  46. it('should get cookies', async () => {
  47. const server = http.createServer((req, res) => {
  48. res.setHeader('Set-Cookie', [`${name}=${value}`]);
  49. res.end('finished');
  50. server.close();
  51. });
  52. const { port } = await listen(server);
  53. const w = new BrowserWindow({ show: false });
  54. await w.loadURL(`${url}:${port}`);
  55. const list = await w.webContents.session.cookies.get({ url });
  56. const cookie = list.find(cookie => cookie.name === name);
  57. expect(cookie).to.exist.and.to.have.property('value', value);
  58. });
  59. it('sets cookies', async () => {
  60. const { cookies } = session.defaultSession;
  61. const name = '1';
  62. const value = '1';
  63. await cookies.set({ url, name, value, expirationDate: (Date.now()) / 1000 + 120 });
  64. const c = (await cookies.get({ url }))[0];
  65. expect(c.name).to.equal(name);
  66. expect(c.value).to.equal(value);
  67. expect(c.session).to.equal(false);
  68. });
  69. it('sets session cookies', async () => {
  70. const { cookies } = session.defaultSession;
  71. const name = '2';
  72. const value = '1';
  73. await cookies.set({ url, name, value });
  74. const c = (await cookies.get({ url }))[0];
  75. expect(c.name).to.equal(name);
  76. expect(c.value).to.equal(value);
  77. expect(c.session).to.equal(true);
  78. });
  79. it('sets cookies without name', async () => {
  80. const { cookies } = session.defaultSession;
  81. const value = '3';
  82. await cookies.set({ url, value });
  83. const c = (await cookies.get({ url }))[0];
  84. expect(c.name).to.be.empty();
  85. expect(c.value).to.equal(value);
  86. });
  87. for (const sameSite of <const>['unspecified', 'no_restriction', 'lax', 'strict']) {
  88. it(`sets cookies with samesite=${sameSite}`, async () => {
  89. const { cookies } = session.defaultSession;
  90. const value = 'hithere';
  91. await cookies.set({ url, value, sameSite });
  92. const c = (await cookies.get({ url }))[0];
  93. expect(c.name).to.be.empty();
  94. expect(c.value).to.equal(value);
  95. expect(c.sameSite).to.equal(sameSite);
  96. });
  97. }
  98. it('fails to set cookies with samesite=garbage', async () => {
  99. const { cookies } = session.defaultSession;
  100. const value = 'hithere';
  101. 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');
  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: (Date.now()) / 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 set cookie with an invalid domain attribute');
  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 set cookie with an invalid domain attribute');
  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: (Date.now()) / 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: (Date.now()) / 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. // DISABLED-FIXME
  146. it('should set cookie for standard scheme', async () => {
  147. const { cookies } = session.defaultSession;
  148. const domain = 'fake-host';
  149. const url = `${standardScheme}://${domain}`;
  150. const name = 'custom';
  151. const value = '1';
  152. await cookies.set({ url, name, value, expirationDate: (Date.now()) / 1000 + 120 });
  153. const list = await cookies.get({ url });
  154. expect(list).to.have.lengthOf(1);
  155. expect(list[0]).to.have.property('name', name);
  156. expect(list[0]).to.have.property('value', value);
  157. expect(list[0]).to.have.property('domain', domain);
  158. });
  159. it('emits a changed event when a cookie is added or removed', async () => {
  160. const { cookies } = session.fromPartition('cookies-changed');
  161. const name = 'foo';
  162. const value = 'bar';
  163. const a = once(cookies, 'changed');
  164. await cookies.set({ url, name, value, expirationDate: (Date.now()) / 1000 + 120 });
  165. const [, setEventCookie, setEventCause, setEventRemoved] = await a;
  166. const b = once(cookies, 'changed');
  167. await cookies.remove(url, name);
  168. const [, removeEventCookie, removeEventCause, removeEventRemoved] = await b;
  169. expect(setEventCookie.name).to.equal(name);
  170. expect(setEventCookie.value).to.equal(value);
  171. expect(setEventCause).to.equal('explicit');
  172. expect(setEventRemoved).to.equal(false);
  173. expect(removeEventCookie.name).to.equal(name);
  174. expect(removeEventCookie.value).to.equal(value);
  175. expect(removeEventCause).to.equal('explicit');
  176. expect(removeEventRemoved).to.equal(true);
  177. });
  178. describe('ses.cookies.flushStore()', async () => {
  179. it('flushes the cookies to disk', async () => {
  180. const name = 'foo';
  181. const value = 'bar';
  182. const { cookies } = session.defaultSession;
  183. await cookies.set({ url, name, value });
  184. await cookies.flushStore();
  185. });
  186. });
  187. it('should survive an app restart for persistent partition', async function () {
  188. this.timeout(60000);
  189. const appPath = path.join(fixtures, 'api', 'cookie-app');
  190. const runAppWithPhase = (phase: string) => {
  191. return new Promise((resolve) => {
  192. let output = '';
  193. const appProcess = ChildProcess.spawn(
  194. process.execPath,
  195. [appPath],
  196. { env: { PHASE: phase, ...process.env } }
  197. );
  198. appProcess.stdout.on('data', data => { output += data; });
  199. appProcess.on('exit', () => {
  200. resolve(output.replace(/(\r\n|\n|\r)/gm, ''));
  201. });
  202. });
  203. };
  204. expect(await runAppWithPhase('one')).to.equal('011');
  205. expect(await runAppWithPhase('two')).to.equal('110');
  206. });
  207. });
  208. describe('ses.clearStorageData(options)', () => {
  209. afterEach(closeAllWindows);
  210. it('clears localstorage data', async () => {
  211. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
  212. await w.loadFile(path.join(fixtures, 'api', 'localstorage.html'));
  213. await w.webContents.session.clearStorageData({
  214. origin: 'file://',
  215. storages: ['localstorage'],
  216. quotas: ['temporary']
  217. });
  218. while (await w.webContents.executeJavaScript('localStorage.length') !== 0) {
  219. // The storage clear isn't instantly visible to the renderer, so keep
  220. // trying until it is.
  221. }
  222. });
  223. });
  224. describe('will-download event', () => {
  225. afterEach(closeAllWindows);
  226. it('can cancel default download behavior', async () => {
  227. const w = new BrowserWindow({ show: false });
  228. const mockFile = Buffer.alloc(1024);
  229. const contentDisposition = 'inline; filename="mockFile.txt"';
  230. const downloadServer = http.createServer((req, res) => {
  231. res.writeHead(200, {
  232. 'Content-Length': mockFile.length,
  233. 'Content-Type': 'application/plain',
  234. 'Content-Disposition': contentDisposition
  235. });
  236. res.end(mockFile);
  237. downloadServer.close();
  238. });
  239. const url = (await listen(downloadServer)).url;
  240. const downloadPrevented: Promise<{itemUrl: string, itemFilename: string, item: Electron.DownloadItem}> = new Promise(resolve => {
  241. w.webContents.session.once('will-download', function (e, item) {
  242. e.preventDefault();
  243. resolve({ itemUrl: item.getURL(), itemFilename: item.getFilename(), item });
  244. });
  245. });
  246. w.loadURL(url);
  247. const { item, itemUrl, itemFilename } = await downloadPrevented;
  248. expect(itemUrl).to.equal(url + '/');
  249. expect(itemFilename).to.equal('mockFile.txt');
  250. // Delay till the next tick.
  251. await new Promise(setImmediate);
  252. expect(() => item.getURL()).to.throw('DownloadItem used after being destroyed');
  253. });
  254. });
  255. describe('ses.protocol', () => {
  256. const partitionName = 'temp';
  257. const protocolName = 'sp';
  258. let customSession: Session;
  259. const protocol = session.defaultSession.protocol;
  260. const handler = (ignoredError: any, callback: Function) => {
  261. callback({ data: '<script>require(\'electron\').ipcRenderer.send(\'hello\')</script>', mimeType: 'text/html' });
  262. };
  263. beforeEach(async () => {
  264. customSession = session.fromPartition(partitionName);
  265. await customSession.protocol.registerStringProtocol(protocolName, handler);
  266. });
  267. afterEach(async () => {
  268. await customSession.protocol.unregisterProtocol(protocolName);
  269. customSession = null as any;
  270. });
  271. afterEach(closeAllWindows);
  272. it('does not affect defaultSession', () => {
  273. const result1 = protocol.isProtocolRegistered(protocolName);
  274. expect(result1).to.equal(false);
  275. const result2 = customSession.protocol.isProtocolRegistered(protocolName);
  276. expect(result2).to.equal(true);
  277. });
  278. it('handles requests from partition', async () => {
  279. const w = new BrowserWindow({
  280. show: false,
  281. webPreferences: {
  282. partition: partitionName,
  283. nodeIntegration: true,
  284. contextIsolation: false
  285. }
  286. });
  287. customSession = session.fromPartition(partitionName);
  288. await customSession.protocol.registerStringProtocol(protocolName, handler);
  289. w.loadURL(`${protocolName}://fake-host`);
  290. await once(ipcMain, 'hello');
  291. });
  292. });
  293. describe('ses.setProxy(options)', () => {
  294. let server: http.Server;
  295. let customSession: Electron.Session;
  296. let created = false;
  297. beforeEach(async () => {
  298. customSession = session.fromPartition('proxyconfig');
  299. if (!created) {
  300. // Work around for https://github.com/electron/electron/issues/26166 to
  301. // reduce flake
  302. await setTimeout(100);
  303. created = true;
  304. }
  305. });
  306. afterEach(() => {
  307. if (server) {
  308. server.close();
  309. }
  310. customSession = null as any;
  311. });
  312. it('allows configuring proxy settings', async () => {
  313. const config = { proxyRules: 'http=myproxy:80' };
  314. await customSession.setProxy(config);
  315. const proxy = await customSession.resolveProxy('http://example.com/');
  316. expect(proxy).to.equal('PROXY myproxy:80');
  317. });
  318. it('allows removing the implicit bypass rules for localhost', async () => {
  319. const config = {
  320. proxyRules: 'http=myproxy:80',
  321. proxyBypassRules: '<-loopback>'
  322. };
  323. await customSession.setProxy(config);
  324. const proxy = await customSession.resolveProxy('http://localhost');
  325. expect(proxy).to.equal('PROXY myproxy:80');
  326. });
  327. it('allows configuring proxy settings with pacScript', async () => {
  328. server = http.createServer((req, res) => {
  329. const pac = `
  330. function FindProxyForURL(url, host) {
  331. return "PROXY myproxy:8132";
  332. }
  333. `;
  334. res.writeHead(200, {
  335. 'Content-Type': 'application/x-ns-proxy-autoconfig'
  336. });
  337. res.end(pac);
  338. });
  339. const { url } = await listen(server);
  340. {
  341. const config = { pacScript: url };
  342. await customSession.setProxy(config);
  343. const proxy = await customSession.resolveProxy('https://google.com');
  344. expect(proxy).to.equal('PROXY myproxy:8132');
  345. }
  346. {
  347. const config = { mode: 'pac_script' as any, pacScript: url };
  348. await customSession.setProxy(config);
  349. const proxy = await customSession.resolveProxy('https://google.com');
  350. expect(proxy).to.equal('PROXY myproxy:8132');
  351. }
  352. });
  353. it('allows bypassing proxy settings', async () => {
  354. const config = {
  355. proxyRules: 'http=myproxy:80',
  356. proxyBypassRules: '<local>'
  357. };
  358. await customSession.setProxy(config);
  359. const proxy = await customSession.resolveProxy('http://example/');
  360. expect(proxy).to.equal('DIRECT');
  361. });
  362. it('allows configuring proxy settings with mode `direct`', async () => {
  363. const config = { mode: 'direct' as const, proxyRules: 'http=myproxy:80' };
  364. await customSession.setProxy(config);
  365. const proxy = await customSession.resolveProxy('http://example.com/');
  366. expect(proxy).to.equal('DIRECT');
  367. });
  368. it('allows configuring proxy settings with mode `auto_detect`', async () => {
  369. const config = { mode: 'auto_detect' as const };
  370. await customSession.setProxy(config);
  371. });
  372. it('allows configuring proxy settings with mode `pac_script`', async () => {
  373. const config = { mode: 'pac_script' as const };
  374. await customSession.setProxy(config);
  375. const proxy = await customSession.resolveProxy('http://example.com/');
  376. expect(proxy).to.equal('DIRECT');
  377. });
  378. it('allows configuring proxy settings with mode `fixed_servers`', async () => {
  379. const config = { mode: 'fixed_servers' as const, proxyRules: 'http=myproxy:80' };
  380. await customSession.setProxy(config);
  381. const proxy = await customSession.resolveProxy('http://example.com/');
  382. expect(proxy).to.equal('PROXY myproxy:80');
  383. });
  384. it('allows configuring proxy settings with mode `system`', async () => {
  385. const config = { mode: 'system' as const };
  386. await customSession.setProxy(config);
  387. });
  388. it('disallows configuring proxy settings with mode `invalid`', async () => {
  389. const config = { mode: 'invalid' as any };
  390. await expect(customSession.setProxy(config)).to.eventually.be.rejectedWith(/Invalid mode/);
  391. });
  392. it('reload proxy configuration', async () => {
  393. let proxyPort = 8132;
  394. server = http.createServer((req, res) => {
  395. const pac = `
  396. function FindProxyForURL(url, host) {
  397. return "PROXY myproxy:${proxyPort}";
  398. }
  399. `;
  400. res.writeHead(200, {
  401. 'Content-Type': 'application/x-ns-proxy-autoconfig'
  402. });
  403. res.end(pac);
  404. });
  405. const { url } = await listen(server);
  406. const config = { mode: 'pac_script' as const, pacScript: url };
  407. await customSession.setProxy(config);
  408. {
  409. const proxy = await customSession.resolveProxy('https://google.com');
  410. expect(proxy).to.equal(`PROXY myproxy:${proxyPort}`);
  411. }
  412. {
  413. proxyPort = 8133;
  414. await customSession.forceReloadProxyConfig();
  415. const proxy = await customSession.resolveProxy('https://google.com');
  416. expect(proxy).to.equal(`PROXY myproxy:${proxyPort}`);
  417. }
  418. });
  419. });
  420. describe('ses.resolveHost(host)', () => {
  421. let customSession: Electron.Session;
  422. beforeEach(async () => {
  423. customSession = session.fromPartition('resolvehost');
  424. });
  425. afterEach(() => {
  426. customSession = null as any;
  427. });
  428. it('resolves ipv4.localhost2', async () => {
  429. const { endpoints } = await customSession.resolveHost('ipv4.localhost2');
  430. expect(endpoints).to.be.a('array');
  431. expect(endpoints).to.have.lengthOf(1);
  432. expect(endpoints[0].family).to.equal('ipv4');
  433. expect(endpoints[0].address).to.equal('10.0.0.1');
  434. });
  435. it('fails to resolve AAAA record for ipv4.localhost2', async () => {
  436. await expect(customSession.resolveHost('ipv4.localhost2', {
  437. queryType: 'AAAA'
  438. }))
  439. .to.eventually.be.rejectedWith(/net::ERR_NAME_NOT_RESOLVED/);
  440. });
  441. it('resolves ipv6.localhost2', async () => {
  442. const { endpoints } = await customSession.resolveHost('ipv6.localhost2');
  443. expect(endpoints).to.be.a('array');
  444. expect(endpoints).to.have.lengthOf(1);
  445. expect(endpoints[0].family).to.equal('ipv6');
  446. expect(endpoints[0].address).to.equal('::1');
  447. });
  448. it('fails to resolve A record for ipv6.localhost2', async () => {
  449. await expect(customSession.resolveHost('notfound.localhost2', {
  450. queryType: 'A'
  451. }))
  452. .to.eventually.be.rejectedWith(/net::ERR_NAME_NOT_RESOLVED/);
  453. });
  454. it('fails to resolve notfound.localhost2', async () => {
  455. await expect(customSession.resolveHost('notfound.localhost2'))
  456. .to.eventually.be.rejectedWith(/net::ERR_NAME_NOT_RESOLVED/);
  457. });
  458. });
  459. describe('ses.getBlobData()', () => {
  460. const scheme = 'cors-blob';
  461. const protocol = session.defaultSession.protocol;
  462. const url = `${scheme}://host`;
  463. after(async () => {
  464. await protocol.unregisterProtocol(scheme);
  465. });
  466. afterEach(closeAllWindows);
  467. it('returns blob data for uuid', (done) => {
  468. const postData = JSON.stringify({
  469. type: 'blob',
  470. value: 'hello'
  471. });
  472. const content = `<html>
  473. <script>
  474. let fd = new FormData();
  475. fd.append('file', new Blob(['${postData}'], {type:'application/json'}));
  476. fetch('${url}', {method:'POST', body: fd });
  477. </script>
  478. </html>`;
  479. protocol.registerStringProtocol(scheme, (request, callback) => {
  480. try {
  481. if (request.method === 'GET') {
  482. callback({ data: content, mimeType: 'text/html' });
  483. } else if (request.method === 'POST') {
  484. const uuid = request.uploadData![1].blobUUID;
  485. expect(uuid).to.be.a('string');
  486. session.defaultSession.getBlobData(uuid!).then(result => {
  487. try {
  488. expect(result.toString()).to.equal(postData);
  489. done();
  490. } catch (e) {
  491. done(e);
  492. }
  493. });
  494. }
  495. } catch (e) {
  496. done(e);
  497. }
  498. });
  499. const w = new BrowserWindow({ show: false });
  500. w.loadURL(url);
  501. });
  502. });
  503. describe('ses.getBlobData2()', () => {
  504. const scheme = 'cors-blob';
  505. const protocol = session.defaultSession.protocol;
  506. const url = `${scheme}://host`;
  507. after(async () => {
  508. await protocol.unregisterProtocol(scheme);
  509. });
  510. afterEach(closeAllWindows);
  511. it('returns blob data for uuid', (done) => {
  512. const content = `<html>
  513. <script>
  514. let fd = new FormData();
  515. fd.append("data", new Blob(new Array(65_537).fill('a')));
  516. fetch('${url}', {method:'POST', body: fd });
  517. </script>
  518. </html>`;
  519. protocol.registerStringProtocol(scheme, (request, callback) => {
  520. try {
  521. if (request.method === 'GET') {
  522. callback({ data: content, mimeType: 'text/html' });
  523. } else if (request.method === 'POST') {
  524. const uuid = request.uploadData![1].blobUUID;
  525. expect(uuid).to.be.a('string');
  526. session.defaultSession.getBlobData(uuid!).then(result => {
  527. try {
  528. const data = new Array(65_537).fill('a');
  529. expect(result.toString()).to.equal(data.join(''));
  530. done();
  531. } catch (e) {
  532. done(e);
  533. }
  534. });
  535. }
  536. } catch (e) {
  537. done(e);
  538. }
  539. });
  540. const w = new BrowserWindow({ show: false });
  541. w.loadURL(url);
  542. });
  543. });
  544. describe('ses.setCertificateVerifyProc(callback)', () => {
  545. let server: http.Server;
  546. let serverUrl: string;
  547. beforeEach(async () => {
  548. const certPath = path.join(fixtures, 'certificates');
  549. const options = {
  550. key: fs.readFileSync(path.join(certPath, 'server.key')),
  551. cert: fs.readFileSync(path.join(certPath, 'server.pem')),
  552. ca: [
  553. fs.readFileSync(path.join(certPath, 'rootCA.pem')),
  554. fs.readFileSync(path.join(certPath, 'intermediateCA.pem'))
  555. ],
  556. rejectUnauthorized: false
  557. };
  558. server = https.createServer(options, (req, res) => {
  559. res.writeHead(200);
  560. res.end('<title>hello</title>');
  561. });
  562. serverUrl = (await listen(server)).url;
  563. });
  564. afterEach((done) => {
  565. server.close(done);
  566. });
  567. afterEach(closeAllWindows);
  568. it('accepts the request when the callback is called with 0', async () => {
  569. const ses = session.fromPartition(`${Math.random()}`);
  570. let validate: () => void;
  571. ses.setCertificateVerifyProc(({ hostname, verificationResult, errorCode }, callback) => {
  572. if (hostname !== '127.0.0.1') return callback(-3);
  573. validate = () => {
  574. expect(verificationResult).to.be.oneOf(['net::ERR_CERT_AUTHORITY_INVALID', 'net::ERR_CERT_COMMON_NAME_INVALID']);
  575. expect(errorCode).to.be.oneOf([-202, -200]);
  576. };
  577. callback(0);
  578. });
  579. const w = new BrowserWindow({ show: false, webPreferences: { session: ses } });
  580. await w.loadURL(serverUrl);
  581. expect(w.webContents.getTitle()).to.equal('hello');
  582. expect(validate!).not.to.be.undefined();
  583. validate!();
  584. });
  585. it('rejects the request when the callback is called with -2', async () => {
  586. const ses = session.fromPartition(`${Math.random()}`);
  587. let validate: () => void;
  588. ses.setCertificateVerifyProc(({ hostname, certificate, verificationResult, isIssuedByKnownRoot }, callback) => {
  589. if (hostname !== '127.0.0.1') return callback(-3);
  590. validate = () => {
  591. expect(certificate.issuerName).to.equal('Intermediate CA');
  592. expect(certificate.subjectName).to.equal('localhost');
  593. expect(certificate.issuer.commonName).to.equal('Intermediate CA');
  594. expect(certificate.subject.commonName).to.equal('localhost');
  595. expect(certificate.issuerCert.issuer.commonName).to.equal('Root CA');
  596. expect(certificate.issuerCert.subject.commonName).to.equal('Intermediate CA');
  597. expect(certificate.issuerCert.issuerCert.issuer.commonName).to.equal('Root CA');
  598. expect(certificate.issuerCert.issuerCert.subject.commonName).to.equal('Root CA');
  599. expect(certificate.issuerCert.issuerCert.issuerCert).to.equal(undefined);
  600. expect(verificationResult).to.be.oneOf(['net::ERR_CERT_AUTHORITY_INVALID', 'net::ERR_CERT_COMMON_NAME_INVALID']);
  601. expect(isIssuedByKnownRoot).to.be.false();
  602. };
  603. callback(-2);
  604. });
  605. const w = new BrowserWindow({ show: false, webPreferences: { session: ses } });
  606. await expect(w.loadURL(serverUrl)).to.eventually.be.rejectedWith(/ERR_FAILED/);
  607. expect(validate!).not.to.be.undefined();
  608. validate!();
  609. });
  610. it('saves cached results', async () => {
  611. const ses = session.fromPartition(`${Math.random()}`);
  612. let numVerificationRequests = 0;
  613. ses.setCertificateVerifyProc((e, callback) => {
  614. if (e.hostname !== '127.0.0.1') return callback(-3);
  615. numVerificationRequests++;
  616. callback(-2);
  617. });
  618. const w = new BrowserWindow({ show: false, webPreferences: { session: ses } });
  619. await expect(w.loadURL(serverUrl), 'first load').to.eventually.be.rejectedWith(/ERR_FAILED/);
  620. await once(w.webContents, 'did-stop-loading');
  621. await expect(w.loadURL(serverUrl + '/test'), 'second load').to.eventually.be.rejectedWith(/ERR_FAILED/);
  622. expect(numVerificationRequests).to.equal(1);
  623. });
  624. it('does not cancel requests in other sessions', async () => {
  625. const ses1 = session.fromPartition(`${Math.random()}`);
  626. ses1.setCertificateVerifyProc((opts, cb) => cb(0));
  627. const ses2 = session.fromPartition(`${Math.random()}`);
  628. const req = net.request({ url: serverUrl, session: ses1, credentials: 'include' });
  629. req.end();
  630. setTimeout().then(() => {
  631. ses2.setCertificateVerifyProc((opts, callback) => callback(0));
  632. });
  633. await expect(new Promise<void>((resolve, reject) => {
  634. req.on('error', (err) => {
  635. reject(err);
  636. });
  637. req.on('response', () => {
  638. resolve();
  639. });
  640. })).to.eventually.be.fulfilled();
  641. });
  642. });
  643. describe('ses.clearAuthCache()', () => {
  644. it('can clear http auth info from cache', async () => {
  645. const ses = session.fromPartition('auth-cache');
  646. const server = http.createServer((req, res) => {
  647. const credentials = auth(req);
  648. if (!credentials || credentials.name !== 'test' || credentials.pass !== 'test') {
  649. res.statusCode = 401;
  650. res.setHeader('WWW-Authenticate', 'Basic realm="Restricted"');
  651. res.end();
  652. } else {
  653. res.end('authenticated');
  654. }
  655. });
  656. const { port } = await listen(server);
  657. const fetch = (url: string) => new Promise((resolve, reject) => {
  658. const request = net.request({ url, session: ses });
  659. request.on('response', (response) => {
  660. let data: string | null = null;
  661. response.on('data', (chunk) => {
  662. if (!data) {
  663. data = '';
  664. }
  665. data += chunk;
  666. });
  667. response.on('end', () => {
  668. if (!data) {
  669. reject(new Error('Empty response'));
  670. } else {
  671. resolve(data);
  672. }
  673. });
  674. response.on('error', (error: any) => { reject(new Error(error)); });
  675. });
  676. request.on('error', (error: any) => { reject(new Error(error)); });
  677. request.end();
  678. });
  679. // the first time should throw due to unauthenticated
  680. await expect(fetch(`http://127.0.0.1:${port}`)).to.eventually.be.rejected();
  681. // passing the password should let us in
  682. expect(await fetch(`http://test:[email protected]:${port}`)).to.equal('authenticated');
  683. // subsequently, the credentials are cached
  684. expect(await fetch(`http://127.0.0.1:${port}`)).to.equal('authenticated');
  685. await ses.clearAuthCache();
  686. // once the cache is cleared, we should get an error again
  687. await expect(fetch(`http://127.0.0.1:${port}`)).to.eventually.be.rejected();
  688. });
  689. });
  690. describe('DownloadItem', () => {
  691. const mockPDF = Buffer.alloc(1024 * 1024 * 5);
  692. const downloadFilePath = path.join(__dirname, '..', 'fixtures', 'mock.pdf');
  693. const protocolName = 'custom-dl';
  694. const contentDisposition = 'inline; filename="mock.pdf"';
  695. let port: number;
  696. let downloadServer: http.Server;
  697. before(async () => {
  698. downloadServer = http.createServer((req, res) => {
  699. res.writeHead(200, {
  700. 'Content-Length': mockPDF.length,
  701. 'Content-Type': 'application/pdf',
  702. 'Content-Disposition': req.url === '/?testFilename' ? 'inline' : contentDisposition
  703. });
  704. res.end(mockPDF);
  705. });
  706. port = (await listen(downloadServer)).port;
  707. });
  708. after(async () => {
  709. await new Promise(resolve => downloadServer.close(resolve));
  710. });
  711. afterEach(closeAllWindows);
  712. const isPathEqual = (path1: string, path2: string) => {
  713. return path.relative(path1, path2) === '';
  714. };
  715. const assertDownload = (state: string, item: Electron.DownloadItem, isCustom = false) => {
  716. expect(state).to.equal('completed');
  717. expect(item.getFilename()).to.equal('mock.pdf');
  718. expect(path.isAbsolute(item.savePath)).to.equal(true);
  719. expect(isPathEqual(item.savePath, downloadFilePath)).to.equal(true);
  720. if (isCustom) {
  721. expect(item.getURL()).to.equal(`${protocolName}://item`);
  722. } else {
  723. expect(item.getURL()).to.be.equal(`${url}:${port}/`);
  724. }
  725. expect(item.getMimeType()).to.equal('application/pdf');
  726. expect(item.getReceivedBytes()).to.equal(mockPDF.length);
  727. expect(item.getTotalBytes()).to.equal(mockPDF.length);
  728. expect(item.getContentDisposition()).to.equal(contentDisposition);
  729. expect(fs.existsSync(downloadFilePath)).to.equal(true);
  730. fs.unlinkSync(downloadFilePath);
  731. };
  732. describe('session.downloadURL', () => {
  733. it('can perform a download', (done) => {
  734. session.defaultSession.once('will-download', function (e, item) {
  735. item.savePath = downloadFilePath;
  736. item.on('done', function (e, state) {
  737. try {
  738. assertDownload(state, item);
  739. done();
  740. } catch (e) {
  741. done(e);
  742. }
  743. });
  744. });
  745. session.defaultSession.downloadURL(`${url}:${port}`);
  746. });
  747. it('can perform a download with a valid auth header', async () => {
  748. const server = http.createServer((req, res) => {
  749. const { authorization } = req.headers;
  750. if (!authorization || authorization !== 'Basic i-am-an-auth-header') {
  751. res.statusCode = 401;
  752. res.setHeader('WWW-Authenticate', 'Basic realm="Restricted"');
  753. res.end();
  754. } else {
  755. res.writeHead(200, {
  756. 'Content-Length': mockPDF.length,
  757. 'Content-Type': 'application/pdf',
  758. 'Content-Disposition': req.url === '/?testFilename' ? 'inline' : contentDisposition
  759. });
  760. res.end(mockPDF);
  761. }
  762. });
  763. const { port } = await listen(server);
  764. const downloadDone: Promise<Electron.DownloadItem> = new Promise((resolve) => {
  765. session.defaultSession.once('will-download', (e, item) => {
  766. item.savePath = downloadFilePath;
  767. item.on('done', () => {
  768. try {
  769. resolve(item);
  770. } catch { }
  771. });
  772. });
  773. });
  774. session.defaultSession.downloadURL(`${url}:${port}`, {
  775. headers: {
  776. Authorization: 'Basic i-am-an-auth-header'
  777. }
  778. });
  779. const item = await downloadDone;
  780. expect(item.getState()).to.equal('completed');
  781. expect(item.getFilename()).to.equal('mock.pdf');
  782. expect(item.getMimeType()).to.equal('application/pdf');
  783. expect(item.getReceivedBytes()).to.equal(mockPDF.length);
  784. expect(item.getTotalBytes()).to.equal(mockPDF.length);
  785. expect(item.getContentDisposition()).to.equal(contentDisposition);
  786. });
  787. it('throws when called with invalid headers', () => {
  788. expect(() => {
  789. session.defaultSession.downloadURL(`${url}:${port}`, {
  790. // @ts-ignore this line is intentionally incorrect
  791. headers: 'i-am-a-bad-header'
  792. });
  793. }).to.throw(/Invalid value for headers - must be an object/);
  794. });
  795. it('correctly handles a download with an invalid auth header', async () => {
  796. const server = http.createServer((req, res) => {
  797. const { authorization } = req.headers;
  798. if (!authorization || authorization !== 'Basic i-am-an-auth-header') {
  799. res.statusCode = 401;
  800. res.setHeader('WWW-Authenticate', 'Basic realm="Restricted"');
  801. res.end();
  802. } else {
  803. res.writeHead(200, {
  804. 'Content-Length': mockPDF.length,
  805. 'Content-Type': 'application/pdf',
  806. 'Content-Disposition': req.url === '/?testFilename' ? 'inline' : contentDisposition
  807. });
  808. res.end(mockPDF);
  809. }
  810. });
  811. const { port } = await listen(server);
  812. const downloadFailed: Promise<Electron.DownloadItem> = new Promise((resolve) => {
  813. session.defaultSession.once('will-download', (_, item) => {
  814. item.savePath = downloadFilePath;
  815. item.on('done', (e, state) => {
  816. console.log(state);
  817. try {
  818. resolve(item);
  819. } catch { }
  820. });
  821. });
  822. });
  823. session.defaultSession.downloadURL(`${url}:${port}`, {
  824. headers: {
  825. Authorization: 'wtf-is-this'
  826. }
  827. });
  828. const item = await downloadFailed;
  829. expect(item.getState()).to.equal('interrupted');
  830. expect(item.getReceivedBytes()).to.equal(0);
  831. expect(item.getTotalBytes()).to.equal(0);
  832. });
  833. });
  834. describe('webContents.downloadURL', () => {
  835. it('can perform a download', (done) => {
  836. const w = new BrowserWindow({ show: false });
  837. w.webContents.session.once('will-download', function (e, item) {
  838. item.savePath = downloadFilePath;
  839. item.on('done', function (e, state) {
  840. try {
  841. assertDownload(state, item);
  842. done();
  843. } catch (e) {
  844. done(e);
  845. }
  846. });
  847. });
  848. w.webContents.downloadURL(`${url}:${port}`);
  849. });
  850. it('can perform a download with a valid auth header', async () => {
  851. const server = http.createServer((req, res) => {
  852. const { authorization } = req.headers;
  853. if (!authorization || authorization !== 'Basic i-am-an-auth-header') {
  854. res.statusCode = 401;
  855. res.setHeader('WWW-Authenticate', 'Basic realm="Restricted"');
  856. res.end();
  857. } else {
  858. res.writeHead(200, {
  859. 'Content-Length': mockPDF.length,
  860. 'Content-Type': 'application/pdf',
  861. 'Content-Disposition': req.url === '/?testFilename' ? 'inline' : contentDisposition
  862. });
  863. res.end(mockPDF);
  864. }
  865. });
  866. const { port } = await listen(server);
  867. const w = new BrowserWindow({ show: false });
  868. const downloadDone: Promise<Electron.DownloadItem> = new Promise((resolve) => {
  869. w.webContents.session.once('will-download', (e, item) => {
  870. item.savePath = downloadFilePath;
  871. item.on('done', () => {
  872. try {
  873. resolve(item);
  874. } catch { }
  875. });
  876. });
  877. });
  878. w.webContents.downloadURL(`${url}:${port}`, {
  879. headers: {
  880. Authorization: 'Basic i-am-an-auth-header'
  881. }
  882. });
  883. const item = await downloadDone;
  884. expect(item.getState()).to.equal('completed');
  885. expect(item.getFilename()).to.equal('mock.pdf');
  886. expect(item.getMimeType()).to.equal('application/pdf');
  887. expect(item.getReceivedBytes()).to.equal(mockPDF.length);
  888. expect(item.getTotalBytes()).to.equal(mockPDF.length);
  889. expect(item.getContentDisposition()).to.equal(contentDisposition);
  890. });
  891. it('throws when called with invalid headers', () => {
  892. const w = new BrowserWindow({ show: false });
  893. expect(() => {
  894. w.webContents.downloadURL(`${url}:${port}`, {
  895. // @ts-ignore this line is intentionally incorrect
  896. headers: 'i-am-a-bad-header'
  897. });
  898. }).to.throw(/Invalid value for headers - must be an object/);
  899. });
  900. it('correctly handles a download and an invalid auth header', async () => {
  901. const server = http.createServer((req, res) => {
  902. const { authorization } = req.headers;
  903. if (!authorization || authorization !== 'Basic i-am-an-auth-header') {
  904. res.statusCode = 401;
  905. res.setHeader('WWW-Authenticate', 'Basic realm="Restricted"');
  906. res.end();
  907. } else {
  908. res.writeHead(200, {
  909. 'Content-Length': mockPDF.length,
  910. 'Content-Type': 'application/pdf',
  911. 'Content-Disposition': req.url === '/?testFilename' ? 'inline' : contentDisposition
  912. });
  913. res.end(mockPDF);
  914. }
  915. });
  916. const { port } = await listen(server);
  917. const w = new BrowserWindow({ show: false });
  918. const downloadFailed: Promise<Electron.DownloadItem> = new Promise((resolve) => {
  919. w.webContents.session.once('will-download', (_, item) => {
  920. item.savePath = downloadFilePath;
  921. item.on('done', (e, state) => {
  922. console.log(state);
  923. try {
  924. resolve(item);
  925. } catch { }
  926. });
  927. });
  928. });
  929. w.webContents.downloadURL(`${url}:${port}`, {
  930. headers: {
  931. Authorization: 'wtf-is-this'
  932. }
  933. });
  934. const item = await downloadFailed;
  935. expect(item.getState()).to.equal('interrupted');
  936. expect(item.getReceivedBytes()).to.equal(0);
  937. expect(item.getTotalBytes()).to.equal(0);
  938. });
  939. it('can download from custom protocols', (done) => {
  940. const protocol = session.defaultSession.protocol;
  941. const handler = (ignoredError: any, callback: Function) => {
  942. callback({ url: `${url}:${port}` });
  943. };
  944. protocol.registerHttpProtocol(protocolName, handler);
  945. const w = new BrowserWindow({ show: false });
  946. w.webContents.session.once('will-download', function (e, item) {
  947. item.savePath = downloadFilePath;
  948. item.on('done', function (e, state) {
  949. try {
  950. assertDownload(state, item, true);
  951. done();
  952. } catch (e) {
  953. done(e);
  954. }
  955. });
  956. });
  957. w.webContents.downloadURL(`${protocolName}://item`);
  958. });
  959. it('can cancel download', (done) => {
  960. const w = new BrowserWindow({ show: false });
  961. w.webContents.session.once('will-download', function (e, item) {
  962. item.savePath = downloadFilePath;
  963. item.on('done', function (e, state) {
  964. try {
  965. expect(state).to.equal('cancelled');
  966. expect(item.getFilename()).to.equal('mock.pdf');
  967. expect(item.getMimeType()).to.equal('application/pdf');
  968. expect(item.getReceivedBytes()).to.equal(0);
  969. expect(item.getTotalBytes()).to.equal(mockPDF.length);
  970. expect(item.getContentDisposition()).to.equal(contentDisposition);
  971. done();
  972. } catch (e) {
  973. done(e);
  974. }
  975. });
  976. item.cancel();
  977. });
  978. w.webContents.downloadURL(`${url}:${port}/`);
  979. });
  980. it('can generate a default filename', function (done) {
  981. if (process.env.APPVEYOR === 'True') {
  982. // FIXME(alexeykuzmin): Skip the test.
  983. // this.skip()
  984. return done();
  985. }
  986. const w = new BrowserWindow({ show: false });
  987. w.webContents.session.once('will-download', function (e, item) {
  988. item.savePath = downloadFilePath;
  989. item.on('done', function () {
  990. try {
  991. expect(item.getFilename()).to.equal('download.pdf');
  992. done();
  993. } catch (e) {
  994. done(e);
  995. }
  996. });
  997. item.cancel();
  998. });
  999. w.webContents.downloadURL(`${url}:${port}/?testFilename`);
  1000. });
  1001. it('can set options for the save dialog', (done) => {
  1002. const filePath = path.join(__dirname, 'fixtures', 'mock.pdf');
  1003. const options = {
  1004. window: null,
  1005. title: 'title',
  1006. message: 'message',
  1007. buttonLabel: 'buttonLabel',
  1008. nameFieldLabel: 'nameFieldLabel',
  1009. defaultPath: '/',
  1010. filters: [{
  1011. name: '1', extensions: ['.1', '.2']
  1012. }, {
  1013. name: '2', extensions: ['.3', '.4', '.5']
  1014. }],
  1015. showsTagField: true,
  1016. securityScopedBookmarks: true
  1017. };
  1018. const w = new BrowserWindow({ show: false });
  1019. w.webContents.session.once('will-download', function (e, item) {
  1020. item.setSavePath(filePath);
  1021. item.setSaveDialogOptions(options);
  1022. item.on('done', function () {
  1023. try {
  1024. expect(item.getSaveDialogOptions()).to.deep.equal(options);
  1025. done();
  1026. } catch (e) {
  1027. done(e);
  1028. }
  1029. });
  1030. item.cancel();
  1031. });
  1032. w.webContents.downloadURL(`${url}:${port}`);
  1033. });
  1034. describe('when a save path is specified and the URL is unavailable', () => {
  1035. it('does not display a save dialog and reports the done state as interrupted', (done) => {
  1036. const w = new BrowserWindow({ show: false });
  1037. w.webContents.session.once('will-download', function (e, item) {
  1038. item.savePath = downloadFilePath;
  1039. if (item.getState() === 'interrupted') {
  1040. item.resume();
  1041. }
  1042. item.on('done', function (e, state) {
  1043. try {
  1044. expect(state).to.equal('interrupted');
  1045. done();
  1046. } catch (e) {
  1047. done(e);
  1048. }
  1049. });
  1050. });
  1051. w.webContents.downloadURL(`file://${path.join(__dirname, 'does-not-exist.txt')}`);
  1052. });
  1053. });
  1054. });
  1055. describe('WebView.downloadURL', () => {
  1056. it('can perform a download', async () => {
  1057. const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true } });
  1058. await w.loadURL('about:blank');
  1059. function webviewDownload ({ fixtures, url, port }: { fixtures: string, url: string, port: string }) {
  1060. const webview = new (window as any).WebView();
  1061. webview.addEventListener('did-finish-load', () => {
  1062. webview.downloadURL(`${url}:${port}/`);
  1063. });
  1064. webview.src = `file://${fixtures}/api/blank.html`;
  1065. document.body.appendChild(webview);
  1066. }
  1067. const done: Promise<[string, Electron.DownloadItem]> = new Promise(resolve => {
  1068. w.webContents.session.once('will-download', function (e, item) {
  1069. item.savePath = downloadFilePath;
  1070. item.on('done', function (e, state) {
  1071. resolve([state, item]);
  1072. });
  1073. });
  1074. });
  1075. await w.webContents.executeJavaScript(`(${webviewDownload})(${JSON.stringify({ fixtures, url, port })})`);
  1076. const [state, item] = await done;
  1077. assertDownload(state, item);
  1078. });
  1079. });
  1080. });
  1081. describe('ses.createInterruptedDownload(options)', () => {
  1082. afterEach(closeAllWindows);
  1083. it('can create an interrupted download item', async () => {
  1084. const downloadFilePath = path.join(__dirname, '..', 'fixtures', 'mock.pdf');
  1085. const options = {
  1086. path: downloadFilePath,
  1087. urlChain: ['http://127.0.0.1/'],
  1088. mimeType: 'application/pdf',
  1089. offset: 0,
  1090. length: 5242880
  1091. };
  1092. const w = new BrowserWindow({ show: false });
  1093. const p = once(w.webContents.session, 'will-download');
  1094. w.webContents.session.createInterruptedDownload(options);
  1095. const [, item] = await p;
  1096. expect(item.getState()).to.equal('interrupted');
  1097. item.cancel();
  1098. expect(item.getURLChain()).to.deep.equal(options.urlChain);
  1099. expect(item.getMimeType()).to.equal(options.mimeType);
  1100. expect(item.getReceivedBytes()).to.equal(options.offset);
  1101. expect(item.getTotalBytes()).to.equal(options.length);
  1102. expect(item.savePath).to.equal(downloadFilePath);
  1103. });
  1104. it('can be resumed', async () => {
  1105. const downloadFilePath = path.join(fixtures, 'logo.png');
  1106. const rangeServer = http.createServer((req, res) => {
  1107. const options = { root: fixtures };
  1108. send(req, req.url!, options)
  1109. .on('error', (error: any) => { throw error; }).pipe(res);
  1110. });
  1111. try {
  1112. const { url } = await listen(rangeServer);
  1113. const w = new BrowserWindow({ show: false });
  1114. const downloadCancelled: Promise<Electron.DownloadItem> = new Promise((resolve) => {
  1115. w.webContents.session.once('will-download', function (e, item) {
  1116. item.setSavePath(downloadFilePath);
  1117. item.on('done', function () {
  1118. resolve(item);
  1119. });
  1120. item.cancel();
  1121. });
  1122. });
  1123. const downloadUrl = `${url}/assets/logo.png`;
  1124. w.webContents.downloadURL(downloadUrl);
  1125. const item = await downloadCancelled;
  1126. expect(item.getState()).to.equal('cancelled');
  1127. const options = {
  1128. path: item.savePath,
  1129. urlChain: item.getURLChain(),
  1130. mimeType: item.getMimeType(),
  1131. offset: item.getReceivedBytes(),
  1132. length: item.getTotalBytes(),
  1133. lastModified: item.getLastModifiedTime(),
  1134. eTag: item.getETag()
  1135. };
  1136. const downloadResumed: Promise<Electron.DownloadItem> = new Promise((resolve) => {
  1137. w.webContents.session.once('will-download', function (e, item) {
  1138. expect(item.getState()).to.equal('interrupted');
  1139. item.setSavePath(downloadFilePath);
  1140. item.resume();
  1141. item.on('done', function () {
  1142. resolve(item);
  1143. });
  1144. });
  1145. });
  1146. w.webContents.session.createInterruptedDownload(options);
  1147. const completedItem = await downloadResumed;
  1148. expect(completedItem.getState()).to.equal('completed');
  1149. expect(completedItem.getFilename()).to.equal('logo.png');
  1150. expect(completedItem.savePath).to.equal(downloadFilePath);
  1151. expect(completedItem.getURL()).to.equal(downloadUrl);
  1152. expect(completedItem.getMimeType()).to.equal('image/png');
  1153. expect(completedItem.getReceivedBytes()).to.equal(14022);
  1154. expect(completedItem.getTotalBytes()).to.equal(14022);
  1155. expect(fs.existsSync(downloadFilePath)).to.equal(true);
  1156. } finally {
  1157. rangeServer.close();
  1158. }
  1159. });
  1160. });
  1161. describe('ses.setPermissionRequestHandler(handler)', () => {
  1162. afterEach(closeAllWindows);
  1163. // These tests are done on an http server because navigator.userAgentData
  1164. // requires a secure context.
  1165. let server: http.Server;
  1166. let serverUrl: string;
  1167. before(async () => {
  1168. server = http.createServer((req, res) => {
  1169. res.setHeader('Content-Type', 'text/html');
  1170. res.end('');
  1171. });
  1172. serverUrl = (await listen(server)).url;
  1173. });
  1174. after(() => {
  1175. server.close();
  1176. });
  1177. it('cancels any pending requests when cleared', async () => {
  1178. const w = new BrowserWindow({
  1179. show: false,
  1180. webPreferences: {
  1181. partition: 'very-temp-permission-handler',
  1182. nodeIntegration: true,
  1183. contextIsolation: false
  1184. }
  1185. });
  1186. const ses = w.webContents.session;
  1187. ses.setPermissionRequestHandler(() => {
  1188. ses.setPermissionRequestHandler(null);
  1189. });
  1190. ses.protocol.interceptStringProtocol('https', (req, cb) => {
  1191. cb(`<html><script>(${remote})()</script></html>`);
  1192. });
  1193. const result = once(require('electron').ipcMain, 'message');
  1194. function remote () {
  1195. (navigator as any).requestMIDIAccess({ sysex: true }).then(() => {}, (err: any) => {
  1196. require('electron').ipcRenderer.send('message', err.name);
  1197. });
  1198. }
  1199. await w.loadURL('https://myfakesite');
  1200. const [, name] = await result;
  1201. expect(name).to.deep.equal('SecurityError');
  1202. });
  1203. it('successfully resolves when calling legacy getUserMedia', async () => {
  1204. const ses = session.fromPartition('' + Math.random());
  1205. ses.setPermissionRequestHandler(
  1206. (_webContents, _permission, callback) => {
  1207. callback(true);
  1208. }
  1209. );
  1210. const w = new BrowserWindow({ show: false, webPreferences: { session: ses } });
  1211. await w.loadURL(serverUrl);
  1212. const { ok, message } = await w.webContents.executeJavaScript(`
  1213. new Promise((resolve, reject) => navigator.getUserMedia({
  1214. video: true,
  1215. audio: true,
  1216. }, x => resolve({ok: x instanceof MediaStream}), e => reject({ok: false, message: e.message})))
  1217. `);
  1218. expect(ok).to.be.true(message);
  1219. });
  1220. it('successfully rejects when calling legacy getUserMedia', async () => {
  1221. const ses = session.fromPartition('' + Math.random());
  1222. ses.setPermissionRequestHandler(
  1223. (_webContents, _permission, callback) => {
  1224. callback(false);
  1225. }
  1226. );
  1227. const w = new BrowserWindow({ show: false, webPreferences: { session: ses } });
  1228. await w.loadURL(serverUrl);
  1229. await expect(w.webContents.executeJavaScript(`
  1230. new Promise((resolve, reject) => navigator.getUserMedia({
  1231. video: true,
  1232. audio: true,
  1233. }, x => resolve({ok: x instanceof MediaStream}), e => reject({ok: false, message: e.message})))
  1234. `)).to.eventually.be.rejectedWith('Permission denied');
  1235. });
  1236. });
  1237. describe('ses.setPermissionCheckHandler(handler)', () => {
  1238. afterEach(closeAllWindows);
  1239. it('details provides requestingURL for mainFrame', async () => {
  1240. const w = new BrowserWindow({
  1241. show: false,
  1242. webPreferences: {
  1243. partition: 'very-temp-permission-handler'
  1244. }
  1245. });
  1246. const ses = w.webContents.session;
  1247. const loadUrl = 'https://myfakesite/';
  1248. let handlerDetails : Electron.PermissionCheckHandlerHandlerDetails;
  1249. ses.protocol.interceptStringProtocol('https', (req, cb) => {
  1250. cb('<html><script>console.log(\'test\');</script></html>');
  1251. });
  1252. ses.setPermissionCheckHandler((wc, permission, requestingOrigin, details) => {
  1253. if (permission === 'clipboard-read') {
  1254. handlerDetails = details;
  1255. return true;
  1256. }
  1257. return false;
  1258. });
  1259. const readClipboardPermission: any = () => {
  1260. return w.webContents.executeJavaScript(`
  1261. navigator.permissions.query({name: 'clipboard-read'})
  1262. .then(permission => permission.state).catch(err => err.message);
  1263. `, true);
  1264. };
  1265. await w.loadURL(loadUrl);
  1266. const state = await readClipboardPermission();
  1267. expect(state).to.equal('granted');
  1268. expect(handlerDetails!.requestingUrl).to.equal(loadUrl);
  1269. });
  1270. it('details provides requestingURL for cross origin subFrame', async () => {
  1271. const w = new BrowserWindow({
  1272. show: false,
  1273. webPreferences: {
  1274. partition: 'very-temp-permission-handler'
  1275. }
  1276. });
  1277. const ses = w.webContents.session;
  1278. const loadUrl = 'https://myfakesite/';
  1279. let handlerDetails : Electron.PermissionCheckHandlerHandlerDetails;
  1280. ses.protocol.interceptStringProtocol('https', (req, cb) => {
  1281. cb('<html><script>console.log(\'test\');</script></html>');
  1282. });
  1283. ses.setPermissionCheckHandler((wc, permission, requestingOrigin, details) => {
  1284. if (permission === 'clipboard-read') {
  1285. handlerDetails = details;
  1286. return true;
  1287. }
  1288. return false;
  1289. });
  1290. const readClipboardPermission: any = (frame: WebFrameMain) => {
  1291. return frame.executeJavaScript(`
  1292. navigator.permissions.query({name: 'clipboard-read'})
  1293. .then(permission => permission.state).catch(err => err.message);
  1294. `, true);
  1295. };
  1296. await w.loadFile(path.join(fixtures, 'api', 'blank.html'));
  1297. w.webContents.executeJavaScript(`
  1298. var iframe = document.createElement('iframe');
  1299. iframe.src = '${loadUrl}';
  1300. document.body.appendChild(iframe);
  1301. null;
  1302. `);
  1303. const [,, frameProcessId, frameRoutingId] = await once(w.webContents, 'did-frame-finish-load');
  1304. const state = await readClipboardPermission(webFrameMain.fromId(frameProcessId, frameRoutingId));
  1305. expect(state).to.equal('granted');
  1306. expect(handlerDetails!.requestingUrl).to.equal(loadUrl);
  1307. expect(handlerDetails!.isMainFrame).to.be.false();
  1308. expect(handlerDetails!.embeddingOrigin).to.equal('file:///');
  1309. });
  1310. });
  1311. describe('ses.isPersistent()', () => {
  1312. afterEach(closeAllWindows);
  1313. it('returns default session as persistent', () => {
  1314. const w = new BrowserWindow({
  1315. show: false
  1316. });
  1317. const ses = w.webContents.session;
  1318. expect(ses.isPersistent()).to.be.true();
  1319. });
  1320. it('returns persist: session as persistent', () => {
  1321. const ses = session.fromPartition(`persist:${Math.random()}`);
  1322. expect(ses.isPersistent()).to.be.true();
  1323. });
  1324. it('returns temporary session as not persistent', () => {
  1325. const ses = session.fromPartition(`${Math.random()}`);
  1326. expect(ses.isPersistent()).to.be.false();
  1327. });
  1328. });
  1329. describe('ses.setUserAgent()', () => {
  1330. afterEach(closeAllWindows);
  1331. it('can be retrieved with getUserAgent()', () => {
  1332. const userAgent = 'test-agent';
  1333. const ses = session.fromPartition('' + Math.random());
  1334. ses.setUserAgent(userAgent);
  1335. expect(ses.getUserAgent()).to.equal(userAgent);
  1336. });
  1337. it('sets the User-Agent header for web requests made from renderers', async () => {
  1338. const userAgent = 'test-agent';
  1339. const ses = session.fromPartition('' + Math.random());
  1340. ses.setUserAgent(userAgent, 'en-US,fr,de');
  1341. const w = new BrowserWindow({ show: false, webPreferences: { session: ses } });
  1342. let headers: http.IncomingHttpHeaders | null = null;
  1343. const server = http.createServer((req, res) => {
  1344. headers = req.headers;
  1345. res.end();
  1346. server.close();
  1347. });
  1348. const { url } = await listen(server);
  1349. await w.loadURL(url);
  1350. expect(headers!['user-agent']).to.equal(userAgent);
  1351. expect(headers!['accept-language']).to.equal('en-US,fr;q=0.9,de;q=0.8');
  1352. });
  1353. });
  1354. describe('session-created event', () => {
  1355. it('is emitted when a session is created', async () => {
  1356. const sessionCreated = once(app, 'session-created') as Promise<[any, Session]>;
  1357. const session1 = session.fromPartition('' + Math.random());
  1358. const [session2] = await sessionCreated;
  1359. expect(session1).to.equal(session2);
  1360. });
  1361. });
  1362. describe('session.storagePage', () => {
  1363. it('returns a string', () => {
  1364. expect(session.defaultSession.storagePath).to.be.a('string');
  1365. });
  1366. it('returns null for in memory sessions', () => {
  1367. expect(session.fromPartition('in-memory').storagePath).to.equal(null);
  1368. });
  1369. it('returns different paths for partitions and the default session', () => {
  1370. expect(session.defaultSession.storagePath).to.not.equal(session.fromPartition('persist:two').storagePath);
  1371. });
  1372. it('returns different paths for different partitions', () => {
  1373. expect(session.fromPartition('persist:one').storagePath).to.not.equal(session.fromPartition('persist:two').storagePath);
  1374. });
  1375. });
  1376. describe('session.setCodeCachePath()', () => {
  1377. it('throws when relative or empty path is provided', () => {
  1378. expect(() => {
  1379. session.defaultSession.setCodeCachePath('../fixtures');
  1380. }).to.throw('Absolute path must be provided to store code cache.');
  1381. expect(() => {
  1382. session.defaultSession.setCodeCachePath('');
  1383. }).to.throw('Absolute path must be provided to store code cache.');
  1384. expect(() => {
  1385. session.defaultSession.setCodeCachePath(path.join(app.getPath('userData'), 'electron-test-code-cache'));
  1386. }).to.not.throw();
  1387. });
  1388. });
  1389. describe('ses.setSSLConfig()', () => {
  1390. it('can disable cipher suites', async () => {
  1391. const ses = session.fromPartition('' + Math.random());
  1392. const fixturesPath = path.resolve(__dirname, 'fixtures');
  1393. const certPath = path.join(fixturesPath, 'certificates');
  1394. const server = https.createServer({
  1395. key: fs.readFileSync(path.join(certPath, 'server.key')),
  1396. cert: fs.readFileSync(path.join(certPath, 'server.pem')),
  1397. ca: [
  1398. fs.readFileSync(path.join(certPath, 'rootCA.pem')),
  1399. fs.readFileSync(path.join(certPath, 'intermediateCA.pem'))
  1400. ],
  1401. minVersion: 'TLSv1.2',
  1402. maxVersion: 'TLSv1.2',
  1403. ciphers: 'AES128-GCM-SHA256'
  1404. }, (req, res) => {
  1405. res.end('hi');
  1406. });
  1407. const { port } = await listen(server);
  1408. defer(() => server.close());
  1409. function request () {
  1410. return new Promise((resolve, reject) => {
  1411. const r = net.request({
  1412. url: `https://127.0.0.1:${port}`,
  1413. session: ses
  1414. });
  1415. r.on('response', (res) => {
  1416. let data = '';
  1417. res.on('data', (chunk) => {
  1418. data += chunk.toString('utf8');
  1419. });
  1420. res.on('end', () => {
  1421. resolve(data);
  1422. });
  1423. });
  1424. r.on('error', (err) => {
  1425. reject(err);
  1426. });
  1427. r.end();
  1428. });
  1429. }
  1430. await expect(request()).to.be.rejectedWith(/ERR_CERT_AUTHORITY_INVALID/);
  1431. ses.setSSLConfig({
  1432. disabledCipherSuites: [0x009C]
  1433. });
  1434. await expect(request()).to.be.rejectedWith(/ERR_SSL_VERSION_OR_CIPHER_MISMATCH/);
  1435. });
  1436. });
  1437. });