api-protocol-spec.ts 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824
  1. import { expect } from 'chai'
  2. import { protocol, webContents, WebContents, session, BrowserWindow, ipcMain } from 'electron'
  3. import { promisify } from 'util'
  4. import { AddressInfo } from 'net'
  5. import * as path from 'path'
  6. import * as http from 'http'
  7. import * as fs from 'fs'
  8. import * as qs from 'querystring'
  9. import * as stream from 'stream'
  10. import { closeWindow } from './window-helpers'
  11. import { emittedOnce } from './events-helpers'
  12. const fixturesPath = path.resolve(__dirname, '..', 'spec', 'fixtures')
  13. const registerStringProtocol = promisify(protocol.registerStringProtocol)
  14. const registerBufferProtocol = promisify(protocol.registerBufferProtocol)
  15. const registerFileProtocol = promisify(protocol.registerFileProtocol)
  16. const registerHttpProtocol = promisify(protocol.registerHttpProtocol)
  17. const registerStreamProtocol = promisify(protocol.registerStreamProtocol)
  18. const interceptStringProtocol = promisify(protocol.interceptStringProtocol)
  19. const interceptBufferProtocol = promisify(protocol.interceptBufferProtocol)
  20. const interceptHttpProtocol = promisify(protocol.interceptHttpProtocol)
  21. const interceptStreamProtocol = promisify(protocol.interceptStreamProtocol)
  22. const unregisterProtocol = promisify(protocol.unregisterProtocol)
  23. const uninterceptProtocol = promisify(protocol.uninterceptProtocol)
  24. const text = 'valar morghulis'
  25. const protocolName = 'sp'
  26. const postData = {
  27. name: 'post test',
  28. type: 'string'
  29. }
  30. function delay (ms: number) {
  31. return new Promise((resolve) => {
  32. setTimeout(resolve, ms)
  33. })
  34. }
  35. function getStream (chunkSize = text.length, data: Buffer | string = text) {
  36. const body = new stream.PassThrough()
  37. async function sendChunks () {
  38. await delay(0) // the stream protocol API breaks if you send data immediately.
  39. let buf = Buffer.from(data as any) // nodejs typings are wrong, Buffer.from can take a Buffer
  40. for (;;) {
  41. body.push(buf.slice(0, chunkSize))
  42. buf = buf.slice(chunkSize)
  43. if (!buf.length) {
  44. break
  45. }
  46. // emulate some network delay
  47. await delay(10)
  48. }
  49. body.push(null)
  50. }
  51. sendChunks()
  52. return body
  53. }
  54. // A promise that can be resolved externally.
  55. function defer(): Promise<any> & {resolve: Function, reject: Function} {
  56. let promiseResolve: Function = null as unknown as Function
  57. let promiseReject: Function = null as unknown as Function
  58. const promise: any = new Promise((resolve, reject) => {
  59. promiseResolve = resolve
  60. promiseReject = reject
  61. })
  62. promise.resolve = promiseResolve
  63. promise.reject = promiseReject
  64. return promise
  65. }
  66. describe('protocol module', () => {
  67. let contents: WebContents = null as unknown as WebContents
  68. // NB. sandbox: true is used because it makes navigations much (~8x) faster.
  69. before(() => contents = (webContents as any).create({sandbox: true}))
  70. after(() => (contents as any).destroy())
  71. async function ajax (url: string, options = {}) {
  72. // Note that we need to do navigation every time after a protocol is
  73. // registered or unregistered, otherwise the new protocol won't be
  74. // recognized by current page when NetworkService is used.
  75. await contents.loadFile(path.join(fixturesPath, 'pages', 'jquery.html'))
  76. return contents.executeJavaScript(`ajax("${url}", ${JSON.stringify(options)})`)
  77. }
  78. afterEach(async () => {
  79. await new Promise(resolve => protocol.unregisterProtocol(protocolName, (/* ignore error */) => resolve()))
  80. await new Promise(resolve => protocol.uninterceptProtocol('http', () => resolve()))
  81. })
  82. describe('protocol.register(Any)Protocol', () => {
  83. it('throws error when scheme is already registered', async () => {
  84. await registerStringProtocol(protocolName, (req, cb) => cb())
  85. await expect(registerBufferProtocol(protocolName, (req, cb) => cb())).to.be.eventually.rejectedWith(Error)
  86. })
  87. it('does not crash when handler is called twice', async () => {
  88. await registerStringProtocol(protocolName, (request, callback) => {
  89. try {
  90. callback(text)
  91. callback()
  92. } catch (error) {
  93. // Ignore error
  94. }
  95. })
  96. const r = await ajax(protocolName + '://fake-host')
  97. expect(r.data).to.equal(text)
  98. })
  99. it('sends error when callback is called with nothing', async () => {
  100. await registerBufferProtocol(protocolName, (req, cb) => cb())
  101. await expect(ajax(protocolName + '://fake-host')).to.be.eventually.rejectedWith(Error, '404')
  102. })
  103. it('does not crash when callback is called in next tick', async () => {
  104. await registerStringProtocol(protocolName, (request, callback) => {
  105. setImmediate(() => callback(text))
  106. })
  107. const r = await ajax(protocolName + '://fake-host')
  108. expect(r.data).to.equal(text)
  109. })
  110. })
  111. describe('protocol.unregisterProtocol', () => {
  112. it('returns error when scheme does not exist', async () => {
  113. await expect(unregisterProtocol('not-exist')).to.be.eventually.rejectedWith(Error)
  114. })
  115. })
  116. describe('protocol.registerStringProtocol', () => {
  117. it('sends string as response', async () => {
  118. await registerStringProtocol(protocolName, (request, callback) => callback(text))
  119. const r = await ajax(protocolName + '://fake-host')
  120. expect(r.data).to.equal(text)
  121. })
  122. it('sets Access-Control-Allow-Origin', async () => {
  123. await registerStringProtocol(protocolName, (request, callback) => callback(text))
  124. const r = await ajax(protocolName + '://fake-host')
  125. expect(r.data).to.equal(text)
  126. expect(r.headers).to.include('access-control-allow-origin: *')
  127. })
  128. it('sends object as response', async () => {
  129. await registerStringProtocol(protocolName, (request, callback) => {
  130. callback({
  131. data: text,
  132. mimeType: 'text/html'
  133. })
  134. })
  135. const r = await ajax(protocolName + '://fake-host')
  136. expect(r.data).to.equal(text)
  137. })
  138. it('fails when sending object other than string', async () => {
  139. const notAString = () => {}
  140. await registerStringProtocol(protocolName, (request, callback) => callback(notAString as any))
  141. await expect(ajax(protocolName + '://fake-host')).to.be.eventually.rejectedWith(Error, '404')
  142. })
  143. })
  144. describe('protocol.registerBufferProtocol', () => {
  145. const buffer = Buffer.from(text)
  146. it('sends Buffer as response', async () => {
  147. await registerBufferProtocol(protocolName, (request, callback) => callback(buffer))
  148. const r = await ajax(protocolName + '://fake-host')
  149. expect(r.data).to.equal(text)
  150. })
  151. it('sets Access-Control-Allow-Origin', async () => {
  152. await registerBufferProtocol(protocolName, (request, callback) => callback(buffer))
  153. const r = await ajax(protocolName + '://fake-host')
  154. expect(r.data).to.equal(text)
  155. expect(r.headers).to.include('access-control-allow-origin: *')
  156. })
  157. it('sends object as response', async () => {
  158. await registerBufferProtocol(protocolName, (request, callback) => {
  159. callback({
  160. data: buffer,
  161. mimeType: 'text/html'
  162. })
  163. })
  164. const r = await ajax(protocolName + '://fake-host')
  165. expect(r.data).to.equal(text)
  166. })
  167. it('fails when sending string', async () => {
  168. await registerBufferProtocol(protocolName, (request, callback) => callback(text as any))
  169. await expect(ajax(protocolName + '://fake-host')).to.be.eventually.rejectedWith(Error, '404')
  170. })
  171. })
  172. describe('protocol.registerFileProtocol', () => {
  173. const filePath = path.join(fixturesPath, 'test.asar', 'a.asar', 'file1')
  174. const fileContent = fs.readFileSync(filePath)
  175. const normalPath = path.join(fixturesPath, 'pages', 'a.html')
  176. const normalContent = fs.readFileSync(normalPath)
  177. it('sends file path as response', async () => {
  178. await registerFileProtocol(protocolName, (request, callback) => callback(filePath))
  179. const r = await ajax(protocolName + '://fake-host')
  180. expect(r.data).to.equal(String(fileContent))
  181. })
  182. it('sets Access-Control-Allow-Origin', async () => {
  183. await registerFileProtocol(protocolName, (request, callback) => callback(filePath))
  184. const r = await ajax(protocolName + '://fake-host')
  185. expect(r.data).to.equal(String(fileContent))
  186. expect(r.headers).to.include('access-control-allow-origin: *')
  187. })
  188. it('sets custom headers', async () => {
  189. await registerFileProtocol(protocolName, (request, callback) => callback({
  190. path: filePath,
  191. headers: { 'X-Great-Header': 'sogreat' }
  192. }))
  193. const r = await ajax(protocolName + '://fake-host')
  194. expect(r.data).to.equal(String(fileContent))
  195. expect(r.headers).to.include('x-great-header: sogreat')
  196. })
  197. it.skip('throws an error when custom headers are invalid', (done) => {
  198. registerFileProtocol(protocolName, (request, callback) => {
  199. expect(() => callback({
  200. path: filePath,
  201. headers: { 'X-Great-Header': (42 as any) }
  202. })).to.throw(Error, `Value of 'X-Great-Header' header has to be a string`)
  203. done()
  204. }).then(() => {
  205. ajax(protocolName + '://fake-host')
  206. })
  207. })
  208. it('sends object as response', async () => {
  209. await registerFileProtocol(protocolName, (request, callback) => callback({ path: filePath }))
  210. const r = await ajax(protocolName + '://fake-host')
  211. expect(r.data).to.equal(String(fileContent))
  212. })
  213. it('can send normal file', async () => {
  214. await registerFileProtocol(protocolName, (request, callback) => callback(normalPath))
  215. const r = await ajax(protocolName + '://fake-host')
  216. expect(r.data).to.equal(String(normalContent))
  217. })
  218. it('fails when sending unexist-file', async () => {
  219. const fakeFilePath = path.join(fixturesPath, 'test.asar', 'a.asar', 'not-exist')
  220. await registerFileProtocol(protocolName, (request, callback) => callback(fakeFilePath))
  221. await expect(ajax(protocolName + '://fake-host')).to.be.eventually.rejectedWith(Error, '404')
  222. })
  223. it('fails when sending unsupported content', async () => {
  224. await registerFileProtocol(protocolName, (request, callback) => callback(new Date() as any))
  225. await expect(ajax(protocolName + '://fake-host')).to.be.eventually.rejectedWith(Error, '404')
  226. })
  227. })
  228. describe('protocol.registerHttpProtocol', () => {
  229. it('sends url as response', async () => {
  230. const server = http.createServer((req, res) => {
  231. expect(req.headers.accept).to.not.equal('')
  232. res.end(text)
  233. server.close()
  234. })
  235. await server.listen(0, '127.0.0.1')
  236. const port = (server.address() as AddressInfo).port
  237. const url = 'http://127.0.0.1:' + port
  238. await registerHttpProtocol(protocolName, (request, callback) => callback({ url }))
  239. const r = await ajax(protocolName + '://fake-host')
  240. expect(r.data).to.equal(text)
  241. })
  242. it('fails when sending invalid url', async () => {
  243. await registerHttpProtocol(protocolName, (request, callback) => callback({ url: 'url' }))
  244. await expect(ajax(protocolName + '://fake-host')).to.be.eventually.rejectedWith(Error, '404')
  245. })
  246. it('fails when sending unsupported content', async () => {
  247. await registerHttpProtocol(protocolName, (request, callback) => callback(new Date() as any))
  248. await expect(ajax(protocolName + '://fake-host')).to.be.eventually.rejectedWith(Error, '404')
  249. })
  250. it('works when target URL redirects', async () => {
  251. const server = http.createServer((req, res) => {
  252. if (req.url === '/serverRedirect') {
  253. res.statusCode = 301
  254. res.setHeader('Location', `http://${req.rawHeaders[1]}`)
  255. res.end()
  256. } else {
  257. res.end(text)
  258. }
  259. })
  260. after(() => server.close())
  261. await server.listen(0, '127.0.0.1')
  262. const port = (server.address() as AddressInfo).port
  263. const url = `${protocolName}://fake-host`
  264. const redirectURL = `http://127.0.0.1:${port}/serverRedirect`
  265. await registerHttpProtocol(protocolName, (request, callback) => callback({ url: redirectURL }))
  266. const r = await ajax(url)
  267. expect(r.data).to.equal(text)
  268. })
  269. it('can access request headers', (done) => {
  270. protocol.registerHttpProtocol(protocolName, (request) => {
  271. expect(request).to.have.property('headers')
  272. done()
  273. }, () => {
  274. ajax(protocolName + '://fake-host')
  275. })
  276. })
  277. })
  278. describe('protocol.registerStreamProtocol', () => {
  279. it('sends Stream as response', async () => {
  280. await registerStreamProtocol(protocolName, (request, callback) => callback(getStream()))
  281. const r = await ajax(protocolName + '://fake-host')
  282. expect(r.data).to.equal(text)
  283. })
  284. it('sends object as response', async () => {
  285. await registerStreamProtocol(protocolName, (request, callback) => callback({ data: getStream() }))
  286. const r = await ajax(protocolName + '://fake-host')
  287. expect(r.data).to.equal(text)
  288. expect(r.status).to.equal(200)
  289. })
  290. it('sends custom response headers', async () => {
  291. await registerStreamProtocol(protocolName, (request, callback) => callback({
  292. data: getStream(3),
  293. headers: {
  294. 'x-electron': ['a', 'b']
  295. }
  296. }))
  297. const r = await ajax(protocolName + '://fake-host')
  298. expect(r.data).to.equal(text)
  299. expect(r.status).to.equal(200)
  300. expect(r.headers).to.include('x-electron: a, b')
  301. })
  302. it('sends custom status code', async () => {
  303. await registerStreamProtocol(protocolName, (request, callback) => callback({
  304. statusCode: 204,
  305. data: null
  306. }))
  307. const r = await ajax(protocolName + '://fake-host')
  308. expect(r.data).to.be.undefined('data')
  309. expect(r.status).to.equal(204)
  310. })
  311. it('receives request headers', async () => {
  312. await registerStreamProtocol(protocolName, (request, callback) => {
  313. callback({
  314. headers: {
  315. 'content-type': 'application/json'
  316. },
  317. data: getStream(5, JSON.stringify(Object.assign({}, request.headers)))
  318. })
  319. })
  320. const r = await ajax(protocolName + '://fake-host', { headers: { 'x-return-headers': 'yes' } })
  321. expect(r.data['x-return-headers']).to.equal('yes')
  322. })
  323. it('returns response multiple response headers with the same name', async () => {
  324. await registerStreamProtocol(protocolName, (request, callback) => {
  325. callback({
  326. headers: {
  327. 'header1': ['value1', 'value2'],
  328. 'header2': 'value3'
  329. },
  330. data: getStream()
  331. })
  332. })
  333. const r = await ajax(protocolName + '://fake-host')
  334. // SUBTLE: when the response headers have multiple values it
  335. // separates values by ", ". When the response headers are incorrectly
  336. // converting an array to a string it separates values by ",".
  337. expect(r.headers).to.equal('header1: value1, value2\r\nheader2: value3\r\n')
  338. })
  339. it('can handle large responses', async () => {
  340. const data = Buffer.alloc(128 * 1024)
  341. await registerStreamProtocol(protocolName, (request, callback) => {
  342. callback(getStream(data.length, data))
  343. })
  344. const r = await ajax(protocolName + '://fake-host')
  345. expect(r.data).to.have.lengthOf(data.length)
  346. })
  347. it('can handle a stream completing while writing', async () => {
  348. function dumbPassthrough () {
  349. return new stream.Transform({
  350. async transform (chunk, encoding, cb) {
  351. cb(null, chunk)
  352. }
  353. })
  354. }
  355. await registerStreamProtocol(protocolName, (request, callback) => {
  356. callback({
  357. statusCode: 200,
  358. headers: { 'Content-Type': 'text/plain' },
  359. data: getStream(1024 * 1024, Buffer.alloc(1024 * 1024 * 2)).pipe(dumbPassthrough())
  360. })
  361. })
  362. const r = await ajax(protocolName + '://fake-host')
  363. expect(r.data).to.have.lengthOf(1024 * 1024 * 2)
  364. })
  365. })
  366. describe('protocol.isProtocolHandled', () => {
  367. it('returns true for built-in protocols', async () => {
  368. for (const p of ['about', 'file', 'http', 'https']) {
  369. const handled = await protocol.isProtocolHandled(p)
  370. expect(handled).to.be.true(`${p}: is handled`)
  371. }
  372. })
  373. it('returns false when scheme is not registered', async () => {
  374. const result = await protocol.isProtocolHandled('no-exist')
  375. expect(result).to.be.false('no-exist: is handled')
  376. })
  377. it('returns true for custom protocol', async () => {
  378. await registerStringProtocol(protocolName, (request, callback) => callback())
  379. const result = await protocol.isProtocolHandled(protocolName)
  380. expect(result).to.be.true('custom protocol is handled')
  381. })
  382. it('returns true for intercepted protocol', async () => {
  383. await interceptStringProtocol('http', (request, callback) => callback())
  384. const result = await protocol.isProtocolHandled('http')
  385. expect(result).to.be.true('intercepted protocol is handled')
  386. })
  387. })
  388. describe('protocol.intercept(Any)Protocol', () => {
  389. it('throws error when scheme is already intercepted', (done) => {
  390. protocol.interceptStringProtocol('http', (request, callback) => callback(), (error) => {
  391. expect(error).to.be.null('error')
  392. protocol.interceptBufferProtocol('http', (request, callback) => callback(), (error) => {
  393. expect(error).to.not.be.null('error')
  394. done()
  395. })
  396. })
  397. })
  398. it('does not crash when handler is called twice', async () => {
  399. await interceptStringProtocol('http', (request, callback) => {
  400. try {
  401. callback(text)
  402. callback()
  403. } catch (error) {
  404. // Ignore error
  405. }
  406. })
  407. const r = await ajax('http://fake-host')
  408. expect(r.data).to.be.equal(text)
  409. })
  410. it('sends error when callback is called with nothing', async () => {
  411. await interceptStringProtocol('http', (request, callback) => callback())
  412. await expect(ajax('http://fake-host')).to.be.eventually.rejectedWith(Error, '404')
  413. })
  414. })
  415. describe('protocol.interceptStringProtocol', () => {
  416. it('can intercept http protocol', async () => {
  417. await interceptStringProtocol('http', (request, callback) => callback(text))
  418. const r = await ajax('http://fake-host')
  419. expect(r.data).to.equal(text)
  420. })
  421. it('can set content-type', async () => {
  422. await interceptStringProtocol('http', (request, callback) => {
  423. callback({
  424. mimeType: 'application/json',
  425. data: '{"value": 1}'
  426. })
  427. })
  428. const r = await ajax('http://fake-host')
  429. expect(r.data).to.be.an('object')
  430. expect(r.data).to.have.property('value').that.is.equal(1)
  431. })
  432. it('can set content-type with charset', async () => {
  433. await interceptStringProtocol('http', (request, callback) => {
  434. callback({
  435. mimeType: 'application/json; charset=UTF-8',
  436. data: '{"value": 1}'
  437. })
  438. })
  439. const r = await ajax('http://fake-host')
  440. expect(r.data).to.be.an('object')
  441. expect(r.data).to.have.property('value').that.is.equal(1)
  442. })
  443. it('can receive post data', async () => {
  444. await interceptStringProtocol('http', (request, callback) => {
  445. const uploadData = request.uploadData[0].bytes.toString()
  446. callback({ data: uploadData })
  447. })
  448. const r = await ajax('http://fake-host', { type: 'POST', data: postData })
  449. expect({ ...qs.parse(r.data) }).to.deep.equal(postData)
  450. })
  451. })
  452. describe('protocol.interceptBufferProtocol', () => {
  453. it('can intercept http protocol', async () => {
  454. await interceptBufferProtocol('http', (request, callback) => callback(Buffer.from(text)))
  455. const r = await ajax('http://fake-host')
  456. expect(r.data).to.equal(text)
  457. })
  458. it('can receive post data', async () => {
  459. await interceptBufferProtocol('http', (request, callback) => {
  460. const uploadData = request.uploadData[0].bytes
  461. callback(uploadData)
  462. })
  463. const r = await ajax('http://fake-host', { type: 'POST', data: postData })
  464. expect(r.data).to.equal('name=post+test&type=string')
  465. })
  466. })
  467. describe('protocol.interceptHttpProtocol', () => {
  468. // FIXME(zcbenz): This test was passing because the test itself was wrong,
  469. // I don't know whether it ever passed before and we should take a look at
  470. // it in future.
  471. xit('can send POST request', async () => {
  472. const server = http.createServer((req, res) => {
  473. let body = ''
  474. req.on('data', (chunk) => {
  475. body += chunk
  476. })
  477. req.on('end', () => {
  478. res.end(body)
  479. })
  480. server.close()
  481. })
  482. after(() => server.close())
  483. await server.listen(0, '127.0.0.1')
  484. const port = (server.address() as AddressInfo).port
  485. const url = `http://127.0.0.1:${port}`
  486. await interceptHttpProtocol('http', (request, callback) => {
  487. const data: Electron.RedirectRequest = {
  488. url: url,
  489. method: 'POST',
  490. uploadData: {
  491. contentType: 'application/x-www-form-urlencoded',
  492. data: request.uploadData[0].bytes
  493. },
  494. session: null
  495. }
  496. callback(data)
  497. })
  498. const r = await ajax('http://fake-host', { type: 'POST', data: postData })
  499. expect({ ...qs.parse(r.data) }).to.deep.equal(postData)
  500. })
  501. it.skip('can use custom session', async () => {
  502. const customSession = session.fromPartition('custom-ses', { cache: false })
  503. customSession.webRequest.onBeforeRequest((details, callback) => {
  504. expect(details.url).to.equal('http://fake-host/')
  505. callback({ cancel: true })
  506. })
  507. after(() => customSession.webRequest.onBeforeRequest(null))
  508. await interceptHttpProtocol('http', (request, callback) => {
  509. callback({
  510. url: request.url,
  511. session: customSession
  512. })
  513. })
  514. await expect(ajax('http://fake-host')).to.be.eventually.rejectedWith(Error)
  515. })
  516. it('can access request headers', (done) => {
  517. protocol.interceptHttpProtocol('http', (request) => {
  518. expect(request).to.have.property('headers')
  519. done()
  520. }, () => {
  521. ajax('http://fake-host')
  522. })
  523. })
  524. })
  525. describe('protocol.interceptStreamProtocol', () => {
  526. it('can intercept http protocol', async () => {
  527. await interceptStreamProtocol('http', (request, callback) => callback(getStream()))
  528. const r = await ajax('http://fake-host')
  529. expect(r.data).to.equal(text)
  530. })
  531. it('can receive post data', async () => {
  532. await interceptStreamProtocol('http', (request, callback) => {
  533. callback(getStream(3, request.uploadData[0].bytes.toString()))
  534. })
  535. const r = await ajax('http://fake-host', { type: 'POST', data: postData })
  536. expect({ ...qs.parse(r.data) }).to.deep.equal(postData)
  537. })
  538. it('can execute redirects', async () => {
  539. await interceptStreamProtocol('http', (request, callback) => {
  540. if (request.url.indexOf('http://fake-host') === 0) {
  541. setTimeout(() => {
  542. callback({
  543. data: null,
  544. statusCode: 302,
  545. headers: {
  546. Location: 'http://fake-redirect'
  547. }
  548. })
  549. }, 300)
  550. } else {
  551. expect(request.url.indexOf('http://fake-redirect')).to.equal(0)
  552. callback(getStream(1, 'redirect'))
  553. }
  554. })
  555. const r = await ajax('http://fake-host')
  556. expect(r.data).to.equal('redirect')
  557. })
  558. })
  559. describe('protocol.uninterceptProtocol', () => {
  560. it('returns error when scheme does not exist', async () => {
  561. await expect(uninterceptProtocol('not-exist')).to.be.eventually.rejectedWith(Error)
  562. })
  563. it('returns error when scheme is not intercepted', async () => {
  564. await expect(uninterceptProtocol('http')).to.be.eventually.rejectedWith(Error)
  565. })
  566. })
  567. describe.skip('protocol.registerSchemesAsPrivileged standard', () => {
  568. const standardScheme = (global as any).standardScheme
  569. const origin = `${standardScheme}://fake-host`
  570. const imageURL = `${origin}/test.png`
  571. const filePath = path.join(fixturesPath, 'pages', 'b.html')
  572. const fileContent = '<img src="/test.png" />'
  573. let w: BrowserWindow = null as unknown as BrowserWindow
  574. beforeEach(() => {
  575. w = new BrowserWindow({
  576. show: false,
  577. webPreferences: {
  578. nodeIntegration: true
  579. }
  580. })
  581. })
  582. afterEach(async () => {
  583. await closeWindow(w)
  584. await unregisterProtocol(standardScheme)
  585. w = null as unknown as BrowserWindow
  586. })
  587. it('resolves relative resources', async () => {
  588. await registerFileProtocol(standardScheme, (request, callback) => {
  589. if (request.url === imageURL) {
  590. callback()
  591. } else {
  592. callback(filePath)
  593. }
  594. })
  595. await w.loadURL(origin)
  596. })
  597. it('resolves absolute resources', async () => {
  598. await registerStringProtocol(standardScheme, (request, callback) => {
  599. if (request.url === imageURL) {
  600. callback()
  601. } else {
  602. callback({
  603. data: fileContent,
  604. mimeType: 'text/html'
  605. })
  606. }
  607. })
  608. await w.loadURL(origin)
  609. })
  610. it('can have fetch working in it', async () => {
  611. const requestReceived = defer()
  612. const server = http.createServer((req, res) => {
  613. res.end()
  614. server.close()
  615. requestReceived.resolve()
  616. })
  617. await new Promise(resolve => server.listen(0, '127.0.0.1', resolve))
  618. const port = (server.address() as AddressInfo).port
  619. const content = `<script>fetch("http://127.0.0.1:${port}")</script>`
  620. await registerStringProtocol(standardScheme, (request, callback) => callback({ data: content, mimeType: 'text/html' }))
  621. await w.loadURL(origin)
  622. await requestReceived
  623. })
  624. it.skip('can access files through the FileSystem API', (done) => {
  625. const filePath = path.join(fixturesPath, 'pages', 'filesystem.html')
  626. protocol.registerFileProtocol(standardScheme, (request, callback) => callback({ path: filePath }), (error) => {
  627. if (error) return done(error)
  628. w.loadURL(origin)
  629. })
  630. ipcMain.once('file-system-error', (event, err) => done(err))
  631. ipcMain.once('file-system-write-end', () => done())
  632. })
  633. it('registers secure, when {secure: true}', (done) => {
  634. const filePath = path.join(fixturesPath, 'pages', 'cache-storage.html')
  635. ipcMain.once('success', () => done())
  636. ipcMain.once('failure', (event, err) => done(err))
  637. protocol.registerFileProtocol(standardScheme, (request, callback) => callback({ path: filePath }), (error) => {
  638. if (error) return done(error)
  639. w.loadURL(origin)
  640. })
  641. })
  642. })
  643. describe.skip('protocol.registerSchemesAsPrivileged cors-fetch', function () {
  644. const standardScheme = (global as any).standardScheme
  645. let w: BrowserWindow = null as unknown as BrowserWindow
  646. beforeEach(async () => {
  647. w = new BrowserWindow({show: false})
  648. })
  649. afterEach(async () => {
  650. await closeWindow(w)
  651. w = null as unknown as BrowserWindow
  652. await Promise.all(
  653. [standardScheme, 'cors', 'no-cors', 'no-fetch'].map(scheme =>
  654. new Promise(resolve => protocol.unregisterProtocol(scheme, (/* ignore error */) => resolve()))
  655. )
  656. )
  657. })
  658. it('supports fetch api by default', async () => {
  659. const url = `file://${fixturesPath}/assets/logo.png`
  660. await w.loadURL(`file://${fixturesPath}/pages/blank.html`)
  661. const ok = await w.webContents.executeJavaScript(`fetch(${JSON.stringify(url)}).then(r => r.ok)`)
  662. expect(ok).to.be.true('response ok')
  663. })
  664. it('allows CORS requests by default', async () => {
  665. await allowsCORSRequests('cors', 200, new RegExp(''), () => {
  666. const {ipcRenderer} = require('electron')
  667. fetch('cors://myhost').then(function (response) {
  668. ipcRenderer.send('response', response.status)
  669. }).catch(function (response) {
  670. ipcRenderer.send('response', 'failed')
  671. })
  672. })
  673. })
  674. it('disallows CORS and fetch requests when only supportFetchAPI is specified', async () => {
  675. await allowsCORSRequests('no-cors', ['failed xhr', 'failed fetch'], /has been blocked by CORS policy/, () => {
  676. const {ipcRenderer} = require('electron')
  677. Promise.all([
  678. new Promise(resolve => {
  679. const req = new XMLHttpRequest()
  680. req.onload = () => resolve('loaded xhr')
  681. req.onerror = () => resolve('failed xhr')
  682. req.open('GET', 'no-cors://myhost')
  683. req.send()
  684. }),
  685. fetch('no-cors://myhost')
  686. .then(() => 'loaded fetch')
  687. .catch(() => 'failed fetch')
  688. ]).then(([xhr, fetch]) => {
  689. ipcRenderer.send('response', [xhr, fetch])
  690. })
  691. })
  692. })
  693. it('allows CORS, but disallows fetch requests, when specified', async () => {
  694. await allowsCORSRequests('no-fetch', ['loaded xhr', 'failed fetch'], /Fetch API cannot load/, () => {
  695. const {ipcRenderer} = require('electron')
  696. Promise.all([
  697. new Promise(resolve => {
  698. const req = new XMLHttpRequest()
  699. req.onload = () => resolve('loaded xhr')
  700. req.onerror = () => resolve('failed xhr')
  701. req.open('GET', 'no-fetch://myhost')
  702. req.send()
  703. }),
  704. fetch('no-fetch://myhost')
  705. .then(() => 'loaded fetch')
  706. .catch(() => 'failed fetch')
  707. ]).then(([xhr, fetch]) => {
  708. ipcRenderer.send('response', [xhr, fetch])
  709. })
  710. })
  711. })
  712. async function allowsCORSRequests (corsScheme: string, expected: any, expectedConsole: RegExp, content: Function) {
  713. await registerStringProtocol(standardScheme, (request, callback) => {
  714. callback({ data: `<script>(${content})()</script>`, mimeType: 'text/html' })
  715. })
  716. await registerStringProtocol(corsScheme, (request, callback) => {
  717. callback('')
  718. })
  719. const newContents: WebContents = (webContents as any).create({ nodeIntegration: true })
  720. const consoleMessages: string[] = []
  721. newContents.on('console-message', (e, level, message, line, sourceId) => consoleMessages.push(message))
  722. try {
  723. newContents.loadURL(standardScheme + '://fake-host')
  724. const [, response] = await emittedOnce(ipcMain, 'response')
  725. expect(response).to.deep.equal(expected)
  726. expect(consoleMessages.join('\n')).to.match(expectedConsole)
  727. } finally {
  728. // This is called in a timeout to avoid a crash that happens when
  729. // calling destroy() in a microtask.
  730. setTimeout(() => {
  731. (newContents as any).destroy()
  732. })
  733. }
  734. }
  735. })
  736. })