api-protocol-spec.ts 32 KB

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