api-protocol-spec.ts 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014
  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. });
  110. describe('protocol.unregisterProtocol', () => {
  111. it('returns false when scheme does not exist', () => {
  112. expect(unregisterProtocol('not-exist')).to.equal(false);
  113. });
  114. });
  115. describe('protocol.registerStringProtocol', () => {
  116. it('sends string as response', async () => {
  117. registerStringProtocol(protocolName, (request, callback) => callback(text));
  118. const r = await ajax(protocolName + '://fake-host');
  119. expect(r.data).to.equal(text);
  120. });
  121. it('sets Access-Control-Allow-Origin', async () => {
  122. registerStringProtocol(protocolName, (request, callback) => callback(text));
  123. const r = await ajax(protocolName + '://fake-host');
  124. expect(r.data).to.equal(text);
  125. expect(r.headers).to.include('access-control-allow-origin: *');
  126. });
  127. it('sends object as response', async () => {
  128. registerStringProtocol(protocolName, (request, callback) => {
  129. callback({
  130. data: text,
  131. mimeType: 'text/html'
  132. });
  133. });
  134. const r = await ajax(protocolName + '://fake-host');
  135. expect(r.data).to.equal(text);
  136. });
  137. it('fails when sending object other than string', async () => {
  138. const notAString = () => {};
  139. registerStringProtocol(protocolName, (request, callback) => callback(notAString as any));
  140. await expect(ajax(protocolName + '://fake-host')).to.be.eventually.rejectedWith(Error, '404');
  141. });
  142. });
  143. describe('protocol.registerBufferProtocol', () => {
  144. const buffer = Buffer.from(text);
  145. it('sends Buffer as response', async () => {
  146. registerBufferProtocol(protocolName, (request, callback) => callback(buffer));
  147. const r = await ajax(protocolName + '://fake-host');
  148. expect(r.data).to.equal(text);
  149. });
  150. it('sets Access-Control-Allow-Origin', async () => {
  151. registerBufferProtocol(protocolName, (request, callback) => callback(buffer));
  152. const r = await ajax(protocolName + '://fake-host');
  153. expect(r.data).to.equal(text);
  154. expect(r.headers).to.include('access-control-allow-origin: *');
  155. });
  156. it('sends object as response', async () => {
  157. registerBufferProtocol(protocolName, (request, callback) => {
  158. callback({
  159. data: buffer,
  160. mimeType: 'text/html'
  161. });
  162. });
  163. const r = await ajax(protocolName + '://fake-host');
  164. expect(r.data).to.equal(text);
  165. });
  166. it('fails when sending string', async () => {
  167. registerBufferProtocol(protocolName, (request, callback) => callback(text as any));
  168. await expect(ajax(protocolName + '://fake-host')).to.be.eventually.rejectedWith(Error, '404');
  169. });
  170. });
  171. describe('protocol.registerFileProtocol', () => {
  172. const filePath = path.join(fixturesPath, 'test.asar', 'a.asar', 'file1');
  173. const fileContent = fs.readFileSync(filePath);
  174. const normalPath = path.join(fixturesPath, 'pages', 'a.html');
  175. const normalContent = fs.readFileSync(normalPath);
  176. it('sends file path as response', async () => {
  177. registerFileProtocol(protocolName, (request, callback) => callback(filePath));
  178. const r = await ajax(protocolName + '://fake-host');
  179. expect(r.data).to.equal(String(fileContent));
  180. });
  181. it('sets Access-Control-Allow-Origin', async () => {
  182. registerFileProtocol(protocolName, (request, callback) => callback(filePath));
  183. const r = await ajax(protocolName + '://fake-host');
  184. expect(r.data).to.equal(String(fileContent));
  185. expect(r.headers).to.include('access-control-allow-origin: *');
  186. });
  187. it('sets custom headers', async () => {
  188. registerFileProtocol(protocolName, (request, callback) => callback({
  189. path: filePath,
  190. headers: { 'X-Great-Header': 'sogreat' }
  191. }));
  192. const r = await ajax(protocolName + '://fake-host');
  193. expect(r.data).to.equal(String(fileContent));
  194. expect(r.headers).to.include('x-great-header: sogreat');
  195. });
  196. it.skip('throws an error when custom headers are invalid', (done) => {
  197. registerFileProtocol(protocolName, (request, callback) => {
  198. expect(() => callback({
  199. path: filePath,
  200. headers: { 'X-Great-Header': (42 as any) }
  201. })).to.throw(Error, 'Value of \'X-Great-Header\' header has to be a string');
  202. done();
  203. });
  204. ajax(protocolName + '://fake-host');
  205. });
  206. it('sends object as response', async () => {
  207. registerFileProtocol(protocolName, (request, callback) => callback({ path: filePath }));
  208. const r = await ajax(protocolName + '://fake-host');
  209. expect(r.data).to.equal(String(fileContent));
  210. });
  211. it('can send normal file', async () => {
  212. registerFileProtocol(protocolName, (request, callback) => callback(normalPath));
  213. const r = await ajax(protocolName + '://fake-host');
  214. expect(r.data).to.equal(String(normalContent));
  215. });
  216. it('fails when sending unexist-file', async () => {
  217. const fakeFilePath = path.join(fixturesPath, 'test.asar', 'a.asar', 'not-exist');
  218. registerFileProtocol(protocolName, (request, callback) => callback(fakeFilePath));
  219. await expect(ajax(protocolName + '://fake-host')).to.be.eventually.rejectedWith(Error, '404');
  220. });
  221. it('fails when sending unsupported content', async () => {
  222. registerFileProtocol(protocolName, (request, callback) => callback(new Date() as any));
  223. await expect(ajax(protocolName + '://fake-host')).to.be.eventually.rejectedWith(Error, '404');
  224. });
  225. });
  226. describe('protocol.registerHttpProtocol', () => {
  227. it('sends url as response', async () => {
  228. const server = http.createServer((req, res) => {
  229. expect(req.headers.accept).to.not.equal('');
  230. res.end(text);
  231. server.close();
  232. });
  233. await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
  234. const port = (server.address() as AddressInfo).port;
  235. const url = 'http://127.0.0.1:' + port;
  236. registerHttpProtocol(protocolName, (request, callback) => callback({ url }));
  237. const r = await ajax(protocolName + '://fake-host');
  238. expect(r.data).to.equal(text);
  239. });
  240. it('fails when sending invalid url', async () => {
  241. registerHttpProtocol(protocolName, (request, callback) => callback({ url: 'url' }));
  242. await expect(ajax(protocolName + '://fake-host')).to.be.eventually.rejectedWith(Error, '404');
  243. });
  244. it('fails when sending unsupported content', async () => {
  245. registerHttpProtocol(protocolName, (request, callback) => callback(new Date() as any));
  246. await expect(ajax(protocolName + '://fake-host')).to.be.eventually.rejectedWith(Error, '404');
  247. });
  248. it('works when target URL redirects', async () => {
  249. const server = http.createServer((req, res) => {
  250. if (req.url === '/serverRedirect') {
  251. res.statusCode = 301;
  252. res.setHeader('Location', `http://${req.rawHeaders[1]}`);
  253. res.end();
  254. } else {
  255. res.end(text);
  256. }
  257. });
  258. after(() => server.close());
  259. await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
  260. const port = (server.address() as AddressInfo).port;
  261. const url = `${protocolName}://fake-host`;
  262. const redirectURL = `http://127.0.0.1:${port}/serverRedirect`;
  263. registerHttpProtocol(protocolName, (request, callback) => callback({ url: redirectURL }));
  264. const r = await ajax(url);
  265. expect(r.data).to.equal(text);
  266. });
  267. it('can access request headers', (done) => {
  268. protocol.registerHttpProtocol(protocolName, (request) => {
  269. try {
  270. expect(request).to.have.property('headers');
  271. done();
  272. } catch (e) {
  273. done(e);
  274. }
  275. });
  276. ajax(protocolName + '://fake-host');
  277. });
  278. });
  279. describe('protocol.registerStreamProtocol', () => {
  280. it('sends Stream as response', async () => {
  281. 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. 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. 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. registerStreamProtocol(protocolName, (request, callback) => callback({
  305. statusCode: 204,
  306. data: null as any
  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. 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. 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. 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. 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.isProtocolRegistered', () => {
  419. it('returns false when scheme is not registered', () => {
  420. const result = protocol.isProtocolRegistered('no-exist');
  421. expect(result).to.be.false('no-exist: is handled');
  422. });
  423. it('returns true for custom protocol', () => {
  424. registerStringProtocol(protocolName, (request, callback) => callback(''));
  425. const result = protocol.isProtocolRegistered(protocolName);
  426. expect(result).to.be.true('custom protocol is handled');
  427. });
  428. });
  429. describe('protocol.isProtocolIntercepted', () => {
  430. it('returns true for intercepted protocol', () => {
  431. interceptStringProtocol('http', (request, callback) => callback(''));
  432. const result = protocol.isProtocolIntercepted('http');
  433. expect(result).to.be.true('intercepted protocol is handled');
  434. });
  435. });
  436. describe('protocol.intercept(Any)Protocol', () => {
  437. it('returns false when scheme is already intercepted', () => {
  438. expect(protocol.interceptStringProtocol('http', (request, callback) => callback(''))).to.equal(true);
  439. expect(protocol.interceptBufferProtocol('http', (request, callback) => callback(Buffer.from('')))).to.equal(false);
  440. });
  441. it('does not crash when handler is called twice', async () => {
  442. interceptStringProtocol('http', (request, callback) => {
  443. try {
  444. callback(text);
  445. callback('');
  446. } catch (error) {
  447. // Ignore error
  448. }
  449. });
  450. const r = await ajax('http://fake-host');
  451. expect(r.data).to.be.equal(text);
  452. });
  453. it('sends error when callback is called with nothing', async () => {
  454. interceptStringProtocol('http', (request, callback: any) => callback());
  455. await expect(ajax('http://fake-host')).to.be.eventually.rejectedWith(Error, '404');
  456. });
  457. });
  458. describe('protocol.interceptStringProtocol', () => {
  459. it('can intercept http protocol', async () => {
  460. interceptStringProtocol('http', (request, callback) => callback(text));
  461. const r = await ajax('http://fake-host');
  462. expect(r.data).to.equal(text);
  463. });
  464. it('can set content-type', async () => {
  465. interceptStringProtocol('http', (request, callback) => {
  466. callback({
  467. mimeType: 'application/json',
  468. data: '{"value": 1}'
  469. });
  470. });
  471. const r = await ajax('http://fake-host');
  472. expect(r.data).to.be.an('object');
  473. expect(r.data).to.have.property('value').that.is.equal(1);
  474. });
  475. it('can set content-type with charset', async () => {
  476. interceptStringProtocol('http', (request, callback) => {
  477. callback({
  478. mimeType: 'application/json; charset=UTF-8',
  479. data: '{"value": 1}'
  480. });
  481. });
  482. const r = await ajax('http://fake-host');
  483. expect(r.data).to.be.an('object');
  484. expect(r.data).to.have.property('value').that.is.equal(1);
  485. });
  486. it('can receive post data', async () => {
  487. interceptStringProtocol('http', (request, callback) => {
  488. const uploadData = request.uploadData![0].bytes.toString();
  489. callback({ data: uploadData });
  490. });
  491. const r = await ajax('http://fake-host', { type: 'POST', data: postData });
  492. expect({ ...qs.parse(r.data) }).to.deep.equal(postData);
  493. });
  494. });
  495. describe('protocol.interceptBufferProtocol', () => {
  496. it('can intercept http protocol', async () => {
  497. interceptBufferProtocol('http', (request, callback) => callback(Buffer.from(text)));
  498. const r = await ajax('http://fake-host');
  499. expect(r.data).to.equal(text);
  500. });
  501. it('can receive post data', async () => {
  502. interceptBufferProtocol('http', (request, callback) => {
  503. const uploadData = request.uploadData![0].bytes;
  504. callback(uploadData);
  505. });
  506. const r = await ajax('http://fake-host', { type: 'POST', data: postData });
  507. expect(r.data).to.equal('name=post+test&type=string');
  508. });
  509. });
  510. describe('protocol.interceptHttpProtocol', () => {
  511. // FIXME(zcbenz): This test was passing because the test itself was wrong,
  512. // I don't know whether it ever passed before and we should take a look at
  513. // it in future.
  514. xit('can send POST request', async () => {
  515. const server = http.createServer((req, res) => {
  516. let body = '';
  517. req.on('data', (chunk) => {
  518. body += chunk;
  519. });
  520. req.on('end', () => {
  521. res.end(body);
  522. });
  523. server.close();
  524. });
  525. after(() => server.close());
  526. server.listen(0, '127.0.0.1');
  527. const port = (server.address() as AddressInfo).port;
  528. const url = `http://127.0.0.1:${port}`;
  529. interceptHttpProtocol('http', (request, callback) => {
  530. const data: Electron.ProtocolResponse = {
  531. url: url,
  532. method: 'POST',
  533. uploadData: {
  534. contentType: 'application/x-www-form-urlencoded',
  535. data: request.uploadData![0].bytes
  536. },
  537. session: undefined
  538. };
  539. callback(data);
  540. });
  541. const r = await ajax('http://fake-host', { type: 'POST', data: postData });
  542. expect({ ...qs.parse(r.data) }).to.deep.equal(postData);
  543. });
  544. it('can use custom session', async () => {
  545. const customSession = session.fromPartition('custom-ses', { cache: false });
  546. customSession.webRequest.onBeforeRequest((details, callback) => {
  547. expect(details.url).to.equal('http://fake-host/');
  548. callback({ cancel: true });
  549. });
  550. after(() => customSession.webRequest.onBeforeRequest(null));
  551. interceptHttpProtocol('http', (request, callback) => {
  552. callback({
  553. url: request.url,
  554. session: customSession
  555. });
  556. });
  557. await expect(ajax('http://fake-host')).to.be.eventually.rejectedWith(Error);
  558. });
  559. it('can access request headers', (done) => {
  560. protocol.interceptHttpProtocol('http', (request) => {
  561. try {
  562. expect(request).to.have.property('headers');
  563. done();
  564. } catch (e) {
  565. done(e);
  566. }
  567. });
  568. ajax('http://fake-host');
  569. });
  570. });
  571. describe('protocol.interceptStreamProtocol', () => {
  572. it('can intercept http protocol', async () => {
  573. interceptStreamProtocol('http', (request, callback) => callback(getStream()));
  574. const r = await ajax('http://fake-host');
  575. expect(r.data).to.equal(text);
  576. });
  577. it('can receive post data', async () => {
  578. interceptStreamProtocol('http', (request, callback) => {
  579. callback(getStream(3, request.uploadData![0].bytes.toString()));
  580. });
  581. const r = await ajax('http://fake-host', { type: 'POST', data: postData });
  582. expect({ ...qs.parse(r.data) }).to.deep.equal(postData);
  583. });
  584. it('can execute redirects', async () => {
  585. interceptStreamProtocol('http', (request, callback) => {
  586. if (request.url.indexOf('http://fake-host') === 0) {
  587. setTimeout(() => {
  588. callback({
  589. data: '',
  590. statusCode: 302,
  591. headers: {
  592. Location: 'http://fake-redirect'
  593. }
  594. });
  595. }, 300);
  596. } else {
  597. expect(request.url.indexOf('http://fake-redirect')).to.equal(0);
  598. callback(getStream(1, 'redirect'));
  599. }
  600. });
  601. const r = await ajax('http://fake-host');
  602. expect(r.data).to.equal('redirect');
  603. });
  604. });
  605. describe('protocol.uninterceptProtocol', () => {
  606. it('returns false when scheme does not exist', () => {
  607. expect(uninterceptProtocol('not-exist')).to.equal(false);
  608. });
  609. it('returns false when scheme is not intercepted', () => {
  610. expect(uninterceptProtocol('http')).to.equal(false);
  611. });
  612. });
  613. describe('protocol.registerSchemeAsPrivileged', () => {
  614. it('does not crash on exit', async () => {
  615. const appPath = path.join(__dirname, 'fixtures', 'api', 'custom-protocol-shutdown.js');
  616. const appProcess = ChildProcess.spawn(process.execPath, ['--enable-logging', appPath]);
  617. let stdout = '';
  618. let stderr = '';
  619. appProcess.stdout.on('data', data => { stdout += data; });
  620. appProcess.stderr.on('data', data => { stderr += data; });
  621. const [code] = await emittedOnce(appProcess, 'exit');
  622. if (code !== 0) {
  623. console.log('Exit code : ', code);
  624. console.log('stdout : ', stdout);
  625. console.log('stderr : ', stderr);
  626. }
  627. expect(code).to.equal(0);
  628. expect(stdout).to.not.contain('VALIDATION_ERROR_DESERIALIZATION_FAILED');
  629. expect(stderr).to.not.contain('VALIDATION_ERROR_DESERIALIZATION_FAILED');
  630. });
  631. });
  632. describe('protocol.registerSchemesAsPrivileged allowServiceWorkers', () => {
  633. const { serviceWorkerScheme } = global as any;
  634. protocol.registerStringProtocol(serviceWorkerScheme, (request, cb) => {
  635. if (request.url.endsWith('.js')) {
  636. cb({
  637. mimeType: 'text/javascript',
  638. charset: 'utf-8',
  639. data: 'console.log("Loaded")'
  640. });
  641. } else {
  642. cb({
  643. mimeType: 'text/html',
  644. charset: 'utf-8',
  645. data: '<!DOCTYPE html>'
  646. });
  647. }
  648. });
  649. after(() => protocol.unregisterProtocol(serviceWorkerScheme));
  650. it('should fail when registering invalid service worker', async () => {
  651. await contents.loadURL(`${serviceWorkerScheme}://${v4()}.com`);
  652. await expect(contents.executeJavaScript(`navigator.serviceWorker.register('${v4()}.notjs', {scope: './'})`)).to.be.rejected();
  653. });
  654. it('should be able to register service worker for custom scheme', async () => {
  655. await contents.loadURL(`${serviceWorkerScheme}://${v4()}.com`);
  656. await contents.executeJavaScript(`navigator.serviceWorker.register('${v4()}.js', {scope: './'})`);
  657. });
  658. });
  659. describe.skip('protocol.registerSchemesAsPrivileged standard', () => {
  660. const standardScheme = (global as any).standardScheme;
  661. const origin = `${standardScheme}://fake-host`;
  662. const imageURL = `${origin}/test.png`;
  663. const filePath = path.join(fixturesPath, 'pages', 'b.html');
  664. const fileContent = '<img src="/test.png" />';
  665. let w: BrowserWindow = null as unknown as BrowserWindow;
  666. beforeEach(() => {
  667. w = new BrowserWindow({
  668. show: false,
  669. webPreferences: {
  670. nodeIntegration: true
  671. }
  672. });
  673. });
  674. afterEach(async () => {
  675. await closeWindow(w);
  676. unregisterProtocol(standardScheme);
  677. w = null as unknown as BrowserWindow;
  678. });
  679. it('resolves relative resources', async () => {
  680. registerFileProtocol(standardScheme, (request, callback) => {
  681. if (request.url === imageURL) {
  682. callback('');
  683. } else {
  684. callback(filePath);
  685. }
  686. });
  687. await w.loadURL(origin);
  688. });
  689. it('resolves absolute resources', async () => {
  690. registerStringProtocol(standardScheme, (request, callback) => {
  691. if (request.url === imageURL) {
  692. callback('');
  693. } else {
  694. callback({
  695. data: fileContent,
  696. mimeType: 'text/html'
  697. });
  698. }
  699. });
  700. await w.loadURL(origin);
  701. });
  702. it('can have fetch working in it', async () => {
  703. const requestReceived = defer();
  704. const server = http.createServer((req, res) => {
  705. res.end();
  706. server.close();
  707. requestReceived.resolve();
  708. });
  709. await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
  710. const port = (server.address() as AddressInfo).port;
  711. const content = `<script>fetch("http://127.0.0.1:${port}")</script>`;
  712. registerStringProtocol(standardScheme, (request, callback) => callback({ data: content, mimeType: 'text/html' }));
  713. await w.loadURL(origin);
  714. await requestReceived;
  715. });
  716. it.skip('can access files through the FileSystem API', (done) => {
  717. const filePath = path.join(fixturesPath, 'pages', 'filesystem.html');
  718. protocol.registerFileProtocol(standardScheme, (request, callback) => callback({ path: filePath }));
  719. w.loadURL(origin);
  720. ipcMain.once('file-system-error', (event, err) => done(err));
  721. ipcMain.once('file-system-write-end', () => done());
  722. });
  723. it('registers secure, when {secure: true}', (done) => {
  724. const filePath = path.join(fixturesPath, 'pages', 'cache-storage.html');
  725. ipcMain.once('success', () => done());
  726. ipcMain.once('failure', (event, err) => done(err));
  727. protocol.registerFileProtocol(standardScheme, (request, callback) => callback({ path: filePath }));
  728. w.loadURL(origin);
  729. });
  730. });
  731. describe.skip('protocol.registerSchemesAsPrivileged cors-fetch', function () {
  732. const standardScheme = (global as any).standardScheme;
  733. let w: BrowserWindow = null as unknown as BrowserWindow;
  734. beforeEach(async () => {
  735. w = new BrowserWindow({ show: false });
  736. });
  737. afterEach(async () => {
  738. await closeWindow(w);
  739. w = null as unknown as BrowserWindow;
  740. for (const scheme of [standardScheme, 'cors', 'no-cors', 'no-fetch']) {
  741. protocol.unregisterProtocol(scheme);
  742. }
  743. });
  744. it('supports fetch api by default', async () => {
  745. const url = `file://${fixturesPath}/assets/logo.png`;
  746. await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
  747. const ok = await w.webContents.executeJavaScript(`fetch(${JSON.stringify(url)}).then(r => r.ok)`);
  748. expect(ok).to.be.true('response ok');
  749. });
  750. it('allows CORS requests by default', async () => {
  751. await allowsCORSRequests('cors', 200, new RegExp(''), () => {
  752. const { ipcRenderer } = require('electron');
  753. fetch('cors://myhost').then(function (response) {
  754. ipcRenderer.send('response', response.status);
  755. }).catch(function () {
  756. ipcRenderer.send('response', 'failed');
  757. });
  758. });
  759. });
  760. it('disallows CORS and fetch requests when only supportFetchAPI is specified', async () => {
  761. await allowsCORSRequests('no-cors', ['failed xhr', 'failed fetch'], /has been blocked by CORS policy/, () => {
  762. const { ipcRenderer } = require('electron');
  763. Promise.all([
  764. new Promise(resolve => {
  765. const req = new XMLHttpRequest();
  766. req.onload = () => resolve('loaded xhr');
  767. req.onerror = () => resolve('failed xhr');
  768. req.open('GET', 'no-cors://myhost');
  769. req.send();
  770. }),
  771. fetch('no-cors://myhost')
  772. .then(() => 'loaded fetch')
  773. .catch(() => 'failed fetch')
  774. ]).then(([xhr, fetch]) => {
  775. ipcRenderer.send('response', [xhr, fetch]);
  776. });
  777. });
  778. });
  779. it('allows CORS, but disallows fetch requests, when specified', async () => {
  780. await allowsCORSRequests('no-fetch', ['loaded xhr', 'failed fetch'], /Fetch API cannot load/, () => {
  781. const { ipcRenderer } = require('electron');
  782. Promise.all([
  783. new Promise(resolve => {
  784. const req = new XMLHttpRequest();
  785. req.onload = () => resolve('loaded xhr');
  786. req.onerror = () => resolve('failed xhr');
  787. req.open('GET', 'no-fetch://myhost');
  788. req.send();
  789. }),
  790. fetch('no-fetch://myhost')
  791. .then(() => 'loaded fetch')
  792. .catch(() => 'failed fetch')
  793. ]).then(([xhr, fetch]) => {
  794. ipcRenderer.send('response', [xhr, fetch]);
  795. });
  796. });
  797. });
  798. async function allowsCORSRequests (corsScheme: string, expected: any, expectedConsole: RegExp, content: Function) {
  799. registerStringProtocol(standardScheme, (request, callback) => {
  800. callback({ data: `<script>(${content})()</script>`, mimeType: 'text/html' });
  801. });
  802. registerStringProtocol(corsScheme, (request, callback) => {
  803. callback('');
  804. });
  805. const newContents: WebContents = (webContents as any).create({ nodeIntegration: true });
  806. const consoleMessages: string[] = [];
  807. newContents.on('console-message', (e, level, message) => consoleMessages.push(message));
  808. try {
  809. newContents.loadURL(standardScheme + '://fake-host');
  810. const [, response] = await emittedOnce(ipcMain, 'response');
  811. expect(response).to.deep.equal(expected);
  812. expect(consoleMessages.join('\n')).to.match(expectedConsole);
  813. } finally {
  814. // This is called in a timeout to avoid a crash that happens when
  815. // calling destroy() in a microtask.
  816. setTimeout(() => {
  817. (newContents as any).destroy();
  818. });
  819. }
  820. }
  821. });
  822. describe('protocol.registerSchemesAsPrivileged stream', async function () {
  823. const pagePath = path.join(fixturesPath, 'pages', 'video.html');
  824. const videoSourceImagePath = path.join(fixturesPath, 'video-source-image.webp');
  825. const videoPath = path.join(fixturesPath, 'video.webm');
  826. const standardScheme = (global as any).standardScheme;
  827. let w: BrowserWindow = null as unknown as BrowserWindow;
  828. before(async () => {
  829. // generate test video
  830. const imageBase64 = await fs.promises.readFile(videoSourceImagePath, 'base64');
  831. const imageDataUrl = `data:image/webp;base64,${imageBase64}`;
  832. const encoder = new WebmGenerator(15);
  833. for (let i = 0; i < 30; i++) {
  834. encoder.add(imageDataUrl);
  835. }
  836. await new Promise((resolve, reject) => {
  837. encoder.compile((output:Uint8Array) => {
  838. fs.promises.writeFile(videoPath, output).then(resolve, reject);
  839. });
  840. });
  841. });
  842. after(async () => {
  843. await fs.promises.unlink(videoPath);
  844. });
  845. beforeEach(async function () {
  846. w = new BrowserWindow({ show: false });
  847. await w.loadURL('about:blank');
  848. if (!await w.webContents.executeJavaScript('document.createElement(\'video\').canPlayType(\'video/webm; codecs="vp8.0"\')')) {
  849. this.skip();
  850. }
  851. });
  852. afterEach(async () => {
  853. await closeWindow(w);
  854. w = null as unknown as BrowserWindow;
  855. await protocol.unregisterProtocol(standardScheme);
  856. await protocol.unregisterProtocol('stream');
  857. });
  858. it('successfully plays videos when content is buffered (stream: false)', async () => {
  859. await streamsResponses(standardScheme, 'play');
  860. });
  861. it('successfully plays videos when streaming content (stream: true)', async () => {
  862. await streamsResponses('stream', 'play');
  863. });
  864. async function streamsResponses (testingScheme: string, expected: any) {
  865. const protocolHandler = (request: any, callback: Function) => {
  866. if (request.url.includes('/video.webm')) {
  867. const stat = fs.statSync(videoPath);
  868. const fileSize = stat.size;
  869. const range = request.headers.Range;
  870. if (range) {
  871. const parts = range.replace(/bytes=/, '').split('-');
  872. const start = parseInt(parts[0], 10);
  873. const end = parts[1] ? parseInt(parts[1], 10) : fileSize - 1;
  874. const chunksize = (end - start) + 1;
  875. const headers = {
  876. 'Content-Range': `bytes ${start}-${end}/${fileSize}`,
  877. 'Accept-Ranges': 'bytes',
  878. 'Content-Length': String(chunksize),
  879. 'Content-Type': 'video/webm'
  880. };
  881. callback({ statusCode: 206, headers, data: fs.createReadStream(videoPath, { start, end }) });
  882. } else {
  883. callback({
  884. statusCode: 200,
  885. headers: {
  886. 'Content-Length': String(fileSize),
  887. 'Content-Type': 'video/webm'
  888. },
  889. data: fs.createReadStream(videoPath)
  890. });
  891. }
  892. } else {
  893. callback({ data: fs.createReadStream(pagePath), headers: { 'Content-Type': 'text/html' }, statusCode: 200 });
  894. }
  895. };
  896. await registerStreamProtocol(standardScheme, protocolHandler);
  897. await registerStreamProtocol('stream', protocolHandler);
  898. const newContents: WebContents = (webContents as any).create({ nodeIntegration: true, contextIsolation: false });
  899. try {
  900. newContents.loadURL(testingScheme + '://fake-host');
  901. const [, response] = await emittedOnce(ipcMain, 'result');
  902. expect(response).to.deep.equal(expected);
  903. } finally {
  904. // This is called in a timeout to avoid a crash that happens when
  905. // calling destroy() in a microtask.
  906. setTimeout(() => {
  907. (newContents as any).destroy();
  908. });
  909. }
  910. }
  911. });
  912. });