fs-wrapper.ts 27 KB

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