asar-fs-wrapper.ts 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155
  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: any, 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. fs.promises.access = util.promisify(fs.access);
  448. const { accessSync } = fs;
  449. fs.accessSync = function (pathArgument: string, mode: any) {
  450. const pathInfo = splitPath(pathArgument);
  451. if (!pathInfo.isAsar) return accessSync.apply(this, arguments);
  452. const { asarPath, filePath } = pathInfo;
  453. if (mode == null) mode = fs.constants.F_OK;
  454. const archive = getOrCreateArchive(asarPath);
  455. if (!archive) {
  456. throw createError(AsarError.INVALID_ARCHIVE, { asarPath });
  457. }
  458. const info = archive.getFileInfo(filePath);
  459. if (!info) {
  460. throw createError(AsarError.NOT_FOUND, { asarPath, filePath });
  461. }
  462. if (info.unpacked) {
  463. const realPath = archive.copyFileOut(filePath);
  464. return fs.accessSync(realPath, mode);
  465. }
  466. const stats = archive.stat(filePath);
  467. if (!stats) {
  468. throw createError(AsarError.NOT_FOUND, { asarPath, filePath });
  469. }
  470. if (mode & fs.constants.W_OK) {
  471. throw createError(AsarError.NO_ACCESS, { asarPath, filePath });
  472. }
  473. };
  474. function fsReadFileAsar (pathArgument: string, options: any, callback: any) {
  475. const pathInfo = splitPath(pathArgument);
  476. if (pathInfo.isAsar) {
  477. const { asarPath, filePath } = pathInfo;
  478. if (typeof options === 'function') {
  479. callback = options;
  480. options = { encoding: null };
  481. } else if (typeof options === 'string') {
  482. options = { encoding: options };
  483. } else if (options === null || options === undefined) {
  484. options = { encoding: null };
  485. } else if (typeof options !== 'object') {
  486. throw new TypeError('Bad arguments');
  487. }
  488. const { encoding } = options;
  489. const archive = getOrCreateArchive(asarPath);
  490. if (!archive) {
  491. const error = createError(AsarError.INVALID_ARCHIVE, { asarPath });
  492. nextTick(callback, [error]);
  493. return;
  494. }
  495. const info = archive.getFileInfo(filePath);
  496. if (!info) {
  497. const error = createError(AsarError.NOT_FOUND, { asarPath, filePath });
  498. nextTick(callback, [error]);
  499. return;
  500. }
  501. if (info.size === 0) {
  502. nextTick(callback, [null, encoding ? '' : Buffer.alloc(0)]);
  503. return;
  504. }
  505. if (info.unpacked) {
  506. const realPath = archive.copyFileOut(filePath);
  507. return fs.readFile(realPath, options, callback);
  508. }
  509. const buffer = Buffer.alloc(info.size);
  510. const fd = archive.getFdAndValidateIntegrityLater();
  511. if (!(fd >= 0)) {
  512. const error = createError(AsarError.NOT_FOUND, { asarPath, filePath });
  513. nextTick(callback, [error]);
  514. return;
  515. }
  516. logASARAccess(asarPath, filePath, info.offset);
  517. fs.read(fd, buffer, 0, info.size, info.offset, (error: Error) => {
  518. validateBufferIntegrity(buffer, info.integrity);
  519. callback(error, encoding ? buffer.toString(encoding) : buffer);
  520. });
  521. }
  522. }
  523. const { readFile } = fs;
  524. fs.readFile = function (pathArgument: string, options: any, callback: any) {
  525. const pathInfo = splitPath(pathArgument);
  526. if (!pathInfo.isAsar) {
  527. return readFile.apply(this, arguments);
  528. }
  529. return fsReadFileAsar(pathArgument, options, callback);
  530. };
  531. const { readFile: readFilePromise } = fs.promises;
  532. fs.promises.readFile = function (pathArgument: string, options: any) {
  533. const pathInfo = splitPath(pathArgument);
  534. if (!pathInfo.isAsar) {
  535. return readFilePromise.apply(this, arguments);
  536. }
  537. const p = util.promisify(fsReadFileAsar);
  538. return p(pathArgument, options);
  539. };
  540. const { readFileSync } = fs;
  541. fs.readFileSync = function (pathArgument: string, options: any) {
  542. const pathInfo = splitPath(pathArgument);
  543. if (!pathInfo.isAsar) return readFileSync.apply(this, arguments);
  544. const { asarPath, filePath } = pathInfo;
  545. const archive = getOrCreateArchive(asarPath);
  546. if (!archive) throw createError(AsarError.INVALID_ARCHIVE, { asarPath });
  547. const info = archive.getFileInfo(filePath);
  548. if (!info) throw createError(AsarError.NOT_FOUND, { asarPath, filePath });
  549. if (info.size === 0) return (options) ? '' : Buffer.alloc(0);
  550. if (info.unpacked) {
  551. const realPath = archive.copyFileOut(filePath);
  552. return fs.readFileSync(realPath, options);
  553. }
  554. if (!options) {
  555. options = { encoding: null };
  556. } else if (typeof options === 'string') {
  557. options = { encoding: options };
  558. } else if (typeof options !== 'object') {
  559. throw new TypeError('Bad arguments');
  560. }
  561. const { encoding } = options;
  562. const buffer = Buffer.alloc(info.size);
  563. const fd = archive.getFdAndValidateIntegrityLater();
  564. if (!(fd >= 0)) throw createError(AsarError.NOT_FOUND, { asarPath, filePath });
  565. logASARAccess(asarPath, filePath, info.offset);
  566. fs.readSync(fd, buffer, 0, info.size, info.offset);
  567. validateBufferIntegrity(buffer, info.integrity);
  568. return (encoding) ? buffer.toString(encoding) : buffer;
  569. };
  570. type ReaddirOptions = { encoding: BufferEncoding | null; withFileTypes?: false, recursive?: false } | undefined | null;
  571. type ReaddirCallback = (err: NodeJS.ErrnoException | null, files: string[]) => void;
  572. const { readdir } = fs;
  573. fs.readdir = function (pathArgument: string, options: ReaddirOptions, callback: ReaddirCallback) {
  574. callback = typeof options === 'function' ? options : callback;
  575. validateFunction(callback, 'callback');
  576. options = getOptions(options);
  577. pathArgument = getValidatedPath(pathArgument);
  578. if (options?.recursive != null) {
  579. validateBoolean(options?.recursive, 'options.recursive');
  580. }
  581. if (options?.recursive) {
  582. nextTick(callback!, [null, readdirSyncRecursive(pathArgument, options)]);
  583. return;
  584. }
  585. const pathInfo = splitPath(pathArgument);
  586. if (!pathInfo.isAsar) return readdir.apply(this, arguments);
  587. const { asarPath, filePath } = pathInfo;
  588. const archive = getOrCreateArchive(asarPath);
  589. if (!archive) {
  590. const error = createError(AsarError.INVALID_ARCHIVE, { asarPath });
  591. nextTick(callback!, [error]);
  592. return;
  593. }
  594. const files = archive.readdir(filePath);
  595. if (!files) {
  596. const error = createError(AsarError.NOT_FOUND, { asarPath, filePath });
  597. nextTick(callback!, [error]);
  598. return;
  599. }
  600. if (options?.withFileTypes) {
  601. const dirents = [];
  602. for (const file of files) {
  603. const childPath = path.join(filePath, file);
  604. const stats = archive.stat(childPath);
  605. if (!stats) {
  606. const error = createError(AsarError.NOT_FOUND, { asarPath, filePath: childPath });
  607. nextTick(callback!, [error]);
  608. return;
  609. }
  610. dirents.push(new fs.Dirent(file, stats.type));
  611. }
  612. nextTick(callback!, [null, dirents]);
  613. return;
  614. }
  615. nextTick(callback!, [null, files]);
  616. };
  617. const { readdir: readdirPromise } = require('fs').promises;
  618. fs.promises.readdir = async function (pathArgument: string, options: ReaddirOptions) {
  619. options = getOptions(options);
  620. pathArgument = getValidatedPath(pathArgument);
  621. if (options?.recursive != null) {
  622. validateBoolean(options?.recursive, 'options.recursive');
  623. }
  624. if (options?.recursive) {
  625. return readdirRecursive(pathArgument, options);
  626. }
  627. const pathInfo = splitPath(pathArgument);
  628. if (!pathInfo.isAsar) return readdirPromise(pathArgument, options);
  629. const { asarPath, filePath } = pathInfo;
  630. const archive = getOrCreateArchive(asarPath);
  631. if (!archive) {
  632. return Promise.reject(createError(AsarError.INVALID_ARCHIVE, { asarPath }));
  633. }
  634. const files = archive.readdir(filePath);
  635. if (!files) {
  636. return Promise.reject(createError(AsarError.NOT_FOUND, { asarPath, filePath }));
  637. }
  638. if (options?.withFileTypes) {
  639. const dirents = [];
  640. for (const file of files) {
  641. const childPath = path.join(filePath, file);
  642. const stats = archive.stat(childPath);
  643. if (!stats) {
  644. throw createError(AsarError.NOT_FOUND, { asarPath, filePath: childPath });
  645. }
  646. dirents.push(new fs.Dirent(file, stats.type));
  647. }
  648. return Promise.resolve(dirents);
  649. }
  650. return Promise.resolve(files);
  651. };
  652. const { readdirSync } = fs;
  653. fs.readdirSync = function (pathArgument: string, options: ReaddirOptions) {
  654. options = getOptions(options);
  655. pathArgument = getValidatedPath(pathArgument);
  656. if (options?.recursive != null) {
  657. validateBoolean(options?.recursive, 'options.recursive');
  658. }
  659. if (options?.recursive) {
  660. return readdirSyncRecursive(pathArgument, options);
  661. }
  662. const pathInfo = splitPath(pathArgument);
  663. if (!pathInfo.isAsar) return readdirSync.apply(this, arguments);
  664. const { asarPath, filePath } = pathInfo;
  665. const archive = getOrCreateArchive(asarPath);
  666. if (!archive) {
  667. throw createError(AsarError.INVALID_ARCHIVE, { asarPath });
  668. }
  669. const files = archive.readdir(filePath);
  670. if (!files) {
  671. throw createError(AsarError.NOT_FOUND, { asarPath, filePath });
  672. }
  673. if (options?.withFileTypes) {
  674. const dirents = [];
  675. for (const file of files) {
  676. const childPath = path.join(filePath, file);
  677. const stats = archive.stat(childPath);
  678. if (!stats) {
  679. throw createError(AsarError.NOT_FOUND, { asarPath, filePath: childPath });
  680. }
  681. dirents.push(new fs.Dirent(file, stats.type));
  682. }
  683. return dirents;
  684. }
  685. return files;
  686. };
  687. const binding = internalBinding('fs');
  688. const { internalModuleReadJSON, kUsePromises } = binding;
  689. internalBinding('fs').internalModuleReadJSON = (pathArgument: string) => {
  690. const pathInfo = splitPath(pathArgument);
  691. if (!pathInfo.isAsar) return internalModuleReadJSON(pathArgument);
  692. const { asarPath, filePath } = pathInfo;
  693. const archive = getOrCreateArchive(asarPath);
  694. if (!archive) return [];
  695. const info = archive.getFileInfo(filePath);
  696. if (!info) return [];
  697. if (info.size === 0) return ['', false];
  698. if (info.unpacked) {
  699. const realPath = archive.copyFileOut(filePath);
  700. const str = fs.readFileSync(realPath, { encoding: 'utf8' });
  701. return [str, str.length > 0];
  702. }
  703. const buffer = Buffer.alloc(info.size);
  704. const fd = archive.getFdAndValidateIntegrityLater();
  705. if (!(fd >= 0)) return [];
  706. logASARAccess(asarPath, filePath, info.offset);
  707. fs.readSync(fd, buffer, 0, info.size, info.offset);
  708. validateBufferIntegrity(buffer, info.integrity);
  709. const str = buffer.toString('utf8');
  710. return [str, str.length > 0];
  711. };
  712. const { internalModuleStat } = internalBinding('fs');
  713. internalBinding('fs').internalModuleStat = (pathArgument: string) => {
  714. const pathInfo = splitPath(pathArgument);
  715. if (!pathInfo.isAsar) return internalModuleStat(pathArgument);
  716. const { asarPath, filePath } = pathInfo;
  717. // -ENOENT
  718. const archive = getOrCreateArchive(asarPath);
  719. if (!archive) return -34;
  720. // -ENOENT
  721. const stats = archive.stat(filePath);
  722. if (!stats) return -34;
  723. return (stats.type === AsarFileType.kDirectory) ? 1 : 0;
  724. };
  725. async function readdirRecursive (originalPath: string, options: ReaddirOptions) {
  726. const result: any[] = [];
  727. const pathInfo = splitPath(originalPath);
  728. let queue: [string, string[]][] = [];
  729. const withFileTypes = Boolean(options?.withFileTypes);
  730. let initialItem = [];
  731. if (pathInfo.isAsar) {
  732. const archive = getOrCreateArchive(pathInfo.asarPath);
  733. if (!archive) return result;
  734. const files = archive.readdir(pathInfo.filePath);
  735. if (!files) return result;
  736. // If we're in an asar dir, we need to ensure the result is in the same format as the
  737. // native call to readdir withFileTypes i.e. an array of arrays.
  738. initialItem = files;
  739. if (withFileTypes) {
  740. initialItem = [
  741. [...initialItem], initialItem.map((p: string) => {
  742. return internalBinding('fs').internalModuleStat(path.join(originalPath, p));
  743. })
  744. ];
  745. }
  746. } else {
  747. initialItem = await binding.readdir(
  748. path.toNamespacedPath(originalPath),
  749. options!.encoding,
  750. withFileTypes,
  751. kUsePromises
  752. );
  753. }
  754. queue = [[originalPath, initialItem]];
  755. if (withFileTypes) {
  756. while (queue.length > 0) {
  757. // @ts-expect-error this is a valid array destructure assignment.
  758. const { 0: pathArg, 1: readDir } = queue.pop();
  759. for (const dirent of getDirents(pathArg, readDir)) {
  760. result.push(dirent);
  761. if (dirent.isDirectory()) {
  762. const direntPath = path.join(pathArg, dirent.name);
  763. const info = splitPath(direntPath);
  764. let readdirResult;
  765. if (info.isAsar) {
  766. const archive = getOrCreateArchive(info.asarPath);
  767. if (!archive) continue;
  768. const files = archive.readdir(info.filePath);
  769. if (!files) continue;
  770. readdirResult = [
  771. [...files], files.map((p: string) => {
  772. return internalBinding('fs').internalModuleStat(path.join(direntPath, p));
  773. })
  774. ];
  775. } else {
  776. readdirResult = await binding.readdir(
  777. direntPath,
  778. options!.encoding,
  779. true,
  780. kUsePromises
  781. );
  782. }
  783. queue.push([direntPath, readdirResult]);
  784. }
  785. }
  786. }
  787. } else {
  788. while (queue.length > 0) {
  789. // @ts-expect-error this is a valid array destructure assignment.
  790. const { 0: pathArg, 1: readDir } = queue.pop();
  791. for (const ent of readDir) {
  792. const direntPath = path.join(pathArg, ent);
  793. const stat = internalBinding('fs').internalModuleStat(direntPath);
  794. result.push(path.relative(originalPath, direntPath));
  795. if (stat === 1) {
  796. const subPathInfo = splitPath(direntPath);
  797. let item = [];
  798. if (subPathInfo.isAsar) {
  799. const archive = getOrCreateArchive(subPathInfo.asarPath);
  800. if (!archive) return;
  801. const files = archive.readdir(subPathInfo.filePath);
  802. if (!files) return result;
  803. item = files;
  804. } else {
  805. item = await binding.readdir(
  806. path.toNamespacedPath(direntPath),
  807. options!.encoding,
  808. false,
  809. kUsePromises
  810. );
  811. }
  812. queue.push([direntPath, item]);
  813. }
  814. }
  815. }
  816. }
  817. return result;
  818. }
  819. function readdirSyncRecursive (basePath: string, options: ReaddirOptions) {
  820. const withFileTypes = Boolean(options!.withFileTypes);
  821. const encoding = options!.encoding;
  822. const readdirResults: string[] = [];
  823. const pathsQueue = [basePath];
  824. function read (pathArg: string) {
  825. let readdirResult;
  826. const pathInfo = splitPath(pathArg);
  827. if (pathInfo.isAsar) {
  828. const { asarPath, filePath } = pathInfo;
  829. const archive = getOrCreateArchive(asarPath);
  830. if (!archive) return;
  831. readdirResult = archive.readdir(filePath);
  832. if (!readdirResult) return;
  833. // If we're in an asar dir, we need to ensure the result is in the same format as the
  834. // native call to readdir withFileTypes i.e. an array of arrays.
  835. if (withFileTypes) {
  836. readdirResult = [
  837. [...readdirResult], readdirResult.map((p: string) => {
  838. return internalBinding('fs').internalModuleStat(path.join(pathArg, p));
  839. })
  840. ];
  841. }
  842. } else {
  843. readdirResult = binding.readdir(
  844. path.toNamespacedPath(pathArg),
  845. encoding,
  846. withFileTypes
  847. );
  848. }
  849. if (readdirResult === undefined) return;
  850. if (withFileTypes) {
  851. const length = readdirResult[0].length;
  852. for (let i = 0; i < length; i++) {
  853. const resultPath = path.join(pathArg, readdirResult[0][i]);
  854. const info = splitPath(resultPath);
  855. let type = readdirResult[1][i];
  856. if (info.isAsar) {
  857. const archive = getOrCreateArchive(info.asarPath);
  858. if (!archive) return;
  859. const stats = archive.stat(info.filePath);
  860. if (!stats) continue;
  861. type = stats.type;
  862. }
  863. const dirent = getDirent(pathArg, readdirResult[0][i], type);
  864. readdirResults.push(dirent);
  865. if (dirent.isDirectory()) {
  866. pathsQueue.push(path.join(dirent.path, dirent.name));
  867. }
  868. }
  869. } else {
  870. for (let i = 0; i < readdirResult.length; i++) {
  871. const resultPath = path.join(pathArg, readdirResult[i]);
  872. const relativeResultPath = path.relative(basePath, resultPath);
  873. const stat = internalBinding('fs').internalModuleStat(resultPath);
  874. readdirResults.push(relativeResultPath);
  875. if (stat === 1) pathsQueue.push(resultPath);
  876. }
  877. }
  878. }
  879. for (let i = 0; i < pathsQueue.length; i++) {
  880. read(pathsQueue[i]);
  881. }
  882. return readdirResults;
  883. }
  884. // Calling mkdir for directory inside asar archive should throw ENOTDIR
  885. // error, but on Windows it throws ENOENT.
  886. if (process.platform === 'win32') {
  887. const { mkdir } = fs;
  888. fs.mkdir = (pathArgument: string, options: any, callback: any) => {
  889. if (typeof options === 'function') {
  890. callback = options;
  891. options = {};
  892. }
  893. const pathInfo = splitPath(pathArgument);
  894. if (pathInfo.isAsar && pathInfo.filePath.length > 0) {
  895. const error = createError(AsarError.NOT_DIR);
  896. nextTick(callback, [error]);
  897. return;
  898. }
  899. mkdir(pathArgument, options, callback);
  900. };
  901. fs.promises.mkdir = util.promisify(fs.mkdir);
  902. const { mkdirSync } = fs;
  903. fs.mkdirSync = function (pathArgument: string, options: any) {
  904. const pathInfo = splitPath(pathArgument);
  905. if (pathInfo.isAsar && pathInfo.filePath.length) throw createError(AsarError.NOT_DIR);
  906. return mkdirSync(pathArgument, options);
  907. };
  908. }
  909. function invokeWithNoAsar (func: Function) {
  910. return function (this: any) {
  911. const processNoAsarOriginalValue = process.noAsar;
  912. process.noAsar = true;
  913. try {
  914. return func.apply(this, arguments);
  915. } finally {
  916. process.noAsar = processNoAsarOriginalValue;
  917. }
  918. };
  919. }
  920. // Strictly implementing the flags of fs.copyFile is hard, just do a simple
  921. // implementation for now. Doing 2 copies won't spend much time more as OS
  922. // has filesystem caching.
  923. overrideAPI(fs, 'copyFile');
  924. overrideAPISync(fs, 'copyFileSync');
  925. overrideAPI(fs, 'open');
  926. overrideAPISync(process, 'dlopen', 1);
  927. overrideAPISync(Module._extensions, '.node', 1);
  928. overrideAPISync(fs, 'openSync');
  929. const overrideChildProcess = (childProcess: Record<string, any>) => {
  930. // Executing a command string containing a path to an asar archive
  931. // confuses `childProcess.execFile`, which is internally called by
  932. // `childProcess.{exec,execSync}`, causing Electron to consider the full
  933. // command as a single path to an archive.
  934. const { exec, execSync } = childProcess;
  935. childProcess.exec = invokeWithNoAsar(exec);
  936. childProcess.exec[util.promisify.custom] = invokeWithNoAsar(exec[util.promisify.custom]);
  937. childProcess.execSync = invokeWithNoAsar(execSync);
  938. overrideAPI(childProcess, 'execFile');
  939. overrideAPISync(childProcess, 'execFileSync');
  940. };
  941. const asarReady = new WeakSet();
  942. // Lazily override the child_process APIs only when child_process is
  943. // fetched the first time. We will eagerly override the child_process APIs
  944. // when this env var is set so that stack traces generated inside node unit
  945. // tests will match. This env var will only slow things down in users apps
  946. // and should not be used.
  947. if (process.env.ELECTRON_EAGER_ASAR_HOOK_FOR_TESTING) {
  948. overrideChildProcess(require('child_process'));
  949. } else {
  950. const originalModuleLoad = Module._load;
  951. Module._load = (request: string, ...args: any[]) => {
  952. const loadResult = originalModuleLoad(request, ...args);
  953. if (request === 'child_process' || request === 'node:child_process') {
  954. if (!asarReady.has(loadResult)) {
  955. asarReady.add(loadResult);
  956. // Just to make it obvious what we are dealing with here
  957. const childProcess = loadResult;
  958. overrideChildProcess(childProcess);
  959. }
  960. }
  961. return loadResult;
  962. };
  963. }
  964. };