api-session-spec.js 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923
  1. const chai = require('chai')
  2. const http = require('http')
  3. const https = require('https')
  4. const path = require('path')
  5. const fs = require('fs')
  6. const send = require('send')
  7. const auth = require('basic-auth')
  8. const ChildProcess = require('child_process')
  9. const { closeAllWindows } = require('./window-helpers')
  10. const { emittedOnce } = require('./events-helpers')
  11. const { session, BrowserWindow, net, ipcMain } = require('electron')
  12. const { expect } = chai
  13. /* The whole session API doesn't use standard callbacks */
  14. /* eslint-disable standard/no-callback-literal */
  15. describe('session module', () => {
  16. const fixtures = path.resolve(__dirname, '..', 'spec', '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. // TODO(codebytere): remove in Electron v8.0.0
  28. it.skip('created session is ref-counted (functions)', () => {
  29. const partition = 'test2'
  30. const userAgent = 'test-agent'
  31. const ses1 = session.fromPartition(partition)
  32. ses1.setUserAgent(userAgent)
  33. expect(ses1.getUserAgent()).to.equal(userAgent)
  34. ses1.destroy()
  35. const ses2 = session.fromPartition(partition)
  36. expect(ses2.getUserAgent()).to.not.equal(userAgent)
  37. })
  38. it('created session is ref-counted', () => {
  39. const partition = 'test2'
  40. const userAgent = 'test-agent'
  41. const ses1 = session.fromPartition(partition)
  42. ses1.userAgent = userAgent
  43. expect(ses1.userAgent).to.equal(userAgent)
  44. ses1.destroy()
  45. const ses2 = session.fromPartition(partition)
  46. expect(ses2.userAgent).to.not.equal(userAgent)
  47. })
  48. })
  49. describe('ses.cookies', () => {
  50. const name = '0'
  51. const value = '0'
  52. afterEach(closeAllWindows)
  53. // Clear cookie of defaultSession after each test.
  54. afterEach(async () => {
  55. const { cookies } = session.defaultSession
  56. const cs = await cookies.get({ url })
  57. for (const c of cs) {
  58. await cookies.remove(url, c.name)
  59. }
  60. })
  61. it('should get cookies', async () => {
  62. const server = http.createServer((req, res) => {
  63. res.setHeader('Set-Cookie', [`${name}=${value}`])
  64. res.end('finished')
  65. server.close()
  66. })
  67. await new Promise(resolve => server.listen(0, '127.0.0.1', resolve))
  68. const { port } = server.address()
  69. const w = new BrowserWindow({ show: false })
  70. await w.loadURL(`${url}:${port}`)
  71. const list = await w.webContents.session.cookies.get({ url })
  72. const cookie = list.find(cookie => cookie.name === name)
  73. expect(cookie).to.exist.and.to.have.property('value', value)
  74. })
  75. it('sets cookies', async () => {
  76. const { cookies } = session.defaultSession
  77. const name = '1'
  78. const value = '1'
  79. await cookies.set({ url, name, value, expirationDate: (+new Date()) / 1000 + 120 })
  80. const c = (await cookies.get({ url }))[0]
  81. expect(c.name).to.equal(name)
  82. expect(c.value).to.equal(value)
  83. expect(c.session).to.equal(false)
  84. })
  85. it('sets session cookies', async () => {
  86. const { cookies } = session.defaultSession
  87. const name = '2'
  88. const value = '1'
  89. await cookies.set({ url, name, value })
  90. const c = (await cookies.get({ url }))[0]
  91. expect(c.name).to.equal(name)
  92. expect(c.value).to.equal(value)
  93. expect(c.session).to.equal(true)
  94. })
  95. it('sets cookies without name', async () => {
  96. const { cookies } = session.defaultSession
  97. const value = '3'
  98. await cookies.set({ url, value })
  99. const c = (await cookies.get({ url }))[0]
  100. expect(c.name).to.be.empty()
  101. expect(c.value).to.equal(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: (+new Date) / 1000 + 120 })
  108. const cs = await cookies.get({ domain: '127.0.0.1' })
  109. expect(cs.some(c => c.name === name && c.value === value)).to.equal(true)
  110. })
  111. it('yields an error when setting a cookie with missing required fields', async () => {
  112. const { cookies } = session.defaultSession
  113. const name = '1'
  114. const value = '1'
  115. await expect(
  116. cookies.set({ url: '', name, value })
  117. ).to.eventually.be.rejectedWith('Failed to get cookie domain')
  118. })
  119. it('yields an error when setting a cookie with an invalid URL', async () => {
  120. const { cookies } = session.defaultSession
  121. const name = '1'
  122. const value = '1'
  123. await expect(
  124. cookies.set({ url: 'asdf', name, value })
  125. ).to.eventually.be.rejectedWith('Failed to get cookie domain')
  126. })
  127. it('should overwrite previous cookies', async () => {
  128. const { cookies } = session.defaultSession
  129. const name = 'DidOverwrite'
  130. for (const value of [ 'No', 'Yes' ]) {
  131. await cookies.set({ url, name, value, expirationDate: (+new Date()) / 1000 + 120 })
  132. const list = await cookies.get({ url })
  133. expect(list.some(cookie => cookie.name === name && cookie.value === value)).to.equal(true)
  134. }
  135. })
  136. it('should remove cookies', async () => {
  137. const { cookies } = session.defaultSession
  138. const name = '2'
  139. const value = '2'
  140. await cookies.set({ url, name, value, expirationDate: (+new Date()) / 1000 + 120 })
  141. await cookies.remove(url, name)
  142. const list = await cookies.get({ url })
  143. expect(list.some(cookie => cookie.name === name && cookie.value === value)).to.equal(false)
  144. })
  145. it.skip('should set cookie for standard scheme', async () => {
  146. const { cookies } = session.defaultSession
  147. const standardScheme = global.standardScheme
  148. const domain = 'fake-host'
  149. const url = `${standardScheme}://${domain}`
  150. const name = 'custom'
  151. const value = '1'
  152. await cookies.set({ url, name, value, expirationDate: (+new Date()) / 1000 + 120 })
  153. const list = await cookies.get({ url })
  154. expect(list).to.have.lengthOf(1)
  155. expect(list[0]).to.have.property('name', name)
  156. expect(list[0]).to.have.property('value', value)
  157. expect(list[0]).to.have.property('domain', domain)
  158. })
  159. it('emits a changed event when a cookie is added or removed', async () => {
  160. const changes = []
  161. const { cookies } = session.fromPartition('cookies-changed')
  162. const name = 'foo'
  163. const value = 'bar'
  164. const listener = (event, cookie, cause, removed) => { changes.push({ cookie, cause, removed }) }
  165. const a = emittedOnce(cookies, 'changed')
  166. await cookies.set({ url, name, value, expirationDate: (+new Date()) / 1000 + 120 })
  167. const [, setEventCookie, setEventCause, setEventRemoved] = await a
  168. const b = emittedOnce(cookies, 'changed')
  169. await cookies.remove(url, name)
  170. const [, removeEventCookie, removeEventCause, removeEventRemoved] = await b
  171. expect(setEventCookie.name).to.equal(name)
  172. expect(setEventCookie.value).to.equal(value)
  173. expect(setEventCause).to.equal('explicit')
  174. expect(setEventRemoved).to.equal(false)
  175. expect(removeEventCookie.name).to.equal(name)
  176. expect(removeEventCookie.value).to.equal(value)
  177. expect(removeEventCause).to.equal('explicit')
  178. expect(removeEventRemoved).to.equal(true)
  179. })
  180. describe('ses.cookies.flushStore()', async () => {
  181. it('flushes the cookies to disk', async () => {
  182. const name = 'foo'
  183. const value = 'bar'
  184. const { cookies } = session.defaultSession
  185. await cookies.set({ url, name, value })
  186. await cookies.flushStore()
  187. })
  188. })
  189. it('should survive an app restart for persistent partition', async () => {
  190. const appPath = path.join(fixtures, 'api', 'cookie-app')
  191. const runAppWithPhase = (phase) => {
  192. return new Promise((resolve, reject) => {
  193. let output = ''
  194. const appProcess = ChildProcess.spawn(
  195. process.execPath,
  196. [appPath],
  197. { env: { PHASE: phase, ...process.env } }
  198. )
  199. appProcess.stdout.on('data', data => { output += data })
  200. appProcess.stdout.on('end', () => {
  201. resolve(output.replace(/(\r\n|\n|\r)/gm, ''))
  202. })
  203. })
  204. }
  205. expect(await runAppWithPhase('one')).to.equal('011')
  206. expect(await runAppWithPhase('two')).to.equal('110')
  207. })
  208. })
  209. describe('ses.clearStorageData(options)', () => {
  210. afterEach(closeAllWindows)
  211. it('clears localstorage data', async () => {
  212. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } })
  213. await w.loadFile(path.join(fixtures, 'api', 'localstorage.html'))
  214. const options = {
  215. origin: 'file://',
  216. storages: ['localstorage'],
  217. quotas: ['persistent']
  218. }
  219. await w.webContents.session.clearStorageData(options)
  220. while (await w.webContents.executeJavaScript('localStorage.length') !== 0) {
  221. // The storage clear isn't instantly visible to the renderer, so keep
  222. // trying until it is.
  223. }
  224. })
  225. })
  226. describe('will-download event', () => {
  227. afterEach(closeAllWindows)
  228. it('can cancel default download behavior', async () => {
  229. const w = new BrowserWindow({ show: false })
  230. const mockFile = Buffer.alloc(1024)
  231. const contentDisposition = 'inline; filename="mockFile.txt"'
  232. const downloadServer = http.createServer((req, res) => {
  233. res.writeHead(200, {
  234. 'Content-Length': mockFile.length,
  235. 'Content-Type': 'application/plain',
  236. 'Content-Disposition': contentDisposition
  237. })
  238. res.end(mockFile)
  239. downloadServer.close()
  240. })
  241. await new Promise(resolve => downloadServer.listen(0, '127.0.0.1', resolve))
  242. const port = downloadServer.address().port
  243. const url = `http://127.0.0.1:${port}/`
  244. const downloadPrevented = new Promise(resolve => {
  245. w.webContents.session.once('will-download', function (e, item) {
  246. e.preventDefault()
  247. resolve(item)
  248. })
  249. })
  250. w.loadURL(url)
  251. const item = await downloadPrevented
  252. expect(item.getURL()).to.equal(url)
  253. expect(item.getFilename()).to.equal('mockFile.txt')
  254. await new Promise(setImmediate)
  255. expect(() => item.getURL()).to.throw('Object has been destroyed')
  256. })
  257. })
  258. describe('ses.protocol', () => {
  259. const partitionName = 'temp'
  260. const protocolName = 'sp'
  261. let customSession = null
  262. const protocol = session.defaultSession.protocol
  263. const handler = (ignoredError, callback) => {
  264. callback({ data: `<script>require('electron').ipcRenderer.send('hello')</script>`, mimeType: 'text/html' })
  265. }
  266. beforeEach(async () => {
  267. customSession = session.fromPartition(partitionName)
  268. await customSession.protocol.registerStringProtocol(protocolName, handler)
  269. })
  270. afterEach(async () => {
  271. await customSession.protocol.unregisterProtocol(protocolName)
  272. customSession = null
  273. })
  274. afterEach(closeAllWindows)
  275. it('does not affect defaultSession', async () => {
  276. const result1 = await protocol.isProtocolHandled(protocolName)
  277. expect(result1).to.equal(false)
  278. const result2 = await customSession.protocol.isProtocolHandled(protocolName)
  279. expect(result2).to.equal(true)
  280. })
  281. it('handles requests from partition', async () => {
  282. const w = new BrowserWindow({
  283. show: false,
  284. webPreferences: {
  285. partition: partitionName,
  286. nodeIntegration: true,
  287. }
  288. })
  289. customSession = session.fromPartition(partitionName)
  290. await customSession.protocol.registerStringProtocol(protocolName, handler)
  291. w.loadURL(`${protocolName}://fake-host`)
  292. await emittedOnce(ipcMain, 'hello')
  293. })
  294. })
  295. describe('ses.setProxy(options)', () => {
  296. let server = null
  297. let customSession = null
  298. beforeEach(async () => {
  299. customSession = session.fromPartition('proxyconfig')
  300. })
  301. afterEach(() => {
  302. if (server) {
  303. server.close()
  304. }
  305. if (customSession) {
  306. customSession.destroy()
  307. }
  308. })
  309. it('allows configuring proxy settings', async () => {
  310. const config = { proxyRules: 'http=myproxy:80' }
  311. await customSession.setProxy(config)
  312. const proxy = await customSession.resolveProxy('http://example.com/')
  313. expect(proxy).to.equal('PROXY myproxy:80')
  314. })
  315. it('allows removing the implicit bypass rules for localhost', async () => {
  316. const config = {
  317. proxyRules: 'http=myproxy:80',
  318. proxyBypassRules: '<-loopback>'
  319. }
  320. await customSession.setProxy(config)
  321. const proxy = await customSession.resolveProxy('http://localhost')
  322. expect(proxy).to.equal('PROXY myproxy:80')
  323. })
  324. it('allows configuring proxy settings with pacScript', async () => {
  325. server = http.createServer((req, res) => {
  326. const pac = `
  327. function FindProxyForURL(url, host) {
  328. return "PROXY myproxy:8132";
  329. }
  330. `
  331. res.writeHead(200, {
  332. 'Content-Type': 'application/x-ns-proxy-autoconfig'
  333. })
  334. res.end(pac)
  335. })
  336. await new Promise(resolve => server.listen(0, '127.0.0.1', resolve))
  337. const config = { pacScript: `http://127.0.0.1:${server.address().port}` }
  338. await customSession.setProxy(config)
  339. const proxy = await customSession.resolveProxy('https://google.com')
  340. expect(proxy).to.equal('PROXY myproxy:8132')
  341. })
  342. it('allows bypassing proxy settings', async () => {
  343. const config = {
  344. proxyRules: 'http=myproxy:80',
  345. proxyBypassRules: '<local>'
  346. }
  347. await customSession.setProxy(config)
  348. const proxy = await customSession.resolveProxy('http://example/')
  349. expect(proxy).to.equal('DIRECT')
  350. })
  351. })
  352. describe('ses.getBlobData()', () => {
  353. const scheme = 'cors-blob'
  354. const protocol = session.defaultSession.protocol
  355. const url = `${scheme}://host`
  356. after(async () => {
  357. await protocol.unregisterProtocol(scheme)
  358. })
  359. afterEach(closeAllWindows)
  360. it('returns blob data for uuid', (done) => {
  361. const postData = JSON.stringify({
  362. type: 'blob',
  363. value: 'hello'
  364. })
  365. const content = `<html>
  366. <script>
  367. let fd = new FormData();
  368. fd.append('file', new Blob(['${postData}'], {type:'application/json'}));
  369. fetch('${url}', {method:'POST', body: fd });
  370. </script>
  371. </html>`
  372. protocol.registerStringProtocol(scheme, (request, callback) => {
  373. if (request.method === 'GET') {
  374. callback({ data: content, mimeType: 'text/html' })
  375. } else if (request.method === 'POST') {
  376. const uuid = request.uploadData[1].blobUUID
  377. expect(uuid).to.be.a('string')
  378. session.defaultSession.getBlobData(uuid).then(result => {
  379. expect(result.toString()).to.equal(postData)
  380. done()
  381. })
  382. }
  383. }, (error) => {
  384. if (error) return done(error)
  385. const w = new BrowserWindow({ show: false })
  386. w.loadURL(url)
  387. })
  388. })
  389. })
  390. describe('ses.setCertificateVerifyProc(callback)', (done) => {
  391. let server = null
  392. beforeEach((done) => {
  393. const certPath = path.join(fixtures, 'certificates')
  394. const options = {
  395. key: fs.readFileSync(path.join(certPath, 'server.key')),
  396. cert: fs.readFileSync(path.join(certPath, 'server.pem')),
  397. ca: [
  398. fs.readFileSync(path.join(certPath, 'rootCA.pem')),
  399. fs.readFileSync(path.join(certPath, 'intermediateCA.pem'))
  400. ],
  401. requestCert: true,
  402. rejectUnauthorized: false
  403. }
  404. server = https.createServer(options, (req, res) => {
  405. res.writeHead(200)
  406. res.end('<title>hello</title>')
  407. })
  408. server.listen(0, '127.0.0.1', done)
  409. })
  410. afterEach((done) => {
  411. session.defaultSession.setCertificateVerifyProc(null)
  412. server.close(done)
  413. })
  414. afterEach(closeAllWindows)
  415. it('accepts the request when the callback is called with 0', async () => {
  416. session.defaultSession.setCertificateVerifyProc(({ hostname, certificate, verificationResult, errorCode }, callback) => {
  417. expect(['net::ERR_CERT_AUTHORITY_INVALID', 'net::ERR_CERT_COMMON_NAME_INVALID'].includes(verificationResult)).to.be.true
  418. expect([-202, -200].includes(errorCode)).to.be.true
  419. callback(0)
  420. })
  421. const w = new BrowserWindow({ show: false })
  422. await w.loadURL(`https://127.0.0.1:${server.address().port}`)
  423. expect(w.webContents.getTitle()).to.equal('hello')
  424. })
  425. it('rejects the request when the callback is called with -2', async () => {
  426. session.defaultSession.setCertificateVerifyProc(({ hostname, certificate, verificationResult }, callback) => {
  427. expect(hostname).to.equal('127.0.0.1')
  428. expect(certificate.issuerName).to.equal('Intermediate CA')
  429. expect(certificate.subjectName).to.equal('localhost')
  430. expect(certificate.issuer.commonName).to.equal('Intermediate CA')
  431. expect(certificate.subject.commonName).to.equal('localhost')
  432. expect(certificate.issuerCert.issuer.commonName).to.equal('Root CA')
  433. expect(certificate.issuerCert.subject.commonName).to.equal('Intermediate CA')
  434. expect(certificate.issuerCert.issuerCert.issuer.commonName).to.equal('Root CA')
  435. expect(certificate.issuerCert.issuerCert.subject.commonName).to.equal('Root CA')
  436. expect(certificate.issuerCert.issuerCert.issuerCert).to.equal(undefined)
  437. expect(['net::ERR_CERT_AUTHORITY_INVALID', 'net::ERR_CERT_COMMON_NAME_INVALID'].includes(verificationResult)).to.be.true
  438. callback(-2)
  439. })
  440. const url = `https://127.0.0.1:${server.address().port}`
  441. const w = new BrowserWindow({ show: false })
  442. await expect(w.loadURL(url)).to.eventually.be.rejectedWith(/ERR_FAILED/)
  443. expect(w.webContents.getTitle()).to.equal(url)
  444. })
  445. it('saves cached results', async () => {
  446. let numVerificationRequests = 0
  447. session.defaultSession.setCertificateVerifyProc(({ hostname, certificate, verificationResult }, callback) => {
  448. numVerificationRequests++
  449. callback(-2)
  450. })
  451. const url = `https://127.0.0.1:${server.address().port}`
  452. const w = new BrowserWindow({ show: false })
  453. await expect(w.loadURL(url), 'first load').to.eventually.be.rejectedWith(/ERR_FAILED/)
  454. await emittedOnce(w.webContents, 'did-stop-loading')
  455. await expect(w.loadURL(url + '/test'), 'second load').to.eventually.be.rejectedWith(/ERR_FAILED/)
  456. expect(w.webContents.getTitle()).to.equal(url + '/test')
  457. expect(numVerificationRequests).to.equal(1)
  458. })
  459. })
  460. describe('ses.clearAuthCache(options)', () => {
  461. it('can clear http auth info from cache', async () => {
  462. const ses = session.fromPartition('auth-cache')
  463. const server = http.createServer((req, res) => {
  464. const credentials = auth(req)
  465. if (!credentials || credentials.name !== 'test' || credentials.pass !== 'test') {
  466. res.statusCode = 401
  467. res.setHeader('WWW-Authenticate', 'Basic realm="Restricted"')
  468. res.end()
  469. } else {
  470. res.end('authenticated')
  471. }
  472. })
  473. await new Promise(resolve => server.listen(0, '127.0.0.1', resolve))
  474. const port = server.address().port
  475. const fetch = (url) => new Promise((resolve, reject) => {
  476. const request = net.request({ url, session: ses })
  477. request.on('response', (response) => {
  478. let data = null
  479. response.on('data', (chunk) => {
  480. if (!data) {
  481. data = ''
  482. }
  483. data += chunk
  484. })
  485. response.on('end', () => {
  486. if (!data) {
  487. reject(new Error('Empty response'))
  488. } else {
  489. resolve(data)
  490. }
  491. })
  492. response.on('error', (error) => { reject(new Error(error)) })
  493. });
  494. request.on('error', (error) => { reject(new Error(error)) })
  495. request.end()
  496. })
  497. // the first time should throw due to unauthenticated
  498. await expect(fetch(`http://127.0.0.1:${port}`)).to.eventually.be.rejected()
  499. // passing the password should let us in
  500. expect(await fetch(`http://test:[email protected]:${port}`)).to.equal('authenticated')
  501. // subsequently, the credentials are cached
  502. expect(await fetch(`http://127.0.0.1:${port}`)).to.equal('authenticated')
  503. await ses.clearAuthCache({ type: 'password' })
  504. // once the cache is cleared, we should get an error again
  505. await expect(fetch(`http://127.0.0.1:${port}`)).to.eventually.be.rejected()
  506. })
  507. })
  508. describe('DownloadItem', () => {
  509. const mockPDF = Buffer.alloc(1024 * 1024 * 5)
  510. const downloadFilePath = path.join(__dirname, '..', 'fixtures', 'mock.pdf')
  511. const protocolName = 'custom-dl'
  512. const contentDisposition = 'inline; filename="mock.pdf"'
  513. let address = null
  514. let downloadServer = null
  515. before(async () => {
  516. downloadServer = http.createServer((req, res) => {
  517. address = downloadServer.address()
  518. res.writeHead(200, {
  519. 'Content-Length': mockPDF.length,
  520. 'Content-Type': 'application/pdf',
  521. 'Content-Disposition': req.url === '/?testFilename' ? 'inline' : contentDisposition
  522. })
  523. res.end(mockPDF)
  524. })
  525. await new Promise(resolve => downloadServer.listen(0, '127.0.0.1', resolve))
  526. })
  527. after(async () => {
  528. await new Promise(resolve => downloadServer.close(resolve))
  529. })
  530. afterEach(closeAllWindows)
  531. const isPathEqual = (path1, path2) => {
  532. return path.relative(path1, path2) === ''
  533. }
  534. const assertDownload = (state, item, isCustom = false) => {
  535. expect(state).to.equal('completed')
  536. expect(item.getFilename()).to.equal('mock.pdf')
  537. expect(path.isAbsolute(item.savePath)).to.equal(true)
  538. expect(isPathEqual(item.savePath, downloadFilePath)).to.equal(true)
  539. if (isCustom) {
  540. expect(item.getURL()).to.equal(`${protocolName}://item`)
  541. } else {
  542. expect(item.getURL()).to.be.equal(`${url}:${address.port}/`)
  543. }
  544. expect(item.getMimeType()).to.equal('application/pdf')
  545. expect(item.getReceivedBytes()).to.equal(mockPDF.length)
  546. expect(item.getTotalBytes()).to.equal(mockPDF.length)
  547. expect(item.getContentDisposition()).to.equal(contentDisposition)
  548. expect(fs.existsSync(downloadFilePath)).to.equal(true)
  549. fs.unlinkSync(downloadFilePath)
  550. }
  551. it('can download using WebContents.downloadURL', (done) => {
  552. const port = downloadServer.address().port
  553. const w = new BrowserWindow({ show: false })
  554. w.webContents.session.once('will-download', function (e, item) {
  555. item.savePath = downloadFilePath
  556. item.on('done', function (e, state) {
  557. assertDownload(state, item)
  558. done()
  559. })
  560. })
  561. w.webContents.downloadURL(`${url}:${port}`)
  562. })
  563. it('can download from custom protocols using WebContents.downloadURL', (done) => {
  564. const protocol = session.defaultSession.protocol
  565. const port = downloadServer.address().port
  566. const handler = (ignoredError, callback) => {
  567. callback({ url: `${url}:${port}` })
  568. }
  569. protocol.registerHttpProtocol(protocolName, handler, (error) => {
  570. if (error) return done(error)
  571. const w = new BrowserWindow({ show: false })
  572. w.webContents.session.once('will-download', function (e, item) {
  573. item.savePath = downloadFilePath
  574. item.on('done', function (e, state) {
  575. assertDownload(state, item, true)
  576. done()
  577. })
  578. })
  579. w.webContents.downloadURL(`${protocolName}://item`)
  580. })
  581. })
  582. it('can download using WebView.downloadURL', async () => {
  583. const port = address.port
  584. const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true } })
  585. await w.loadURL('about:blank')
  586. function webviewDownload({fixtures, url, port}) {
  587. const webview = new WebView()
  588. webview.addEventListener('did-finish-load', () => {
  589. webview.downloadURL(`${url}:${port}/`)
  590. })
  591. webview.src = `file://${fixtures}/api/blank.html`
  592. document.body.appendChild(webview)
  593. }
  594. const done = new Promise(resolve => {
  595. w.webContents.session.once('will-download', function (e, item) {
  596. item.savePath = downloadFilePath
  597. item.on('done', function (e, state) {
  598. resolve([state, item])
  599. })
  600. })
  601. })
  602. await w.webContents.executeJavaScript(`(${webviewDownload})(${JSON.stringify({fixtures, url, port})})`)
  603. const [state, item] = await done
  604. assertDownload(state, item)
  605. })
  606. it('can cancel download', (done) => {
  607. const port = address.port
  608. const w = new BrowserWindow({ show: false })
  609. w.webContents.session.once('will-download', function (e, item) {
  610. item.savePath = downloadFilePath
  611. item.on('done', function (e, state) {
  612. expect(state).to.equal('cancelled')
  613. expect(item.getFilename()).to.equal('mock.pdf')
  614. expect(item.getMimeType()).to.equal('application/pdf')
  615. expect(item.getReceivedBytes()).to.equal(0)
  616. expect(item.getTotalBytes()).to.equal(mockPDF.length)
  617. expect(item.getContentDisposition()).to.equal(contentDisposition)
  618. done()
  619. })
  620. item.cancel()
  621. })
  622. w.webContents.downloadURL(`${url}:${port}/`)
  623. })
  624. it('can generate a default filename', function (done) {
  625. if (process.env.APPVEYOR === 'True') {
  626. // FIXME(alexeykuzmin): Skip the test.
  627. // this.skip()
  628. return done()
  629. }
  630. const port = address.port
  631. const w = new BrowserWindow({ show: false })
  632. w.webContents.session.once('will-download', function (e, item) {
  633. item.savePath = downloadFilePath
  634. item.on('done', function (e, state) {
  635. expect(item.getFilename()).to.equal('download.pdf')
  636. done()
  637. })
  638. item.cancel()
  639. })
  640. w.webContents.downloadURL(`${url}:${port}/?testFilename`)
  641. })
  642. it('can set options for the save dialog', (done) => {
  643. const filePath = path.join(__dirname, 'fixtures', 'mock.pdf')
  644. const port = downloadServer.address().port
  645. const options = {
  646. window: null,
  647. title: 'title',
  648. message: 'message',
  649. buttonLabel: 'buttonLabel',
  650. nameFieldLabel: 'nameFieldLabel',
  651. defaultPath: '/',
  652. filters: [{
  653. name: '1', extensions: ['.1', '.2']
  654. }, {
  655. name: '2', extensions: ['.3', '.4', '.5']
  656. }],
  657. showsTagField: true,
  658. securityScopedBookmarks: true
  659. }
  660. const w = new BrowserWindow({ show: false })
  661. w.webContents.session.once('will-download', function (e, item) {
  662. item.setSavePath(filePath)
  663. item.setSaveDialogOptions(options)
  664. item.on('done', function (e, state) {
  665. expect(item.getSaveDialogOptions()).to.deep.equal(options)
  666. done()
  667. })
  668. item.cancel()
  669. })
  670. w.webContents.downloadURL(`${url}:${port}`)
  671. })
  672. describe('when a save path is specified and the URL is unavailable', () => {
  673. it('does not display a save dialog and reports the done state as interrupted', (done) => {
  674. const w = new BrowserWindow({ show: false })
  675. w.webContents.session.once('will-download', function (e, item) {
  676. item.savePath = downloadFilePath
  677. if (item.getState() === 'interrupted') {
  678. item.resume()
  679. }
  680. item.on('done', function (e, state) {
  681. expect(state).to.equal('interrupted')
  682. done()
  683. })
  684. })
  685. w.webContents.downloadURL(`file://${path.join(__dirname, 'does-not-exist.txt')}`)
  686. })
  687. })
  688. })
  689. describe('ses.createInterruptedDownload(options)', () => {
  690. afterEach(closeAllWindows)
  691. it('can create an interrupted download item', (done) => {
  692. const downloadFilePath = path.join(__dirname, '..', 'fixtures', 'mock.pdf')
  693. const options = {
  694. path: downloadFilePath,
  695. urlChain: ['http://127.0.0.1/'],
  696. mimeType: 'application/pdf',
  697. offset: 0,
  698. length: 5242880
  699. }
  700. const w = new BrowserWindow({ show: false })
  701. w.webContents.session.once('will-download', function (e, item) {
  702. expect(item.getState()).to.equal('interrupted')
  703. item.cancel()
  704. expect(item.getURLChain()).to.deep.equal(options.urlChain)
  705. expect(item.getMimeType()).to.equal(options.mimeType)
  706. expect(item.getReceivedBytes()).to.equal(options.offset)
  707. expect(item.getTotalBytes()).to.equal(options.length)
  708. expect(item.savePath).to.equal(downloadFilePath)
  709. done()
  710. })
  711. w.webContents.session.createInterruptedDownload(options)
  712. })
  713. it('can be resumed', async () => {
  714. const downloadFilePath = path.join(fixtures, 'logo.png')
  715. const rangeServer = http.createServer((req, res) => {
  716. const options = { root: fixtures }
  717. send(req, req.url, options)
  718. .on('error', (error) => { done(error) }).pipe(res)
  719. })
  720. try {
  721. await new Promise(resolve => rangeServer.listen(0, '127.0.0.1', resolve))
  722. const port = rangeServer.address().port
  723. const w = new BrowserWindow({ show: false })
  724. const downloadCancelled = new Promise((resolve) => {
  725. w.webContents.session.once('will-download', function (e, item) {
  726. item.setSavePath(downloadFilePath)
  727. item.on('done', function (e, state) {
  728. resolve(item)
  729. })
  730. item.cancel()
  731. })
  732. })
  733. const downloadUrl = `http://127.0.0.1:${port}/assets/logo.png`
  734. w.webContents.downloadURL(downloadUrl)
  735. const item = await downloadCancelled
  736. expect(item.getState()).to.equal('cancelled')
  737. const options = {
  738. path: item.savePath,
  739. urlChain: item.getURLChain(),
  740. mimeType: item.getMimeType(),
  741. offset: item.getReceivedBytes(),
  742. length: item.getTotalBytes(),
  743. lastModified: item.getLastModifiedTime(),
  744. eTag: item.getETag(),
  745. }
  746. const downloadResumed = new Promise((resolve) => {
  747. w.webContents.session.once('will-download', function (e, item) {
  748. expect(item.getState()).to.equal('interrupted')
  749. item.setSavePath(downloadFilePath)
  750. item.resume()
  751. item.on('done', function (e, state) {
  752. resolve(item)
  753. })
  754. })
  755. })
  756. w.webContents.session.createInterruptedDownload(options)
  757. const completedItem = await downloadResumed
  758. expect(completedItem.getState()).to.equal('completed')
  759. expect(completedItem.getFilename()).to.equal('logo.png')
  760. expect(completedItem.savePath).to.equal(downloadFilePath)
  761. expect(completedItem.getURL()).to.equal(downloadUrl)
  762. expect(completedItem.getMimeType()).to.equal('image/png')
  763. expect(completedItem.getReceivedBytes()).to.equal(14022)
  764. expect(completedItem.getTotalBytes()).to.equal(14022)
  765. expect(fs.existsSync(downloadFilePath)).to.equal(true)
  766. } finally {
  767. rangeServer.close()
  768. }
  769. })
  770. })
  771. describe('ses.setPermissionRequestHandler(handler)', () => {
  772. afterEach(closeAllWindows)
  773. it('cancels any pending requests when cleared', async () => {
  774. const w = new BrowserWindow({
  775. show: false,
  776. webPreferences: {
  777. partition: `very-temp-permision-handler`,
  778. nodeIntegration: true,
  779. }
  780. })
  781. const ses = w.webContents.session
  782. ses.setPermissionRequestHandler(() => {
  783. ses.setPermissionRequestHandler(null)
  784. })
  785. ses.protocol.interceptStringProtocol('https', (req, cb) => {
  786. cb(`<html><script>(${remote})()</script></html>`)
  787. })
  788. const result = emittedOnce(require('electron').ipcMain, 'message')
  789. function remote() {
  790. navigator.requestMIDIAccess({sysex: true}).then(() => {}, (err) => {
  791. require('electron').ipcRenderer.send('message', err.name);
  792. });
  793. }
  794. await w.loadURL('https://myfakesite')
  795. const [,name] = await result
  796. expect(name).to.deep.equal('SecurityError')
  797. })
  798. })
  799. describe('ses.setUserAgent()', () => {
  800. afterEach(closeAllWindows)
  801. it('can be retrieved with getUserAgent()', () => {
  802. const userAgent = 'test-agent'
  803. const ses = session.fromPartition(''+Math.random())
  804. ses.setUserAgent(userAgent)
  805. expect(ses.getUserAgent()).to.equal(userAgent)
  806. })
  807. it('sets the User-Agent header for web requests made from renderers', async () => {
  808. const userAgent = 'test-agent'
  809. const ses = session.fromPartition(''+Math.random())
  810. ses.setUserAgent(userAgent, 'en-US,fr,de');
  811. const w = new BrowserWindow({ show: false, webPreferences: { session: ses } })
  812. let headers = null
  813. const server = http.createServer((req, res) => {
  814. headers = req.headers
  815. res.end()
  816. server.close()
  817. })
  818. await new Promise(resolve => server.listen(0, '127.0.0.1', resolve))
  819. await w.loadURL(`http://127.0.0.1:${server.address().port}`)
  820. expect(headers['user-agent']).to.equal(userAgent)
  821. expect(headers['accept-language']).to.equal('en-US,fr;q=0.9,de;q=0.8');
  822. })
  823. })
  824. })