node-spec.ts 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024
  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 allow --require in utility process of non-packaged apps', async () => {
  599. const appPath = path.join(fixtures, 'apps', 'node-options-utility-process');
  600. // App should exit with code 1.
  601. const child = childProcess.spawn(process.execPath, [appPath]);
  602. const [code] = await once(child, 'exit');
  603. expect(code).to.equal(1);
  604. });
  605. // TODO(deepak1556): will be enabled in follow-up PR
  606. // https://github.com/electron/electron/pull/46210
  607. it.skip('does not allow --require in utility process of packaged apps', async () => {
  608. const appPath = path.join(fixtures, 'apps', 'node-options-utility-process');
  609. // App should exit with code 1.
  610. const child = childProcess.spawn(process.execPath, [appPath], {
  611. env: {
  612. ...process.env,
  613. ELECTRON_FORCE_IS_PACKAGED: 'true'
  614. }
  615. });
  616. const [code] = await once(child, 'exit');
  617. expect(code).to.equal(0);
  618. });
  619. it('does not allow --require in packaged apps', async () => {
  620. const appPath = path.join(fixtures, 'module', 'noop.js');
  621. const env = {
  622. ...process.env,
  623. ELECTRON_FORCE_IS_PACKAGED: 'true',
  624. NODE_OPTIONS: `--require=${path.join(fixtures, 'module', 'fail.js')}`
  625. };
  626. // App should exit with code 0.
  627. const child = childProcess.spawn(process.execPath, [appPath], { env });
  628. const [code] = await once(child, 'exit');
  629. expect(code).to.equal(0);
  630. });
  631. });
  632. ifdescribe(shouldRunCodesignTests)('NODE_OPTIONS in signed app', function () {
  633. let identity = '';
  634. beforeEach(function () {
  635. const result = getCodesignIdentity();
  636. if (result === null) {
  637. this.skip();
  638. } else {
  639. identity = result;
  640. }
  641. });
  642. const script = path.join(fixtures, 'api', 'fork-with-node-options.js');
  643. const nodeOptionsWarning = 'Node.js environment variables are disabled because this process is invoked by other apps';
  644. it('is disabled when invoked by other apps in ELECTRON_RUN_AS_NODE mode', async () => {
  645. await withTempDirectory(async (dir) => {
  646. const appPath = await copyMacOSFixtureApp(dir);
  647. await signApp(appPath, identity);
  648. // Invoke Electron by using the system node binary as middle layer, so
  649. // the check of NODE_OPTIONS will think the process is started by other
  650. // apps.
  651. const { code, out } = await spawn('node', [script, path.join(appPath, 'Contents/MacOS/Electron')]);
  652. expect(code).to.equal(0);
  653. expect(out).to.include(nodeOptionsWarning);
  654. });
  655. });
  656. it('is disabled when invoked by alien binary in app bundle in ELECTRON_RUN_AS_NODE mode', async function () {
  657. await withTempDirectory(async (dir) => {
  658. const appPath = await copyMacOSFixtureApp(dir);
  659. await signApp(appPath, identity);
  660. // Find system node and copy it to app bundle.
  661. const nodePath = process.env.PATH?.split(path.delimiter).find(dir => fs.existsSync(path.join(dir, 'node')));
  662. if (!nodePath) {
  663. this.skip();
  664. return;
  665. }
  666. const alienBinary = path.join(appPath, 'Contents/MacOS/node');
  667. await fs.promises.cp(path.join(nodePath, 'node'), alienBinary, { recursive: true });
  668. // Try to execute electron app from the alien node in app bundle.
  669. const { code, out } = await spawn(alienBinary, [script, path.join(appPath, 'Contents/MacOS/Electron')]);
  670. expect(code).to.equal(0);
  671. expect(out).to.include(nodeOptionsWarning);
  672. });
  673. });
  674. it('is respected when invoked from self', async () => {
  675. await withTempDirectory(async (dir) => {
  676. const appPath = await copyMacOSFixtureApp(dir, null);
  677. await signApp(appPath, identity);
  678. const appExePath = path.join(appPath, 'Contents/MacOS/Electron');
  679. const { code, out } = await spawn(appExePath, [script, appExePath]);
  680. expect(code).to.equal(1);
  681. expect(out).to.not.include(nodeOptionsWarning);
  682. expect(out).to.include('NODE_OPTIONS passed to child');
  683. });
  684. });
  685. });
  686. describe('Node.js cli flags', () => {
  687. let child: childProcess.ChildProcessWithoutNullStreams;
  688. let exitPromise: Promise<any[]>;
  689. it('Prohibits crypto-related flags in ELECTRON_RUN_AS_NODE mode', (done) => {
  690. after(async () => {
  691. const [code, signal] = await exitPromise;
  692. expect(signal).to.equal(null);
  693. expect(code).to.equal(9);
  694. child.kill();
  695. });
  696. child = childProcess.spawn(process.execPath, ['--force-fips'], {
  697. env: { ELECTRON_RUN_AS_NODE: 'true' }
  698. });
  699. exitPromise = once(child, 'exit');
  700. let output = '';
  701. const cleanup = () => {
  702. child.stderr.removeListener('data', listener);
  703. child.stdout.removeListener('data', listener);
  704. };
  705. const listener = (data: Buffer) => {
  706. output += data;
  707. if (/.*The Node.js cli flag --force-fips is not supported in Electron/m.test(output)) {
  708. cleanup();
  709. done();
  710. }
  711. };
  712. child.stderr.on('data', listener);
  713. child.stdout.on('data', listener);
  714. });
  715. });
  716. describe('process.stdout', () => {
  717. it('is a real Node stream', () => {
  718. expect((process.stdout as any)._type).to.not.be.undefined();
  719. });
  720. });
  721. describe('fs.readFile', () => {
  722. it('can accept a FileHandle as the Path argument', async () => {
  723. const filePathForHandle = path.resolve(mainFixturesPath, 'dogs-running.txt');
  724. const fileHandle = await fs.promises.open(filePathForHandle, 'r');
  725. const file = await fs.promises.readFile(fileHandle, { encoding: 'utf8' });
  726. expect(file).to.not.be.empty();
  727. await fileHandle.close();
  728. });
  729. });
  730. describe('inspector', () => {
  731. let child: childProcess.ChildProcessWithoutNullStreams;
  732. let exitPromise: Promise<any[]> | null;
  733. afterEach(async () => {
  734. if (child && exitPromise) {
  735. const [code, signal] = await exitPromise;
  736. expect(signal).to.equal(null);
  737. expect(code).to.equal(0);
  738. } else if (child) {
  739. child.kill();
  740. }
  741. child = null as any;
  742. exitPromise = null as any;
  743. });
  744. it('Supports starting the v8 inspector with --inspect/--inspect-brk', (done) => {
  745. child = childProcess.spawn(process.execPath, ['--inspect-brk', path.join(fixtures, 'module', 'run-as-node.js')], {
  746. env: { ELECTRON_RUN_AS_NODE: 'true' }
  747. });
  748. let output = '';
  749. const cleanup = () => {
  750. child.stderr.removeListener('data', listener);
  751. child.stdout.removeListener('data', listener);
  752. };
  753. const listener = (data: Buffer) => {
  754. output += data;
  755. if (/Debugger listening on ws:/m.test(output)) {
  756. cleanup();
  757. done();
  758. }
  759. };
  760. child.stderr.on('data', listener);
  761. child.stdout.on('data', listener);
  762. });
  763. it('Supports starting the v8 inspector with --inspect and a provided port', async () => {
  764. child = childProcess.spawn(process.execPath, ['--inspect=17364', path.join(fixtures, 'module', 'run-as-node.js')], {
  765. env: { ELECTRON_RUN_AS_NODE: 'true' }
  766. });
  767. exitPromise = once(child, 'exit');
  768. let output = '';
  769. const listener = (data: Buffer) => { output += data; };
  770. const cleanup = () => {
  771. child.stderr.removeListener('data', listener);
  772. child.stdout.removeListener('data', listener);
  773. };
  774. child.stderr.on('data', listener);
  775. child.stdout.on('data', listener);
  776. await once(child, 'exit');
  777. cleanup();
  778. if (/^Debugger listening on ws:/m.test(output)) {
  779. expect(output.trim()).to.contain(':17364', 'should be listening on port 17364');
  780. } else {
  781. throw new Error(`Unexpected output: ${output.toString()}`);
  782. }
  783. });
  784. it('Does not start the v8 inspector when --inspect is after a -- argument', async () => {
  785. child = childProcess.spawn(process.execPath, [path.join(fixtures, 'module', 'noop.js'), '--', '--inspect']);
  786. exitPromise = once(child, 'exit');
  787. let output = '';
  788. const listener = (data: Buffer) => { output += data; };
  789. child.stderr.on('data', listener);
  790. child.stdout.on('data', listener);
  791. await once(child, 'exit');
  792. if (output.trim().startsWith('Debugger listening on ws://')) {
  793. throw new Error('Inspector was started when it should not have been');
  794. }
  795. });
  796. // IPC Electron child process not supported on Windows.
  797. ifit(process.platform !== 'win32')('does not crash when quitting with the inspector connected', function (done) {
  798. child = childProcess.spawn(process.execPath, [path.join(fixtures, 'module', 'delay-exit'), '--inspect=0'], {
  799. stdio: ['ipc']
  800. }) as childProcess.ChildProcessWithoutNullStreams;
  801. exitPromise = once(child, 'exit');
  802. const cleanup = () => {
  803. child.stderr.removeListener('data', listener);
  804. child.stdout.removeListener('data', listener);
  805. };
  806. let output = '';
  807. const success = false;
  808. function listener (data: Buffer) {
  809. output += data;
  810. console.log(data.toString()); // NOTE: temporary debug logging to try to catch flake.
  811. const match = /^Debugger listening on (ws:\/\/.+:\d+\/.+)\n/m.exec(output.trim());
  812. if (match) {
  813. cleanup();
  814. // NOTE: temporary debug logging to try to catch flake.
  815. child.stderr.on('data', (m) => console.log(m.toString()));
  816. child.stdout.on('data', (m) => console.log(m.toString()));
  817. const w = (webContents as typeof ElectronInternal.WebContents).create();
  818. w.loadURL('about:blank')
  819. .then(() => w.executeJavaScript(`new Promise(resolve => {
  820. const connection = new WebSocket(${JSON.stringify(match[1])})
  821. connection.onopen = () => {
  822. connection.onclose = () => resolve()
  823. connection.close()
  824. }
  825. })`))
  826. .then(() => {
  827. w.destroy();
  828. child.send('plz-quit');
  829. done();
  830. });
  831. }
  832. }
  833. child.stderr.on('data', listener);
  834. child.stdout.on('data', listener);
  835. child.on('exit', () => {
  836. if (!success) cleanup();
  837. });
  838. });
  839. it('Supports js binding', async () => {
  840. child = childProcess.spawn(process.execPath, ['--inspect', path.join(fixtures, 'module', 'inspector-binding.js')], {
  841. env: { ELECTRON_RUN_AS_NODE: 'true' },
  842. stdio: ['ipc']
  843. }) as childProcess.ChildProcessWithoutNullStreams;
  844. exitPromise = once(child, 'exit');
  845. const [{ cmd, debuggerEnabled, success }] = await once(child, 'message');
  846. expect(cmd).to.equal('assert');
  847. expect(debuggerEnabled).to.be.true();
  848. expect(success).to.be.true();
  849. });
  850. });
  851. it('Can find a module using a package.json main field', () => {
  852. const result = childProcess.spawnSync(process.execPath, [path.resolve(fixtures, 'api', 'electron-main-module', 'app.asar')], { stdio: 'inherit' });
  853. expect(result.status).to.equal(0);
  854. });
  855. it('handles Promise timeouts correctly', async () => {
  856. const scriptPath = path.join(fixtures, 'module', 'node-promise-timer.js');
  857. const child = childProcess.spawn(process.execPath, [scriptPath], {
  858. env: { ELECTRON_RUN_AS_NODE: 'true' }
  859. });
  860. const [code, signal] = await once(child, 'exit');
  861. expect(code).to.equal(0);
  862. expect(signal).to.equal(null);
  863. child.kill();
  864. });
  865. it('performs microtask checkpoint correctly', (done) => {
  866. let timer : NodeJS.Timeout;
  867. const listener = () => {
  868. done(new Error('catch block is delayed to next tick'));
  869. };
  870. const f3 = async () => {
  871. return new Promise((resolve, reject) => {
  872. timer = setTimeout(listener);
  873. reject(new Error('oops'));
  874. });
  875. };
  876. setTimeout(() => {
  877. f3().catch(() => {
  878. clearTimeout(timer);
  879. done();
  880. });
  881. });
  882. });
  883. });