fs-wrapper.ts 27 KB

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