node-spec.ts 35 KB

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