api-protocol-spec.ts 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579
  1. import { expect } from 'chai';
  2. import { v4 } from 'uuid';
  3. import { protocol, webContents, WebContents, session, BrowserWindow, ipcMain, net } from 'electron/main';
  4. import * as ChildProcess from 'child_process';
  5. import * as path from 'path';
  6. import * as url from 'url';
  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, once } from 'events';
  12. import { closeAllWindows, closeWindow } from './lib/window-helpers';
  13. import { WebmGenerator } from './lib/video-helpers';
  14. import { listen, defer, ifit } from './lib/spec-helpers';
  15. import { setTimeout } from 'timers/promises';
  16. const fixturesPath = path.resolve(__dirname, 'fixtures');
  17. const registerStringProtocol = protocol.registerStringProtocol;
  18. const registerBufferProtocol = protocol.registerBufferProtocol;
  19. const registerFileProtocol = protocol.registerFileProtocol;
  20. const registerStreamProtocol = protocol.registerStreamProtocol;
  21. const interceptStringProtocol = protocol.interceptStringProtocol;
  22. const interceptBufferProtocol = protocol.interceptBufferProtocol;
  23. const interceptHttpProtocol = protocol.interceptHttpProtocol;
  24. const interceptStreamProtocol = protocol.interceptStreamProtocol;
  25. const unregisterProtocol = protocol.unregisterProtocol;
  26. const uninterceptProtocol = protocol.uninterceptProtocol;
  27. const text = 'valar morghulis';
  28. const protocolName = 'no-cors';
  29. const postData = {
  30. name: 'post test',
  31. type: 'string'
  32. };
  33. function getStream (chunkSize = text.length, data: Buffer | string = text) {
  34. // allowHalfOpen required, otherwise Readable.toWeb gets confused and thinks
  35. // the stream isn't done when the readable half ends.
  36. const body = new stream.PassThrough({ allowHalfOpen: false });
  37. async function sendChunks () {
  38. await setTimeout(0); // the stream protocol API breaks if you send data immediately.
  39. let buf = Buffer.from(data as any); // nodejs typings are wrong, Buffer.from can take a Buffer
  40. for (;;) {
  41. body.push(buf.slice(0, chunkSize));
  42. buf = buf.slice(chunkSize);
  43. if (!buf.length) {
  44. break;
  45. }
  46. // emulate some network delay
  47. await setTimeout(10);
  48. }
  49. body.push(null);
  50. }
  51. sendChunks();
  52. return body;
  53. }
  54. function getWebStream (chunkSize = text.length, data: Buffer | string = text): ReadableStream<ArrayBufferView> {
  55. return stream.Readable.toWeb(getStream(chunkSize, data)) as ReadableStream<ArrayBufferView>;
  56. }
  57. // A promise that can be resolved externally.
  58. function deferPromise (): Promise<any> & {resolve: Function, reject: Function} {
  59. let promiseResolve: Function = null as unknown as Function;
  60. let promiseReject: Function = null as unknown as Function;
  61. const promise: any = new Promise((resolve, reject) => {
  62. promiseResolve = resolve;
  63. promiseReject = reject;
  64. });
  65. promise.resolve = promiseResolve;
  66. promise.reject = promiseReject;
  67. return promise;
  68. }
  69. describe('protocol module', () => {
  70. let contents: WebContents;
  71. // NB. sandbox: true is used because it makes navigations much (~8x) faster.
  72. before(() => { contents = (webContents as typeof ElectronInternal.WebContents).create({ sandbox: true }); });
  73. after(() => contents.destroy());
  74. async function ajax (url: string, options = {}) {
  75. // Note that we need to do navigation every time after a protocol is
  76. // registered or unregistered, otherwise the new protocol won't be
  77. // recognized by current page when NetworkService is used.
  78. await contents.loadFile(path.join(__dirname, 'fixtures', 'pages', 'fetch.html'));
  79. return contents.executeJavaScript(`ajax("${url}", ${JSON.stringify(options)})`);
  80. }
  81. afterEach(() => {
  82. protocol.unregisterProtocol(protocolName);
  83. protocol.uninterceptProtocol('http');
  84. });
  85. describe('protocol.register(Any)Protocol', () => {
  86. it('fails when scheme is already registered', () => {
  87. expect(registerStringProtocol(protocolName, (req, cb) => cb(''))).to.equal(true);
  88. expect(registerBufferProtocol(protocolName, (req, cb) => cb(Buffer.from('')))).to.equal(false);
  89. });
  90. it('does not crash when handler is called twice', async () => {
  91. registerStringProtocol(protocolName, (request, callback) => {
  92. try {
  93. callback(text);
  94. callback('');
  95. } catch (error) {
  96. // Ignore error
  97. }
  98. });
  99. const r = await ajax(protocolName + '://fake-host');
  100. expect(r.data).to.equal(text);
  101. });
  102. it('sends error when callback is called with nothing', async () => {
  103. registerBufferProtocol(protocolName, (req, cb: any) => cb());
  104. await expect(ajax(protocolName + '://fake-host')).to.eventually.be.rejected();
  105. });
  106. it('does not crash when callback is called in next tick', async () => {
  107. registerStringProtocol(protocolName, (request, callback) => {
  108. setImmediate(() => callback(text));
  109. });
  110. const r = await ajax(protocolName + '://fake-host');
  111. expect(r.data).to.equal(text);
  112. });
  113. it('can redirect to the same scheme', async () => {
  114. registerStringProtocol(protocolName, (request, callback) => {
  115. if (request.url === `${protocolName}://fake-host/redirect`) {
  116. callback({
  117. statusCode: 302,
  118. headers: {
  119. Location: `${protocolName}://fake-host`
  120. }
  121. });
  122. } else {
  123. expect(request.url).to.equal(`${protocolName}://fake-host`);
  124. callback('redirected');
  125. }
  126. });
  127. const r = await ajax(`${protocolName}://fake-host/redirect`);
  128. expect(r.data).to.equal('redirected');
  129. });
  130. });
  131. describe('protocol.unregisterProtocol', () => {
  132. it('returns false when scheme does not exist', () => {
  133. expect(unregisterProtocol('not-exist')).to.equal(false);
  134. });
  135. });
  136. for (const [registerStringProtocol, name] of [
  137. [protocol.registerStringProtocol, 'protocol.registerStringProtocol'] as const,
  138. [(protocol as any).registerProtocol as typeof protocol.registerStringProtocol, 'protocol.registerProtocol'] as const
  139. ]) {
  140. describe(name, () => {
  141. it('sends string as response', async () => {
  142. registerStringProtocol(protocolName, (request, callback) => callback(text));
  143. const r = await ajax(protocolName + '://fake-host');
  144. expect(r.data).to.equal(text);
  145. });
  146. it('sets Access-Control-Allow-Origin', async () => {
  147. registerStringProtocol(protocolName, (request, callback) => callback(text));
  148. const r = await ajax(protocolName + '://fake-host');
  149. expect(r.data).to.equal(text);
  150. expect(r.headers).to.have.property('access-control-allow-origin', '*');
  151. });
  152. it('sends object as response', async () => {
  153. registerStringProtocol(protocolName, (request, callback) => {
  154. callback({
  155. data: text,
  156. mimeType: 'text/html'
  157. });
  158. });
  159. const r = await ajax(protocolName + '://fake-host');
  160. expect(r.data).to.equal(text);
  161. });
  162. it('fails when sending object other than string', async () => {
  163. const notAString = () => {};
  164. registerStringProtocol(protocolName, (request, callback) => callback(notAString as any));
  165. await expect(ajax(protocolName + '://fake-host')).to.be.eventually.rejected();
  166. });
  167. });
  168. }
  169. for (const [registerBufferProtocol, name] of [
  170. [protocol.registerBufferProtocol, 'protocol.registerBufferProtocol'] as const,
  171. [(protocol as any).registerProtocol as typeof protocol.registerBufferProtocol, 'protocol.registerProtocol'] as const
  172. ]) {
  173. describe(name, () => {
  174. const buffer = Buffer.from(text);
  175. it('sends Buffer as response', async () => {
  176. registerBufferProtocol(protocolName, (request, callback) => callback(buffer));
  177. const r = await ajax(protocolName + '://fake-host');
  178. expect(r.data).to.equal(text);
  179. });
  180. it('sets Access-Control-Allow-Origin', async () => {
  181. registerBufferProtocol(protocolName, (request, callback) => callback(buffer));
  182. const r = await ajax(protocolName + '://fake-host');
  183. expect(r.data).to.equal(text);
  184. expect(r.headers).to.have.property('access-control-allow-origin', '*');
  185. });
  186. it('sends object as response', async () => {
  187. registerBufferProtocol(protocolName, (request, callback) => {
  188. callback({
  189. data: buffer,
  190. mimeType: 'text/html'
  191. });
  192. });
  193. const r = await ajax(protocolName + '://fake-host');
  194. expect(r.data).to.equal(text);
  195. });
  196. if (name !== 'protocol.registerProtocol') {
  197. it('fails when sending string', async () => {
  198. registerBufferProtocol(protocolName, (request, callback) => callback(text as any));
  199. await expect(ajax(protocolName + '://fake-host')).to.be.eventually.rejected();
  200. });
  201. }
  202. });
  203. }
  204. for (const [registerFileProtocol, name] of [
  205. [protocol.registerFileProtocol, 'protocol.registerFileProtocol'] as const,
  206. [(protocol as any).registerProtocol as typeof protocol.registerFileProtocol, 'protocol.registerProtocol'] as const
  207. ]) {
  208. describe(name, () => {
  209. const filePath = path.join(fixturesPath, 'test.asar', 'a.asar', 'file1');
  210. const fileContent = fs.readFileSync(filePath);
  211. const normalPath = path.join(fixturesPath, 'pages', 'a.html');
  212. const normalContent = fs.readFileSync(normalPath);
  213. afterEach(closeAllWindows);
  214. if (name === 'protocol.registerFileProtocol') {
  215. it('sends file path as response', async () => {
  216. registerFileProtocol(protocolName, (request, callback) => callback(filePath));
  217. const r = await ajax(protocolName + '://fake-host');
  218. expect(r.data).to.equal(String(fileContent));
  219. });
  220. }
  221. it('sets Access-Control-Allow-Origin', async () => {
  222. registerFileProtocol(protocolName, (request, callback) => callback({ path: filePath }));
  223. const r = await ajax(protocolName + '://fake-host');
  224. expect(r.data).to.equal(String(fileContent));
  225. expect(r.headers).to.have.property('access-control-allow-origin', '*');
  226. });
  227. it('sets custom headers', async () => {
  228. registerFileProtocol(protocolName, (request, callback) => callback({
  229. path: filePath,
  230. headers: { 'X-Great-Header': 'sogreat' }
  231. }));
  232. const r = await ajax(protocolName + '://fake-host');
  233. expect(r.data).to.equal(String(fileContent));
  234. expect(r.headers).to.have.property('x-great-header', 'sogreat');
  235. });
  236. it('can load iframes with custom protocols', (done) => {
  237. registerFileProtocol('custom', (request, callback) => {
  238. const filename = request.url.substring(9);
  239. const p = path.join(__dirname, 'fixtures', 'pages', filename);
  240. callback({ path: p });
  241. });
  242. const w = new BrowserWindow({
  243. show: false,
  244. webPreferences: {
  245. nodeIntegration: true,
  246. contextIsolation: false
  247. }
  248. });
  249. w.loadFile(path.join(__dirname, 'fixtures', 'pages', 'iframe-protocol.html'));
  250. ipcMain.once('loaded-iframe-custom-protocol', () => done());
  251. });
  252. // DISABLED-FIXME
  253. it('throws an error when custom headers are invalid', (done) => {
  254. registerFileProtocol(protocolName, (request, callback) => {
  255. expect(() => callback({
  256. path: filePath,
  257. headers: { 'X-Great-Header': (42 as any) }
  258. })).to.throw(Error, 'Value of \'X-Great-Header\' header has to be a string');
  259. done();
  260. });
  261. ajax(protocolName + '://fake-host').catch(() => {});
  262. });
  263. it('sends object as response', async () => {
  264. registerFileProtocol(protocolName, (request, callback) => callback({ path: filePath }));
  265. const r = await ajax(protocolName + '://fake-host');
  266. expect(r.data).to.equal(String(fileContent));
  267. });
  268. it('can send normal file', async () => {
  269. registerFileProtocol(protocolName, (request, callback) => callback({ path: normalPath }));
  270. const r = await ajax(protocolName + '://fake-host');
  271. expect(r.data).to.equal(String(normalContent));
  272. });
  273. it('fails when sending unexist-file', async () => {
  274. const fakeFilePath = path.join(fixturesPath, 'test.asar', 'a.asar', 'not-exist');
  275. registerFileProtocol(protocolName, (request, callback) => callback({ path: fakeFilePath }));
  276. await expect(ajax(protocolName + '://fake-host')).to.be.eventually.rejected();
  277. });
  278. it('fails when sending unsupported content', async () => {
  279. registerFileProtocol(protocolName, (request, callback) => callback(new Date() as any));
  280. await expect(ajax(protocolName + '://fake-host')).to.be.eventually.rejected();
  281. });
  282. });
  283. }
  284. for (const [registerHttpProtocol, name] of [
  285. [protocol.registerHttpProtocol, 'protocol.registerHttpProtocol'] as const,
  286. [(protocol as any).registerProtocol as typeof protocol.registerHttpProtocol, 'protocol.registerProtocol'] as const
  287. ]) {
  288. describe(name, () => {
  289. it('sends url as response', async () => {
  290. const server = http.createServer((req, res) => {
  291. expect(req.headers.accept).to.not.equal('');
  292. res.end(text);
  293. server.close();
  294. });
  295. const { url } = await listen(server);
  296. registerHttpProtocol(protocolName, (request, callback) => callback({ url }));
  297. const r = await ajax(protocolName + '://fake-host');
  298. expect(r.data).to.equal(text);
  299. });
  300. it('fails when sending invalid url', async () => {
  301. registerHttpProtocol(protocolName, (request, callback) => callback({ url: 'url' }));
  302. await expect(ajax(protocolName + '://fake-host')).to.be.eventually.rejected();
  303. });
  304. it('fails when sending unsupported content', async () => {
  305. registerHttpProtocol(protocolName, (request, callback) => callback(new Date() as any));
  306. await expect(ajax(protocolName + '://fake-host')).to.be.eventually.rejected();
  307. });
  308. it('works when target URL redirects', async () => {
  309. const server = http.createServer((req, res) => {
  310. if (req.url === '/serverRedirect') {
  311. res.statusCode = 301;
  312. res.setHeader('Location', `http://${req.rawHeaders[1]}`);
  313. res.end();
  314. } else {
  315. res.end(text);
  316. }
  317. });
  318. after(() => server.close());
  319. const { port } = await listen(server);
  320. const url = `${protocolName}://fake-host`;
  321. const redirectURL = `http://127.0.0.1:${port}/serverRedirect`;
  322. registerHttpProtocol(protocolName, (request, callback) => callback({ url: redirectURL }));
  323. const r = await ajax(url);
  324. expect(r.data).to.equal(text);
  325. });
  326. it('can access request headers', (done) => {
  327. protocol.registerHttpProtocol(protocolName, (request) => {
  328. try {
  329. expect(request).to.have.property('headers');
  330. done();
  331. } catch (e) {
  332. done(e);
  333. }
  334. });
  335. ajax(protocolName + '://fake-host').catch(() => {});
  336. });
  337. });
  338. }
  339. for (const [registerStreamProtocol, name] of [
  340. [protocol.registerStreamProtocol, 'protocol.registerStreamProtocol'] as const,
  341. [(protocol as any).registerProtocol as typeof protocol.registerStreamProtocol, 'protocol.registerProtocol'] as const
  342. ]) {
  343. describe(name, () => {
  344. it('sends Stream as response', async () => {
  345. registerStreamProtocol(protocolName, (request, callback) => callback(getStream()));
  346. const r = await ajax(protocolName + '://fake-host');
  347. expect(r.data).to.equal(text);
  348. });
  349. it('sends object as response', async () => {
  350. registerStreamProtocol(protocolName, (request, callback) => callback({ data: getStream() }));
  351. const r = await ajax(protocolName + '://fake-host');
  352. expect(r.data).to.equal(text);
  353. expect(r.status).to.equal(200);
  354. });
  355. it('sends custom response headers', async () => {
  356. registerStreamProtocol(protocolName, (request, callback) => callback({
  357. data: getStream(3),
  358. headers: {
  359. 'x-electron': ['a', 'b']
  360. }
  361. }));
  362. const r = await ajax(protocolName + '://fake-host');
  363. expect(r.data).to.equal(text);
  364. expect(r.status).to.equal(200);
  365. expect(r.headers).to.have.property('x-electron', 'a, b');
  366. });
  367. it('sends custom status code', async () => {
  368. registerStreamProtocol(protocolName, (request, callback) => callback({
  369. statusCode: 204,
  370. data: null as any
  371. }));
  372. const r = await ajax(protocolName + '://fake-host');
  373. expect(r.data).to.be.empty('data');
  374. expect(r.status).to.equal(204);
  375. });
  376. it('receives request headers', async () => {
  377. registerStreamProtocol(protocolName, (request, callback) => {
  378. callback({
  379. headers: {
  380. 'content-type': 'application/json'
  381. },
  382. data: getStream(5, JSON.stringify(Object.assign({}, request.headers)))
  383. });
  384. });
  385. const r = await ajax(protocolName + '://fake-host', { headers: { 'x-return-headers': 'yes' } });
  386. expect(JSON.parse(r.data)['x-return-headers']).to.equal('yes');
  387. });
  388. it('returns response multiple response headers with the same name', async () => {
  389. registerStreamProtocol(protocolName, (request, callback) => {
  390. callback({
  391. headers: {
  392. header1: ['value1', 'value2'],
  393. header2: 'value3'
  394. },
  395. data: getStream()
  396. });
  397. });
  398. const r = await ajax(protocolName + '://fake-host');
  399. // SUBTLE: when the response headers have multiple values it
  400. // separates values by ", ". When the response headers are incorrectly
  401. // converting an array to a string it separates values by ",".
  402. expect(r.headers).to.have.property('header1', 'value1, value2');
  403. expect(r.headers).to.have.property('header2', 'value3');
  404. });
  405. it('can handle large responses', async () => {
  406. const data = Buffer.alloc(128 * 1024);
  407. registerStreamProtocol(protocolName, (request, callback) => {
  408. callback(getStream(data.length, data));
  409. });
  410. const r = await ajax(protocolName + '://fake-host');
  411. expect(r.data).to.have.lengthOf(data.length);
  412. });
  413. it('can handle a stream completing while writing', async () => {
  414. function dumbPassthrough () {
  415. return new stream.Transform({
  416. async transform (chunk, encoding, cb) {
  417. cb(null, chunk);
  418. }
  419. });
  420. }
  421. registerStreamProtocol(protocolName, (request, callback) => {
  422. callback({
  423. statusCode: 200,
  424. headers: { 'Content-Type': 'text/plain' },
  425. data: getStream(1024 * 1024, Buffer.alloc(1024 * 1024 * 2)).pipe(dumbPassthrough())
  426. });
  427. });
  428. const r = await ajax(protocolName + '://fake-host');
  429. expect(r.data).to.have.lengthOf(1024 * 1024 * 2);
  430. });
  431. it('can handle next-tick scheduling during read calls', async () => {
  432. const events = new EventEmitter();
  433. function createStream () {
  434. const buffers = [
  435. Buffer.alloc(65536),
  436. Buffer.alloc(65537),
  437. Buffer.alloc(39156)
  438. ];
  439. const e = new stream.Readable({ highWaterMark: 0 });
  440. e.push(buffers.shift());
  441. e._read = function () {
  442. process.nextTick(() => this.push(buffers.shift() || null));
  443. };
  444. e.on('end', function () {
  445. events.emit('end');
  446. });
  447. return e;
  448. }
  449. registerStreamProtocol(protocolName, (request, callback) => {
  450. callback({
  451. statusCode: 200,
  452. headers: { 'Content-Type': 'text/plain' },
  453. data: createStream()
  454. });
  455. });
  456. const hasEndedPromise = once(events, 'end');
  457. ajax(protocolName + '://fake-host').catch(() => {});
  458. await hasEndedPromise;
  459. });
  460. it('destroys response streams when aborted before completion', async () => {
  461. const events = new EventEmitter();
  462. registerStreamProtocol(protocolName, (request, callback) => {
  463. const responseStream = new stream.PassThrough();
  464. responseStream.push('data\r\n');
  465. responseStream.on('close', () => {
  466. events.emit('close');
  467. });
  468. callback({
  469. statusCode: 200,
  470. headers: { 'Content-Type': 'text/plain' },
  471. data: responseStream
  472. });
  473. events.emit('respond');
  474. });
  475. const hasRespondedPromise = once(events, 'respond');
  476. const hasClosedPromise = once(events, 'close');
  477. ajax(protocolName + '://fake-host').catch(() => {});
  478. await hasRespondedPromise;
  479. await contents.loadFile(path.join(__dirname, 'fixtures', 'pages', 'fetch.html'));
  480. await hasClosedPromise;
  481. });
  482. });
  483. }
  484. describe('protocol.isProtocolRegistered', () => {
  485. it('returns false when scheme is not registered', () => {
  486. const result = protocol.isProtocolRegistered('no-exist');
  487. expect(result).to.be.false('no-exist: is handled');
  488. });
  489. it('returns true for custom protocol', () => {
  490. registerStringProtocol(protocolName, (request, callback) => callback(''));
  491. const result = protocol.isProtocolRegistered(protocolName);
  492. expect(result).to.be.true('custom protocol is handled');
  493. });
  494. });
  495. describe('protocol.isProtocolIntercepted', () => {
  496. it('returns true for intercepted protocol', () => {
  497. interceptStringProtocol('http', (request, callback) => callback(''));
  498. const result = protocol.isProtocolIntercepted('http');
  499. expect(result).to.be.true('intercepted protocol is handled');
  500. });
  501. });
  502. describe('protocol.intercept(Any)Protocol', () => {
  503. it('returns false when scheme is already intercepted', () => {
  504. expect(protocol.interceptStringProtocol('http', (request, callback) => callback(''))).to.equal(true);
  505. expect(protocol.interceptBufferProtocol('http', (request, callback) => callback(Buffer.from('')))).to.equal(false);
  506. });
  507. it('does not crash when handler is called twice', async () => {
  508. interceptStringProtocol('http', (request, callback) => {
  509. try {
  510. callback(text);
  511. callback('');
  512. } catch (error) {
  513. // Ignore error
  514. }
  515. });
  516. const r = await ajax('http://fake-host');
  517. expect(r.data).to.be.equal(text);
  518. });
  519. it('sends error when callback is called with nothing', async () => {
  520. interceptStringProtocol('http', (request, callback: any) => callback());
  521. await expect(ajax('http://fake-host')).to.be.eventually.rejected();
  522. });
  523. });
  524. describe('protocol.interceptStringProtocol', () => {
  525. it('can intercept http protocol', async () => {
  526. interceptStringProtocol('http', (request, callback) => callback(text));
  527. const r = await ajax('http://fake-host');
  528. expect(r.data).to.equal(text);
  529. });
  530. it('can set content-type', async () => {
  531. interceptStringProtocol('http', (request, callback) => {
  532. callback({
  533. mimeType: 'application/json',
  534. data: '{"value": 1}'
  535. });
  536. });
  537. const r = await ajax('http://fake-host');
  538. expect(JSON.parse(r.data)).to.have.property('value').that.is.equal(1);
  539. });
  540. it('can set content-type with charset', async () => {
  541. interceptStringProtocol('http', (request, callback) => {
  542. callback({
  543. mimeType: 'application/json; charset=UTF-8',
  544. data: '{"value": 1}'
  545. });
  546. });
  547. const r = await ajax('http://fake-host');
  548. expect(JSON.parse(r.data)).to.have.property('value').that.is.equal(1);
  549. });
  550. it('can receive post data', async () => {
  551. interceptStringProtocol('http', (request, callback) => {
  552. const uploadData = request.uploadData![0].bytes.toString();
  553. callback({ data: uploadData });
  554. });
  555. const r = await ajax('http://fake-host', { method: 'POST', body: qs.stringify(postData) });
  556. expect({ ...qs.parse(r.data) }).to.deep.equal(postData);
  557. });
  558. });
  559. describe('protocol.interceptBufferProtocol', () => {
  560. it('can intercept http protocol', async () => {
  561. interceptBufferProtocol('http', (request, callback) => callback(Buffer.from(text)));
  562. const r = await ajax('http://fake-host');
  563. expect(r.data).to.equal(text);
  564. });
  565. it('can receive post data', async () => {
  566. interceptBufferProtocol('http', (request, callback) => {
  567. const uploadData = request.uploadData![0].bytes;
  568. callback(uploadData);
  569. });
  570. const r = await ajax('http://fake-host', { method: 'POST', body: qs.stringify(postData) });
  571. expect(qs.parse(r.data)).to.deep.equal({ name: 'post test', type: 'string' });
  572. });
  573. });
  574. describe('protocol.interceptHttpProtocol', () => {
  575. // FIXME(zcbenz): This test was passing because the test itself was wrong,
  576. // I don't know whether it ever passed before and we should take a look at
  577. // it in future.
  578. xit('can send POST request', async () => {
  579. const server = http.createServer((req, res) => {
  580. let body = '';
  581. req.on('data', (chunk) => {
  582. body += chunk;
  583. });
  584. req.on('end', () => {
  585. res.end(body);
  586. });
  587. server.close();
  588. });
  589. after(() => server.close());
  590. const { url } = await listen(server);
  591. interceptHttpProtocol('http', (request, callback) => {
  592. const data: Electron.ProtocolResponse = {
  593. url: url,
  594. method: 'POST',
  595. uploadData: {
  596. contentType: 'application/x-www-form-urlencoded',
  597. data: request.uploadData![0].bytes
  598. },
  599. session: undefined
  600. };
  601. callback(data);
  602. });
  603. const r = await ajax('http://fake-host', { type: 'POST', data: postData });
  604. expect({ ...qs.parse(r.data) }).to.deep.equal(postData);
  605. });
  606. it('can use custom session', async () => {
  607. const customSession = session.fromPartition('custom-ses', { cache: false });
  608. customSession.webRequest.onBeforeRequest((details, callback) => {
  609. expect(details.url).to.equal('http://fake-host/');
  610. callback({ cancel: true });
  611. });
  612. after(() => customSession.webRequest.onBeforeRequest(null));
  613. interceptHttpProtocol('http', (request, callback) => {
  614. callback({
  615. url: request.url,
  616. session: customSession
  617. });
  618. });
  619. await expect(ajax('http://fake-host')).to.be.eventually.rejectedWith(Error);
  620. });
  621. it('can access request headers', (done) => {
  622. protocol.interceptHttpProtocol('http', (request) => {
  623. try {
  624. expect(request).to.have.property('headers');
  625. done();
  626. } catch (e) {
  627. done(e);
  628. }
  629. });
  630. ajax('http://fake-host').catch(() => {});
  631. });
  632. });
  633. describe('protocol.interceptStreamProtocol', () => {
  634. it('can intercept http protocol', async () => {
  635. interceptStreamProtocol('http', (request, callback) => callback(getStream()));
  636. const r = await ajax('http://fake-host');
  637. expect(r.data).to.equal(text);
  638. });
  639. it('can receive post data', async () => {
  640. interceptStreamProtocol('http', (request, callback) => {
  641. callback(getStream(3, request.uploadData![0].bytes.toString()));
  642. });
  643. const r = await ajax('http://fake-host', { method: 'POST', body: qs.stringify(postData) });
  644. expect({ ...qs.parse(r.data) }).to.deep.equal(postData);
  645. });
  646. it('can execute redirects', async () => {
  647. interceptStreamProtocol('http', (request, callback) => {
  648. if (request.url.indexOf('http://fake-host') === 0) {
  649. setTimeout(300).then(() => {
  650. callback({
  651. data: '',
  652. statusCode: 302,
  653. headers: {
  654. Location: 'http://fake-redirect'
  655. }
  656. });
  657. });
  658. } else {
  659. expect(request.url.indexOf('http://fake-redirect')).to.equal(0);
  660. callback(getStream(1, 'redirect'));
  661. }
  662. });
  663. const r = await ajax('http://fake-host');
  664. expect(r.data).to.equal('redirect');
  665. });
  666. it('should discard post data after redirection', async () => {
  667. interceptStreamProtocol('http', (request, callback) => {
  668. if (request.url.indexOf('http://fake-host') === 0) {
  669. setTimeout(300).then(() => {
  670. callback({
  671. statusCode: 302,
  672. headers: {
  673. Location: 'http://fake-redirect'
  674. }
  675. });
  676. });
  677. } else {
  678. expect(request.url.indexOf('http://fake-redirect')).to.equal(0);
  679. callback(getStream(3, request.method));
  680. }
  681. });
  682. const r = await ajax('http://fake-host', { type: 'POST', data: postData });
  683. expect(r.data).to.equal('GET');
  684. });
  685. });
  686. describe('protocol.uninterceptProtocol', () => {
  687. it('returns false when scheme does not exist', () => {
  688. expect(uninterceptProtocol('not-exist')).to.equal(false);
  689. });
  690. it('returns false when scheme is not intercepted', () => {
  691. expect(uninterceptProtocol('http')).to.equal(false);
  692. });
  693. });
  694. describe('protocol.registerSchemeAsPrivileged', () => {
  695. it('does not crash on exit', async () => {
  696. const appPath = path.join(__dirname, 'fixtures', 'api', 'custom-protocol-shutdown.js');
  697. const appProcess = ChildProcess.spawn(process.execPath, ['--enable-logging', appPath]);
  698. let stdout = '';
  699. let stderr = '';
  700. appProcess.stdout.on('data', data => { process.stdout.write(data); stdout += data; });
  701. appProcess.stderr.on('data', data => { process.stderr.write(data); stderr += data; });
  702. const [code] = await once(appProcess, 'exit');
  703. if (code !== 0) {
  704. console.log('Exit code : ', code);
  705. console.log('stdout : ', stdout);
  706. console.log('stderr : ', stderr);
  707. }
  708. expect(code).to.equal(0);
  709. expect(stdout).to.not.contain('VALIDATION_ERROR_DESERIALIZATION_FAILED');
  710. expect(stderr).to.not.contain('VALIDATION_ERROR_DESERIALIZATION_FAILED');
  711. });
  712. });
  713. describe('protocol.registerSchemesAsPrivileged allowServiceWorkers', () => {
  714. protocol.registerStringProtocol(serviceWorkerScheme, (request, cb) => {
  715. if (request.url.endsWith('.js')) {
  716. cb({
  717. mimeType: 'text/javascript',
  718. charset: 'utf-8',
  719. data: 'console.log("Loaded")'
  720. });
  721. } else {
  722. cb({
  723. mimeType: 'text/html',
  724. charset: 'utf-8',
  725. data: '<!DOCTYPE html>'
  726. });
  727. }
  728. });
  729. after(() => protocol.unregisterProtocol(serviceWorkerScheme));
  730. it('should fail when registering invalid service worker', async () => {
  731. await contents.loadURL(`${serviceWorkerScheme}://${v4()}.com`);
  732. await expect(contents.executeJavaScript(`navigator.serviceWorker.register('${v4()}.notjs', {scope: './'})`)).to.be.rejected();
  733. });
  734. it('should be able to register service worker for custom scheme', async () => {
  735. await contents.loadURL(`${serviceWorkerScheme}://${v4()}.com`);
  736. await contents.executeJavaScript(`navigator.serviceWorker.register('${v4()}.js', {scope: './'})`);
  737. });
  738. });
  739. describe('protocol.registerSchemesAsPrivileged standard', () => {
  740. const origin = `${standardScheme}://fake-host`;
  741. const imageURL = `${origin}/test.png`;
  742. const filePath = path.join(fixturesPath, 'pages', 'b.html');
  743. const fileContent = '<img src="/test.png" />';
  744. let w: BrowserWindow;
  745. beforeEach(() => {
  746. w = new BrowserWindow({
  747. show: false,
  748. webPreferences: {
  749. nodeIntegration: true,
  750. contextIsolation: false
  751. }
  752. });
  753. });
  754. afterEach(async () => {
  755. await closeWindow(w);
  756. unregisterProtocol(standardScheme);
  757. w = null as unknown as BrowserWindow;
  758. });
  759. it('resolves relative resources', async () => {
  760. registerFileProtocol(standardScheme, (request, callback) => {
  761. if (request.url === imageURL) {
  762. callback('');
  763. } else {
  764. callback(filePath);
  765. }
  766. });
  767. await w.loadURL(origin);
  768. });
  769. it('resolves absolute resources', async () => {
  770. registerStringProtocol(standardScheme, (request, callback) => {
  771. if (request.url === imageURL) {
  772. callback('');
  773. } else {
  774. callback({
  775. data: fileContent,
  776. mimeType: 'text/html'
  777. });
  778. }
  779. });
  780. await w.loadURL(origin);
  781. });
  782. it('can have fetch working in it', async () => {
  783. const requestReceived = deferPromise();
  784. const server = http.createServer((req, res) => {
  785. res.end();
  786. server.close();
  787. requestReceived.resolve();
  788. });
  789. const { url } = await listen(server);
  790. const content = `<script>fetch(${JSON.stringify(url)})</script>`;
  791. registerStringProtocol(standardScheme, (request, callback) => callback({ data: content, mimeType: 'text/html' }));
  792. await w.loadURL(origin);
  793. await requestReceived;
  794. });
  795. // DISABLED-FIXME
  796. it('can access files through the FileSystem API', (done) => {
  797. const filePath = path.join(fixturesPath, 'pages', 'filesystem.html');
  798. protocol.registerFileProtocol(standardScheme, (request, callback) => callback({ path: filePath }));
  799. w.loadURL(origin);
  800. ipcMain.once('file-system-error', (event, err) => done(err));
  801. ipcMain.once('file-system-write-end', () => done());
  802. });
  803. it('registers secure, when {secure: true}', (done) => {
  804. const filePath = path.join(fixturesPath, 'pages', 'cache-storage.html');
  805. ipcMain.once('success', () => done());
  806. ipcMain.once('failure', (event, err) => done(err));
  807. protocol.registerFileProtocol(standardScheme, (request, callback) => callback({ path: filePath }));
  808. w.loadURL(origin);
  809. });
  810. });
  811. describe('protocol.registerSchemesAsPrivileged cors-fetch', function () {
  812. let w: BrowserWindow;
  813. beforeEach(async () => {
  814. w = new BrowserWindow({ show: false });
  815. });
  816. afterEach(async () => {
  817. await closeWindow(w);
  818. w = null as unknown as BrowserWindow;
  819. for (const scheme of [standardScheme, 'cors', 'no-cors', 'no-fetch']) {
  820. protocol.unregisterProtocol(scheme);
  821. }
  822. });
  823. it('supports fetch api by default', async () => {
  824. const url = `file://${fixturesPath}/assets/logo.png`;
  825. await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
  826. const ok = await w.webContents.executeJavaScript(`fetch(${JSON.stringify(url)}).then(r => r.ok)`);
  827. expect(ok).to.be.true('response ok');
  828. });
  829. it('allows CORS requests by default', async () => {
  830. await allowsCORSRequests('cors', 200, new RegExp(''), () => {
  831. const { ipcRenderer } = require('electron');
  832. fetch('cors://myhost').then(function (response) {
  833. ipcRenderer.send('response', response.status);
  834. }).catch(function () {
  835. ipcRenderer.send('response', 'failed');
  836. });
  837. });
  838. });
  839. // DISABLED-FIXME: Figure out why this test is failing
  840. it('disallows CORS and fetch requests when only supportFetchAPI is specified', async () => {
  841. await allowsCORSRequests('no-cors', ['failed xhr', 'failed fetch'], /has been blocked by CORS policy/, () => {
  842. const { ipcRenderer } = require('electron');
  843. Promise.all([
  844. new Promise(resolve => {
  845. const req = new XMLHttpRequest();
  846. req.onload = () => resolve('loaded xhr');
  847. req.onerror = () => resolve('failed xhr');
  848. req.open('GET', 'no-cors://myhost');
  849. req.send();
  850. }),
  851. fetch('no-cors://myhost')
  852. .then(() => 'loaded fetch')
  853. .catch(() => 'failed fetch')
  854. ]).then(([xhr, fetch]) => {
  855. ipcRenderer.send('response', [xhr, fetch]);
  856. });
  857. });
  858. });
  859. it('allows CORS, but disallows fetch requests, when specified', async () => {
  860. await allowsCORSRequests('no-fetch', ['loaded xhr', 'failed fetch'], /Fetch API cannot load/, () => {
  861. const { ipcRenderer } = require('electron');
  862. Promise.all([
  863. new Promise(resolve => {
  864. const req = new XMLHttpRequest();
  865. req.onload = () => resolve('loaded xhr');
  866. req.onerror = () => resolve('failed xhr');
  867. req.open('GET', 'no-fetch://myhost');
  868. req.send();
  869. }),
  870. fetch('no-fetch://myhost')
  871. .then(() => 'loaded fetch')
  872. .catch(() => 'failed fetch')
  873. ]).then(([xhr, fetch]) => {
  874. ipcRenderer.send('response', [xhr, fetch]);
  875. });
  876. });
  877. });
  878. async function allowsCORSRequests (corsScheme: string, expected: any, expectedConsole: RegExp, content: Function) {
  879. registerStringProtocol(standardScheme, (request, callback) => {
  880. callback({ data: `<script>(${content})()</script>`, mimeType: 'text/html' });
  881. });
  882. registerStringProtocol(corsScheme, (request, callback) => {
  883. callback('');
  884. });
  885. const newContents = (webContents as typeof ElectronInternal.WebContents).create({
  886. nodeIntegration: true,
  887. contextIsolation: false
  888. });
  889. const consoleMessages: string[] = [];
  890. newContents.on('console-message', (e, level, message) => consoleMessages.push(message));
  891. try {
  892. newContents.loadURL(standardScheme + '://fake-host');
  893. const [, response] = await once(ipcMain, 'response');
  894. expect(response).to.deep.equal(expected);
  895. expect(consoleMessages.join('\n')).to.match(expectedConsole);
  896. } finally {
  897. // This is called in a timeout to avoid a crash that happens when
  898. // calling destroy() in a microtask.
  899. setTimeout().then(() => {
  900. newContents.destroy();
  901. });
  902. }
  903. }
  904. });
  905. describe('protocol.registerSchemesAsPrivileged stream', async function () {
  906. const pagePath = path.join(fixturesPath, 'pages', 'video.html');
  907. const videoSourceImagePath = path.join(fixturesPath, 'video-source-image.webp');
  908. const videoPath = path.join(fixturesPath, 'video.webm');
  909. let w: BrowserWindow;
  910. before(async () => {
  911. // generate test video
  912. const imageBase64 = await fs.promises.readFile(videoSourceImagePath, 'base64');
  913. const imageDataUrl = `data:image/webp;base64,${imageBase64}`;
  914. const encoder = new WebmGenerator(15);
  915. for (let i = 0; i < 30; i++) {
  916. encoder.add(imageDataUrl);
  917. }
  918. await new Promise((resolve, reject) => {
  919. encoder.compile((output:Uint8Array) => {
  920. fs.promises.writeFile(videoPath, output).then(resolve, reject);
  921. });
  922. });
  923. });
  924. after(async () => {
  925. await fs.promises.unlink(videoPath);
  926. });
  927. beforeEach(async function () {
  928. w = new BrowserWindow({ show: false });
  929. await w.loadURL('about:blank');
  930. if (!await w.webContents.executeJavaScript('document.createElement(\'video\').canPlayType(\'video/webm; codecs="vp8.0"\')')) {
  931. this.skip();
  932. }
  933. });
  934. afterEach(async () => {
  935. await closeWindow(w);
  936. w = null as unknown as BrowserWindow;
  937. await protocol.unregisterProtocol(standardScheme);
  938. await protocol.unregisterProtocol('stream');
  939. });
  940. it('successfully plays videos when content is buffered (stream: false)', async () => {
  941. await streamsResponses(standardScheme, 'play');
  942. });
  943. it('successfully plays videos when streaming content (stream: true)', async () => {
  944. await streamsResponses('stream', 'play');
  945. });
  946. async function streamsResponses (testingScheme: string, expected: any) {
  947. const protocolHandler = (request: any, callback: Function) => {
  948. if (request.url.includes('/video.webm')) {
  949. const stat = fs.statSync(videoPath);
  950. const fileSize = stat.size;
  951. const range = request.headers.Range;
  952. if (range) {
  953. const parts = range.replace(/bytes=/, '').split('-');
  954. const start = parseInt(parts[0], 10);
  955. const end = parts[1] ? parseInt(parts[1], 10) : fileSize - 1;
  956. const chunksize = (end - start) + 1;
  957. const headers = {
  958. 'Content-Range': `bytes ${start}-${end}/${fileSize}`,
  959. 'Accept-Ranges': 'bytes',
  960. 'Content-Length': String(chunksize),
  961. 'Content-Type': 'video/webm'
  962. };
  963. callback({ statusCode: 206, headers, data: fs.createReadStream(videoPath, { start, end }) });
  964. } else {
  965. callback({
  966. statusCode: 200,
  967. headers: {
  968. 'Content-Length': String(fileSize),
  969. 'Content-Type': 'video/webm'
  970. },
  971. data: fs.createReadStream(videoPath)
  972. });
  973. }
  974. } else {
  975. callback({ data: fs.createReadStream(pagePath), headers: { 'Content-Type': 'text/html' }, statusCode: 200 });
  976. }
  977. };
  978. await registerStreamProtocol(standardScheme, protocolHandler);
  979. await registerStreamProtocol('stream', protocolHandler);
  980. const newContents = (webContents as typeof ElectronInternal.WebContents).create({
  981. nodeIntegration: true,
  982. contextIsolation: false
  983. });
  984. try {
  985. newContents.loadURL(testingScheme + '://fake-host');
  986. const [, response] = await once(ipcMain, 'result');
  987. expect(response).to.deep.equal(expected);
  988. } finally {
  989. // This is called in a timeout to avoid a crash that happens when
  990. // calling destroy() in a microtask.
  991. setTimeout().then(() => {
  992. newContents.destroy();
  993. });
  994. }
  995. }
  996. });
  997. describe('handle', () => {
  998. afterEach(closeAllWindows);
  999. it('receives requests to a custom scheme', async () => {
  1000. protocol.handle('test-scheme', (req) => new Response('hello ' + req.url));
  1001. defer(() => { protocol.unhandle('test-scheme'); });
  1002. const resp = await net.fetch('test-scheme://foo');
  1003. expect(resp.status).to.equal(200);
  1004. });
  1005. it('can be unhandled', async () => {
  1006. protocol.handle('test-scheme', (req) => new Response('hello ' + req.url));
  1007. defer(() => {
  1008. try {
  1009. // In case of failure, make sure we unhandle. But we should succeed
  1010. // :)
  1011. protocol.unhandle('test-scheme');
  1012. } catch (_ignored) { /* ignore */ }
  1013. });
  1014. const resp1 = await net.fetch('test-scheme://foo');
  1015. expect(resp1.status).to.equal(200);
  1016. protocol.unhandle('test-scheme');
  1017. await expect(net.fetch('test-scheme://foo')).to.eventually.be.rejectedWith(/ERR_UNKNOWN_URL_SCHEME/);
  1018. });
  1019. it('receives requests to the existing https scheme', async () => {
  1020. protocol.handle('https', (req) => new Response('hello ' + req.url));
  1021. defer(() => { protocol.unhandle('https'); });
  1022. const body = await net.fetch('https://foo').then(r => r.text());
  1023. expect(body).to.equal('hello https://foo/');
  1024. });
  1025. it('receives requests to the existing file scheme', (done) => {
  1026. const filePath = path.join(__dirname, 'fixtures', 'pages', 'a.html');
  1027. protocol.handle('file', (req) => {
  1028. let file;
  1029. if (process.platform === 'win32') {
  1030. file = `file:///${filePath.replace(/\\/g, '/')}`;
  1031. } else {
  1032. file = `file://${filePath}`;
  1033. }
  1034. if (req.url === file) done();
  1035. return new Response(req.url);
  1036. });
  1037. defer(() => { protocol.unhandle('file'); });
  1038. const w = new BrowserWindow();
  1039. w.loadFile(filePath);
  1040. });
  1041. it('receives requests to an existing scheme when navigating', async () => {
  1042. protocol.handle('https', (req) => new Response('hello ' + req.url));
  1043. defer(() => { protocol.unhandle('https'); });
  1044. const w = new BrowserWindow({ show: false });
  1045. await w.loadURL('https://localhost');
  1046. expect(await w.webContents.executeJavaScript('document.body.textContent')).to.equal('hello https://localhost/');
  1047. });
  1048. it('can send buffer body', async () => {
  1049. protocol.handle('test-scheme', (req) => new Response(Buffer.from('hello ' + req.url)));
  1050. defer(() => { protocol.unhandle('test-scheme'); });
  1051. const body = await net.fetch('test-scheme://foo').then(r => r.text());
  1052. expect(body).to.equal('hello test-scheme://foo');
  1053. });
  1054. it('can send stream body', async () => {
  1055. protocol.handle('test-scheme', () => new Response(getWebStream()));
  1056. defer(() => { protocol.unhandle('test-scheme'); });
  1057. const body = await net.fetch('test-scheme://foo').then(r => r.text());
  1058. expect(body).to.equal(text);
  1059. });
  1060. it('accepts urls with no hostname in non-standard schemes', async () => {
  1061. protocol.handle('test-scheme', (req) => new Response(req.url));
  1062. defer(() => { protocol.unhandle('test-scheme'); });
  1063. {
  1064. const body = await net.fetch('test-scheme://foo').then(r => r.text());
  1065. expect(body).to.equal('test-scheme://foo');
  1066. }
  1067. {
  1068. const body = await net.fetch('test-scheme:///foo').then(r => r.text());
  1069. expect(body).to.equal('test-scheme:///foo');
  1070. }
  1071. {
  1072. const body = await net.fetch('test-scheme://').then(r => r.text());
  1073. expect(body).to.equal('test-scheme://');
  1074. }
  1075. });
  1076. it('accepts urls with a port-like component in non-standard schemes', async () => {
  1077. protocol.handle('test-scheme', (req) => new Response(req.url));
  1078. defer(() => { protocol.unhandle('test-scheme'); });
  1079. {
  1080. const body = await net.fetch('test-scheme://foo:30').then(r => r.text());
  1081. expect(body).to.equal('test-scheme://foo:30');
  1082. }
  1083. });
  1084. it('normalizes urls in standard schemes', async () => {
  1085. // NB. 'app' is registered as a standard scheme in test setup.
  1086. protocol.handle('app', (req) => new Response(req.url));
  1087. defer(() => { protocol.unhandle('app'); });
  1088. {
  1089. const body = await net.fetch('app://foo').then(r => r.text());
  1090. expect(body).to.equal('app://foo/');
  1091. }
  1092. {
  1093. const body = await net.fetch('app:///foo').then(r => r.text());
  1094. expect(body).to.equal('app://foo/');
  1095. }
  1096. // NB. 'app' is registered with the default scheme type of 'host'.
  1097. {
  1098. const body = await net.fetch('app://foo:1234').then(r => r.text());
  1099. expect(body).to.equal('app://foo/');
  1100. }
  1101. await expect(net.fetch('app://')).to.be.rejectedWith('Invalid URL');
  1102. });
  1103. it('fails on URLs with a username', async () => {
  1104. // NB. 'app' is registered as a standard scheme in test setup.
  1105. protocol.handle('http', (req) => new Response(req.url));
  1106. defer(() => { protocol.unhandle('http'); });
  1107. await expect(contents.loadURL('http://x@foo:1234')).to.be.rejectedWith(/ERR_UNEXPECTED/);
  1108. });
  1109. it('normalizes http urls', async () => {
  1110. protocol.handle('http', (req) => new Response(req.url));
  1111. defer(() => { protocol.unhandle('http'); });
  1112. {
  1113. const body = await net.fetch('http://foo').then(r => r.text());
  1114. expect(body).to.equal('http://foo/');
  1115. }
  1116. });
  1117. it('can send errors', async () => {
  1118. protocol.handle('test-scheme', () => Response.error());
  1119. defer(() => { protocol.unhandle('test-scheme'); });
  1120. await expect(net.fetch('test-scheme://foo')).to.eventually.be.rejectedWith('net::ERR_FAILED');
  1121. });
  1122. it('handles invalid protocol response status', async () => {
  1123. protocol.handle('test-scheme', () => {
  1124. return { status: [] } as any;
  1125. });
  1126. defer(() => { protocol.unhandle('test-scheme'); });
  1127. await expect(net.fetch('test-scheme://foo')).to.be.rejectedWith('net::ERR_UNEXPECTED');
  1128. });
  1129. it('handles invalid protocol response statusText', async () => {
  1130. protocol.handle('test-scheme', () => {
  1131. return { statusText: false } as any;
  1132. });
  1133. defer(() => { protocol.unhandle('test-scheme'); });
  1134. await expect(net.fetch('test-scheme://foo')).to.be.rejectedWith('net::ERR_UNEXPECTED');
  1135. });
  1136. it('handles invalid protocol response header parameters', async () => {
  1137. protocol.handle('test-scheme', () => {
  1138. return { headers: false } as any;
  1139. });
  1140. defer(() => { protocol.unhandle('test-scheme'); });
  1141. await expect(net.fetch('test-scheme://foo')).to.be.rejectedWith('net::ERR_UNEXPECTED');
  1142. });
  1143. it('handles invalid protocol response body parameters', async () => {
  1144. protocol.handle('test-scheme', () => {
  1145. return { body: false } as any;
  1146. });
  1147. defer(() => { protocol.unhandle('test-scheme'); });
  1148. await expect(net.fetch('test-scheme://foo')).to.be.rejectedWith('net::ERR_UNEXPECTED');
  1149. });
  1150. it('handles a synchronous error in the handler', async () => {
  1151. protocol.handle('test-scheme', () => { throw new Error('test'); });
  1152. defer(() => { protocol.unhandle('test-scheme'); });
  1153. await expect(net.fetch('test-scheme://foo')).to.be.rejectedWith('net::ERR_UNEXPECTED');
  1154. });
  1155. it('handles an asynchronous error in the handler', async () => {
  1156. protocol.handle('test-scheme', () => Promise.reject(new Error('rejected promise')));
  1157. defer(() => { protocol.unhandle('test-scheme'); });
  1158. await expect(net.fetch('test-scheme://foo')).to.be.rejectedWith('net::ERR_UNEXPECTED');
  1159. });
  1160. it('correctly sets statusCode', async () => {
  1161. protocol.handle('test-scheme', () => new Response(null, { status: 201 }));
  1162. defer(() => { protocol.unhandle('test-scheme'); });
  1163. const resp = await net.fetch('test-scheme://foo');
  1164. expect(resp.status).to.equal(201);
  1165. });
  1166. it('correctly sets content-type and charset', async () => {
  1167. protocol.handle('test-scheme', () => new Response(null, { headers: { 'content-type': 'text/html; charset=testcharset' } }));
  1168. defer(() => { protocol.unhandle('test-scheme'); });
  1169. const resp = await net.fetch('test-scheme://foo');
  1170. expect(resp.headers.get('content-type')).to.equal('text/html; charset=testcharset');
  1171. });
  1172. it('can forward to http', async () => {
  1173. const server = http.createServer((req, res) => {
  1174. res.end(text);
  1175. });
  1176. defer(() => { server.close(); });
  1177. const { url } = await listen(server);
  1178. protocol.handle('test-scheme', () => net.fetch(url));
  1179. defer(() => { protocol.unhandle('test-scheme'); });
  1180. const body = await net.fetch('test-scheme://foo').then(r => r.text());
  1181. expect(body).to.equal(text);
  1182. });
  1183. it('can forward an http request with headers', async () => {
  1184. const server = http.createServer((req, res) => {
  1185. res.setHeader('foo', 'bar');
  1186. res.end(text);
  1187. });
  1188. defer(() => { server.close(); });
  1189. const { url } = await listen(server);
  1190. protocol.handle('test-scheme', (req) => net.fetch(url, { headers: req.headers }));
  1191. defer(() => { protocol.unhandle('test-scheme'); });
  1192. const resp = await net.fetch('test-scheme://foo');
  1193. expect(resp.headers.get('foo')).to.equal('bar');
  1194. });
  1195. it('can forward to file', async () => {
  1196. protocol.handle('test-scheme', () => net.fetch(url.pathToFileURL(path.join(__dirname, 'fixtures', 'hello.txt')).toString()));
  1197. defer(() => { protocol.unhandle('test-scheme'); });
  1198. const body = await net.fetch('test-scheme://foo').then(r => r.text());
  1199. expect(body.trimEnd()).to.equal('hello world');
  1200. });
  1201. it('can receive simple request body', async () => {
  1202. protocol.handle('test-scheme', (req) => new Response(req.body));
  1203. defer(() => { protocol.unhandle('test-scheme'); });
  1204. const body = await net.fetch('test-scheme://foo', {
  1205. method: 'POST',
  1206. body: 'foobar'
  1207. }).then(r => r.text());
  1208. expect(body).to.equal('foobar');
  1209. });
  1210. it('can receive stream request body', async () => {
  1211. protocol.handle('test-scheme', (req) => new Response(req.body));
  1212. defer(() => { protocol.unhandle('test-scheme'); });
  1213. const body = await net.fetch('test-scheme://foo', {
  1214. method: 'POST',
  1215. body: getWebStream(),
  1216. duplex: 'half' // https://github.com/microsoft/TypeScript/issues/53157
  1217. } as any).then(r => r.text());
  1218. expect(body).to.equal(text);
  1219. });
  1220. it('can receive multi-part postData from loadURL', async () => {
  1221. protocol.handle('test-scheme', (req) => new Response(req.body));
  1222. defer(() => { protocol.unhandle('test-scheme'); });
  1223. await contents.loadURL('test-scheme://foo', { postData: [{ type: 'rawData', bytes: Buffer.from('a') }, { type: 'rawData', bytes: Buffer.from('b') }] });
  1224. expect(await contents.executeJavaScript('document.documentElement.textContent')).to.equal('ab');
  1225. });
  1226. it('can receive file postData from loadURL', async () => {
  1227. protocol.handle('test-scheme', (req) => new Response(req.body));
  1228. defer(() => { protocol.unhandle('test-scheme'); });
  1229. await contents.loadURL('test-scheme://foo', { postData: [{ type: 'file', filePath: path.join(fixturesPath, 'hello.txt'), length: 'hello world\n'.length, offset: 0, modificationTime: 0 }] });
  1230. expect(await contents.executeJavaScript('document.documentElement.textContent')).to.equal('hello world\n');
  1231. });
  1232. it('can receive file postData from a form', async () => {
  1233. protocol.handle('test-scheme', (req) => new Response(req.body));
  1234. defer(() => { protocol.unhandle('test-scheme'); });
  1235. await contents.loadURL('data:text/html,<form action="test-scheme://foo" method=POST enctype="multipart/form-data"><input name=foo type=file>');
  1236. const { debugger: dbg } = contents;
  1237. dbg.attach();
  1238. const { root } = await dbg.sendCommand('DOM.getDocument');
  1239. const { nodeId: fileInputNodeId } = await dbg.sendCommand('DOM.querySelector', { nodeId: root.nodeId, selector: 'input' });
  1240. await dbg.sendCommand('DOM.setFileInputFiles', {
  1241. nodeId: fileInputNodeId,
  1242. files: [
  1243. path.join(fixturesPath, 'hello.txt')
  1244. ]
  1245. });
  1246. const navigated = once(contents, 'did-finish-load');
  1247. await contents.executeJavaScript('document.querySelector("form").submit()');
  1248. await navigated;
  1249. expect(await contents.executeJavaScript('document.documentElement.textContent')).to.match(/------WebKitFormBoundary.*\nContent-Disposition: form-data; name="foo"; filename="hello.txt"\nContent-Type: text\/plain\n\nhello world\n\n------WebKitFormBoundary.*--\n/);
  1250. });
  1251. it('can receive streaming fetch upload', async () => {
  1252. protocol.handle('no-cors', (req) => new Response(req.body));
  1253. defer(() => { protocol.unhandle('no-cors'); });
  1254. await contents.loadURL('no-cors://foo');
  1255. const fetchBodyResult = await contents.executeJavaScript(`
  1256. const stream = new ReadableStream({
  1257. async start(controller) {
  1258. controller.enqueue('hello world');
  1259. controller.close();
  1260. },
  1261. }).pipeThrough(new TextEncoderStream());
  1262. fetch(location.href, {method: 'POST', body: stream, duplex: 'half'}).then(x => x.text())
  1263. `);
  1264. expect(fetchBodyResult).to.equal('hello world');
  1265. });
  1266. it('can receive streaming fetch upload when a webRequest handler is present', async () => {
  1267. session.defaultSession.webRequest.onBeforeRequest((details, cb) => {
  1268. console.log('webRequest', details.url, details.method);
  1269. cb({});
  1270. });
  1271. defer(() => {
  1272. session.defaultSession.webRequest.onBeforeRequest(null);
  1273. });
  1274. protocol.handle('no-cors', (req) => {
  1275. console.log('handle', req.url, req.method);
  1276. return new Response(req.body);
  1277. });
  1278. defer(() => { protocol.unhandle('no-cors'); });
  1279. await contents.loadURL('no-cors://foo');
  1280. const fetchBodyResult = await contents.executeJavaScript(`
  1281. const stream = new ReadableStream({
  1282. async start(controller) {
  1283. controller.enqueue('hello world');
  1284. controller.close();
  1285. },
  1286. }).pipeThrough(new TextEncoderStream());
  1287. fetch(location.href, {method: 'POST', body: stream, duplex: 'half'}).then(x => x.text())
  1288. `);
  1289. expect(fetchBodyResult).to.equal('hello world');
  1290. });
  1291. it('can receive an error from streaming fetch upload', async () => {
  1292. protocol.handle('no-cors', (req) => new Response(req.body));
  1293. defer(() => { protocol.unhandle('no-cors'); });
  1294. await contents.loadURL('no-cors://foo');
  1295. const fetchBodyResult = await contents.executeJavaScript(`
  1296. const stream = new ReadableStream({
  1297. async start(controller) {
  1298. controller.error('test')
  1299. },
  1300. });
  1301. fetch(location.href, {method: 'POST', body: stream, duplex: 'half'}).then(x => x.text()).catch(err => err)
  1302. `);
  1303. expect(fetchBodyResult).to.be.an.instanceOf(Error);
  1304. });
  1305. it('gets an error from streaming fetch upload when the renderer dies', async () => {
  1306. let gotRequest: Function;
  1307. const receivedRequest = new Promise<Request>(resolve => { gotRequest = resolve; });
  1308. protocol.handle('no-cors', (req) => {
  1309. if (/fetch/.test(req.url)) gotRequest(req);
  1310. return new Response();
  1311. });
  1312. defer(() => { protocol.unhandle('no-cors'); });
  1313. await contents.loadURL('no-cors://foo');
  1314. contents.executeJavaScript(`
  1315. const stream = new ReadableStream({
  1316. async start(controller) {
  1317. window.controller = controller // no GC
  1318. },
  1319. });
  1320. fetch(location.href + '/fetch', {method: 'POST', body: stream, duplex: 'half'}).then(x => x.text()).catch(err => err)
  1321. `);
  1322. const req = await receivedRequest;
  1323. contents.destroy();
  1324. // Undo .destroy() for the next test
  1325. contents = (webContents as typeof ElectronInternal.WebContents).create({ sandbox: true });
  1326. await expect(req.body!.getReader().read()).to.eventually.be.rejectedWith('net::ERR_FAILED');
  1327. });
  1328. it('can bypass intercepeted protocol handlers', async () => {
  1329. protocol.handle('http', () => new Response('custom'));
  1330. defer(() => { protocol.unhandle('http'); });
  1331. const server = http.createServer((req, res) => {
  1332. res.end('default');
  1333. });
  1334. defer(() => server.close());
  1335. const { url } = await listen(server);
  1336. expect(await net.fetch(url, { bypassCustomProtocolHandlers: true }).then(r => r.text())).to.equal('default');
  1337. });
  1338. it('bypassing custom protocol handlers also bypasses new protocols', async () => {
  1339. protocol.handle('app', () => new Response('custom'));
  1340. defer(() => { protocol.unhandle('app'); });
  1341. await expect(net.fetch('app://foo', { bypassCustomProtocolHandlers: true })).to.be.rejectedWith('net::ERR_UNKNOWN_URL_SCHEME');
  1342. });
  1343. it('can forward to the original handler', async () => {
  1344. protocol.handle('http', (req) => net.fetch(req, { bypassCustomProtocolHandlers: true }));
  1345. defer(() => { protocol.unhandle('http'); });
  1346. const server = http.createServer((req, res) => {
  1347. res.end('hello');
  1348. server.close();
  1349. });
  1350. const { url } = await listen(server);
  1351. await contents.loadURL(url);
  1352. expect(await contents.executeJavaScript('document.documentElement.textContent')).to.equal('hello');
  1353. });
  1354. it('supports sniffing mime type', async () => {
  1355. protocol.handle('http', async (req) => {
  1356. return net.fetch(req, { bypassCustomProtocolHandlers: true });
  1357. });
  1358. defer(() => { protocol.unhandle('http'); });
  1359. const server = http.createServer((req, res) => {
  1360. if (/html/.test(req.url ?? '')) { res.end('<!doctype html><body>hi'); } else { res.end('hi'); }
  1361. });
  1362. const { url } = await listen(server);
  1363. defer(() => server.close());
  1364. {
  1365. await contents.loadURL(url);
  1366. const doc = await contents.executeJavaScript('document.documentElement.outerHTML');
  1367. expect(doc).to.match(/white-space: pre-wrap/);
  1368. }
  1369. {
  1370. await contents.loadURL(url + '?html');
  1371. const doc = await contents.executeJavaScript('document.documentElement.outerHTML');
  1372. expect(doc).to.equal('<html><head></head><body>hi</body></html>');
  1373. }
  1374. });
  1375. // TODO(nornagon): this test doesn't pass on Linux currently, investigate.
  1376. ifit(process.platform !== 'linux')('is fast', async () => {
  1377. // 128 MB of spaces.
  1378. const chunk = new Uint8Array(128 * 1024 * 1024);
  1379. chunk.fill(' '.charCodeAt(0));
  1380. const server = http.createServer((req, res) => {
  1381. // The sniffed mime type for the space-filled chunk will be
  1382. // text/plain, which chews up all its performance in the renderer
  1383. // trying to wrap lines. Setting content-type to text/html measures
  1384. // something closer to just the raw cost of getting the bytes over
  1385. // the wire.
  1386. res.setHeader('content-type', 'text/html');
  1387. res.end(chunk);
  1388. });
  1389. defer(() => server.close());
  1390. const { url } = await listen(server);
  1391. const rawTime = await (async () => {
  1392. await contents.loadURL(url); // warm
  1393. const begin = Date.now();
  1394. await contents.loadURL(url);
  1395. const end = Date.now();
  1396. return end - begin;
  1397. })();
  1398. // Fetching through an intercepted handler should not be too much slower
  1399. // than it would be if the protocol hadn't been intercepted.
  1400. protocol.handle('http', async (req) => {
  1401. return net.fetch(req, { bypassCustomProtocolHandlers: true });
  1402. });
  1403. defer(() => { protocol.unhandle('http'); });
  1404. const interceptedTime = await (async () => {
  1405. const begin = Date.now();
  1406. await contents.loadURL(url);
  1407. const end = Date.now();
  1408. return end - begin;
  1409. })();
  1410. expect(interceptedTime).to.be.lessThan(rawTime * 1.5);
  1411. });
  1412. });
  1413. });