api-protocol-spec.ts 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054
  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('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. contextIsolation: false
  708. }
  709. });
  710. });
  711. afterEach(async () => {
  712. await closeWindow(w);
  713. unregisterProtocol(standardScheme);
  714. w = null as unknown as BrowserWindow;
  715. });
  716. it('resolves relative resources', async () => {
  717. registerFileProtocol(standardScheme, (request, callback) => {
  718. if (request.url === imageURL) {
  719. callback('');
  720. } else {
  721. callback(filePath);
  722. }
  723. });
  724. await w.loadURL(origin);
  725. });
  726. it('resolves absolute resources', async () => {
  727. registerStringProtocol(standardScheme, (request, callback) => {
  728. if (request.url === imageURL) {
  729. callback('');
  730. } else {
  731. callback({
  732. data: fileContent,
  733. mimeType: 'text/html'
  734. });
  735. }
  736. });
  737. await w.loadURL(origin);
  738. });
  739. it('can have fetch working in it', async () => {
  740. const requestReceived = defer();
  741. const server = http.createServer((req, res) => {
  742. res.end();
  743. server.close();
  744. requestReceived.resolve();
  745. });
  746. await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
  747. const port = (server.address() as AddressInfo).port;
  748. const content = `<script>fetch("http://127.0.0.1:${port}")</script>`;
  749. registerStringProtocol(standardScheme, (request, callback) => callback({ data: content, mimeType: 'text/html' }));
  750. await w.loadURL(origin);
  751. await requestReceived;
  752. });
  753. it.skip('can access files through the FileSystem API', (done) => {
  754. const filePath = path.join(fixturesPath, 'pages', 'filesystem.html');
  755. protocol.registerFileProtocol(standardScheme, (request, callback) => callback({ path: filePath }));
  756. w.loadURL(origin);
  757. ipcMain.once('file-system-error', (event, err) => done(err));
  758. ipcMain.once('file-system-write-end', () => done());
  759. });
  760. it('registers secure, when {secure: true}', (done) => {
  761. const filePath = path.join(fixturesPath, 'pages', 'cache-storage.html');
  762. ipcMain.once('success', () => done());
  763. ipcMain.once('failure', (event, err) => done(err));
  764. protocol.registerFileProtocol(standardScheme, (request, callback) => callback({ path: filePath }));
  765. w.loadURL(origin);
  766. });
  767. });
  768. describe('protocol.registerSchemesAsPrivileged cors-fetch', function () {
  769. const standardScheme = (global as any).standardScheme;
  770. let w: BrowserWindow = null as unknown as BrowserWindow;
  771. beforeEach(async () => {
  772. w = new BrowserWindow({ show: false });
  773. });
  774. afterEach(async () => {
  775. await closeWindow(w);
  776. w = null as unknown as BrowserWindow;
  777. for (const scheme of [standardScheme, 'cors', 'no-cors', 'no-fetch']) {
  778. protocol.unregisterProtocol(scheme);
  779. }
  780. });
  781. it('supports fetch api by default', async () => {
  782. const url = `file://${fixturesPath}/assets/logo.png`;
  783. await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
  784. const ok = await w.webContents.executeJavaScript(`fetch(${JSON.stringify(url)}).then(r => r.ok)`);
  785. expect(ok).to.be.true('response ok');
  786. });
  787. it('allows CORS requests by default', async () => {
  788. await allowsCORSRequests('cors', 200, new RegExp(''), () => {
  789. const { ipcRenderer } = require('electron');
  790. fetch('cors://myhost').then(function (response) {
  791. ipcRenderer.send('response', response.status);
  792. }).catch(function () {
  793. ipcRenderer.send('response', 'failed');
  794. });
  795. });
  796. });
  797. // FIXME: Figure out why this test is failing
  798. it.skip('disallows CORS and fetch requests when only supportFetchAPI is specified', async () => {
  799. await allowsCORSRequests('no-cors', ['failed xhr', 'failed fetch'], /has been blocked by CORS policy/, () => {
  800. const { ipcRenderer } = require('electron');
  801. Promise.all([
  802. new Promise(resolve => {
  803. const req = new XMLHttpRequest();
  804. req.onload = () => resolve('loaded xhr');
  805. req.onerror = () => resolve('failed xhr');
  806. req.open('GET', 'no-cors://myhost');
  807. req.send();
  808. }),
  809. fetch('no-cors://myhost')
  810. .then(() => 'loaded fetch')
  811. .catch(() => 'failed fetch')
  812. ]).then(([xhr, fetch]) => {
  813. ipcRenderer.send('response', [xhr, fetch]);
  814. });
  815. });
  816. });
  817. it('allows CORS, but disallows fetch requests, when specified', async () => {
  818. await allowsCORSRequests('no-fetch', ['loaded xhr', 'failed fetch'], /Fetch API cannot load/, () => {
  819. const { ipcRenderer } = require('electron');
  820. Promise.all([
  821. new Promise(resolve => {
  822. const req = new XMLHttpRequest();
  823. req.onload = () => resolve('loaded xhr');
  824. req.onerror = () => resolve('failed xhr');
  825. req.open('GET', 'no-fetch://myhost');
  826. req.send();
  827. }),
  828. fetch('no-fetch://myhost')
  829. .then(() => 'loaded fetch')
  830. .catch(() => 'failed fetch')
  831. ]).then(([xhr, fetch]) => {
  832. ipcRenderer.send('response', [xhr, fetch]);
  833. });
  834. });
  835. });
  836. async function allowsCORSRequests (corsScheme: string, expected: any, expectedConsole: RegExp, content: Function) {
  837. registerStringProtocol(standardScheme, (request, callback) => {
  838. callback({ data: `<script>(${content})()</script>`, mimeType: 'text/html' });
  839. });
  840. registerStringProtocol(corsScheme, (request, callback) => {
  841. callback('');
  842. });
  843. const newContents: WebContents = (webContents as any).create({ nodeIntegration: true, contextIsolation: false });
  844. const consoleMessages: string[] = [];
  845. newContents.on('console-message', (e, level, message) => consoleMessages.push(message));
  846. try {
  847. newContents.loadURL(standardScheme + '://fake-host');
  848. const [, response] = await emittedOnce(ipcMain, 'response');
  849. expect(response).to.deep.equal(expected);
  850. expect(consoleMessages.join('\n')).to.match(expectedConsole);
  851. } finally {
  852. // This is called in a timeout to avoid a crash that happens when
  853. // calling destroy() in a microtask.
  854. setTimeout(() => {
  855. (newContents as any).destroy();
  856. });
  857. }
  858. }
  859. });
  860. describe('protocol.registerSchemesAsPrivileged stream', async function () {
  861. const pagePath = path.join(fixturesPath, 'pages', 'video.html');
  862. const videoSourceImagePath = path.join(fixturesPath, 'video-source-image.webp');
  863. const videoPath = path.join(fixturesPath, 'video.webm');
  864. const standardScheme = (global as any).standardScheme;
  865. let w: BrowserWindow = null as unknown as BrowserWindow;
  866. before(async () => {
  867. // generate test video
  868. const imageBase64 = await fs.promises.readFile(videoSourceImagePath, 'base64');
  869. const imageDataUrl = `data:image/webp;base64,${imageBase64}`;
  870. const encoder = new WebmGenerator(15);
  871. for (let i = 0; i < 30; i++) {
  872. encoder.add(imageDataUrl);
  873. }
  874. await new Promise((resolve, reject) => {
  875. encoder.compile((output:Uint8Array) => {
  876. fs.promises.writeFile(videoPath, output).then(resolve, reject);
  877. });
  878. });
  879. });
  880. after(async () => {
  881. await fs.promises.unlink(videoPath);
  882. });
  883. beforeEach(async function () {
  884. w = new BrowserWindow({ show: false });
  885. await w.loadURL('about:blank');
  886. if (!await w.webContents.executeJavaScript('document.createElement(\'video\').canPlayType(\'video/webm; codecs="vp8.0"\')')) {
  887. this.skip();
  888. }
  889. });
  890. afterEach(async () => {
  891. await closeWindow(w);
  892. w = null as unknown as BrowserWindow;
  893. await protocol.unregisterProtocol(standardScheme);
  894. await protocol.unregisterProtocol('stream');
  895. });
  896. it('successfully plays videos when content is buffered (stream: false)', async () => {
  897. await streamsResponses(standardScheme, 'play');
  898. });
  899. it('successfully plays videos when streaming content (stream: true)', async () => {
  900. await streamsResponses('stream', 'play');
  901. });
  902. async function streamsResponses (testingScheme: string, expected: any) {
  903. const protocolHandler = (request: any, callback: Function) => {
  904. if (request.url.includes('/video.webm')) {
  905. const stat = fs.statSync(videoPath);
  906. const fileSize = stat.size;
  907. const range = request.headers.Range;
  908. if (range) {
  909. const parts = range.replace(/bytes=/, '').split('-');
  910. const start = parseInt(parts[0], 10);
  911. const end = parts[1] ? parseInt(parts[1], 10) : fileSize - 1;
  912. const chunksize = (end - start) + 1;
  913. const headers = {
  914. 'Content-Range': `bytes ${start}-${end}/${fileSize}`,
  915. 'Accept-Ranges': 'bytes',
  916. 'Content-Length': String(chunksize),
  917. 'Content-Type': 'video/webm'
  918. };
  919. callback({ statusCode: 206, headers, data: fs.createReadStream(videoPath, { start, end }) });
  920. } else {
  921. callback({
  922. statusCode: 200,
  923. headers: {
  924. 'Content-Length': String(fileSize),
  925. 'Content-Type': 'video/webm'
  926. },
  927. data: fs.createReadStream(videoPath)
  928. });
  929. }
  930. } else {
  931. callback({ data: fs.createReadStream(pagePath), headers: { 'Content-Type': 'text/html' }, statusCode: 200 });
  932. }
  933. };
  934. await registerStreamProtocol(standardScheme, protocolHandler);
  935. await registerStreamProtocol('stream', protocolHandler);
  936. const newContents: WebContents = (webContents as any).create({ nodeIntegration: true, contextIsolation: false });
  937. try {
  938. newContents.loadURL(testingScheme + '://fake-host');
  939. const [, response] = await emittedOnce(ipcMain, 'result');
  940. expect(response).to.deep.equal(expected);
  941. } finally {
  942. // This is called in a timeout to avoid a crash that happens when
  943. // calling destroy() in a microtask.
  944. setTimeout(() => {
  945. (newContents as any).destroy();
  946. });
  947. }
  948. }
  949. });
  950. });