node-spec.ts 36 KB

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