api-session-spec.ts 52 KB

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