api-session-spec.ts 63 KB

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