node-spec.ts 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001
  1. import { webContents } from 'electron/main';
  2. import { expect } from 'chai';
  3. import * as childProcess from 'node:child_process';
  4. import { once } from 'node:events';
  5. import * as fs from 'node:fs';
  6. import * as path from 'node:path';
  7. import { EventEmitter } from 'node:stream';
  8. import * as util from 'node:util';
  9. import { copyMacOSFixtureApp, getCodesignIdentity, shouldRunCodesignTests, signApp, spawn } from './lib/codesign-helpers';
  10. import { withTempDirectory } from './lib/fs-helpers';
  11. import { getRemoteContext, ifdescribe, ifit, itremote, useRemoteContext } from './lib/spec-helpers';
  12. const mainFixturesPath = path.resolve(__dirname, 'fixtures');
  13. describe('node feature', () => {
  14. const fixtures = path.join(__dirname, 'fixtures');
  15. describe('child_process', () => {
  16. describe('child_process.fork', () => {
  17. it('Works in browser process', async () => {
  18. const child = childProcess.fork(path.join(fixtures, 'module', 'ping.js'));
  19. const message = once(child, 'message');
  20. child.send('message');
  21. const [msg] = await message;
  22. expect(msg).to.equal('message');
  23. });
  24. it('Has its module searth paths restricted', async () => {
  25. const child = childProcess.fork(path.join(fixtures, 'module', 'module-paths.js'));
  26. const [msg] = await once(child, 'message');
  27. expect(msg.length).to.equal(2);
  28. });
  29. });
  30. });
  31. describe('child_process in renderer', () => {
  32. useRemoteContext();
  33. describe('child_process.fork', () => {
  34. itremote('works in current process', async (fixtures: string) => {
  35. const child = require('node:child_process').fork(require('node:path').join(fixtures, 'module', 'ping.js'));
  36. const message = new Promise<any>(resolve => child.once('message', resolve));
  37. child.send('message');
  38. const msg = await message;
  39. expect(msg).to.equal('message');
  40. }, [fixtures]);
  41. itremote('preserves args', async (fixtures: string) => {
  42. const args = ['--expose_gc', '-test', '1'];
  43. const child = require('node:child_process').fork(require('node:path').join(fixtures, 'module', 'process_args.js'), args);
  44. const message = new Promise<any>(resolve => child.once('message', resolve));
  45. child.send('message');
  46. const msg = await message;
  47. expect(args).to.deep.equal(msg.slice(2));
  48. }, [fixtures]);
  49. itremote('works in forked process', async (fixtures: string) => {
  50. const child = require('node:child_process').fork(require('node:path').join(fixtures, 'module', 'fork_ping.js'));
  51. const message = new Promise<any>(resolve => child.once('message', resolve));
  52. child.send('message');
  53. const msg = await message;
  54. expect(msg).to.equal('message');
  55. }, [fixtures]);
  56. itremote('works in forked process when options.env is specified', async (fixtures: string) => {
  57. const child = require('node:child_process').fork(require('node:path').join(fixtures, 'module', 'fork_ping.js'), [], {
  58. path: process.env.PATH
  59. });
  60. const message = new Promise<any>(resolve => child.once('message', resolve));
  61. child.send('message');
  62. const msg = await message;
  63. expect(msg).to.equal('message');
  64. }, [fixtures]);
  65. itremote('has String::localeCompare working in script', async (fixtures: string) => {
  66. const child = require('node:child_process').fork(require('node:path').join(fixtures, 'module', 'locale-compare.js'));
  67. const message = new Promise<any>(resolve => child.once('message', resolve));
  68. child.send('message');
  69. const msg = await message;
  70. expect(msg).to.deep.equal([0, -1, 1]);
  71. }, [fixtures]);
  72. itremote('has setImmediate working in script', async (fixtures: string) => {
  73. const child = require('node:child_process').fork(require('node:path').join(fixtures, 'module', 'set-immediate.js'));
  74. const message = new Promise<any>(resolve => child.once('message', resolve));
  75. child.send('message');
  76. const msg = await message;
  77. expect(msg).to.equal('ok');
  78. }, [fixtures]);
  79. itremote('pipes stdio', async (fixtures: string) => {
  80. const child = require('node:child_process').fork(require('node:path').join(fixtures, 'module', 'process-stdout.js'), { silent: true });
  81. let data = '';
  82. child.stdout.on('data', (chunk: any) => {
  83. data += String(chunk);
  84. });
  85. const code = await new Promise<any>(resolve => child.once('close', resolve));
  86. expect(code).to.equal(0);
  87. expect(data).to.equal('pipes stdio');
  88. }, [fixtures]);
  89. itremote('works when sending a message to a process forked with the --eval argument', async () => {
  90. const source = "process.on('message', (message) => { process.send(message) })";
  91. const forked = require('node:child_process').fork('--eval', [source]);
  92. const message = new Promise(resolve => forked.once('message', resolve));
  93. forked.send('hello');
  94. const msg = await message;
  95. expect(msg).to.equal('hello');
  96. });
  97. it('has the electron version in process.versions', async () => {
  98. const source = 'process.send(process.versions)';
  99. const forked = require('node:child_process').fork('--eval', [source]);
  100. const [message] = await once(forked, 'message');
  101. expect(message)
  102. .to.have.own.property('electron')
  103. .that.is.a('string')
  104. .and.matches(/^\d+\.\d+\.\d+(\S*)?$/);
  105. });
  106. });
  107. describe('child_process.spawn', () => {
  108. itremote('supports spawning Electron as a node process via the ELECTRON_RUN_AS_NODE env var', async (fixtures: string) => {
  109. const child = require('node:child_process').spawn(process.execPath, [require('node:path').join(fixtures, 'module', 'run-as-node.js')], {
  110. env: {
  111. ELECTRON_RUN_AS_NODE: true
  112. }
  113. });
  114. let output = '';
  115. child.stdout.on('data', (data: any) => {
  116. output += data;
  117. });
  118. try {
  119. await new Promise(resolve => child.stdout.once('close', resolve));
  120. expect(JSON.parse(output)).to.deep.equal({
  121. stdoutType: 'pipe',
  122. processType: 'undefined',
  123. window: 'undefined'
  124. });
  125. } finally {
  126. child.kill();
  127. }
  128. }, [fixtures]);
  129. });
  130. describe('child_process.exec', () => {
  131. ifit(process.platform === 'linux')('allows executing a setuid binary from non-sandboxed renderer', async () => {
  132. // Chrome uses prctl(2) to set the NO_NEW_PRIVILEGES flag on Linux (see
  133. // https://github.com/torvalds/linux/blob/40fde647cc/Documentation/userspace-api/no_new_privs.rst).
  134. // We disable this for unsandboxed processes, which the renderer tests
  135. // are running in. If this test fails with an error like 'effective uid
  136. // is not 0', then it's likely that our patch to prevent the flag from
  137. // being set has become ineffective.
  138. const w = await getRemoteContext();
  139. const stdout = await w.webContents.executeJavaScript('require(\'child_process\').execSync(\'sudo --help\')');
  140. expect(stdout).to.not.be.empty();
  141. });
  142. });
  143. });
  144. describe('EventSource', () => {
  145. itremote('works correctly when nodeIntegration is enabled in the renderer', () => {
  146. const es = new EventSource('https://example.com');
  147. expect(es).to.have.property('url').that.is.a('string');
  148. expect(es).to.have.property('readyState').that.is.a('number');
  149. expect(es).to.have.property('withCredentials').that.is.a('boolean');
  150. });
  151. });
  152. describe('fetch', () => {
  153. itremote('works correctly when nodeIntegration is enabled in the renderer', async (fixtures: string) => {
  154. const file = require('node:path').join(fixtures, 'hello.txt');
  155. expect(() => {
  156. fetch('file://' + file);
  157. }).to.not.throw();
  158. expect(() => {
  159. const formData = new FormData();
  160. formData.append('username', 'Groucho');
  161. }).not.to.throw();
  162. expect(() => {
  163. const request = new Request('https://example.com', {
  164. method: 'POST',
  165. body: JSON.stringify({ foo: 'bar' })
  166. });
  167. expect(request.method).to.equal('POST');
  168. }).not.to.throw();
  169. expect(() => {
  170. const response = new Response('Hello, world!');
  171. expect(response.status).to.equal(200);
  172. }).not.to.throw();
  173. expect(() => {
  174. const headers = new Headers();
  175. headers.append('Content-Type', 'text/xml');
  176. }).not.to.throw();
  177. }, [fixtures]);
  178. });
  179. it('does not hang when using the fs module in the renderer process', async () => {
  180. const appPath = path.join(mainFixturesPath, 'apps', 'libuv-hang', 'main.js');
  181. const appProcess = childProcess.spawn(process.execPath, [appPath], {
  182. cwd: path.join(mainFixturesPath, 'apps', 'libuv-hang'),
  183. stdio: 'inherit'
  184. });
  185. const [code] = await once(appProcess, 'close');
  186. expect(code).to.equal(0);
  187. });
  188. describe('contexts', () => {
  189. describe('setTimeout called under Chromium event loop in browser process', () => {
  190. it('Can be scheduled in time', (done) => {
  191. setTimeout(done, 0);
  192. });
  193. it('Can be promisified', (done) => {
  194. util.promisify(setTimeout)(0).then(done);
  195. });
  196. });
  197. describe('setInterval called under Chromium event loop in browser process', () => {
  198. it('can be scheduled in time', (done) => {
  199. let interval: any = null;
  200. let clearing = false;
  201. const clear = () => {
  202. if (interval === null || clearing) return;
  203. // interval might trigger while clearing (remote is slow sometimes)
  204. clearing = true;
  205. clearInterval(interval);
  206. clearing = false;
  207. interval = null;
  208. done();
  209. };
  210. interval = setInterval(clear, 10);
  211. });
  212. });
  213. const suspendListeners = (emitter: EventEmitter, eventName: string, callback: (...args: any[]) => void) => {
  214. const listeners = emitter.listeners(eventName) as ((...args: any[]) => void)[];
  215. emitter.removeAllListeners(eventName);
  216. emitter.once(eventName, (...args) => {
  217. emitter.removeAllListeners(eventName);
  218. for (const listener of listeners) {
  219. emitter.on(eventName, listener);
  220. }
  221. callback(...args);
  222. });
  223. };
  224. describe('error thrown in main process node context', () => {
  225. it('gets emitted as a process uncaughtException event', async () => {
  226. fs.readFile(__filename, () => {
  227. throw new Error('hello');
  228. });
  229. const result = await new Promise(resolve => suspendListeners(process, 'uncaughtException', (error) => {
  230. resolve(error.message);
  231. }));
  232. expect(result).to.equal('hello');
  233. });
  234. });
  235. describe('promise rejection in main process node context', () => {
  236. it('gets emitted as a process unhandledRejection event', async () => {
  237. fs.readFile(__filename, () => {
  238. Promise.reject(new Error('hello'));
  239. });
  240. const result = await new Promise(resolve => suspendListeners(process, 'unhandledRejection', (error) => {
  241. resolve(error.message);
  242. }));
  243. expect(result).to.equal('hello');
  244. });
  245. it('does not log the warning more than once when the rejection is unhandled', async () => {
  246. const appPath = path.join(mainFixturesPath, 'api', 'unhandled-rejection.js');
  247. const appProcess = childProcess.spawn(process.execPath, [appPath]);
  248. let output = '';
  249. const out = (data: string) => {
  250. output += data;
  251. if (/UnhandledPromiseRejectionWarning/.test(data)) {
  252. appProcess.kill();
  253. }
  254. };
  255. appProcess.stdout!.on('data', out);
  256. appProcess.stderr!.on('data', out);
  257. await once(appProcess, 'exit');
  258. expect(/UnhandledPromiseRejectionWarning/.test(output)).to.equal(true);
  259. const matches = output.match(/Error: oops/gm);
  260. expect(matches).to.have.lengthOf(1);
  261. });
  262. it('does not log the warning more than once when the rejection is handled', async () => {
  263. const appPath = path.join(mainFixturesPath, 'api', 'unhandled-rejection-handled.js');
  264. const appProcess = childProcess.spawn(process.execPath, [appPath]);
  265. let output = '';
  266. const out = (data: string) => { output += data; };
  267. appProcess.stdout!.on('data', out);
  268. appProcess.stderr!.on('data', out);
  269. const [code] = await once(appProcess, 'exit');
  270. expect(code).to.equal(0);
  271. expect(/UnhandledPromiseRejectionWarning/.test(output)).to.equal(false);
  272. const matches = output.match(/Error: oops/gm);
  273. expect(matches).to.have.lengthOf(1);
  274. });
  275. });
  276. });
  277. describe('contexts in renderer', () => {
  278. useRemoteContext();
  279. describe('setTimeout in fs callback', () => {
  280. itremote('does not crash', async (filename: string) => {
  281. await new Promise(resolve => require('node:fs').readFile(filename, () => {
  282. setTimeout(resolve, 0);
  283. }));
  284. }, [__filename]);
  285. });
  286. describe('error thrown in renderer process node context', () => {
  287. itremote('gets emitted as a process uncaughtException event', async (filename: string) => {
  288. const error = new Error('boo!');
  289. require('node:fs').readFile(filename, () => {
  290. throw error;
  291. });
  292. await new Promise<void>((resolve, reject) => {
  293. process.once('uncaughtException', (thrown) => {
  294. try {
  295. expect(thrown).to.equal(error);
  296. resolve();
  297. } catch (e) {
  298. reject(e);
  299. }
  300. });
  301. });
  302. }, [__filename]);
  303. });
  304. describe('URL handling in the renderer process', () => {
  305. itremote('can successfully handle WHATWG URLs constructed by Blink', (fixtures: string) => {
  306. const url = new URL('file://' + require('node:path').resolve(fixtures, 'pages', 'base-page.html'));
  307. expect(() => {
  308. require('node:fs').createReadStream(url);
  309. }).to.not.throw();
  310. }, [fixtures]);
  311. });
  312. describe('setTimeout called under blink env in renderer process', () => {
  313. itremote('can be scheduled in time', async () => {
  314. await new Promise(resolve => setTimeout(resolve, 10));
  315. });
  316. itremote('works from the timers module', async () => {
  317. await new Promise(resolve => require('node:timers').setTimeout(resolve, 10));
  318. });
  319. });
  320. describe('setInterval called under blink env in renderer process', () => {
  321. itremote('can be scheduled in time', async () => {
  322. await new Promise<void>(resolve => {
  323. const id = setInterval(() => {
  324. clearInterval(id);
  325. resolve();
  326. }, 10);
  327. });
  328. });
  329. itremote('can be scheduled in time from timers module', async () => {
  330. const { setInterval, clearInterval } = require('node:timers');
  331. await new Promise<void>(resolve => {
  332. const id = setInterval(() => {
  333. clearInterval(id);
  334. resolve();
  335. }, 10);
  336. });
  337. });
  338. });
  339. });
  340. describe('message loop in renderer', () => {
  341. useRemoteContext();
  342. describe('process.nextTick', () => {
  343. itremote('emits the callback', () => new Promise(resolve => process.nextTick(resolve)));
  344. itremote('works in nested calls', () =>
  345. new Promise(resolve => {
  346. process.nextTick(() => {
  347. process.nextTick(() => process.nextTick(resolve));
  348. });
  349. }));
  350. });
  351. describe('setImmediate', () => {
  352. itremote('emits the callback', () => new Promise(resolve => setImmediate(resolve)));
  353. itremote('works in nested calls', () => new Promise(resolve => {
  354. setImmediate(() => {
  355. setImmediate(() => setImmediate(resolve));
  356. });
  357. }));
  358. });
  359. });
  360. ifdescribe(process.platform === 'darwin')('net.connect', () => {
  361. itremote('emit error when connect to a socket path without listeners', async (fixtures: string) => {
  362. const socketPath = require('node:path').join(require('node:os').tmpdir(), 'electron-test.sock');
  363. const script = require('node:path').join(fixtures, 'module', 'create_socket.js');
  364. const child = require('node:child_process').fork(script, [socketPath]);
  365. const code = await new Promise(resolve => child.once('exit', resolve));
  366. expect(code).to.equal(0);
  367. const client = require('node:net').connect(socketPath);
  368. const error = await new Promise<any>(resolve => client.once('error', resolve));
  369. expect(error.code).to.equal('ECONNREFUSED');
  370. }, [fixtures]);
  371. });
  372. describe('Buffer', () => {
  373. useRemoteContext();
  374. itremote('can be created from Blink external string', () => {
  375. const p = document.createElement('p');
  376. p.innerText = '闲云潭影日悠悠,物换星移几度秋';
  377. const b = Buffer.from(p.innerText);
  378. expect(b.toString()).to.equal('闲云潭影日悠悠,物换星移几度秋');
  379. expect(Buffer.byteLength(p.innerText)).to.equal(45);
  380. });
  381. itremote('correctly parses external one-byte UTF8 string', () => {
  382. const p = document.createElement('p');
  383. p.innerText = 'Jøhänñéß';
  384. const b = Buffer.from(p.innerText);
  385. expect(b.toString()).to.equal('Jøhänñéß');
  386. expect(Buffer.byteLength(p.innerText)).to.equal(13);
  387. });
  388. itremote('does not crash when creating large Buffers', () => {
  389. let buffer = Buffer.from(new Array(4096).join(' '));
  390. expect(buffer.length).to.equal(4095);
  391. buffer = Buffer.from(new Array(4097).join(' '));
  392. expect(buffer.length).to.equal(4096);
  393. });
  394. itremote('does not crash for crypto operations', () => {
  395. const crypto = require('node:crypto');
  396. const data = 'lG9E+/g4JmRmedDAnihtBD4Dfaha/GFOjd+xUOQI05UtfVX3DjUXvrS98p7kZQwY3LNhdiFo7MY5rGft8yBuDhKuNNag9vRx/44IuClDhdQ=';
  397. const key = 'q90K9yBqhWZnAMCMTOJfPQ==';
  398. const cipherText = '{"error_code":114,"error_message":"Tham số không hợp lệ","data":null}';
  399. for (let i = 0; i < 10000; ++i) {
  400. const iv = Buffer.from('0'.repeat(32), 'hex');
  401. const input = Buffer.from(data, 'base64');
  402. const decipher = crypto.createDecipheriv('aes-128-cbc', Buffer.from(key, 'base64'), iv);
  403. const result = Buffer.concat([decipher.update(input), decipher.final()]).toString('utf8');
  404. expect(cipherText).to.equal(result);
  405. }
  406. });
  407. itremote('does not crash when using crypto.diffieHellman() constructors', () => {
  408. const crypto = require('node:crypto');
  409. crypto.createDiffieHellman('abc');
  410. crypto.createDiffieHellman('abc', 2);
  411. // Needed to test specific DiffieHellman ctors.
  412. crypto.createDiffieHellman('abc', Buffer.from([2]));
  413. crypto.createDiffieHellman('abc', '123');
  414. });
  415. itremote('does not crash when calling crypto.createPrivateKey() with an unsupported algorithm', () => {
  416. const crypto = require('node:crypto');
  417. const ed448 = {
  418. crv: 'Ed448',
  419. x: 'KYWcaDwgH77xdAwcbzOgvCVcGMy9I6prRQBhQTTdKXUcr-VquTz7Fd5adJO0wT2VHysF3bk3kBoA',
  420. d: 'UhC3-vN5vp_g9PnTknXZgfXUez7Xvw-OfuJ0pYkuwzpYkcTvacqoFkV_O05WMHpyXkzH9q2wzx5n',
  421. kty: 'OKP'
  422. };
  423. expect(() => {
  424. crypto.createPrivateKey({ key: ed448, format: 'jwk' });
  425. }).to.throw(/Invalid JWK data/);
  426. });
  427. });
  428. describe('process.stdout', () => {
  429. useRemoteContext();
  430. itremote('does not throw an exception when accessed', () => {
  431. expect(() => process.stdout).to.not.throw();
  432. });
  433. itremote('does not throw an exception when calling write()', () => {
  434. expect(() => {
  435. process.stdout.write('test');
  436. }).to.not.throw();
  437. });
  438. // TODO: figure out why process.stdout.isTTY is true on Darwin but not Linux/Win.
  439. ifdescribe(process.platform !== 'darwin')('isTTY', () => {
  440. itremote('should be undefined in the renderer process', function () {
  441. expect(process.stdout.isTTY).to.be.undefined();
  442. });
  443. });
  444. });
  445. describe('process.stdin', () => {
  446. useRemoteContext();
  447. itremote('does not throw an exception when accessed', () => {
  448. expect(() => process.stdin).to.not.throw();
  449. });
  450. itremote('returns null when read from', () => {
  451. expect(process.stdin.read()).to.be.null();
  452. });
  453. });
  454. describe('process.version', () => {
  455. itremote('should not have -pre', () => {
  456. expect(process.version.endsWith('-pre')).to.be.false();
  457. });
  458. });
  459. describe('vm.runInNewContext', () => {
  460. itremote('should not crash', () => {
  461. require('node:vm').runInNewContext('');
  462. });
  463. });
  464. describe('crypto', () => {
  465. useRemoteContext();
  466. itremote('should list the ripemd160 hash in getHashes', () => {
  467. expect(require('node:crypto').getHashes()).to.include('ripemd160');
  468. });
  469. itremote('should be able to create a ripemd160 hash and use it', () => {
  470. const hash = require('node:crypto').createHash('ripemd160');
  471. hash.update('electron-ripemd160');
  472. expect(hash.digest('hex')).to.equal('fa7fec13c624009ab126ebb99eda6525583395fe');
  473. });
  474. itremote('should list aes-{128,256}-cfb in getCiphers', () => {
  475. expect(require('node:crypto').getCiphers()).to.include.members(['aes-128-cfb', 'aes-256-cfb']);
  476. });
  477. itremote('should be able to create an aes-128-cfb cipher', () => {
  478. require('node:crypto').createCipheriv('aes-128-cfb', '0123456789abcdef', '0123456789abcdef');
  479. });
  480. itremote('should be able to create an aes-256-cfb cipher', () => {
  481. require('node:crypto').createCipheriv('aes-256-cfb', '0123456789abcdef0123456789abcdef', '0123456789abcdef');
  482. });
  483. itremote('should be able to create a bf-{cbc,cfb,ecb} ciphers', () => {
  484. require('node:crypto').createCipheriv('bf-cbc', Buffer.from('0123456789abcdef'), Buffer.from('01234567'));
  485. require('node:crypto').createCipheriv('bf-cfb', Buffer.from('0123456789abcdef'), Buffer.from('01234567'));
  486. require('node:crypto').createCipheriv('bf-ecb', Buffer.from('0123456789abcdef'), Buffer.from('01234567'));
  487. });
  488. itremote('should list des-ede-cbc in getCiphers', () => {
  489. expect(require('node:crypto').getCiphers()).to.include('des-ede-cbc');
  490. });
  491. itremote('should be able to create an des-ede-cbc cipher', () => {
  492. const key = Buffer.from('0123456789abcdeff1e0d3c2b5a49786', 'hex');
  493. const iv = Buffer.from('fedcba9876543210', 'hex');
  494. require('node:crypto').createCipheriv('des-ede-cbc', key, iv);
  495. });
  496. itremote('should not crash when getting an ECDH key', () => {
  497. const ecdh = require('node:crypto').createECDH('prime256v1');
  498. expect(ecdh.generateKeys()).to.be.an.instanceof(Buffer);
  499. expect(ecdh.getPrivateKey()).to.be.an.instanceof(Buffer);
  500. });
  501. itremote('should not crash when generating DH keys or fetching DH fields', () => {
  502. const dh = require('node:crypto').createDiffieHellman('modp15');
  503. expect(dh.generateKeys()).to.be.an.instanceof(Buffer);
  504. expect(dh.getPublicKey()).to.be.an.instanceof(Buffer);
  505. expect(dh.getPrivateKey()).to.be.an.instanceof(Buffer);
  506. expect(dh.getPrime()).to.be.an.instanceof(Buffer);
  507. expect(dh.getGenerator()).to.be.an.instanceof(Buffer);
  508. });
  509. itremote('should not crash when creating an ECDH cipher', () => {
  510. const crypto = require('node:crypto');
  511. const dh = crypto.createECDH('prime256v1');
  512. dh.generateKeys();
  513. dh.setPrivateKey(dh.getPrivateKey());
  514. });
  515. });
  516. itremote('includes the electron version in process.versions', () => {
  517. expect(process.versions)
  518. .to.have.own.property('electron')
  519. .that.is.a('string')
  520. .and.matches(/^\d+\.\d+\.\d+(\S*)?$/);
  521. });
  522. itremote('includes the chrome version in process.versions', () => {
  523. expect(process.versions)
  524. .to.have.own.property('chrome')
  525. .that.is.a('string')
  526. .and.matches(/^\d+\.\d+\.\d+\.\d+$/);
  527. });
  528. describe('NODE_OPTIONS', () => {
  529. let child: childProcess.ChildProcessWithoutNullStreams;
  530. let exitPromise: Promise<any[]>;
  531. it('Fails for options disallowed by Node.js itself', (done) => {
  532. after(async () => {
  533. const [code, signal] = await exitPromise;
  534. expect(signal).to.equal(null);
  535. // Exit code 9 indicates cli flag parsing failure
  536. expect(code).to.equal(9);
  537. child.kill();
  538. });
  539. const env = { ...process.env, NODE_OPTIONS: '--v8-options' };
  540. child = childProcess.spawn(process.execPath, { env });
  541. exitPromise = once(child, 'exit');
  542. let output = '';
  543. let success = false;
  544. const cleanup = () => {
  545. child.stderr.removeListener('data', listener);
  546. child.stdout.removeListener('data', listener);
  547. };
  548. const listener = (data: Buffer) => {
  549. output += data;
  550. if (/electron: --v8-options is not allowed in NODE_OPTIONS/m.test(output)) {
  551. success = true;
  552. cleanup();
  553. done();
  554. }
  555. };
  556. child.stderr.on('data', listener);
  557. child.stdout.on('data', listener);
  558. child.on('exit', () => {
  559. if (!success) {
  560. cleanup();
  561. done(new Error(`Unexpected output: ${output.toString()}`));
  562. }
  563. });
  564. });
  565. it('Disallows crypto-related options', (done) => {
  566. after(() => {
  567. child.kill();
  568. });
  569. const appPath = path.join(fixtures, 'module', 'noop.js');
  570. const env = { ...process.env, NODE_OPTIONS: '--use-openssl-ca' };
  571. child = childProcess.spawn(process.execPath, ['--enable-logging', appPath], { env });
  572. let output = '';
  573. const cleanup = () => {
  574. child.stderr.removeListener('data', listener);
  575. child.stdout.removeListener('data', listener);
  576. };
  577. const listener = (data: Buffer) => {
  578. output += data;
  579. if (/The NODE_OPTION --use-openssl-ca is not supported in Electron/m.test(output)) {
  580. cleanup();
  581. done();
  582. }
  583. };
  584. child.stderr.on('data', listener);
  585. child.stdout.on('data', listener);
  586. });
  587. it('does allow --require in non-packaged apps', async () => {
  588. const appPath = path.join(fixtures, 'module', 'noop.js');
  589. const env = {
  590. ...process.env,
  591. NODE_OPTIONS: `--require=${path.join(fixtures, 'module', 'fail.js')}`
  592. };
  593. // App should exit with code 1.
  594. const child = childProcess.spawn(process.execPath, [appPath], { env });
  595. const [code] = await once(child, 'exit');
  596. expect(code).to.equal(1);
  597. });
  598. it('does not allow --require in packaged apps', async () => {
  599. const appPath = path.join(fixtures, 'module', 'noop.js');
  600. const env = {
  601. ...process.env,
  602. ELECTRON_FORCE_IS_PACKAGED: 'true',
  603. NODE_OPTIONS: `--require=${path.join(fixtures, 'module', 'fail.js')}`
  604. };
  605. // App should exit with code 0.
  606. const child = childProcess.spawn(process.execPath, [appPath], { env });
  607. const [code] = await once(child, 'exit');
  608. expect(code).to.equal(0);
  609. });
  610. });
  611. ifdescribe(shouldRunCodesignTests)('NODE_OPTIONS in signed app', function () {
  612. let identity = '';
  613. beforeEach(function () {
  614. const result = getCodesignIdentity();
  615. if (result === null) {
  616. this.skip();
  617. } else {
  618. identity = result;
  619. }
  620. });
  621. const script = path.join(fixtures, 'api', 'fork-with-node-options.js');
  622. const nodeOptionsWarning = 'Node.js environment variables are disabled because this process is invoked by other apps';
  623. it('is disabled when invoked by other apps in ELECTRON_RUN_AS_NODE mode', async () => {
  624. await withTempDirectory(async (dir) => {
  625. const appPath = await copyMacOSFixtureApp(dir);
  626. await signApp(appPath, identity);
  627. // Invoke Electron by using the system node binary as middle layer, so
  628. // the check of NODE_OPTIONS will think the process is started by other
  629. // apps.
  630. const { code, out } = await spawn('node', [script, path.join(appPath, 'Contents/MacOS/Electron')]);
  631. expect(code).to.equal(0);
  632. expect(out).to.include(nodeOptionsWarning);
  633. });
  634. });
  635. it('is disabled when invoked by alien binary in app bundle in ELECTRON_RUN_AS_NODE mode', async function () {
  636. await withTempDirectory(async (dir) => {
  637. const appPath = await copyMacOSFixtureApp(dir);
  638. await signApp(appPath, identity);
  639. // Find system node and copy it to app bundle.
  640. const nodePath = process.env.PATH?.split(path.delimiter).find(dir => fs.existsSync(path.join(dir, 'node')));
  641. if (!nodePath) {
  642. this.skip();
  643. return;
  644. }
  645. const alienBinary = path.join(appPath, 'Contents/MacOS/node');
  646. await fs.promises.cp(path.join(nodePath, 'node'), alienBinary, { recursive: true });
  647. // Try to execute electron app from the alien node in app bundle.
  648. const { code, out } = await spawn(alienBinary, [script, path.join(appPath, 'Contents/MacOS/Electron')]);
  649. expect(code).to.equal(0);
  650. expect(out).to.include(nodeOptionsWarning);
  651. });
  652. });
  653. it('is respected when invoked from self', async () => {
  654. await withTempDirectory(async (dir) => {
  655. const appPath = await copyMacOSFixtureApp(dir, null);
  656. await signApp(appPath, identity);
  657. const appExePath = path.join(appPath, 'Contents/MacOS/Electron');
  658. const { code, out } = await spawn(appExePath, [script, appExePath]);
  659. expect(code).to.equal(1);
  660. expect(out).to.not.include(nodeOptionsWarning);
  661. expect(out).to.include('NODE_OPTIONS passed to child');
  662. });
  663. });
  664. });
  665. describe('Node.js cli flags', () => {
  666. let child: childProcess.ChildProcessWithoutNullStreams;
  667. let exitPromise: Promise<any[]>;
  668. it('Prohibits crypto-related flags in ELECTRON_RUN_AS_NODE mode', (done) => {
  669. after(async () => {
  670. const [code, signal] = await exitPromise;
  671. expect(signal).to.equal(null);
  672. expect(code).to.equal(9);
  673. child.kill();
  674. });
  675. child = childProcess.spawn(process.execPath, ['--force-fips'], {
  676. env: { ELECTRON_RUN_AS_NODE: 'true' }
  677. });
  678. exitPromise = once(child, 'exit');
  679. let output = '';
  680. const cleanup = () => {
  681. child.stderr.removeListener('data', listener);
  682. child.stdout.removeListener('data', listener);
  683. };
  684. const listener = (data: Buffer) => {
  685. output += data;
  686. if (/.*The Node.js cli flag --force-fips is not supported in Electron/m.test(output)) {
  687. cleanup();
  688. done();
  689. }
  690. };
  691. child.stderr.on('data', listener);
  692. child.stdout.on('data', listener);
  693. });
  694. });
  695. describe('process.stdout', () => {
  696. it('is a real Node stream', () => {
  697. expect((process.stdout as any)._type).to.not.be.undefined();
  698. });
  699. });
  700. describe('fs.readFile', () => {
  701. it('can accept a FileHandle as the Path argument', async () => {
  702. const filePathForHandle = path.resolve(mainFixturesPath, 'dogs-running.txt');
  703. const fileHandle = await fs.promises.open(filePathForHandle, 'r');
  704. const file = await fs.promises.readFile(fileHandle, { encoding: 'utf8' });
  705. expect(file).to.not.be.empty();
  706. await fileHandle.close();
  707. });
  708. });
  709. describe('inspector', () => {
  710. let child: childProcess.ChildProcessWithoutNullStreams;
  711. let exitPromise: Promise<any[]> | null;
  712. afterEach(async () => {
  713. if (child && exitPromise) {
  714. const [code, signal] = await exitPromise;
  715. expect(signal).to.equal(null);
  716. expect(code).to.equal(0);
  717. } else if (child) {
  718. child.kill();
  719. }
  720. child = null as any;
  721. exitPromise = null as any;
  722. });
  723. it('Supports starting the v8 inspector with --inspect/--inspect-brk', (done) => {
  724. child = childProcess.spawn(process.execPath, ['--inspect-brk', path.join(fixtures, 'module', 'run-as-node.js')], {
  725. env: { ELECTRON_RUN_AS_NODE: 'true' }
  726. });
  727. let output = '';
  728. const cleanup = () => {
  729. child.stderr.removeListener('data', listener);
  730. child.stdout.removeListener('data', listener);
  731. };
  732. const listener = (data: Buffer) => {
  733. output += data;
  734. if (/Debugger listening on ws:/m.test(output)) {
  735. cleanup();
  736. done();
  737. }
  738. };
  739. child.stderr.on('data', listener);
  740. child.stdout.on('data', listener);
  741. });
  742. it('Supports starting the v8 inspector with --inspect and a provided port', async () => {
  743. child = childProcess.spawn(process.execPath, ['--inspect=17364', path.join(fixtures, 'module', 'run-as-node.js')], {
  744. env: { ELECTRON_RUN_AS_NODE: 'true' }
  745. });
  746. exitPromise = once(child, 'exit');
  747. let output = '';
  748. const listener = (data: Buffer) => { output += data; };
  749. const cleanup = () => {
  750. child.stderr.removeListener('data', listener);
  751. child.stdout.removeListener('data', listener);
  752. };
  753. child.stderr.on('data', listener);
  754. child.stdout.on('data', listener);
  755. await once(child, 'exit');
  756. cleanup();
  757. if (/^Debugger listening on ws:/m.test(output)) {
  758. expect(output.trim()).to.contain(':17364', 'should be listening on port 17364');
  759. } else {
  760. throw new Error(`Unexpected output: ${output.toString()}`);
  761. }
  762. });
  763. it('Does not start the v8 inspector when --inspect is after a -- argument', async () => {
  764. child = childProcess.spawn(process.execPath, [path.join(fixtures, 'module', 'noop.js'), '--', '--inspect']);
  765. exitPromise = once(child, 'exit');
  766. let output = '';
  767. const listener = (data: Buffer) => { output += data; };
  768. child.stderr.on('data', listener);
  769. child.stdout.on('data', listener);
  770. await once(child, 'exit');
  771. if (output.trim().startsWith('Debugger listening on ws://')) {
  772. throw new Error('Inspector was started when it should not have been');
  773. }
  774. });
  775. // IPC Electron child process not supported on Windows.
  776. ifit(process.platform !== 'win32')('does not crash when quitting with the inspector connected', function (done) {
  777. child = childProcess.spawn(process.execPath, [path.join(fixtures, 'module', 'delay-exit'), '--inspect=0'], {
  778. stdio: ['ipc']
  779. }) as childProcess.ChildProcessWithoutNullStreams;
  780. exitPromise = once(child, 'exit');
  781. const cleanup = () => {
  782. child.stderr.removeListener('data', listener);
  783. child.stdout.removeListener('data', listener);
  784. };
  785. let output = '';
  786. const success = false;
  787. function listener (data: Buffer) {
  788. output += data;
  789. console.log(data.toString()); // NOTE: temporary debug logging to try to catch flake.
  790. const match = /^Debugger listening on (ws:\/\/.+:\d+\/.+)\n/m.exec(output.trim());
  791. if (match) {
  792. cleanup();
  793. // NOTE: temporary debug logging to try to catch flake.
  794. child.stderr.on('data', (m) => console.log(m.toString()));
  795. child.stdout.on('data', (m) => console.log(m.toString()));
  796. const w = (webContents as typeof ElectronInternal.WebContents).create();
  797. w.loadURL('about:blank')
  798. .then(() => w.executeJavaScript(`new Promise(resolve => {
  799. const connection = new WebSocket(${JSON.stringify(match[1])})
  800. connection.onopen = () => {
  801. connection.onclose = () => resolve()
  802. connection.close()
  803. }
  804. })`))
  805. .then(() => {
  806. w.destroy();
  807. child.send('plz-quit');
  808. done();
  809. });
  810. }
  811. }
  812. child.stderr.on('data', listener);
  813. child.stdout.on('data', listener);
  814. child.on('exit', () => {
  815. if (!success) cleanup();
  816. });
  817. });
  818. it('Supports js binding', async () => {
  819. child = childProcess.spawn(process.execPath, ['--inspect', path.join(fixtures, 'module', 'inspector-binding.js')], {
  820. env: { ELECTRON_RUN_AS_NODE: 'true' },
  821. stdio: ['ipc']
  822. }) as childProcess.ChildProcessWithoutNullStreams;
  823. exitPromise = once(child, 'exit');
  824. const [{ cmd, debuggerEnabled, success }] = await once(child, 'message');
  825. expect(cmd).to.equal('assert');
  826. expect(debuggerEnabled).to.be.true();
  827. expect(success).to.be.true();
  828. });
  829. });
  830. it('Can find a module using a package.json main field', () => {
  831. const result = childProcess.spawnSync(process.execPath, [path.resolve(fixtures, 'api', 'electron-main-module', 'app.asar')], { stdio: 'inherit' });
  832. expect(result.status).to.equal(0);
  833. });
  834. it('handles Promise timeouts correctly', async () => {
  835. const scriptPath = path.join(fixtures, 'module', 'node-promise-timer.js');
  836. const child = childProcess.spawn(process.execPath, [scriptPath], {
  837. env: { ELECTRON_RUN_AS_NODE: 'true' }
  838. });
  839. const [code, signal] = await once(child, 'exit');
  840. expect(code).to.equal(0);
  841. expect(signal).to.equal(null);
  842. child.kill();
  843. });
  844. it('performs microtask checkpoint correctly', (done) => {
  845. let timer : NodeJS.Timeout;
  846. const listener = () => {
  847. done(new Error('catch block is delayed to next tick'));
  848. };
  849. const f3 = async () => {
  850. return new Promise((resolve, reject) => {
  851. timer = setTimeout(listener);
  852. reject(new Error('oops'));
  853. });
  854. };
  855. setTimeout(() => {
  856. f3().catch(() => {
  857. clearTimeout(timer);
  858. done();
  859. });
  860. });
  861. });
  862. });