api-session-spec.ts 54 KB

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