asar-fs-wrapper.ts 28 KB

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