api-session-spec.ts 75 KB

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