fs-wrapper.ts 28 KB

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