asar-fs-wrapper.ts 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882
  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: any, 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. fs.promises.access = util.promisify(fs.access);
  425. const { accessSync } = fs;
  426. fs.accessSync = function (pathArgument: string, mode: any) {
  427. const pathInfo = splitPath(pathArgument);
  428. if (!pathInfo.isAsar) return accessSync.apply(this, arguments);
  429. const { asarPath, filePath } = pathInfo;
  430. if (mode == null) mode = fs.constants.F_OK;
  431. const archive = getOrCreateArchive(asarPath);
  432. if (!archive) {
  433. throw createError(AsarError.INVALID_ARCHIVE, { asarPath });
  434. }
  435. const info = archive.getFileInfo(filePath);
  436. if (!info) {
  437. throw createError(AsarError.NOT_FOUND, { asarPath, filePath });
  438. }
  439. if (info.unpacked) {
  440. const realPath = archive.copyFileOut(filePath);
  441. return fs.accessSync(realPath, mode);
  442. }
  443. const stats = archive.stat(filePath);
  444. if (!stats) {
  445. throw createError(AsarError.NOT_FOUND, { asarPath, filePath });
  446. }
  447. if (mode & fs.constants.W_OK) {
  448. throw createError(AsarError.NO_ACCESS, { asarPath, filePath });
  449. }
  450. };
  451. function fsReadFileAsar (pathArgument: string, options: any, callback: any) {
  452. const pathInfo = splitPath(pathArgument);
  453. if (pathInfo.isAsar) {
  454. const { asarPath, filePath } = pathInfo;
  455. if (typeof options === 'function') {
  456. callback = options;
  457. options = { encoding: null };
  458. } else if (typeof options === 'string') {
  459. options = { encoding: options };
  460. } else if (options === null || options === undefined) {
  461. options = { encoding: null };
  462. } else if (typeof options !== 'object') {
  463. throw new TypeError('Bad arguments');
  464. }
  465. const { encoding } = options;
  466. const archive = getOrCreateArchive(asarPath);
  467. if (!archive) {
  468. const error = createError(AsarError.INVALID_ARCHIVE, { asarPath });
  469. nextTick(callback, [error]);
  470. return;
  471. }
  472. const info = archive.getFileInfo(filePath);
  473. if (!info) {
  474. const error = createError(AsarError.NOT_FOUND, { asarPath, filePath });
  475. nextTick(callback, [error]);
  476. return;
  477. }
  478. if (info.size === 0) {
  479. nextTick(callback, [null, encoding ? '' : Buffer.alloc(0)]);
  480. return;
  481. }
  482. if (info.unpacked) {
  483. const realPath = archive.copyFileOut(filePath);
  484. return fs.readFile(realPath, options, callback);
  485. }
  486. const buffer = Buffer.alloc(info.size);
  487. const fd = archive.getFdAndValidateIntegrityLater();
  488. if (!(fd >= 0)) {
  489. const error = createError(AsarError.NOT_FOUND, { asarPath, filePath });
  490. nextTick(callback, [error]);
  491. return;
  492. }
  493. logASARAccess(asarPath, filePath, info.offset);
  494. fs.read(fd, buffer, 0, info.size, info.offset, (error: Error) => {
  495. validateBufferIntegrity(buffer, info.integrity);
  496. callback(error, encoding ? buffer.toString(encoding) : buffer);
  497. });
  498. }
  499. }
  500. const { readFile } = fs;
  501. fs.readFile = function (pathArgument: string, options: any, callback: any) {
  502. const pathInfo = splitPath(pathArgument);
  503. if (!pathInfo.isAsar) {
  504. return readFile.apply(this, arguments);
  505. }
  506. return fsReadFileAsar(pathArgument, options, callback);
  507. };
  508. const { readFile: readFilePromise } = fs.promises;
  509. fs.promises.readFile = function (pathArgument: string, options: any) {
  510. const pathInfo = splitPath(pathArgument);
  511. if (!pathInfo.isAsar) {
  512. return readFilePromise.apply(this, arguments);
  513. }
  514. const p = util.promisify(fsReadFileAsar);
  515. return p(pathArgument, options);
  516. };
  517. const { readFileSync } = fs;
  518. fs.readFileSync = function (pathArgument: string, options: any) {
  519. const pathInfo = splitPath(pathArgument);
  520. if (!pathInfo.isAsar) return readFileSync.apply(this, arguments);
  521. const { asarPath, filePath } = pathInfo;
  522. const archive = getOrCreateArchive(asarPath);
  523. if (!archive) throw createError(AsarError.INVALID_ARCHIVE, { asarPath });
  524. const info = archive.getFileInfo(filePath);
  525. if (!info) throw createError(AsarError.NOT_FOUND, { asarPath, filePath });
  526. if (info.size === 0) return (options) ? '' : Buffer.alloc(0);
  527. if (info.unpacked) {
  528. const realPath = archive.copyFileOut(filePath);
  529. return fs.readFileSync(realPath, options);
  530. }
  531. if (!options) {
  532. options = { encoding: null };
  533. } else if (typeof options === 'string') {
  534. options = { encoding: options };
  535. } else if (typeof options !== 'object') {
  536. throw new TypeError('Bad arguments');
  537. }
  538. const { encoding } = options;
  539. const buffer = Buffer.alloc(info.size);
  540. const fd = archive.getFdAndValidateIntegrityLater();
  541. if (!(fd >= 0)) throw createError(AsarError.NOT_FOUND, { asarPath, filePath });
  542. logASARAccess(asarPath, filePath, info.offset);
  543. fs.readSync(fd, buffer, 0, info.size, info.offset);
  544. validateBufferIntegrity(buffer, info.integrity);
  545. return (encoding) ? buffer.toString(encoding) : buffer;
  546. };
  547. const { readdir } = fs;
  548. fs.readdir = function (pathArgument: string, options?: { encoding?: string | null; withFileTypes?: boolean } | null, callback?: Function) {
  549. const pathInfo = splitPath(pathArgument);
  550. if (typeof options === 'function') {
  551. callback = options;
  552. options = undefined;
  553. }
  554. if (!pathInfo.isAsar) return readdir.apply(this, arguments);
  555. const { asarPath, filePath } = pathInfo;
  556. const archive = getOrCreateArchive(asarPath);
  557. if (!archive) {
  558. const error = createError(AsarError.INVALID_ARCHIVE, { asarPath });
  559. nextTick(callback!, [error]);
  560. return;
  561. }
  562. const files = archive.readdir(filePath);
  563. if (!files) {
  564. const error = createError(AsarError.NOT_FOUND, { asarPath, filePath });
  565. nextTick(callback!, [error]);
  566. return;
  567. }
  568. if (options?.withFileTypes) {
  569. const dirents = [];
  570. for (const file of files) {
  571. const childPath = path.join(filePath, file);
  572. const stats = archive.stat(childPath);
  573. if (!stats) {
  574. const error = createError(AsarError.NOT_FOUND, { asarPath, filePath: childPath });
  575. nextTick(callback!, [error]);
  576. return;
  577. }
  578. dirents.push(new fs.Dirent(file, stats.type));
  579. }
  580. nextTick(callback!, [null, dirents]);
  581. return;
  582. }
  583. nextTick(callback!, [null, files]);
  584. };
  585. fs.promises.readdir = util.promisify(fs.readdir);
  586. type ReaddirSyncOptions = { encoding: BufferEncoding | null; withFileTypes?: false };
  587. const { readdirSync } = fs;
  588. fs.readdirSync = function (pathArgument: string, options: ReaddirSyncOptions | BufferEncoding | null) {
  589. const pathInfo = splitPath(pathArgument);
  590. if (!pathInfo.isAsar) return readdirSync.apply(this, arguments);
  591. const { asarPath, filePath } = pathInfo;
  592. const archive = getOrCreateArchive(asarPath);
  593. if (!archive) {
  594. throw createError(AsarError.INVALID_ARCHIVE, { asarPath });
  595. }
  596. const files = archive.readdir(filePath);
  597. if (!files) {
  598. throw createError(AsarError.NOT_FOUND, { asarPath, filePath });
  599. }
  600. if (options && (options as ReaddirSyncOptions).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. throw createError(AsarError.NOT_FOUND, { asarPath, filePath: childPath });
  607. }
  608. dirents.push(new fs.Dirent(file, stats.type));
  609. }
  610. return dirents;
  611. }
  612. return files;
  613. };
  614. const { internalModuleReadJSON } = internalBinding('fs');
  615. internalBinding('fs').internalModuleReadJSON = (pathArgument: string) => {
  616. const pathInfo = splitPath(pathArgument);
  617. if (!pathInfo.isAsar) return internalModuleReadJSON(pathArgument);
  618. const { asarPath, filePath } = pathInfo;
  619. const archive = getOrCreateArchive(asarPath);
  620. if (!archive) return [];
  621. const info = archive.getFileInfo(filePath);
  622. if (!info) return [];
  623. if (info.size === 0) return ['', false];
  624. if (info.unpacked) {
  625. const realPath = archive.copyFileOut(filePath);
  626. const str = fs.readFileSync(realPath, { encoding: 'utf8' });
  627. return [str, str.length > 0];
  628. }
  629. const buffer = Buffer.alloc(info.size);
  630. const fd = archive.getFdAndValidateIntegrityLater();
  631. if (!(fd >= 0)) return [];
  632. logASARAccess(asarPath, filePath, info.offset);
  633. fs.readSync(fd, buffer, 0, info.size, info.offset);
  634. validateBufferIntegrity(buffer, info.integrity);
  635. const str = buffer.toString('utf8');
  636. return [str, str.length > 0];
  637. };
  638. const { internalModuleStat } = internalBinding('fs');
  639. internalBinding('fs').internalModuleStat = (pathArgument: string) => {
  640. const pathInfo = splitPath(pathArgument);
  641. if (!pathInfo.isAsar) return internalModuleStat(pathArgument);
  642. const { asarPath, filePath } = pathInfo;
  643. // -ENOENT
  644. const archive = getOrCreateArchive(asarPath);
  645. if (!archive) return -34;
  646. // -ENOENT
  647. const stats = archive.stat(filePath);
  648. if (!stats) return -34;
  649. return (stats.type === AsarFileType.kDirectory) ? 1 : 0;
  650. };
  651. // Calling mkdir for directory inside asar archive should throw ENOTDIR
  652. // error, but on Windows it throws ENOENT.
  653. if (process.platform === 'win32') {
  654. const { mkdir } = fs;
  655. fs.mkdir = (pathArgument: string, options: any, callback: any) => {
  656. if (typeof options === 'function') {
  657. callback = options;
  658. options = {};
  659. }
  660. const pathInfo = splitPath(pathArgument);
  661. if (pathInfo.isAsar && pathInfo.filePath.length > 0) {
  662. const error = createError(AsarError.NOT_DIR);
  663. nextTick(callback, [error]);
  664. return;
  665. }
  666. mkdir(pathArgument, options, callback);
  667. };
  668. fs.promises.mkdir = util.promisify(fs.mkdir);
  669. const { mkdirSync } = fs;
  670. fs.mkdirSync = function (pathArgument: string, options: any) {
  671. const pathInfo = splitPath(pathArgument);
  672. if (pathInfo.isAsar && pathInfo.filePath.length) throw createError(AsarError.NOT_DIR);
  673. return mkdirSync(pathArgument, options);
  674. };
  675. }
  676. function invokeWithNoAsar (func: Function) {
  677. return function (this: any) {
  678. const processNoAsarOriginalValue = process.noAsar;
  679. process.noAsar = true;
  680. try {
  681. return func.apply(this, arguments);
  682. } finally {
  683. process.noAsar = processNoAsarOriginalValue;
  684. }
  685. };
  686. }
  687. // Strictly implementing the flags of fs.copyFile is hard, just do a simple
  688. // implementation for now. Doing 2 copies won't spend much time more as OS
  689. // has filesystem caching.
  690. overrideAPI(fs, 'copyFile');
  691. overrideAPISync(fs, 'copyFileSync');
  692. overrideAPI(fs, 'open');
  693. overrideAPISync(process, 'dlopen', 1);
  694. overrideAPISync(Module._extensions, '.node', 1);
  695. overrideAPISync(fs, 'openSync');
  696. const overrideChildProcess = (childProcess: Record<string, any>) => {
  697. // Executing a command string containing a path to an asar archive
  698. // confuses `childProcess.execFile`, which is internally called by
  699. // `childProcess.{exec,execSync}`, causing Electron to consider the full
  700. // command as a single path to an archive.
  701. const { exec, execSync } = childProcess;
  702. childProcess.exec = invokeWithNoAsar(exec);
  703. childProcess.exec[util.promisify.custom] = invokeWithNoAsar(exec[util.promisify.custom]);
  704. childProcess.execSync = invokeWithNoAsar(execSync);
  705. overrideAPI(childProcess, 'execFile');
  706. overrideAPISync(childProcess, 'execFileSync');
  707. };
  708. const asarReady = new WeakSet();
  709. // Lazily override the child_process APIs only when child_process is
  710. // fetched the first time. We will eagerly override the child_process APIs
  711. // when this env var is set so that stack traces generated inside node unit
  712. // tests will match. This env var will only slow things down in users apps
  713. // and should not be used.
  714. if (process.env.ELECTRON_EAGER_ASAR_HOOK_FOR_TESTING) {
  715. overrideChildProcess(require('child_process'));
  716. } else {
  717. const originalModuleLoad = Module._load;
  718. Module._load = (request: string, ...args: any[]) => {
  719. const loadResult = originalModuleLoad(request, ...args);
  720. if (request === 'child_process' || request === 'node:child_process') {
  721. if (!asarReady.has(loadResult)) {
  722. asarReady.add(loadResult);
  723. // Just to make it obvious what we are dealing with here
  724. const childProcess = loadResult;
  725. overrideChildProcess(childProcess);
  726. }
  727. }
  728. return loadResult;
  729. };
  730. }
  731. };