node-spec.ts 32 KB

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