api-protocol-spec.ts 39 KB

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