api-session-spec.ts 63 KB

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