fs-wrapper.ts 28 KB

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