node-spec.ts 35 KB

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