node-spec.ts 31 KB

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