asar-fs-wrapper.ts 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164
  1. import { Buffer } from 'buffer';
  2. import { Dirent, 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 {
  37. getValidatedPath,
  38. getOptions,
  39. getDirent
  40. } = __non_webpack_require__('internal/fs/utils');
  41. const {
  42. validateBoolean,
  43. validateFunction
  44. } = __non_webpack_require__('internal/validators');
  45. // In the renderer node internals use the node global URL but we do not set that to be
  46. // the global URL instance. We need to do instanceof checks against the internal URL impl
  47. const { URL: NodeURL } = __non_webpack_require__('internal/url');
  48. // Separate asar package's path from full path.
  49. const splitPath = (archivePathOrBuffer: string | Buffer | URL) => {
  50. // Shortcut for disabled asar.
  51. if (isAsarDisabled()) return { isAsar: <const>false };
  52. // Check for a bad argument type.
  53. let archivePath = archivePathOrBuffer;
  54. if (Buffer.isBuffer(archivePathOrBuffer)) {
  55. archivePath = archivePathOrBuffer.toString();
  56. }
  57. if (archivePath instanceof NodeURL) {
  58. archivePath = getValidatedPath(archivePath);
  59. }
  60. if (typeof archivePath !== 'string') return { isAsar: <const>false };
  61. if (!asarRe.test(archivePath)) return { isAsar: <const>false };
  62. return asar.splitPath(path.normalize(archivePath));
  63. };
  64. // Convert asar archive's Stats object to fs's Stats object.
  65. let nextInode = 0;
  66. const uid = process.getuid?.() ?? 0;
  67. const gid = process.getgid?.() ?? 0;
  68. const fakeTime = new Date();
  69. function getDirents (p: string, { 0: names, 1: types }: any[][]): Dirent[] {
  70. for (let i = 0; i < names.length; i++) {
  71. let type = types[i];
  72. const info = splitPath(path.join(p, names[i]));
  73. if (info.isAsar) {
  74. const archive = getOrCreateArchive(info.asarPath);
  75. if (!archive) continue;
  76. const stats = archive.stat(info.filePath);
  77. if (!stats) continue;
  78. type = stats.type;
  79. }
  80. names[i] = getDirent(p, names[i], type);
  81. }
  82. return names;
  83. }
  84. enum AsarFileType {
  85. kFile = (constants as any).UV_DIRENT_FILE,
  86. kDirectory = (constants as any).UV_DIRENT_DIR,
  87. kLink = (constants as any).UV_DIRENT_LINK,
  88. }
  89. const fileTypeToMode = new Map<AsarFileType, number>([
  90. [AsarFileType.kFile, constants.S_IFREG],
  91. [AsarFileType.kDirectory, constants.S_IFDIR],
  92. [AsarFileType.kLink, constants.S_IFLNK]
  93. ]);
  94. const asarStatsToFsStats = function (stats: NodeJS.AsarFileStat) {
  95. const { Stats } = require('fs');
  96. const mode = constants.S_IROTH | constants.S_IRGRP | constants.S_IRUSR | constants.S_IWUSR | fileTypeToMode.get(stats.type)!;
  97. return new Stats(
  98. 1, // dev
  99. mode, // mode
  100. 1, // nlink
  101. uid,
  102. gid,
  103. 0, // rdev
  104. undefined, // blksize
  105. ++nextInode, // ino
  106. stats.size,
  107. undefined, // blocks,
  108. fakeTime.getTime(), // atim_msec
  109. fakeTime.getTime(), // mtim_msec
  110. fakeTime.getTime(), // ctim_msec
  111. fakeTime.getTime() // birthtim_msec
  112. );
  113. };
  114. const enum AsarError {
  115. NOT_FOUND = 'NOT_FOUND',
  116. NOT_DIR = 'NOT_DIR',
  117. NO_ACCESS = 'NO_ACCESS',
  118. INVALID_ARCHIVE = 'INVALID_ARCHIVE'
  119. }
  120. type AsarErrorObject = Error & { code?: string, errno?: number };
  121. const createError = (errorType: AsarError, { asarPath, filePath }: { asarPath?: string, filePath?: string } = {}) => {
  122. let error: AsarErrorObject;
  123. switch (errorType) {
  124. case AsarError.NOT_FOUND:
  125. error = new Error(`ENOENT, ${filePath} not found in ${asarPath}`);
  126. error.code = 'ENOENT';
  127. error.errno = -2;
  128. break;
  129. case AsarError.NOT_DIR:
  130. error = new Error('ENOTDIR, not a directory');
  131. error.code = 'ENOTDIR';
  132. error.errno = -20;
  133. break;
  134. case AsarError.NO_ACCESS:
  135. error = new Error(`EACCES: permission denied, access '${filePath}'`);
  136. error.code = 'EACCES';
  137. error.errno = -13;
  138. break;
  139. case AsarError.INVALID_ARCHIVE:
  140. error = new Error(`Invalid package ${asarPath}`);
  141. break;
  142. default:
  143. throw new Error(`Invalid error type "${errorType}" passed to createError.`);
  144. }
  145. return error;
  146. };
  147. const overrideAPISync = function (module: Record<string, any>, name: string, pathArgumentIndex?: number | null, fromAsync: boolean = false) {
  148. if (pathArgumentIndex == null) pathArgumentIndex = 0;
  149. const old = module[name];
  150. const func = function (this: any, ...args: any[]) {
  151. const pathArgument = args[pathArgumentIndex!];
  152. const pathInfo = splitPath(pathArgument);
  153. if (!pathInfo.isAsar) return old.apply(this, args);
  154. const { asarPath, filePath } = pathInfo;
  155. const archive = getOrCreateArchive(asarPath);
  156. if (!archive) throw createError(AsarError.INVALID_ARCHIVE, { asarPath });
  157. const newPath = archive.copyFileOut(filePath);
  158. if (!newPath) throw createError(AsarError.NOT_FOUND, { asarPath, filePath });
  159. args[pathArgumentIndex!] = newPath;
  160. return old.apply(this, args);
  161. };
  162. if (fromAsync) {
  163. return func;
  164. }
  165. module[name] = func;
  166. };
  167. const overrideAPI = function (module: Record<string, any>, name: string, pathArgumentIndex?: number | null) {
  168. if (pathArgumentIndex == null) pathArgumentIndex = 0;
  169. const old = module[name];
  170. module[name] = function (this: any, ...args: any[]) {
  171. const pathArgument = args[pathArgumentIndex!];
  172. const pathInfo = splitPath(pathArgument);
  173. if (!pathInfo.isAsar) return old.apply(this, args);
  174. const { asarPath, filePath } = pathInfo;
  175. const callback = args[args.length - 1];
  176. if (typeof callback !== 'function') {
  177. return overrideAPISync(module, name, pathArgumentIndex!, true)!.apply(this, args);
  178. }
  179. const archive = getOrCreateArchive(asarPath);
  180. if (!archive) {
  181. const error = createError(AsarError.INVALID_ARCHIVE, { asarPath });
  182. nextTick(callback, [error]);
  183. return;
  184. }
  185. const newPath = archive.copyFileOut(filePath);
  186. if (!newPath) {
  187. const error = createError(AsarError.NOT_FOUND, { asarPath, filePath });
  188. nextTick(callback, [error]);
  189. return;
  190. }
  191. args[pathArgumentIndex!] = newPath;
  192. return old.apply(this, args);
  193. };
  194. if (old[util.promisify.custom]) {
  195. module[name][util.promisify.custom] = makePromiseFunction(old[util.promisify.custom], pathArgumentIndex);
  196. }
  197. if (module.promises && module.promises[name]) {
  198. module.promises[name] = makePromiseFunction(module.promises[name], pathArgumentIndex);
  199. }
  200. };
  201. let crypto: typeof Crypto;
  202. function validateBufferIntegrity (buffer: Buffer, integrity: NodeJS.AsarFileInfo['integrity']) {
  203. if (!integrity) return;
  204. // Delay load crypto to improve app boot performance
  205. // when integrity protection is not enabled
  206. crypto = crypto || require('crypto');
  207. const actual = crypto.createHash(integrity.algorithm).update(buffer).digest('hex');
  208. if (actual !== integrity.hash) {
  209. console.error(`ASAR Integrity Violation: got a hash mismatch (${actual} vs ${integrity.hash})`);
  210. process.exit(1);
  211. }
  212. }
  213. const makePromiseFunction = function (orig: Function, pathArgumentIndex: number) {
  214. return function (this: any, ...args: any[]) {
  215. const pathArgument = args[pathArgumentIndex];
  216. const pathInfo = splitPath(pathArgument);
  217. if (!pathInfo.isAsar) return orig.apply(this, args);
  218. const { asarPath, filePath } = pathInfo;
  219. const archive = getOrCreateArchive(asarPath);
  220. if (!archive) {
  221. return Promise.reject(createError(AsarError.INVALID_ARCHIVE, { asarPath }));
  222. }
  223. const newPath = archive.copyFileOut(filePath);
  224. if (!newPath) {
  225. return Promise.reject(createError(AsarError.NOT_FOUND, { asarPath, filePath }));
  226. }
  227. args[pathArgumentIndex] = newPath;
  228. return orig.apply(this, args);
  229. };
  230. };
  231. // Override fs APIs.
  232. export const wrapFsWithAsar = (fs: Record<string, any>) => {
  233. const logFDs = new Map<string, number>();
  234. const logASARAccess = (asarPath: string, filePath: string, offset: number) => {
  235. if (!process.env.ELECTRON_LOG_ASAR_READS) return;
  236. if (!logFDs.has(asarPath)) {
  237. const logFilename = `${path.basename(asarPath, '.asar')}-access-log.txt`;
  238. const logPath = path.join((require('os') as typeof os).tmpdir(), logFilename);
  239. logFDs.set(asarPath, fs.openSync(logPath, 'a'));
  240. }
  241. fs.writeSync(logFDs.get(asarPath), `${offset}: ${filePath}\n`);
  242. };
  243. const shouldThrowStatError = (options: any) => {
  244. if (options && typeof options === 'object' && options.throwIfNoEntry === false) {
  245. return false;
  246. }
  247. return true;
  248. };
  249. const { lstatSync } = fs;
  250. fs.lstatSync = (pathArgument: string, options: any) => {
  251. const pathInfo = splitPath(pathArgument);
  252. if (!pathInfo.isAsar) return lstatSync(pathArgument, options);
  253. const { asarPath, filePath } = pathInfo;
  254. const archive = getOrCreateArchive(asarPath);
  255. if (!archive) {
  256. if (shouldThrowStatError(options)) throw createError(AsarError.INVALID_ARCHIVE, { asarPath });
  257. return null;
  258. }
  259. const stats = archive.stat(filePath);
  260. if (!stats) {
  261. if (shouldThrowStatError(options)) throw createError(AsarError.NOT_FOUND, { asarPath, filePath });
  262. return null;
  263. }
  264. return asarStatsToFsStats(stats);
  265. };
  266. const { lstat } = fs;
  267. fs.lstat = (pathArgument: string, options: any, callback: any) => {
  268. const pathInfo = splitPath(pathArgument);
  269. if (typeof options === 'function') {
  270. callback = options;
  271. options = {};
  272. }
  273. if (!pathInfo.isAsar) return lstat(pathArgument, options, callback);
  274. const { asarPath, filePath } = pathInfo;
  275. const archive = getOrCreateArchive(asarPath);
  276. if (!archive) {
  277. const error = createError(AsarError.INVALID_ARCHIVE, { asarPath });
  278. nextTick(callback, [error]);
  279. return;
  280. }
  281. const stats = archive.stat(filePath);
  282. if (!stats) {
  283. const error = createError(AsarError.NOT_FOUND, { asarPath, filePath });
  284. nextTick(callback, [error]);
  285. return;
  286. }
  287. const fsStats = asarStatsToFsStats(stats);
  288. nextTick(callback, [null, fsStats]);
  289. };
  290. fs.promises.lstat = util.promisify(fs.lstat);
  291. const { statSync } = fs;
  292. fs.statSync = (pathArgument: string, options: any) => {
  293. const { isAsar } = splitPath(pathArgument);
  294. if (!isAsar) return statSync(pathArgument, options);
  295. // Do not distinguish links for now.
  296. return fs.lstatSync(pathArgument, options);
  297. };
  298. const { stat } = fs;
  299. fs.stat = (pathArgument: string, options: any, callback: any) => {
  300. const { isAsar } = splitPath(pathArgument);
  301. if (typeof options === 'function') {
  302. callback = options;
  303. options = {};
  304. }
  305. if (!isAsar) return stat(pathArgument, options, callback);
  306. // Do not distinguish links for now.
  307. process.nextTick(() => fs.lstat(pathArgument, options, callback));
  308. };
  309. fs.promises.stat = util.promisify(fs.stat);
  310. const wrapRealpathSync = function (realpathSync: Function) {
  311. return function (this: any, pathArgument: string, options: any) {
  312. const pathInfo = splitPath(pathArgument);
  313. if (!pathInfo.isAsar) return realpathSync.apply(this, arguments);
  314. const { asarPath, filePath } = pathInfo;
  315. const archive = getOrCreateArchive(asarPath);
  316. if (!archive) {
  317. throw createError(AsarError.INVALID_ARCHIVE, { asarPath });
  318. }
  319. const fileRealPath = archive.realpath(filePath);
  320. if (fileRealPath === false) {
  321. throw createError(AsarError.NOT_FOUND, { asarPath, filePath });
  322. }
  323. return path.join(realpathSync(asarPath, options), fileRealPath);
  324. };
  325. };
  326. const { realpathSync } = fs;
  327. fs.realpathSync = wrapRealpathSync(realpathSync);
  328. fs.realpathSync.native = wrapRealpathSync(realpathSync.native);
  329. const wrapRealpath = function (realpath: Function) {
  330. return function (this: any, pathArgument: string, options: any, callback: any) {
  331. const pathInfo = splitPath(pathArgument);
  332. if (!pathInfo.isAsar) return realpath.apply(this, arguments);
  333. const { asarPath, filePath } = pathInfo;
  334. if (arguments.length < 3) {
  335. callback = options;
  336. options = {};
  337. }
  338. const archive = getOrCreateArchive(asarPath);
  339. if (!archive) {
  340. const error = createError(AsarError.INVALID_ARCHIVE, { asarPath });
  341. nextTick(callback, [error]);
  342. return;
  343. }
  344. const fileRealPath = archive.realpath(filePath);
  345. if (fileRealPath === false) {
  346. const error = createError(AsarError.NOT_FOUND, { asarPath, filePath });
  347. nextTick(callback, [error]);
  348. return;
  349. }
  350. realpath(asarPath, options, (error: Error | null, archiveRealPath: string) => {
  351. if (error === null) {
  352. const fullPath = path.join(archiveRealPath, fileRealPath);
  353. callback(null, fullPath);
  354. } else {
  355. callback(error);
  356. }
  357. });
  358. };
  359. };
  360. const { realpath } = fs;
  361. fs.realpath = wrapRealpath(realpath);
  362. fs.realpath.native = wrapRealpath(realpath.native);
  363. fs.promises.realpath = util.promisify(fs.realpath.native);
  364. const { exists: nativeExists } = fs;
  365. fs.exists = function exists (pathArgument: string, callback: any) {
  366. let pathInfo: ReturnType<typeof splitPath>;
  367. try {
  368. pathInfo = splitPath(pathArgument);
  369. } catch {
  370. nextTick(callback, [false]);
  371. return;
  372. }
  373. if (!pathInfo.isAsar) return nativeExists(pathArgument, callback);
  374. const { asarPath, filePath } = pathInfo;
  375. const archive = getOrCreateArchive(asarPath);
  376. if (!archive) {
  377. const error = createError(AsarError.INVALID_ARCHIVE, { asarPath });
  378. nextTick(callback, [error]);
  379. return;
  380. }
  381. const pathExists = (archive.stat(filePath) !== false);
  382. nextTick(callback, [pathExists]);
  383. };
  384. fs.exists[util.promisify.custom] = function exists (pathArgument: string) {
  385. const pathInfo = splitPath(pathArgument);
  386. if (!pathInfo.isAsar) return nativeExists[util.promisify.custom](pathArgument);
  387. const { asarPath, filePath } = pathInfo;
  388. const archive = getOrCreateArchive(asarPath);
  389. if (!archive) {
  390. const error = createError(AsarError.INVALID_ARCHIVE, { asarPath });
  391. return Promise.reject(error);
  392. }
  393. return Promise.resolve(archive.stat(filePath) !== false);
  394. };
  395. const { existsSync } = fs;
  396. fs.existsSync = (pathArgument: string) => {
  397. let pathInfo: ReturnType<typeof splitPath>;
  398. try {
  399. pathInfo = splitPath(pathArgument);
  400. } catch {
  401. return false;
  402. }
  403. if (!pathInfo.isAsar) return existsSync(pathArgument);
  404. const { asarPath, filePath } = pathInfo;
  405. const archive = getOrCreateArchive(asarPath);
  406. if (!archive) return false;
  407. return archive.stat(filePath) !== false;
  408. };
  409. const { access } = fs;
  410. fs.access = function (pathArgument: string, mode: number, callback: any) {
  411. const pathInfo = splitPath(pathArgument);
  412. if (!pathInfo.isAsar) return access.apply(this, arguments);
  413. const { asarPath, filePath } = pathInfo;
  414. if (typeof mode === 'function') {
  415. callback = mode;
  416. mode = fs.constants.F_OK;
  417. }
  418. const archive = getOrCreateArchive(asarPath);
  419. if (!archive) {
  420. const error = createError(AsarError.INVALID_ARCHIVE, { asarPath });
  421. nextTick(callback, [error]);
  422. return;
  423. }
  424. const info = archive.getFileInfo(filePath);
  425. if (!info) {
  426. const error = createError(AsarError.NOT_FOUND, { asarPath, filePath });
  427. nextTick(callback, [error]);
  428. return;
  429. }
  430. if (info.unpacked) {
  431. const realPath = archive.copyFileOut(filePath);
  432. return fs.access(realPath, mode, callback);
  433. }
  434. const stats = archive.stat(filePath);
  435. if (!stats) {
  436. const error = createError(AsarError.NOT_FOUND, { asarPath, filePath });
  437. nextTick(callback, [error]);
  438. return;
  439. }
  440. if (mode & fs.constants.W_OK) {
  441. const error = createError(AsarError.NO_ACCESS, { asarPath, filePath });
  442. nextTick(callback, [error]);
  443. return;
  444. }
  445. nextTick(callback);
  446. };
  447. const { access: accessPromise } = fs.promises;
  448. fs.promises.access = function (pathArgument: string, mode: number) {
  449. const pathInfo = splitPath(pathArgument);
  450. if (!pathInfo.isAsar) {
  451. return accessPromise.apply(this, arguments);
  452. }
  453. const p = util.promisify(fs.access);
  454. return p(pathArgument, mode);
  455. };
  456. const { accessSync } = fs;
  457. fs.accessSync = function (pathArgument: string, mode: any) {
  458. const pathInfo = splitPath(pathArgument);
  459. if (!pathInfo.isAsar) return accessSync.apply(this, arguments);
  460. const { asarPath, filePath } = pathInfo;
  461. if (mode == null) mode = fs.constants.F_OK;
  462. const archive = getOrCreateArchive(asarPath);
  463. if (!archive) {
  464. throw createError(AsarError.INVALID_ARCHIVE, { asarPath });
  465. }
  466. const info = archive.getFileInfo(filePath);
  467. if (!info) {
  468. throw createError(AsarError.NOT_FOUND, { asarPath, filePath });
  469. }
  470. if (info.unpacked) {
  471. const realPath = archive.copyFileOut(filePath);
  472. return fs.accessSync(realPath, mode);
  473. }
  474. const stats = archive.stat(filePath);
  475. if (!stats) {
  476. throw createError(AsarError.NOT_FOUND, { asarPath, filePath });
  477. }
  478. if (mode & fs.constants.W_OK) {
  479. throw createError(AsarError.NO_ACCESS, { asarPath, filePath });
  480. }
  481. };
  482. function fsReadFileAsar (pathArgument: string, options: any, callback: any) {
  483. const pathInfo = splitPath(pathArgument);
  484. if (pathInfo.isAsar) {
  485. const { asarPath, filePath } = pathInfo;
  486. if (typeof options === 'function') {
  487. callback = options;
  488. options = { encoding: null };
  489. } else if (typeof options === 'string') {
  490. options = { encoding: options };
  491. } else if (options === null || options === undefined) {
  492. options = { encoding: null };
  493. } else if (typeof options !== 'object') {
  494. throw new TypeError('Bad arguments');
  495. }
  496. const { encoding } = options;
  497. const archive = getOrCreateArchive(asarPath);
  498. if (!archive) {
  499. const error = createError(AsarError.INVALID_ARCHIVE, { asarPath });
  500. nextTick(callback, [error]);
  501. return;
  502. }
  503. const info = archive.getFileInfo(filePath);
  504. if (!info) {
  505. const error = createError(AsarError.NOT_FOUND, { asarPath, filePath });
  506. nextTick(callback, [error]);
  507. return;
  508. }
  509. if (info.size === 0) {
  510. nextTick(callback, [null, encoding ? '' : Buffer.alloc(0)]);
  511. return;
  512. }
  513. if (info.unpacked) {
  514. const realPath = archive.copyFileOut(filePath);
  515. return fs.readFile(realPath, options, callback);
  516. }
  517. const buffer = Buffer.alloc(info.size);
  518. const fd = archive.getFdAndValidateIntegrityLater();
  519. if (!(fd >= 0)) {
  520. const error = createError(AsarError.NOT_FOUND, { asarPath, filePath });
  521. nextTick(callback, [error]);
  522. return;
  523. }
  524. logASARAccess(asarPath, filePath, info.offset);
  525. fs.read(fd, buffer, 0, info.size, info.offset, (error: Error) => {
  526. validateBufferIntegrity(buffer, info.integrity);
  527. callback(error, encoding ? buffer.toString(encoding) : buffer);
  528. });
  529. }
  530. }
  531. const { readFile } = fs;
  532. fs.readFile = function (pathArgument: string, options: any, callback: any) {
  533. const pathInfo = splitPath(pathArgument);
  534. if (!pathInfo.isAsar) {
  535. return readFile.apply(this, arguments);
  536. }
  537. return fsReadFileAsar(pathArgument, options, callback);
  538. };
  539. const { readFile: readFilePromise } = fs.promises;
  540. fs.promises.readFile = function (pathArgument: string, options: any) {
  541. const pathInfo = splitPath(pathArgument);
  542. if (!pathInfo.isAsar) {
  543. return readFilePromise.apply(this, arguments);
  544. }
  545. const p = util.promisify(fsReadFileAsar);
  546. return p(pathArgument, options);
  547. };
  548. const { readFileSync } = fs;
  549. fs.readFileSync = function (pathArgument: string, options: any) {
  550. const pathInfo = splitPath(pathArgument);
  551. if (!pathInfo.isAsar) return readFileSync.apply(this, arguments);
  552. const { asarPath, filePath } = pathInfo;
  553. const archive = getOrCreateArchive(asarPath);
  554. if (!archive) throw createError(AsarError.INVALID_ARCHIVE, { asarPath });
  555. const info = archive.getFileInfo(filePath);
  556. if (!info) throw createError(AsarError.NOT_FOUND, { asarPath, filePath });
  557. if (info.size === 0) return (options) ? '' : Buffer.alloc(0);
  558. if (info.unpacked) {
  559. const realPath = archive.copyFileOut(filePath);
  560. return fs.readFileSync(realPath, options);
  561. }
  562. if (!options) {
  563. options = { encoding: null };
  564. } else if (typeof options === 'string') {
  565. options = { encoding: options };
  566. } else if (typeof options !== 'object') {
  567. throw new TypeError('Bad arguments');
  568. }
  569. const { encoding } = options;
  570. const buffer = Buffer.alloc(info.size);
  571. const fd = archive.getFdAndValidateIntegrityLater();
  572. if (!(fd >= 0)) throw createError(AsarError.NOT_FOUND, { asarPath, filePath });
  573. logASARAccess(asarPath, filePath, info.offset);
  574. fs.readSync(fd, buffer, 0, info.size, info.offset);
  575. validateBufferIntegrity(buffer, info.integrity);
  576. return (encoding) ? buffer.toString(encoding) : buffer;
  577. };
  578. type ReaddirOptions = { encoding: BufferEncoding | null; withFileTypes?: false, recursive?: false } | undefined | null;
  579. type ReaddirCallback = (err: NodeJS.ErrnoException | null, files: string[]) => void;
  580. const { readdir } = fs;
  581. fs.readdir = function (pathArgument: string, options: ReaddirOptions, callback: ReaddirCallback) {
  582. callback = typeof options === 'function' ? options : callback;
  583. validateFunction(callback, 'callback');
  584. options = getOptions(options);
  585. pathArgument = getValidatedPath(pathArgument);
  586. if (options?.recursive != null) {
  587. validateBoolean(options?.recursive, 'options.recursive');
  588. }
  589. if (options?.recursive) {
  590. nextTick(callback!, [null, readdirSyncRecursive(pathArgument, options)]);
  591. return;
  592. }
  593. const pathInfo = splitPath(pathArgument);
  594. if (!pathInfo.isAsar) return readdir.apply(this, arguments);
  595. const { asarPath, filePath } = pathInfo;
  596. const archive = getOrCreateArchive(asarPath);
  597. if (!archive) {
  598. const error = createError(AsarError.INVALID_ARCHIVE, { asarPath });
  599. nextTick(callback!, [error]);
  600. return;
  601. }
  602. const files = archive.readdir(filePath);
  603. if (!files) {
  604. const error = createError(AsarError.NOT_FOUND, { asarPath, filePath });
  605. nextTick(callback!, [error]);
  606. return;
  607. }
  608. if (options?.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. const error = createError(AsarError.NOT_FOUND, { asarPath, filePath: childPath });
  615. nextTick(callback!, [error]);
  616. return;
  617. }
  618. dirents.push(new fs.Dirent(file, stats.type));
  619. }
  620. nextTick(callback!, [null, dirents]);
  621. return;
  622. }
  623. nextTick(callback!, [null, files]);
  624. };
  625. const { readdir: readdirPromise } = require('fs').promises;
  626. fs.promises.readdir = async function (pathArgument: string, options: ReaddirOptions) {
  627. options = getOptions(options);
  628. pathArgument = getValidatedPath(pathArgument);
  629. if (options?.recursive != null) {
  630. validateBoolean(options?.recursive, 'options.recursive');
  631. }
  632. if (options?.recursive) {
  633. return readdirRecursive(pathArgument, options);
  634. }
  635. const pathInfo = splitPath(pathArgument);
  636. if (!pathInfo.isAsar) return readdirPromise(pathArgument, options);
  637. const { asarPath, filePath } = pathInfo;
  638. const archive = getOrCreateArchive(asarPath);
  639. if (!archive) {
  640. return Promise.reject(createError(AsarError.INVALID_ARCHIVE, { asarPath }));
  641. }
  642. const files = archive.readdir(filePath);
  643. if (!files) {
  644. return Promise.reject(createError(AsarError.NOT_FOUND, { asarPath, filePath }));
  645. }
  646. if (options?.withFileTypes) {
  647. const dirents = [];
  648. for (const file of files) {
  649. const childPath = path.join(filePath, file);
  650. const stats = archive.stat(childPath);
  651. if (!stats) {
  652. throw createError(AsarError.NOT_FOUND, { asarPath, filePath: childPath });
  653. }
  654. dirents.push(new fs.Dirent(file, stats.type));
  655. }
  656. return Promise.resolve(dirents);
  657. }
  658. return Promise.resolve(files);
  659. };
  660. const { readdirSync } = fs;
  661. fs.readdirSync = function (pathArgument: string, options: ReaddirOptions) {
  662. options = getOptions(options);
  663. pathArgument = getValidatedPath(pathArgument);
  664. if (options?.recursive != null) {
  665. validateBoolean(options?.recursive, 'options.recursive');
  666. }
  667. if (options?.recursive) {
  668. return readdirSyncRecursive(pathArgument, options);
  669. }
  670. const pathInfo = splitPath(pathArgument);
  671. if (!pathInfo.isAsar) return readdirSync.apply(this, arguments);
  672. const { asarPath, filePath } = pathInfo;
  673. const archive = getOrCreateArchive(asarPath);
  674. if (!archive) {
  675. throw createError(AsarError.INVALID_ARCHIVE, { asarPath });
  676. }
  677. const files = archive.readdir(filePath);
  678. if (!files) {
  679. throw createError(AsarError.NOT_FOUND, { asarPath, filePath });
  680. }
  681. if (options?.withFileTypes) {
  682. const dirents = [];
  683. for (const file of files) {
  684. const childPath = path.join(filePath, file);
  685. const stats = archive.stat(childPath);
  686. if (!stats) {
  687. throw createError(AsarError.NOT_FOUND, { asarPath, filePath: childPath });
  688. }
  689. dirents.push(new fs.Dirent(file, stats.type));
  690. }
  691. return dirents;
  692. }
  693. return files;
  694. };
  695. const binding = internalBinding('fs');
  696. const { internalModuleReadJSON, kUsePromises } = binding;
  697. internalBinding('fs').internalModuleReadJSON = (pathArgument: string) => {
  698. const pathInfo = splitPath(pathArgument);
  699. if (!pathInfo.isAsar) return internalModuleReadJSON(pathArgument);
  700. const { asarPath, filePath } = pathInfo;
  701. const archive = getOrCreateArchive(asarPath);
  702. if (!archive) return [];
  703. const info = archive.getFileInfo(filePath);
  704. if (!info) return [];
  705. if (info.size === 0) return ['', false];
  706. if (info.unpacked) {
  707. const realPath = archive.copyFileOut(filePath);
  708. const str = fs.readFileSync(realPath, { encoding: 'utf8' });
  709. return [str, str.length > 0];
  710. }
  711. const buffer = Buffer.alloc(info.size);
  712. const fd = archive.getFdAndValidateIntegrityLater();
  713. if (!(fd >= 0)) return [];
  714. logASARAccess(asarPath, filePath, info.offset);
  715. fs.readSync(fd, buffer, 0, info.size, info.offset);
  716. validateBufferIntegrity(buffer, info.integrity);
  717. const str = buffer.toString('utf8');
  718. return [str, str.length > 0];
  719. };
  720. const { internalModuleStat } = internalBinding('fs');
  721. internalBinding('fs').internalModuleStat = (pathArgument: string) => {
  722. const pathInfo = splitPath(pathArgument);
  723. if (!pathInfo.isAsar) return internalModuleStat(pathArgument);
  724. const { asarPath, filePath } = pathInfo;
  725. // -ENOENT
  726. const archive = getOrCreateArchive(asarPath);
  727. if (!archive) return -34;
  728. // -ENOENT
  729. const stats = archive.stat(filePath);
  730. if (!stats) return -34;
  731. return (stats.type === AsarFileType.kDirectory) ? 1 : 0;
  732. };
  733. async function readdirRecursive (originalPath: string, options: ReaddirOptions) {
  734. const result: any[] = [];
  735. const pathInfo = splitPath(originalPath);
  736. let queue: [string, string[]][] = [];
  737. const withFileTypes = Boolean(options?.withFileTypes);
  738. let initialItem = [];
  739. if (pathInfo.isAsar) {
  740. const archive = getOrCreateArchive(pathInfo.asarPath);
  741. if (!archive) return result;
  742. const files = archive.readdir(pathInfo.filePath);
  743. if (!files) return result;
  744. // If we're in an asar dir, we need to ensure the result is in the same format as the
  745. // native call to readdir withFileTypes i.e. an array of arrays.
  746. initialItem = files;
  747. if (withFileTypes) {
  748. initialItem = [
  749. [...initialItem], initialItem.map((p: string) => {
  750. return internalBinding('fs').internalModuleStat(path.join(originalPath, p));
  751. })
  752. ];
  753. }
  754. } else {
  755. initialItem = await binding.readdir(
  756. path.toNamespacedPath(originalPath),
  757. options!.encoding,
  758. withFileTypes,
  759. kUsePromises
  760. );
  761. }
  762. queue = [[originalPath, initialItem]];
  763. if (withFileTypes) {
  764. while (queue.length > 0) {
  765. // @ts-expect-error this is a valid array destructure assignment.
  766. const { 0: pathArg, 1: readDir } = queue.pop();
  767. for (const dirent of getDirents(pathArg, readDir)) {
  768. result.push(dirent);
  769. if (dirent.isDirectory()) {
  770. const direntPath = path.join(pathArg, dirent.name);
  771. const info = splitPath(direntPath);
  772. let readdirResult;
  773. if (info.isAsar) {
  774. const archive = getOrCreateArchive(info.asarPath);
  775. if (!archive) continue;
  776. const files = archive.readdir(info.filePath);
  777. if (!files) continue;
  778. readdirResult = [
  779. [...files], files.map((p: string) => {
  780. return internalBinding('fs').internalModuleStat(path.join(direntPath, p));
  781. })
  782. ];
  783. } else {
  784. readdirResult = await binding.readdir(
  785. direntPath,
  786. options!.encoding,
  787. true,
  788. kUsePromises
  789. );
  790. }
  791. queue.push([direntPath, readdirResult]);
  792. }
  793. }
  794. }
  795. } else {
  796. while (queue.length > 0) {
  797. // @ts-expect-error this is a valid array destructure assignment.
  798. const { 0: pathArg, 1: readDir } = queue.pop();
  799. for (const ent of readDir) {
  800. const direntPath = path.join(pathArg, ent);
  801. const stat = internalBinding('fs').internalModuleStat(direntPath);
  802. result.push(path.relative(originalPath, direntPath));
  803. if (stat === 1) {
  804. const subPathInfo = splitPath(direntPath);
  805. let item = [];
  806. if (subPathInfo.isAsar) {
  807. const archive = getOrCreateArchive(subPathInfo.asarPath);
  808. if (!archive) return;
  809. const files = archive.readdir(subPathInfo.filePath);
  810. if (!files) return result;
  811. item = files;
  812. } else {
  813. item = await binding.readdir(
  814. path.toNamespacedPath(direntPath),
  815. options!.encoding,
  816. false,
  817. kUsePromises
  818. );
  819. }
  820. queue.push([direntPath, item]);
  821. }
  822. }
  823. }
  824. }
  825. return result;
  826. }
  827. function readdirSyncRecursive (basePath: string, options: ReaddirOptions) {
  828. const withFileTypes = Boolean(options!.withFileTypes);
  829. const encoding = options!.encoding;
  830. const readdirResults: string[] = [];
  831. const pathsQueue = [basePath];
  832. function read (pathArg: string) {
  833. let readdirResult;
  834. const pathInfo = splitPath(pathArg);
  835. if (pathInfo.isAsar) {
  836. const { asarPath, filePath } = pathInfo;
  837. const archive = getOrCreateArchive(asarPath);
  838. if (!archive) return;
  839. readdirResult = archive.readdir(filePath);
  840. if (!readdirResult) return;
  841. // If we're in an asar dir, we need to ensure the result is in the same format as the
  842. // native call to readdir withFileTypes i.e. an array of arrays.
  843. if (withFileTypes) {
  844. readdirResult = [
  845. [...readdirResult], readdirResult.map((p: string) => {
  846. return internalBinding('fs').internalModuleStat(path.join(pathArg, p));
  847. })
  848. ];
  849. }
  850. } else {
  851. readdirResult = binding.readdir(
  852. path.toNamespacedPath(pathArg),
  853. encoding,
  854. withFileTypes
  855. );
  856. }
  857. if (readdirResult === undefined) return;
  858. if (withFileTypes) {
  859. const length = readdirResult[0].length;
  860. for (let i = 0; i < length; i++) {
  861. const resultPath = path.join(pathArg, readdirResult[0][i]);
  862. const info = splitPath(resultPath);
  863. let type = readdirResult[1][i];
  864. if (info.isAsar) {
  865. const archive = getOrCreateArchive(info.asarPath);
  866. if (!archive) return;
  867. const stats = archive.stat(info.filePath);
  868. if (!stats) continue;
  869. type = stats.type;
  870. }
  871. const dirent = getDirent(pathArg, readdirResult[0][i], type);
  872. readdirResults.push(dirent);
  873. if (dirent.isDirectory()) {
  874. pathsQueue.push(path.join(dirent.path, dirent.name));
  875. }
  876. }
  877. } else {
  878. for (let i = 0; i < readdirResult.length; i++) {
  879. const resultPath = path.join(pathArg, readdirResult[i]);
  880. const relativeResultPath = path.relative(basePath, resultPath);
  881. const stat = internalBinding('fs').internalModuleStat(resultPath);
  882. readdirResults.push(relativeResultPath);
  883. if (stat === 1) pathsQueue.push(resultPath);
  884. }
  885. }
  886. }
  887. for (let i = 0; i < pathsQueue.length; i++) {
  888. read(pathsQueue[i]);
  889. }
  890. return readdirResults;
  891. }
  892. // Calling mkdir for directory inside asar archive should throw ENOTDIR
  893. // error, but on Windows it throws ENOENT.
  894. if (process.platform === 'win32') {
  895. const { mkdir } = fs;
  896. fs.mkdir = (pathArgument: string, options: any, callback: any) => {
  897. if (typeof options === 'function') {
  898. callback = options;
  899. options = {};
  900. }
  901. const pathInfo = splitPath(pathArgument);
  902. if (pathInfo.isAsar && pathInfo.filePath.length > 0) {
  903. const error = createError(AsarError.NOT_DIR);
  904. nextTick(callback, [error]);
  905. return;
  906. }
  907. mkdir(pathArgument, options, callback);
  908. };
  909. fs.promises.mkdir = util.promisify(fs.mkdir);
  910. const { mkdirSync } = fs;
  911. fs.mkdirSync = function (pathArgument: string, options: any) {
  912. const pathInfo = splitPath(pathArgument);
  913. if (pathInfo.isAsar && pathInfo.filePath.length) throw createError(AsarError.NOT_DIR);
  914. return mkdirSync(pathArgument, options);
  915. };
  916. }
  917. function invokeWithNoAsar (func: Function) {
  918. return function (this: any) {
  919. const processNoAsarOriginalValue = process.noAsar;
  920. process.noAsar = true;
  921. try {
  922. return func.apply(this, arguments);
  923. } finally {
  924. process.noAsar = processNoAsarOriginalValue;
  925. }
  926. };
  927. }
  928. // Strictly implementing the flags of fs.copyFile is hard, just do a simple
  929. // implementation for now. Doing 2 copies won't spend much time more as OS
  930. // has filesystem caching.
  931. overrideAPI(fs, 'copyFile');
  932. overrideAPISync(fs, 'copyFileSync');
  933. overrideAPI(fs, 'open');
  934. overrideAPISync(process, 'dlopen', 1);
  935. overrideAPISync(Module._extensions, '.node', 1);
  936. overrideAPISync(fs, 'openSync');
  937. const overrideChildProcess = (childProcess: Record<string, any>) => {
  938. // Executing a command string containing a path to an asar archive
  939. // confuses `childProcess.execFile`, which is internally called by
  940. // `childProcess.{exec,execSync}`, causing Electron to consider the full
  941. // command as a single path to an archive.
  942. const { exec, execSync } = childProcess;
  943. childProcess.exec = invokeWithNoAsar(exec);
  944. childProcess.exec[util.promisify.custom] = invokeWithNoAsar(exec[util.promisify.custom]);
  945. childProcess.execSync = invokeWithNoAsar(execSync);
  946. overrideAPI(childProcess, 'execFile');
  947. overrideAPISync(childProcess, 'execFileSync');
  948. };
  949. const asarReady = new WeakSet();
  950. // Lazily override the child_process APIs only when child_process is
  951. // fetched the first time. We will eagerly override the child_process APIs
  952. // when this env var is set so that stack traces generated inside node unit
  953. // tests will match. This env var will only slow things down in users apps
  954. // and should not be used.
  955. if (process.env.ELECTRON_EAGER_ASAR_HOOK_FOR_TESTING) {
  956. overrideChildProcess(require('child_process'));
  957. } else {
  958. const originalModuleLoad = Module._load;
  959. Module._load = (request: string, ...args: any[]) => {
  960. const loadResult = originalModuleLoad(request, ...args);
  961. if (request === 'child_process' || request === 'node:child_process') {
  962. if (!asarReady.has(loadResult)) {
  963. asarReady.add(loadResult);
  964. // Just to make it obvious what we are dealing with here
  965. const childProcess = loadResult;
  966. overrideChildProcess(childProcess);
  967. }
  968. }
  969. return loadResult;
  970. };
  971. }
  972. };