api-protocol-spec.ts 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052
  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 = 'sp';
  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', 'jquery.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.rejectedWith(Error, '404');
  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.include('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.rejectedWith(Error, '404');
  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.include('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.rejectedWith(Error, '404');
  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.include('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.include('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');
  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.rejectedWith(Error, '404');
  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.rejectedWith(Error, '404');
  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.rejectedWith(Error, '404');
  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.rejectedWith(Error, '404');
  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');
  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.include('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.undefined('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(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.equal('header1: value1, value2\r\nheader2: value3\r\n');
  356. });
  357. it('can handle large responses', async () => {
  358. const data = Buffer.alloc(128 * 1024);
  359. registerStreamProtocol(protocolName, (request, callback) => {
  360. callback(getStream(data.length, data));
  361. });
  362. const r = await ajax(protocolName + '://fake-host');
  363. expect(r.data).to.have.lengthOf(data.length);
  364. });
  365. it('can handle a stream completing while writing', async () => {
  366. function dumbPassthrough () {
  367. return new stream.Transform({
  368. async transform (chunk, encoding, cb) {
  369. cb(null, chunk);
  370. }
  371. });
  372. }
  373. registerStreamProtocol(protocolName, (request, callback) => {
  374. callback({
  375. statusCode: 200,
  376. headers: { 'Content-Type': 'text/plain' },
  377. data: getStream(1024 * 1024, Buffer.alloc(1024 * 1024 * 2)).pipe(dumbPassthrough())
  378. });
  379. });
  380. const r = await ajax(protocolName + '://fake-host');
  381. expect(r.data).to.have.lengthOf(1024 * 1024 * 2);
  382. });
  383. it('can handle next-tick scheduling during read calls', async () => {
  384. const events = new EventEmitter();
  385. function createStream () {
  386. const buffers = [
  387. Buffer.alloc(65536),
  388. Buffer.alloc(65537),
  389. Buffer.alloc(39156)
  390. ];
  391. const e = new stream.Readable({ highWaterMark: 0 });
  392. e.push(buffers.shift());
  393. e._read = function () {
  394. process.nextTick(() => this.push(buffers.shift() || null));
  395. };
  396. e.on('end', function () {
  397. events.emit('end');
  398. });
  399. return e;
  400. }
  401. registerStreamProtocol(protocolName, (request, callback) => {
  402. callback({
  403. statusCode: 200,
  404. headers: { 'Content-Type': 'text/plain' },
  405. data: createStream()
  406. });
  407. });
  408. const hasEndedPromise = emittedOnce(events, 'end');
  409. ajax(protocolName + '://fake-host');
  410. await hasEndedPromise;
  411. });
  412. it('destroys response streams when aborted before completion', async () => {
  413. const events = new EventEmitter();
  414. registerStreamProtocol(protocolName, (request, callback) => {
  415. const responseStream = new stream.PassThrough();
  416. responseStream.push('data\r\n');
  417. responseStream.on('close', () => {
  418. events.emit('close');
  419. });
  420. callback({
  421. statusCode: 200,
  422. headers: { 'Content-Type': 'text/plain' },
  423. data: responseStream
  424. });
  425. events.emit('respond');
  426. });
  427. const hasRespondedPromise = emittedOnce(events, 'respond');
  428. const hasClosedPromise = emittedOnce(events, 'close');
  429. ajax(protocolName + '://fake-host');
  430. await hasRespondedPromise;
  431. await contents.loadFile(path.join(__dirname, 'fixtures', 'pages', 'jquery.html'));
  432. await hasClosedPromise;
  433. });
  434. });
  435. describe('protocol.isProtocolRegistered', () => {
  436. it('returns false when scheme is not registered', () => {
  437. const result = protocol.isProtocolRegistered('no-exist');
  438. expect(result).to.be.false('no-exist: is handled');
  439. });
  440. it('returns true for custom protocol', () => {
  441. registerStringProtocol(protocolName, (request, callback) => callback(''));
  442. const result = protocol.isProtocolRegistered(protocolName);
  443. expect(result).to.be.true('custom protocol is handled');
  444. });
  445. });
  446. describe('protocol.isProtocolIntercepted', () => {
  447. it('returns true for intercepted protocol', () => {
  448. interceptStringProtocol('http', (request, callback) => callback(''));
  449. const result = protocol.isProtocolIntercepted('http');
  450. expect(result).to.be.true('intercepted protocol is handled');
  451. });
  452. });
  453. describe('protocol.intercept(Any)Protocol', () => {
  454. it('returns false when scheme is already intercepted', () => {
  455. expect(protocol.interceptStringProtocol('http', (request, callback) => callback(''))).to.equal(true);
  456. expect(protocol.interceptBufferProtocol('http', (request, callback) => callback(Buffer.from('')))).to.equal(false);
  457. });
  458. it('does not crash when handler is called twice', async () => {
  459. interceptStringProtocol('http', (request, callback) => {
  460. try {
  461. callback(text);
  462. callback('');
  463. } catch (error) {
  464. // Ignore error
  465. }
  466. });
  467. const r = await ajax('http://fake-host');
  468. expect(r.data).to.be.equal(text);
  469. });
  470. it('sends error when callback is called with nothing', async () => {
  471. interceptStringProtocol('http', (request, callback: any) => callback());
  472. await expect(ajax('http://fake-host')).to.be.eventually.rejectedWith(Error, '404');
  473. });
  474. });
  475. describe('protocol.interceptStringProtocol', () => {
  476. it('can intercept http protocol', async () => {
  477. interceptStringProtocol('http', (request, callback) => callback(text));
  478. const r = await ajax('http://fake-host');
  479. expect(r.data).to.equal(text);
  480. });
  481. it('can set content-type', async () => {
  482. interceptStringProtocol('http', (request, callback) => {
  483. callback({
  484. mimeType: 'application/json',
  485. data: '{"value": 1}'
  486. });
  487. });
  488. const r = await ajax('http://fake-host');
  489. expect(r.data).to.be.an('object');
  490. expect(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(r.data).to.be.an('object');
  501. expect(r.data).to.have.property('value').that.is.equal(1);
  502. });
  503. it('can receive post data', async () => {
  504. interceptStringProtocol('http', (request, callback) => {
  505. const uploadData = request.uploadData![0].bytes.toString();
  506. callback({ data: uploadData });
  507. });
  508. const r = await ajax('http://fake-host', { type: 'POST', data: postData });
  509. expect({ ...qs.parse(r.data) }).to.deep.equal(postData);
  510. });
  511. });
  512. describe('protocol.interceptBufferProtocol', () => {
  513. it('can intercept http protocol', async () => {
  514. interceptBufferProtocol('http', (request, callback) => callback(Buffer.from(text)));
  515. const r = await ajax('http://fake-host');
  516. expect(r.data).to.equal(text);
  517. });
  518. it('can receive post data', async () => {
  519. interceptBufferProtocol('http', (request, callback) => {
  520. const uploadData = request.uploadData![0].bytes;
  521. callback(uploadData);
  522. });
  523. const r = await ajax('http://fake-host', { type: 'POST', data: postData });
  524. expect(r.data).to.equal('name=post+test&type=string');
  525. });
  526. });
  527. describe('protocol.interceptHttpProtocol', () => {
  528. // FIXME(zcbenz): This test was passing because the test itself was wrong,
  529. // I don't know whether it ever passed before and we should take a look at
  530. // it in future.
  531. xit('can send POST request', async () => {
  532. const server = http.createServer((req, res) => {
  533. let body = '';
  534. req.on('data', (chunk) => {
  535. body += chunk;
  536. });
  537. req.on('end', () => {
  538. res.end(body);
  539. });
  540. server.close();
  541. });
  542. after(() => server.close());
  543. server.listen(0, '127.0.0.1');
  544. const port = (server.address() as AddressInfo).port;
  545. const url = `http://127.0.0.1:${port}`;
  546. interceptHttpProtocol('http', (request, callback) => {
  547. const data: Electron.ProtocolResponse = {
  548. url: url,
  549. method: 'POST',
  550. uploadData: {
  551. contentType: 'application/x-www-form-urlencoded',
  552. data: request.uploadData![0].bytes
  553. },
  554. session: undefined
  555. };
  556. callback(data);
  557. });
  558. const r = await ajax('http://fake-host', { type: 'POST', data: postData });
  559. expect({ ...qs.parse(r.data) }).to.deep.equal(postData);
  560. });
  561. it('can use custom session', async () => {
  562. const customSession = session.fromPartition('custom-ses', { cache: false });
  563. customSession.webRequest.onBeforeRequest((details, callback) => {
  564. expect(details.url).to.equal('http://fake-host/');
  565. callback({ cancel: true });
  566. });
  567. after(() => customSession.webRequest.onBeforeRequest(null));
  568. interceptHttpProtocol('http', (request, callback) => {
  569. callback({
  570. url: request.url,
  571. session: customSession
  572. });
  573. });
  574. await expect(ajax('http://fake-host')).to.be.eventually.rejectedWith(Error);
  575. });
  576. it('can access request headers', (done) => {
  577. protocol.interceptHttpProtocol('http', (request) => {
  578. try {
  579. expect(request).to.have.property('headers');
  580. done();
  581. } catch (e) {
  582. done(e);
  583. }
  584. });
  585. ajax('http://fake-host');
  586. });
  587. });
  588. describe('protocol.interceptStreamProtocol', () => {
  589. it('can intercept http protocol', async () => {
  590. interceptStreamProtocol('http', (request, callback) => callback(getStream()));
  591. const r = await ajax('http://fake-host');
  592. expect(r.data).to.equal(text);
  593. });
  594. it('can receive post data', async () => {
  595. interceptStreamProtocol('http', (request, callback) => {
  596. callback(getStream(3, request.uploadData![0].bytes.toString()));
  597. });
  598. const r = await ajax('http://fake-host', { type: 'POST', data: postData });
  599. expect({ ...qs.parse(r.data) }).to.deep.equal(postData);
  600. });
  601. it('can execute redirects', async () => {
  602. interceptStreamProtocol('http', (request, callback) => {
  603. if (request.url.indexOf('http://fake-host') === 0) {
  604. setTimeout(() => {
  605. callback({
  606. data: '',
  607. statusCode: 302,
  608. headers: {
  609. Location: 'http://fake-redirect'
  610. }
  611. });
  612. }, 300);
  613. } else {
  614. expect(request.url.indexOf('http://fake-redirect')).to.equal(0);
  615. callback(getStream(1, 'redirect'));
  616. }
  617. });
  618. const r = await ajax('http://fake-host');
  619. expect(r.data).to.equal('redirect');
  620. });
  621. it('should discard post data after redirection', async () => {
  622. interceptStreamProtocol('http', (request, callback) => {
  623. if (request.url.indexOf('http://fake-host') === 0) {
  624. setTimeout(() => {
  625. callback({
  626. statusCode: 302,
  627. headers: {
  628. Location: 'http://fake-redirect'
  629. }
  630. });
  631. }, 300);
  632. } else {
  633. expect(request.url.indexOf('http://fake-redirect')).to.equal(0);
  634. callback(getStream(3, request.method));
  635. }
  636. });
  637. const r = await ajax('http://fake-host', { type: 'POST', data: postData });
  638. expect(r.data).to.equal('GET');
  639. });
  640. });
  641. describe('protocol.uninterceptProtocol', () => {
  642. it('returns false when scheme does not exist', () => {
  643. expect(uninterceptProtocol('not-exist')).to.equal(false);
  644. });
  645. it('returns false when scheme is not intercepted', () => {
  646. expect(uninterceptProtocol('http')).to.equal(false);
  647. });
  648. });
  649. describe('protocol.registerSchemeAsPrivileged', () => {
  650. it('does not crash on exit', async () => {
  651. const appPath = path.join(__dirname, 'fixtures', 'api', 'custom-protocol-shutdown.js');
  652. const appProcess = ChildProcess.spawn(process.execPath, ['--enable-logging', appPath]);
  653. let stdout = '';
  654. let stderr = '';
  655. appProcess.stdout.on('data', data => { process.stdout.write(data); stdout += data; });
  656. appProcess.stderr.on('data', data => { process.stderr.write(data); stderr += data; });
  657. const [code] = await emittedOnce(appProcess, 'exit');
  658. if (code !== 0) {
  659. console.log('Exit code : ', code);
  660. console.log('stdout : ', stdout);
  661. console.log('stderr : ', stderr);
  662. }
  663. expect(code).to.equal(0);
  664. expect(stdout).to.not.contain('VALIDATION_ERROR_DESERIALIZATION_FAILED');
  665. expect(stderr).to.not.contain('VALIDATION_ERROR_DESERIALIZATION_FAILED');
  666. });
  667. });
  668. describe('protocol.registerSchemesAsPrivileged allowServiceWorkers', () => {
  669. const { serviceWorkerScheme } = global as any;
  670. protocol.registerStringProtocol(serviceWorkerScheme, (request, cb) => {
  671. if (request.url.endsWith('.js')) {
  672. cb({
  673. mimeType: 'text/javascript',
  674. charset: 'utf-8',
  675. data: 'console.log("Loaded")'
  676. });
  677. } else {
  678. cb({
  679. mimeType: 'text/html',
  680. charset: 'utf-8',
  681. data: '<!DOCTYPE html>'
  682. });
  683. }
  684. });
  685. after(() => protocol.unregisterProtocol(serviceWorkerScheme));
  686. it('should fail when registering invalid service worker', async () => {
  687. await contents.loadURL(`${serviceWorkerScheme}://${v4()}.com`);
  688. await expect(contents.executeJavaScript(`navigator.serviceWorker.register('${v4()}.notjs', {scope: './'})`)).to.be.rejected();
  689. });
  690. it('should be able to register service worker for custom scheme', async () => {
  691. await contents.loadURL(`${serviceWorkerScheme}://${v4()}.com`);
  692. await contents.executeJavaScript(`navigator.serviceWorker.register('${v4()}.js', {scope: './'})`);
  693. });
  694. });
  695. describe.skip('protocol.registerSchemesAsPrivileged standard', () => {
  696. const standardScheme = (global as any).standardScheme;
  697. const origin = `${standardScheme}://fake-host`;
  698. const imageURL = `${origin}/test.png`;
  699. const filePath = path.join(fixturesPath, 'pages', 'b.html');
  700. const fileContent = '<img src="/test.png" />';
  701. let w: BrowserWindow = null as unknown as BrowserWindow;
  702. beforeEach(() => {
  703. w = new BrowserWindow({
  704. show: false,
  705. webPreferences: {
  706. nodeIntegration: true
  707. }
  708. });
  709. });
  710. afterEach(async () => {
  711. await closeWindow(w);
  712. unregisterProtocol(standardScheme);
  713. w = null as unknown as BrowserWindow;
  714. });
  715. it('resolves relative resources', async () => {
  716. registerFileProtocol(standardScheme, (request, callback) => {
  717. if (request.url === imageURL) {
  718. callback('');
  719. } else {
  720. callback(filePath);
  721. }
  722. });
  723. await w.loadURL(origin);
  724. });
  725. it('resolves absolute resources', async () => {
  726. registerStringProtocol(standardScheme, (request, callback) => {
  727. if (request.url === imageURL) {
  728. callback('');
  729. } else {
  730. callback({
  731. data: fileContent,
  732. mimeType: 'text/html'
  733. });
  734. }
  735. });
  736. await w.loadURL(origin);
  737. });
  738. it('can have fetch working in it', async () => {
  739. const requestReceived = defer();
  740. const server = http.createServer((req, res) => {
  741. res.end();
  742. server.close();
  743. requestReceived.resolve();
  744. });
  745. await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
  746. const port = (server.address() as AddressInfo).port;
  747. const content = `<script>fetch("http://127.0.0.1:${port}")</script>`;
  748. registerStringProtocol(standardScheme, (request, callback) => callback({ data: content, mimeType: 'text/html' }));
  749. await w.loadURL(origin);
  750. await requestReceived;
  751. });
  752. it.skip('can access files through the FileSystem API', (done) => {
  753. const filePath = path.join(fixturesPath, 'pages', 'filesystem.html');
  754. protocol.registerFileProtocol(standardScheme, (request, callback) => callback({ path: filePath }));
  755. w.loadURL(origin);
  756. ipcMain.once('file-system-error', (event, err) => done(err));
  757. ipcMain.once('file-system-write-end', () => done());
  758. });
  759. it('registers secure, when {secure: true}', (done) => {
  760. const filePath = path.join(fixturesPath, 'pages', 'cache-storage.html');
  761. ipcMain.once('success', () => done());
  762. ipcMain.once('failure', (event, err) => done(err));
  763. protocol.registerFileProtocol(standardScheme, (request, callback) => callback({ path: filePath }));
  764. w.loadURL(origin);
  765. });
  766. });
  767. describe.skip('protocol.registerSchemesAsPrivileged cors-fetch', function () {
  768. const standardScheme = (global as any).standardScheme;
  769. let w: BrowserWindow = null as unknown as BrowserWindow;
  770. beforeEach(async () => {
  771. w = new BrowserWindow({ show: false });
  772. });
  773. afterEach(async () => {
  774. await closeWindow(w);
  775. w = null as unknown as BrowserWindow;
  776. for (const scheme of [standardScheme, 'cors', 'no-cors', 'no-fetch']) {
  777. protocol.unregisterProtocol(scheme);
  778. }
  779. });
  780. it('supports fetch api by default', async () => {
  781. const url = `file://${fixturesPath}/assets/logo.png`;
  782. await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
  783. const ok = await w.webContents.executeJavaScript(`fetch(${JSON.stringify(url)}).then(r => r.ok)`);
  784. expect(ok).to.be.true('response ok');
  785. });
  786. it('allows CORS requests by default', async () => {
  787. await allowsCORSRequests('cors', 200, new RegExp(''), () => {
  788. const { ipcRenderer } = require('electron');
  789. fetch('cors://myhost').then(function (response) {
  790. ipcRenderer.send('response', response.status);
  791. }).catch(function () {
  792. ipcRenderer.send('response', 'failed');
  793. });
  794. });
  795. });
  796. it('disallows CORS and fetch requests when only supportFetchAPI is specified', async () => {
  797. await allowsCORSRequests('no-cors', ['failed xhr', 'failed fetch'], /has been blocked by CORS policy/, () => {
  798. const { ipcRenderer } = require('electron');
  799. Promise.all([
  800. new Promise(resolve => {
  801. const req = new XMLHttpRequest();
  802. req.onload = () => resolve('loaded xhr');
  803. req.onerror = () => resolve('failed xhr');
  804. req.open('GET', 'no-cors://myhost');
  805. req.send();
  806. }),
  807. fetch('no-cors://myhost')
  808. .then(() => 'loaded fetch')
  809. .catch(() => 'failed fetch')
  810. ]).then(([xhr, fetch]) => {
  811. ipcRenderer.send('response', [xhr, fetch]);
  812. });
  813. });
  814. });
  815. it('allows CORS, but disallows fetch requests, when specified', async () => {
  816. await allowsCORSRequests('no-fetch', ['loaded xhr', 'failed fetch'], /Fetch API cannot load/, () => {
  817. const { ipcRenderer } = require('electron');
  818. Promise.all([
  819. new Promise(resolve => {
  820. const req = new XMLHttpRequest();
  821. req.onload = () => resolve('loaded xhr');
  822. req.onerror = () => resolve('failed xhr');
  823. req.open('GET', 'no-fetch://myhost');
  824. req.send();
  825. }),
  826. fetch('no-fetch://myhost')
  827. .then(() => 'loaded fetch')
  828. .catch(() => 'failed fetch')
  829. ]).then(([xhr, fetch]) => {
  830. ipcRenderer.send('response', [xhr, fetch]);
  831. });
  832. });
  833. });
  834. async function allowsCORSRequests (corsScheme: string, expected: any, expectedConsole: RegExp, content: Function) {
  835. registerStringProtocol(standardScheme, (request, callback) => {
  836. callback({ data: `<script>(${content})()</script>`, mimeType: 'text/html' });
  837. });
  838. registerStringProtocol(corsScheme, (request, callback) => {
  839. callback('');
  840. });
  841. const newContents: WebContents = (webContents as any).create({ nodeIntegration: true });
  842. const consoleMessages: string[] = [];
  843. newContents.on('console-message', (e, level, message) => consoleMessages.push(message));
  844. try {
  845. newContents.loadURL(standardScheme + '://fake-host');
  846. const [, response] = await emittedOnce(ipcMain, 'response');
  847. expect(response).to.deep.equal(expected);
  848. expect(consoleMessages.join('\n')).to.match(expectedConsole);
  849. } finally {
  850. // This is called in a timeout to avoid a crash that happens when
  851. // calling destroy() in a microtask.
  852. setTimeout(() => {
  853. (newContents as any).destroy();
  854. });
  855. }
  856. }
  857. });
  858. describe('protocol.registerSchemesAsPrivileged stream', async function () {
  859. const pagePath = path.join(fixturesPath, 'pages', 'video.html');
  860. const videoSourceImagePath = path.join(fixturesPath, 'video-source-image.webp');
  861. const videoPath = path.join(fixturesPath, 'video.webm');
  862. const standardScheme = (global as any).standardScheme;
  863. let w: BrowserWindow = null as unknown as BrowserWindow;
  864. before(async () => {
  865. // generate test video
  866. const imageBase64 = await fs.promises.readFile(videoSourceImagePath, 'base64');
  867. const imageDataUrl = `data:image/webp;base64,${imageBase64}`;
  868. const encoder = new WebmGenerator(15);
  869. for (let i = 0; i < 30; i++) {
  870. encoder.add(imageDataUrl);
  871. }
  872. await new Promise((resolve, reject) => {
  873. encoder.compile((output:Uint8Array) => {
  874. fs.promises.writeFile(videoPath, output).then(resolve, reject);
  875. });
  876. });
  877. });
  878. after(async () => {
  879. await fs.promises.unlink(videoPath);
  880. });
  881. beforeEach(async function () {
  882. w = new BrowserWindow({ show: false });
  883. await w.loadURL('about:blank');
  884. if (!await w.webContents.executeJavaScript('document.createElement(\'video\').canPlayType(\'video/webm; codecs="vp8.0"\')')) {
  885. this.skip();
  886. }
  887. });
  888. afterEach(async () => {
  889. await closeWindow(w);
  890. w = null as unknown as BrowserWindow;
  891. await protocol.unregisterProtocol(standardScheme);
  892. await protocol.unregisterProtocol('stream');
  893. });
  894. it('successfully plays videos when content is buffered (stream: false)', async () => {
  895. await streamsResponses(standardScheme, 'play');
  896. });
  897. it('successfully plays videos when streaming content (stream: true)', async () => {
  898. await streamsResponses('stream', 'play');
  899. });
  900. async function streamsResponses (testingScheme: string, expected: any) {
  901. const protocolHandler = (request: any, callback: Function) => {
  902. if (request.url.includes('/video.webm')) {
  903. const stat = fs.statSync(videoPath);
  904. const fileSize = stat.size;
  905. const range = request.headers.Range;
  906. if (range) {
  907. const parts = range.replace(/bytes=/, '').split('-');
  908. const start = parseInt(parts[0], 10);
  909. const end = parts[1] ? parseInt(parts[1], 10) : fileSize - 1;
  910. const chunksize = (end - start) + 1;
  911. const headers = {
  912. 'Content-Range': `bytes ${start}-${end}/${fileSize}`,
  913. 'Accept-Ranges': 'bytes',
  914. 'Content-Length': String(chunksize),
  915. 'Content-Type': 'video/webm'
  916. };
  917. callback({ statusCode: 206, headers, data: fs.createReadStream(videoPath, { start, end }) });
  918. } else {
  919. callback({
  920. statusCode: 200,
  921. headers: {
  922. 'Content-Length': String(fileSize),
  923. 'Content-Type': 'video/webm'
  924. },
  925. data: fs.createReadStream(videoPath)
  926. });
  927. }
  928. } else {
  929. callback({ data: fs.createReadStream(pagePath), headers: { 'Content-Type': 'text/html' }, statusCode: 200 });
  930. }
  931. };
  932. await registerStreamProtocol(standardScheme, protocolHandler);
  933. await registerStreamProtocol('stream', protocolHandler);
  934. const newContents: WebContents = (webContents as any).create({ nodeIntegration: true, contextIsolation: false });
  935. try {
  936. newContents.loadURL(testingScheme + '://fake-host');
  937. const [, response] = await emittedOnce(ipcMain, 'result');
  938. expect(response).to.deep.equal(expected);
  939. } finally {
  940. // This is called in a timeout to avoid a crash that happens when
  941. // calling destroy() in a microtask.
  942. setTimeout(() => {
  943. (newContents as any).destroy();
  944. });
  945. }
  946. }
  947. });
  948. });