node-spec.ts 33 KB

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