fs-wrapper.ts 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872
  1. import { Buffer } from 'buffer';
  2. import * as path from 'path';
  3. import * as util from 'util';
  4. import type * as Crypto from 'crypto';
  5. const asar = process._linkedBinding('electron_common_asar');
  6. const Module = require('module');
  7. const Promise: PromiseConstructor = global.Promise;
  8. const envNoAsar = process.env.ELECTRON_NO_ASAR &&
  9. process.type !== 'browser' &&
  10. process.type !== 'renderer';
  11. const isAsarDisabled = () => process.noAsar || envNoAsar;
  12. const internalBinding = process.internalBinding!;
  13. delete process.internalBinding;
  14. const nextTick = (functionToCall: Function, args: any[] = []) => {
  15. process.nextTick(() => functionToCall(...args));
  16. };
  17. // Cache asar archive objects.
  18. const cachedArchives = new Map<string, NodeJS.AsarArchive>();
  19. const getOrCreateArchive = (archivePath: string) => {
  20. const isCached = cachedArchives.has(archivePath);
  21. if (isCached) {
  22. return cachedArchives.get(archivePath);
  23. }
  24. try {
  25. const newArchive = new asar.Archive(archivePath);
  26. cachedArchives.set(archivePath, newArchive);
  27. return newArchive;
  28. } catch {
  29. return null;
  30. }
  31. };
  32. const asarRe = /\.asar/i;
  33. const { getValidatedPath } = __non_webpack_require__('internal/fs/utils');
  34. // In the renderer node internals use the node global URL but we do not set that to be
  35. // the global URL instance. We need to do instanceof checks against the internal URL impl
  36. const { URL: NodeURL } = __non_webpack_require__('internal/url');
  37. // Separate asar package's path from full path.
  38. const splitPath = (archivePathOrBuffer: string | Buffer | URL) => {
  39. // Shortcut for disabled asar.
  40. if (isAsarDisabled()) return { isAsar: <const>false };
  41. // Check for a bad argument type.
  42. let archivePath = archivePathOrBuffer;
  43. if (Buffer.isBuffer(archivePathOrBuffer)) {
  44. archivePath = archivePathOrBuffer.toString();
  45. }
  46. if (archivePath instanceof NodeURL) {
  47. archivePath = getValidatedPath(archivePath);
  48. }
  49. if (typeof archivePath !== 'string') return { isAsar: <const>false };
  50. if (!asarRe.test(archivePath)) return { isAsar: <const>false };
  51. return asar.splitPath(path.normalize(archivePath));
  52. };
  53. // Convert asar archive's Stats object to fs's Stats object.
  54. let nextInode = 0;
  55. const uid = process.getuid?.() ?? 0;
  56. const gid = process.getgid?.() ?? 0;
  57. const fakeTime = new Date();
  58. const asarStatsToFsStats = function (stats: NodeJS.AsarFileStat) {
  59. const { Stats, constants } = require('fs');
  60. let mode = constants.S_IROTH ^ constants.S_IRGRP ^ constants.S_IRUSR ^ constants.S_IWUSR;
  61. if (stats.isFile) {
  62. mode ^= constants.S_IFREG;
  63. } else if (stats.isDirectory) {
  64. mode ^= constants.S_IFDIR;
  65. } else if (stats.isLink) {
  66. mode ^= constants.S_IFLNK;
  67. }
  68. return new Stats(
  69. 1, // dev
  70. mode, // mode
  71. 1, // nlink
  72. uid,
  73. gid,
  74. 0, // rdev
  75. undefined, // blksize
  76. ++nextInode, // ino
  77. stats.size,
  78. undefined, // blocks,
  79. fakeTime.getTime(), // atim_msec
  80. fakeTime.getTime(), // mtim_msec
  81. fakeTime.getTime(), // ctim_msec
  82. fakeTime.getTime() // birthtim_msec
  83. );
  84. };
  85. const enum AsarError {
  86. NOT_FOUND = 'NOT_FOUND',
  87. NOT_DIR = 'NOT_DIR',
  88. NO_ACCESS = 'NO_ACCESS',
  89. INVALID_ARCHIVE = 'INVALID_ARCHIVE'
  90. }
  91. type AsarErrorObject = Error & { code?: string, errno?: number };
  92. const createError = (errorType: AsarError, { asarPath, filePath }: { asarPath?: string, filePath?: string } = {}) => {
  93. let error: AsarErrorObject;
  94. switch (errorType) {
  95. case AsarError.NOT_FOUND:
  96. error = new Error(`ENOENT, ${filePath} not found in ${asarPath}`);
  97. error.code = 'ENOENT';
  98. error.errno = -2;
  99. break;
  100. case AsarError.NOT_DIR:
  101. error = new Error('ENOTDIR, not a directory');
  102. error.code = 'ENOTDIR';
  103. error.errno = -20;
  104. break;
  105. case AsarError.NO_ACCESS:
  106. error = new Error(`EACCES: permission denied, access '${filePath}'`);
  107. error.code = 'EACCES';
  108. error.errno = -13;
  109. break;
  110. case AsarError.INVALID_ARCHIVE:
  111. error = new Error(`Invalid package ${asarPath}`);
  112. break;
  113. default:
  114. throw new Error(`Invalid error type "${errorType}" passed to createError.`);
  115. }
  116. return error;
  117. };
  118. const overrideAPISync = function (module: Record<string, any>, name: string, pathArgumentIndex?: number | null, fromAsync: boolean = false) {
  119. if (pathArgumentIndex == null) pathArgumentIndex = 0;
  120. const old = module[name];
  121. const func = function (this: any, ...args: any[]) {
  122. const pathArgument = args[pathArgumentIndex!];
  123. const pathInfo = splitPath(pathArgument);
  124. if (!pathInfo.isAsar) return old.apply(this, args);
  125. const { asarPath, filePath } = pathInfo;
  126. const archive = getOrCreateArchive(asarPath);
  127. if (!archive) throw createError(AsarError.INVALID_ARCHIVE, { asarPath });
  128. const newPath = archive.copyFileOut(filePath);
  129. if (!newPath) throw createError(AsarError.NOT_FOUND, { asarPath, filePath });
  130. args[pathArgumentIndex!] = newPath;
  131. return old.apply(this, args);
  132. };
  133. if (fromAsync) {
  134. return func;
  135. }
  136. module[name] = func;
  137. };
  138. const overrideAPI = function (module: Record<string, any>, name: string, pathArgumentIndex?: number | null) {
  139. if (pathArgumentIndex == null) pathArgumentIndex = 0;
  140. const old = module[name];
  141. module[name] = function (this: any, ...args: any[]) {
  142. const pathArgument = args[pathArgumentIndex!];
  143. const pathInfo = splitPath(pathArgument);
  144. if (!pathInfo.isAsar) return old.apply(this, args);
  145. const { asarPath, filePath } = pathInfo;
  146. const callback = args[args.length - 1];
  147. if (typeof callback !== 'function') {
  148. return overrideAPISync(module, name, pathArgumentIndex!, true)!.apply(this, args);
  149. }
  150. const archive = getOrCreateArchive(asarPath);
  151. if (!archive) {
  152. const error = createError(AsarError.INVALID_ARCHIVE, { asarPath });
  153. nextTick(callback, [error]);
  154. return;
  155. }
  156. const newPath = archive.copyFileOut(filePath);
  157. if (!newPath) {
  158. const error = createError(AsarError.NOT_FOUND, { asarPath, filePath });
  159. nextTick(callback, [error]);
  160. return;
  161. }
  162. args[pathArgumentIndex!] = newPath;
  163. return old.apply(this, args);
  164. };
  165. if (old[util.promisify.custom]) {
  166. module[name][util.promisify.custom] = makePromiseFunction(old[util.promisify.custom], pathArgumentIndex);
  167. }
  168. if (module.promises && module.promises[name]) {
  169. module.promises[name] = makePromiseFunction(module.promises[name], pathArgumentIndex);
  170. }
  171. };
  172. let crypto: typeof Crypto;
  173. function validateBufferIntegrity (buffer: Buffer, integrity: NodeJS.AsarFileInfo['integrity']) {
  174. if (!integrity) return;
  175. // Delay load crypto to improve app boot performance
  176. // when integrity protection is not enabled
  177. crypto = crypto || require('crypto');
  178. const actual = crypto.createHash(integrity.algorithm).update(buffer).digest('hex');
  179. if (actual !== integrity.hash) {
  180. console.error(`ASAR Integrity Violation: got a hash mismatch (${actual} vs ${integrity.hash})`);
  181. process.exit(1);
  182. }
  183. }
  184. const makePromiseFunction = function (orig: Function, pathArgumentIndex: number) {
  185. return function (this: any, ...args: any[]) {
  186. const pathArgument = args[pathArgumentIndex];
  187. const pathInfo = splitPath(pathArgument);
  188. if (!pathInfo.isAsar) return orig.apply(this, args);
  189. const { asarPath, filePath } = pathInfo;
  190. const archive = getOrCreateArchive(asarPath);
  191. if (!archive) {
  192. return Promise.reject(createError(AsarError.INVALID_ARCHIVE, { asarPath }));
  193. }
  194. const newPath = archive.copyFileOut(filePath);
  195. if (!newPath) {
  196. return Promise.reject(createError(AsarError.NOT_FOUND, { asarPath, filePath }));
  197. }
  198. args[pathArgumentIndex] = newPath;
  199. return orig.apply(this, args);
  200. };
  201. };
  202. // Override fs APIs.
  203. export const wrapFsWithAsar = (fs: Record<string, any>) => {
  204. const logFDs = new Map<string, number>();
  205. const logASARAccess = (asarPath: string, filePath: string, offset: number) => {
  206. if (!process.env.ELECTRON_LOG_ASAR_READS) return;
  207. if (!logFDs.has(asarPath)) {
  208. const path = require('path');
  209. const logFilename = `${path.basename(asarPath, '.asar')}-access-log.txt`;
  210. const logPath = path.join(require('os').tmpdir(), logFilename);
  211. logFDs.set(asarPath, fs.openSync(logPath, 'a'));
  212. }
  213. fs.writeSync(logFDs.get(asarPath), `${offset}: ${filePath}\n`);
  214. };
  215. const { lstatSync } = fs;
  216. fs.lstatSync = (pathArgument: string, options: any) => {
  217. const pathInfo = splitPath(pathArgument);
  218. if (!pathInfo.isAsar) return lstatSync(pathArgument, options);
  219. const { asarPath, filePath } = pathInfo;
  220. const archive = getOrCreateArchive(asarPath);
  221. if (!archive) throw createError(AsarError.INVALID_ARCHIVE, { asarPath });
  222. const stats = archive.stat(filePath);
  223. if (!stats) throw createError(AsarError.NOT_FOUND, { asarPath, filePath });
  224. return asarStatsToFsStats(stats);
  225. };
  226. const { lstat } = fs;
  227. fs.lstat = (pathArgument: string, options: any, callback: any) => {
  228. const pathInfo = splitPath(pathArgument);
  229. if (typeof options === 'function') {
  230. callback = options;
  231. options = {};
  232. }
  233. if (!pathInfo.isAsar) return lstat(pathArgument, options, callback);
  234. const { asarPath, filePath } = pathInfo;
  235. const archive = getOrCreateArchive(asarPath);
  236. if (!archive) {
  237. const error = createError(AsarError.INVALID_ARCHIVE, { asarPath });
  238. nextTick(callback, [error]);
  239. return;
  240. }
  241. const stats = archive.stat(filePath);
  242. if (!stats) {
  243. const error = createError(AsarError.NOT_FOUND, { asarPath, filePath });
  244. nextTick(callback, [error]);
  245. return;
  246. }
  247. const fsStats = asarStatsToFsStats(stats);
  248. nextTick(callback, [null, fsStats]);
  249. };
  250. fs.promises.lstat = util.promisify(fs.lstat);
  251. const { statSync } = fs;
  252. fs.statSync = (pathArgument: string, options: any) => {
  253. const { isAsar } = splitPath(pathArgument);
  254. if (!isAsar) return statSync(pathArgument, options);
  255. // Do not distinguish links for now.
  256. return fs.lstatSync(pathArgument, options);
  257. };
  258. const { stat } = fs;
  259. fs.stat = (pathArgument: string, options: any, callback: any) => {
  260. const { isAsar } = splitPath(pathArgument);
  261. if (typeof options === 'function') {
  262. callback = options;
  263. options = {};
  264. }
  265. if (!isAsar) return stat(pathArgument, options, callback);
  266. // Do not distinguish links for now.
  267. process.nextTick(() => fs.lstat(pathArgument, options, callback));
  268. };
  269. fs.promises.stat = util.promisify(fs.stat);
  270. const wrapRealpathSync = function (realpathSync: Function) {
  271. return function (this: any, pathArgument: string, options: any) {
  272. const pathInfo = splitPath(pathArgument);
  273. if (!pathInfo.isAsar) return realpathSync.apply(this, arguments);
  274. const { asarPath, filePath } = pathInfo;
  275. const archive = getOrCreateArchive(asarPath);
  276. if (!archive) {
  277. throw createError(AsarError.INVALID_ARCHIVE, { asarPath });
  278. }
  279. const fileRealPath = archive.realpath(filePath);
  280. if (fileRealPath === false) {
  281. throw createError(AsarError.NOT_FOUND, { asarPath, filePath });
  282. }
  283. return path.join(realpathSync(asarPath, options), fileRealPath);
  284. };
  285. };
  286. const { realpathSync } = fs;
  287. fs.realpathSync = wrapRealpathSync(realpathSync);
  288. fs.realpathSync.native = wrapRealpathSync(realpathSync.native);
  289. const wrapRealpath = function (realpath: Function) {
  290. return function (this: any, pathArgument: string, options: any, callback: any) {
  291. const pathInfo = splitPath(pathArgument);
  292. if (!pathInfo.isAsar) return realpath.apply(this, arguments);
  293. const { asarPath, filePath } = pathInfo;
  294. if (arguments.length < 3) {
  295. callback = options;
  296. options = {};
  297. }
  298. const archive = getOrCreateArchive(asarPath);
  299. if (!archive) {
  300. const error = createError(AsarError.INVALID_ARCHIVE, { asarPath });
  301. nextTick(callback, [error]);
  302. return;
  303. }
  304. const fileRealPath = archive.realpath(filePath);
  305. if (fileRealPath === false) {
  306. const error = createError(AsarError.NOT_FOUND, { asarPath, filePath });
  307. nextTick(callback, [error]);
  308. return;
  309. }
  310. realpath(asarPath, options, (error: Error | null, archiveRealPath: string) => {
  311. if (error === null) {
  312. const fullPath = path.join(archiveRealPath, fileRealPath);
  313. callback(null, fullPath);
  314. } else {
  315. callback(error);
  316. }
  317. });
  318. };
  319. };
  320. const { realpath } = fs;
  321. fs.realpath = wrapRealpath(realpath);
  322. fs.realpath.native = wrapRealpath(realpath.native);
  323. fs.promises.realpath = util.promisify(fs.realpath.native);
  324. const { exists: nativeExists } = fs;
  325. fs.exists = function exists (pathArgument: string, callback: any) {
  326. let pathInfo: ReturnType<typeof splitPath>;
  327. try {
  328. pathInfo = splitPath(pathArgument);
  329. } catch {
  330. nextTick(callback, [false]);
  331. return;
  332. }
  333. if (!pathInfo.isAsar) return nativeExists(pathArgument, callback);
  334. const { asarPath, filePath } = pathInfo;
  335. const archive = getOrCreateArchive(asarPath);
  336. if (!archive) {
  337. const error = createError(AsarError.INVALID_ARCHIVE, { asarPath });
  338. nextTick(callback, [error]);
  339. return;
  340. }
  341. const pathExists = (archive.stat(filePath) !== false);
  342. nextTick(callback, [pathExists]);
  343. };
  344. fs.exists[util.promisify.custom] = function exists (pathArgument: string) {
  345. const pathInfo = splitPath(pathArgument);
  346. if (!pathInfo.isAsar) return nativeExists[util.promisify.custom](pathArgument);
  347. const { asarPath, filePath } = pathInfo;
  348. const archive = getOrCreateArchive(asarPath);
  349. if (!archive) {
  350. const error = createError(AsarError.INVALID_ARCHIVE, { asarPath });
  351. return Promise.reject(error);
  352. }
  353. return Promise.resolve(archive.stat(filePath) !== false);
  354. };
  355. const { existsSync } = fs;
  356. fs.existsSync = (pathArgument: string) => {
  357. let pathInfo: ReturnType<typeof splitPath>;
  358. try {
  359. pathInfo = splitPath(pathArgument);
  360. } catch {
  361. return false;
  362. }
  363. if (!pathInfo.isAsar) return existsSync(pathArgument);
  364. const { asarPath, filePath } = pathInfo;
  365. const archive = getOrCreateArchive(asarPath);
  366. if (!archive) return false;
  367. return archive.stat(filePath) !== false;
  368. };
  369. const { access } = fs;
  370. fs.access = function (pathArgument: string, mode: any, callback: any) {
  371. const pathInfo = splitPath(pathArgument);
  372. if (!pathInfo.isAsar) return access.apply(this, arguments);
  373. const { asarPath, filePath } = pathInfo;
  374. if (typeof mode === 'function') {
  375. callback = mode;
  376. mode = fs.constants.F_OK;
  377. }
  378. const archive = getOrCreateArchive(asarPath);
  379. if (!archive) {
  380. const error = createError(AsarError.INVALID_ARCHIVE, { asarPath });
  381. nextTick(callback, [error]);
  382. return;
  383. }
  384. const info = archive.getFileInfo(filePath);
  385. if (!info) {
  386. const error = createError(AsarError.NOT_FOUND, { asarPath, filePath });
  387. nextTick(callback, [error]);
  388. return;
  389. }
  390. if (info.unpacked) {
  391. const realPath = archive.copyFileOut(filePath);
  392. return fs.access(realPath, mode, callback);
  393. }
  394. const stats = archive.stat(filePath);
  395. if (!stats) {
  396. const error = createError(AsarError.NOT_FOUND, { asarPath, filePath });
  397. nextTick(callback, [error]);
  398. return;
  399. }
  400. if (mode & fs.constants.W_OK) {
  401. const error = createError(AsarError.NO_ACCESS, { asarPath, filePath });
  402. nextTick(callback, [error]);
  403. return;
  404. }
  405. nextTick(callback);
  406. };
  407. fs.promises.access = util.promisify(fs.access);
  408. const { accessSync } = fs;
  409. fs.accessSync = function (pathArgument: string, mode: any) {
  410. const pathInfo = splitPath(pathArgument);
  411. if (!pathInfo.isAsar) return accessSync.apply(this, arguments);
  412. const { asarPath, filePath } = pathInfo;
  413. if (mode == null) mode = fs.constants.F_OK;
  414. const archive = getOrCreateArchive(asarPath);
  415. if (!archive) {
  416. throw createError(AsarError.INVALID_ARCHIVE, { asarPath });
  417. }
  418. const info = archive.getFileInfo(filePath);
  419. if (!info) {
  420. throw createError(AsarError.NOT_FOUND, { asarPath, filePath });
  421. }
  422. if (info.unpacked) {
  423. const realPath = archive.copyFileOut(filePath);
  424. return fs.accessSync(realPath, mode);
  425. }
  426. const stats = archive.stat(filePath);
  427. if (!stats) {
  428. throw createError(AsarError.NOT_FOUND, { asarPath, filePath });
  429. }
  430. if (mode & fs.constants.W_OK) {
  431. throw createError(AsarError.NO_ACCESS, { asarPath, filePath });
  432. }
  433. };
  434. function fsReadFileAsar (pathArgument: string, options: any, callback: any) {
  435. const pathInfo = splitPath(pathArgument);
  436. if (pathInfo.isAsar) {
  437. const { asarPath, filePath } = pathInfo;
  438. if (typeof options === 'function') {
  439. callback = options;
  440. options = { encoding: null };
  441. } else if (typeof options === 'string') {
  442. options = { encoding: options };
  443. } else if (options === null || options === undefined) {
  444. options = { encoding: null };
  445. } else if (typeof options !== 'object') {
  446. throw new TypeError('Bad arguments');
  447. }
  448. const { encoding } = options;
  449. const archive = getOrCreateArchive(asarPath);
  450. if (!archive) {
  451. const error = createError(AsarError.INVALID_ARCHIVE, { asarPath });
  452. nextTick(callback, [error]);
  453. return;
  454. }
  455. const info = archive.getFileInfo(filePath);
  456. if (!info) {
  457. const error = createError(AsarError.NOT_FOUND, { asarPath, filePath });
  458. nextTick(callback, [error]);
  459. return;
  460. }
  461. if (info.size === 0) {
  462. nextTick(callback, [null, encoding ? '' : Buffer.alloc(0)]);
  463. return;
  464. }
  465. if (info.unpacked) {
  466. const realPath = archive.copyFileOut(filePath);
  467. return fs.readFile(realPath, options, callback);
  468. }
  469. const buffer = Buffer.alloc(info.size);
  470. const fd = archive.getFdAndValidateIntegrityLater();
  471. if (!(fd >= 0)) {
  472. const error = createError(AsarError.NOT_FOUND, { asarPath, filePath });
  473. nextTick(callback, [error]);
  474. return;
  475. }
  476. logASARAccess(asarPath, filePath, info.offset);
  477. fs.read(fd, buffer, 0, info.size, info.offset, (error: Error) => {
  478. validateBufferIntegrity(buffer, info.integrity);
  479. callback(error, encoding ? buffer.toString(encoding) : buffer);
  480. });
  481. }
  482. }
  483. const { readFile } = fs;
  484. fs.readFile = function (pathArgument: string, options: any, callback: any) {
  485. const pathInfo = splitPath(pathArgument);
  486. if (!pathInfo.isAsar) {
  487. return readFile.apply(this, arguments);
  488. }
  489. return fsReadFileAsar(pathArgument, options, callback);
  490. };
  491. const { readFile: readFilePromise } = fs.promises;
  492. fs.promises.readFile = function (pathArgument: string, options: any) {
  493. const pathInfo = splitPath(pathArgument);
  494. if (!pathInfo.isAsar) {
  495. return readFilePromise.apply(this, arguments);
  496. }
  497. const p = util.promisify(fsReadFileAsar);
  498. return p(pathArgument, options);
  499. };
  500. const { readFileSync } = fs;
  501. fs.readFileSync = function (pathArgument: string, options: any) {
  502. const pathInfo = splitPath(pathArgument);
  503. if (!pathInfo.isAsar) return readFileSync.apply(this, arguments);
  504. const { asarPath, filePath } = pathInfo;
  505. const archive = getOrCreateArchive(asarPath);
  506. if (!archive) throw createError(AsarError.INVALID_ARCHIVE, { asarPath });
  507. const info = archive.getFileInfo(filePath);
  508. if (!info) throw createError(AsarError.NOT_FOUND, { asarPath, filePath });
  509. if (info.size === 0) return (options) ? '' : Buffer.alloc(0);
  510. if (info.unpacked) {
  511. const realPath = archive.copyFileOut(filePath);
  512. return fs.readFileSync(realPath, options);
  513. }
  514. if (!options) {
  515. options = { encoding: null };
  516. } else if (typeof options === 'string') {
  517. options = { encoding: options };
  518. } else if (typeof options !== 'object') {
  519. throw new TypeError('Bad arguments');
  520. }
  521. const { encoding } = options;
  522. const buffer = Buffer.alloc(info.size);
  523. const fd = archive.getFdAndValidateIntegrityLater();
  524. if (!(fd >= 0)) throw createError(AsarError.NOT_FOUND, { asarPath, filePath });
  525. logASARAccess(asarPath, filePath, info.offset);
  526. fs.readSync(fd, buffer, 0, info.size, info.offset);
  527. validateBufferIntegrity(buffer, info.integrity);
  528. return (encoding) ? buffer.toString(encoding) : buffer;
  529. };
  530. const { readdir } = fs;
  531. fs.readdir = function (pathArgument: string, options?: { encoding?: string | null; withFileTypes?: boolean } | null, callback?: Function) {
  532. const pathInfo = splitPath(pathArgument);
  533. if (typeof options === 'function') {
  534. callback = options;
  535. options = undefined;
  536. }
  537. if (!pathInfo.isAsar) return readdir.apply(this, arguments);
  538. const { asarPath, filePath } = pathInfo;
  539. const archive = getOrCreateArchive(asarPath);
  540. if (!archive) {
  541. const error = createError(AsarError.INVALID_ARCHIVE, { asarPath });
  542. nextTick(callback!, [error]);
  543. return;
  544. }
  545. const files = archive.readdir(filePath);
  546. if (!files) {
  547. const error = createError(AsarError.NOT_FOUND, { asarPath, filePath });
  548. nextTick(callback!, [error]);
  549. return;
  550. }
  551. if (options?.withFileTypes) {
  552. const dirents = [];
  553. for (const file of files) {
  554. const childPath = path.join(filePath, file);
  555. const stats = archive.stat(childPath);
  556. if (!stats) {
  557. const error = createError(AsarError.NOT_FOUND, { asarPath, filePath: childPath });
  558. nextTick(callback!, [error]);
  559. return;
  560. }
  561. if (stats.isFile) {
  562. dirents.push(new fs.Dirent(file, fs.constants.UV_DIRENT_FILE));
  563. } else if (stats.isDirectory) {
  564. dirents.push(new fs.Dirent(file, fs.constants.UV_DIRENT_DIR));
  565. } else if (stats.isLink) {
  566. dirents.push(new fs.Dirent(file, fs.constants.UV_DIRENT_LINK));
  567. }
  568. }
  569. nextTick(callback!, [null, dirents]);
  570. return;
  571. }
  572. nextTick(callback!, [null, files]);
  573. };
  574. fs.promises.readdir = util.promisify(fs.readdir);
  575. type ReaddirSyncOptions = { encoding: BufferEncoding | null; withFileTypes?: false };
  576. const { readdirSync } = fs;
  577. fs.readdirSync = function (pathArgument: string, options: ReaddirSyncOptions | BufferEncoding | null) {
  578. const pathInfo = splitPath(pathArgument);
  579. if (!pathInfo.isAsar) return readdirSync.apply(this, arguments);
  580. const { asarPath, filePath } = pathInfo;
  581. const archive = getOrCreateArchive(asarPath);
  582. if (!archive) {
  583. throw createError(AsarError.INVALID_ARCHIVE, { asarPath });
  584. }
  585. const files = archive.readdir(filePath);
  586. if (!files) {
  587. throw createError(AsarError.NOT_FOUND, { asarPath, filePath });
  588. }
  589. if (options && (options as ReaddirSyncOptions).withFileTypes) {
  590. const dirents = [];
  591. for (const file of files) {
  592. const childPath = path.join(filePath, file);
  593. const stats = archive.stat(childPath);
  594. if (!stats) {
  595. throw createError(AsarError.NOT_FOUND, { asarPath, filePath: childPath });
  596. }
  597. if (stats.isFile) {
  598. dirents.push(new fs.Dirent(file, fs.constants.UV_DIRENT_FILE));
  599. } else if (stats.isDirectory) {
  600. dirents.push(new fs.Dirent(file, fs.constants.UV_DIRENT_DIR));
  601. } else if (stats.isLink) {
  602. dirents.push(new fs.Dirent(file, fs.constants.UV_DIRENT_LINK));
  603. }
  604. }
  605. return dirents;
  606. }
  607. return files;
  608. };
  609. const { internalModuleReadJSON } = internalBinding('fs');
  610. internalBinding('fs').internalModuleReadJSON = (pathArgument: string) => {
  611. const pathInfo = splitPath(pathArgument);
  612. if (!pathInfo.isAsar) return internalModuleReadJSON(pathArgument);
  613. const { asarPath, filePath } = pathInfo;
  614. const archive = getOrCreateArchive(asarPath);
  615. if (!archive) return [];
  616. const info = archive.getFileInfo(filePath);
  617. if (!info) return [];
  618. if (info.size === 0) return ['', false];
  619. if (info.unpacked) {
  620. const realPath = archive.copyFileOut(filePath);
  621. const str = fs.readFileSync(realPath, { encoding: 'utf8' });
  622. return [str, str.length > 0];
  623. }
  624. const buffer = Buffer.alloc(info.size);
  625. const fd = archive.getFdAndValidateIntegrityLater();
  626. if (!(fd >= 0)) return [];
  627. logASARAccess(asarPath, filePath, info.offset);
  628. fs.readSync(fd, buffer, 0, info.size, info.offset);
  629. validateBufferIntegrity(buffer, info.integrity);
  630. const str = buffer.toString('utf8');
  631. return [str, str.length > 0];
  632. };
  633. const { internalModuleStat } = internalBinding('fs');
  634. internalBinding('fs').internalModuleStat = (pathArgument: string) => {
  635. const pathInfo = splitPath(pathArgument);
  636. if (!pathInfo.isAsar) return internalModuleStat(pathArgument);
  637. const { asarPath, filePath } = pathInfo;
  638. // -ENOENT
  639. const archive = getOrCreateArchive(asarPath);
  640. if (!archive) return -34;
  641. // -ENOENT
  642. const stats = archive.stat(filePath);
  643. if (!stats) return -34;
  644. return (stats.isDirectory) ? 1 : 0;
  645. };
  646. // Calling mkdir for directory inside asar archive should throw ENOTDIR
  647. // error, but on Windows it throws ENOENT.
  648. if (process.platform === 'win32') {
  649. const { mkdir } = fs;
  650. fs.mkdir = (pathArgument: string, options: any, callback: any) => {
  651. if (typeof options === 'function') {
  652. callback = options;
  653. options = {};
  654. }
  655. const pathInfo = splitPath(pathArgument);
  656. if (pathInfo.isAsar && pathInfo.filePath.length > 0) {
  657. const error = createError(AsarError.NOT_DIR);
  658. nextTick(callback, [error]);
  659. return;
  660. }
  661. mkdir(pathArgument, options, callback);
  662. };
  663. fs.promises.mkdir = util.promisify(fs.mkdir);
  664. const { mkdirSync } = fs;
  665. fs.mkdirSync = function (pathArgument: string, options: any) {
  666. const pathInfo = splitPath(pathArgument);
  667. if (pathInfo.isAsar && pathInfo.filePath.length) throw createError(AsarError.NOT_DIR);
  668. return mkdirSync(pathArgument, options);
  669. };
  670. }
  671. function invokeWithNoAsar (func: Function) {
  672. return function (this: any) {
  673. const processNoAsarOriginalValue = process.noAsar;
  674. process.noAsar = true;
  675. try {
  676. return func.apply(this, arguments);
  677. } finally {
  678. process.noAsar = processNoAsarOriginalValue;
  679. }
  680. };
  681. }
  682. // Strictly implementing the flags of fs.copyFile is hard, just do a simple
  683. // implementation for now. Doing 2 copies won't spend much time more as OS
  684. // has filesystem caching.
  685. overrideAPI(fs, 'copyFile');
  686. overrideAPISync(fs, 'copyFileSync');
  687. overrideAPI(fs, 'open');
  688. overrideAPISync(process, 'dlopen', 1);
  689. overrideAPISync(Module._extensions, '.node', 1);
  690. overrideAPISync(fs, 'openSync');
  691. const overrideChildProcess = (childProcess: Record<string, any>) => {
  692. // Executing a command string containing a path to an asar archive
  693. // confuses `childProcess.execFile`, which is internally called by
  694. // `childProcess.{exec,execSync}`, causing Electron to consider the full
  695. // command as a single path to an archive.
  696. const { exec, execSync } = childProcess;
  697. childProcess.exec = invokeWithNoAsar(exec);
  698. childProcess.exec[util.promisify.custom] = invokeWithNoAsar(exec[util.promisify.custom]);
  699. childProcess.execSync = invokeWithNoAsar(execSync);
  700. overrideAPI(childProcess, 'execFile');
  701. overrideAPISync(childProcess, 'execFileSync');
  702. };
  703. const asarReady = new WeakSet();
  704. // Lazily override the child_process APIs only when child_process is
  705. // fetched the first time. We will eagerly override the child_process APIs
  706. // when this env var is set so that stack traces generated inside node unit
  707. // tests will match. This env var will only slow things down in users apps
  708. // and should not be used.
  709. if (process.env.ELECTRON_EAGER_ASAR_HOOK_FOR_TESTING) {
  710. overrideChildProcess(require('child_process'));
  711. } else {
  712. const originalModuleLoad = Module._load;
  713. Module._load = (request: string, ...args: any[]) => {
  714. const loadResult = originalModuleLoad(request, ...args);
  715. if (request === 'child_process' || request === 'node:child_process') {
  716. if (!asarReady.has(loadResult)) {
  717. asarReady.add(loadResult);
  718. // Just to make it obvious what we are dealing with here
  719. const childProcess = loadResult;
  720. overrideChildProcess(childProcess);
  721. }
  722. }
  723. return loadResult;
  724. };
  725. }
  726. };