api-session-spec.ts 65 KB

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