api-session-spec.ts 67 KB

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