node-spec.ts 36 KB

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