Repository navigation
feat: serve asar file descriptors, streams and copies from the archive - #52833
Conversation
codebytere
left a comment
There was a problem hiding this comment.
Went through the fd/stream/copy paths, the block-validation logic and the original-fs snapshot fairly carefully — this is really nice, and the integrity story (per-reader last-block cache + synchronous reallyExit) is a clear improvement over what we had. A handful of small things inline; only the readv one is an actual wrong-result bug, the rest are parity nits / hardening.
One drive-by that I couldn't anchor because the line is unchanged: in handleDirents (~L1245) the if (!archive) return; bails out of the whole loop, silently dropping every sibling after an unreadable *.asar entry from a recursive withFileTypes readdir. It predates this PR, but the new getDirents helper right at the bottom does the same thing with continue, so it'd be nice to make them match while this function is being touched anyway.
| const handle = new binding.FileHandle(reader.fd); | ||
| if (openAsarFiles.size > 256) sweepStaleAsarFds(); | ||
| openAsarFiles.set(reader.fd, { reader, handle: new WeakRef(handle) }); |
There was a problem hiding this comment.
Minor fd-reuse window here: FileHandle#close() doesn't go through binding.close, so this entry is only dropped lazily by lookupAsarFd's handle.fd !== fd check. That accessor reads the C++ fd_, which is only reset to -1 in AfterClose() on the loop thread — but the actual close(2) runs on the threadpool. So with an un-awaited close:
const fh = await fs.promises.open(packedPath);
fh.close(); // close(2) may complete on the pool right away
const fd = fs.openSync(someRealFile); // can be handed the same number
fs.readSync(fd, buf); // lookupAsarFd(fd) still matches → served from the stale readerthe new, unrelated fd gets its reads/fstat routed through the old AsarEntryReader (wrong offset → wrong/empty bytes, or an integrity "violation" exit) until AfterClose lands. Narrow, but cheap to close off since you construct the C++ handle yourself — e.g. shadow close on the instance:
const handle = new binding.FileHandle(reader.fd);
const { close } = handle;
handle.close = function (this: any) { forgetAsarFd(reader.fd); return close.call(this); };(or wrap binding.FileHandle.prototype.close once and check the map).
There was a problem hiding this comment.
Agreed, that window is real (fd_ is only reset in AfterClose on the loop thread). Went with shadowing close on the instance since we build the handle ourselves; forgetAsarFd runs before the pool close is even queued. Added a test that opens a packed handle, calls close() without awaiting, opens a real file and checks the reads on it aren't routed through the reader (200 iterations).
|
Thanks for the thorough pass. Everything inline is addressed in c9adc6d, plus the handleDirents drive-by (return -> continue so an unreadable archive entry no longer drops the rest of a recursive withFileTypes listing). The code-quality bot comments are all the same false positive: promisify is a global installed in the remote renderer context (with the TS dummy at the top of asar-spec.ts), same as every existing promisify(fs.lstat) test in that file, so I've left those. |
c9adc6d to
f6543f6
Compare
|
Rebased on main (conflicted with #52825, which landed the same GetFileInfo link-depth bound; took upstream's version and dropped mine). Also fixed the three CI failures: the nn-test one was real (test-require-delete-array-iterator deletes Array's iterator and my binding hooks used spread/destructuring on the pass-through path, now Function#apply + index access), the Windows ones were the new mode assertions exposing that S_IRGRP/S_IROTH/S_IX* don't exist there (fake modes now use literal bits), and #52808 started calling CopyFileOut from the UI thread which tripped the blocking DCHECK on the new temp-file chmod. |
codebytere
left a comment
There was a problem hiding this comment.
went back over f6543f6 and the fixes from the last round all look right to me (readv, FICLONE_FORCE, the close shadow, EISDIR, name encodings, and the apply/index rewrite). A few more below; the fs.cp one is the only wrong-result bug, the other two are a docs gap for one Node API that regressed with the fd change and a small leak in the block cache accounting.
|
Cross-linking what I believe (from my naive/quick read of this PR) to be related issues / superceded PR's/etc related to this: While I haven't deeply validated this myself, and my understanding of the codebase / etc here is too naive to be able to easily say; this one note from GitHub Copilot (GPT-5.6 Terra) that popped up / I captured in #52807 (comment) sounded like it may be potentially relevant to this PR, that the seemingly superseded #52807 may have previously handled differently/maybe better:
|
|
@0xdevalias You honestly shouldn't be doing In a future version of Electron it's more likely we remove the |
|
API LGTM |
deepak1556
left a comment
There was a problem hiding this comment.
Overall good to me, not blocking but regards to
Passing one of these descriptors to code outside of Node's
fs
module (for example a native addon that reads from the raw descriptor,
child_processstdio,net.Socket({ fd })or
http2stream.respondWithFile()) is not supported:
Was it considered keeping the archive fd an implementation detail, while the one exposed can be an fd (like write end to /dev/null) that would fail these callsites. If we keep the fds in a RAII class
class AsarEntryHandle : public node::ObjectWrap {
public:
AsarEntryHandle(base::ScopedPlatformFile archive_fd,
int exposed_fd,
FileInfo info);
int exposed_fd() const;
int archive_fd() const;
void Close();
private:
base::ScopedPlatformFile archive_fd_;
FileInfo info_;
};The lifetime could be
JS FileHandle
├── Node FileHandle -> owns exposed_fd
└── AsarEntryHandle -> owns archive_fde996137 to
befad80
Compare
|
@deepak1556 took your sentinel fd suggestion in befad80, with one simplification: there's no per-open archive fd at all now. The exposed descriptor is a dup of a process-wide write-only null device, reads go through the archive's retained handle positionally (same as readFile already did), so no handle to the archive ever escapes and a raw read of the descriptor gets EBADF instead of archive bytes at the wrong offset. Because /dev/null would quietly accept writes I also refuse writeBuffer/writeBuffers/writeString/ftruncate through those descriptors with EACCES (was relying on O_RDONLY before). Didn't go for the RAII ObjectWrap since it'd only cover FileHandles, plain openSync numbers still need the JS table either way. Also rebased onto main (the internalModuleStat cache from #52923 is merged with the symlink following) and CI is re-running. |
fs.open/openSync/promises.open, fs.createReadStream, fs.copyFile/cp (and their sync/promise variants) previously extracted a packed asar entry into a temporary file first (Archive::CopyFileOut): a synchronous, main-thread copy of the whole file on first access, a temp copy left behind for the life of the process, and a cached copy that later opens with write flags could corrupt. The wrapper now hands out real file descriptors duplicated from the archive's retained handle and hooks the fs binding so every fd-based API (read/readv/ fstat/close/readFile(fd), ReadStream, FileHandle) reads straight out of the archive. With ASAR integrity enabled, bytes are only ever served from a block whose hash was just verified, and a violation terminates the process synchronously instead of after the tampered data was already handed back. Copies stream from the archive to the destination; opening a packed file for writing fails with EACCES; fchmod/fchown/futimes on such descriptors are refused. Only process.dlopen and child_process.execFile still need a real path and keep using the temporary copy (now made read-only). Also adds fs.opendir/readlink support for archives, makes fs.stat follow archive symlinks (fs.cp dereference now works), returns BigIntStats when asked, and gives original-fs its own pristine copy of the fs binding so it is unaffected by these overrides.
- readv on a packed entry: a zero-length buffer no longer ends the clamped read early; later buffers are still filled, like preadv. - copyFile with COPYFILE_FICLONE_FORCE on an unpacked entry is passed to native fs (which may reflink); only packed entries reject it with ENOTSUP. - FileHandle#close() forgets the descriptor entry immediately instead of waiting for the C++ handle's fd to be reset after the threadpool close, so a real file that reuses the number in that window is never routed through the archive reader. - open() of a symbolic link to a directory reports EISDIR, not ENOENT. - readlink and opendir honour name encodings other than 'buffer'. - recursive readdir withFileTypes skips an unreadable archive entry instead of dropping the rest of the listing.
…deleted - Forward pass-through calls with Function#apply and index access instead of spread / array destructuring, which need Array.prototype[Symbol.iterator] (user code may delete it; parallel/test-require-delete-array-iterator). - Use literal permission bits for the fake asar stats: the S_IRGRP/S_IROTH/ S_IX* constants do not exist on Windows, so the modes came out as 0600. - Allow blocking around the chmod of a copied-out temp file; CopyFileOut is also reached from the UI thread via WebContents.downloadURL().
- Archive::Stat now exposes `executable`, so fs.stat/lstat of a packed executable report 0755 like fs.fstat does; fs.cp no longer strips the bit that copyFile preserved when it chmods the destination to the source mode. - A descriptor for a packed entry can be closed without going through fs.close (a native FileHandle built on it, e.g. http2's respondWithFile, a FileHandle moved to a worker, or one closed on GC). Whenever fs hands out a descriptor number (native pass-through open or a new archive-backed one), any stale entry for that number is dropped first, so it can never capture the new owner's reads, and its retained block is returned to the budget. - Document http2stream.respondWithFile()/respondWithFD() among the APIs that read the raw descriptor.
…archive
The descriptor returned by open() for a packed entry used to be a dup of the
archive's own handle. Code that read it directly instead of through fs (a
native addon, a child's stdio, net.Socket({ fd }), http2's respondWithFile)
silently got bytes of the archive at the wrong offset, and a raw handle to
the archive escaped to user code.
Hand out a per-open dup of a write-only null device instead. It identifies
the entry to fs, which serves every read from the archive's retained handle
positionally as before, and it is useless to anything else: direct reads
fail with EBADF, the archive itself is never exposed, and a descriptor
closed behind our back can at worst misroute through fs, never leak archive
bytes. Writes, truncation and metadata changes through such a descriptor are
refused with EACCES rather than vanishing into the null device. copyFile and
the writeFile fast path read the entry without allocating a descriptor at
all.
libuv's error numbers differ from POSIX errno on Windows (UV_EACCES is -4092 there, not -13) and Node decodes `errno` through libuv's table, so the hand-written errno values decoded as UNKNOWN on Windows. Take them from the uv binding instead. Also refuse writeFileSync's utf8 fast path when it is given a packed entry's descriptor rather than a path.
fc6810a to
6233957
Compare
|
Release Notes Persisted
|
…9748) A long-running macOS desktop app could reload into a white page that showed only `{"message":"ENOENT: no such file or directory, open '/var/folders/…/T/.com.electron.trilium-notes.XXXXXX'"}`. Electron implements `fs.open()` on an entry inside `app.asar` by extracting it to a file in the OS temp directory, once per process, and returns that cached path on every later open without checking that it still exists. The packaged app serves the whole UI from `app.asar/public` through `send` (`express.static()` and `res.sendFile()`), which streams each file with `fs.createReadStream()` and so goes through that copy. macOS deletes temp files nobody accessed for about three days, after which every open of an affected file fails. `index.html` is sent with `no-cache`, so the next reload of the window hits it first and the Express error handler's JSON becomes the page. `setupAsarReadStreams()` wraps `fs.createReadStream()` when the app runs from an asar archive: a path inside the archive, with no `fd` or `encoding`, is read with `fs.promises.readFile()`, which reads the archive directly, and the inclusive `start`/`end` range `send` asks for is sliced out of it. Everything else goes to the original. This also stops the packaged app from copying every asset it serves into the temp directory; on Linux those copies (`/tmp/.org.chromium.Chromium.*`) outlive the process. Checked against a packaged build (`electron-forge:package`, run under the matching Nix Electron 44.7.0): the 99 files the setup page loads all went through the wrapper, with no error responses and no new temp files, while the unwrapped `createReadStream()` on the same archive opened a fresh `/tmp/.org.chromium.Chromium.*` copy. Unpacking the served folders instead was rejected: they are about 100 MB, and files outside the archive are not covered by the `EnableEmbeddedAsarIntegrityValidation` fuse. Upstream: electron/electron#52804. Electron 45 fixes it with electron/electron#52833, which serves descriptors, streams and copies from the archive and is not backported to 43/44. Remove this module in the commit that upgrades to Electron 45. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Electron 45 reads asar entries in place (electron/electron#52833) instead of through a temp copy that macOS cleans up, so the `setupAsarReadStreams()` wrapper from 5b91f87 (#9748) is no longer needed. Assisted-by: Claude Code (Claude Opus 5.5)
Description of Change
Removes the temp-file extraction (
Archive::CopyFileOut) from every fs path exceptprocess.dlopenandchild_process.execFile*, which need a real path.fs.open/openSync/promises.openon a packed entry return a descriptordup'd from the archive's retained handle (CLOEXEC / non-inheritable). The fs binding (read,readBuffers,fstat,close,readFileUtf8) is hooked so every fd-based API —read*,readv*,fstat*,readFile(fd),createReadStream,FileHandle— reads straight out of the archive; positions are translated and clamped to the entry. Non-integrity reads are passed to native with the caller's own request (no extra hop).process.reallyExit); previously the gracefulapp.exit()let tampered bytes reachrequire()first.EACCES(was: silently wrote to the cached temp copy, poisoning later reads);fchmod/fchown/futimeson such fds →EACCES;writeFileSyncfast path routed through the same check.copyFile/copyFileSync/promises.copyFilestream archive→destination (mode flags validated like Node,COPYFILE_EXCLhonored,FICLONE_FORCE→ENOTSUP, executable bit preserved).fs.cp/promises.cpnow work for directories via Node's own implementation;cpSyncnatives get archive-aware equivalents.fs.opendir*andfs.readlink*for archives (readlink returns the link-relative target).fs.statfollows archive symlinks (socp({ dereference })works);bigintstats supported; stats built viagetStatsFromBinding(drops the DEP0180fs.Statsconstructor warning); directories/symlinks report 0755/0777 so copies stay traversable.original-fsis generated from the same sources and shared the binding object; it now gets a pristine snapshot (script/node/generate_original_fs.py) and is covered by a spec.fs.existson an invalid archive returned anError(truthy) instead offalse;readFilevalidated integrity before checking the read error and ignored short reads;readFileSyncreturned''for empty files when given an options object.Breaking (semantic narrowing, documented in
breaking-changes.md): the descriptor is only meaningful throughfs; handing it to a native addon /child_processstdio /net.Socket({fd})is not supported.Benchmarks
Median of 3 runs on an M-series Mac,
testingbuild, 376 MB archive; "cold" = first access of a distinct entry (the old temp copy was cached per entry after that).openSync+ read 64 KB + close, 16 MB entrycreateReadStreamfirst 64 KB, 16 MBpromises.open+ read 64 KB, 16 MBopenSync+ read 64 KB, 1 MBcopyFileSync16 MBcreateReadStreamwhole 16 MBcopyFileSync64 MBpromises.copyFile64 MBcreateReadStream64 MBcreateReadStream4 MBpromises.cpdirectory (100 × 4 KB)¹ the one regression: a first-ever whole-file stream of a cold entry now issues 64 KB preads against the cold region instead of one sequential copy followed by a hot-cache stream. Small-file steady-state numbers are within noise of each other.
Checklist
npm testpasses (spec/asar-spec.ts258,spec/asar-integrity-spec.ts20 incl. new fuse-backed multi-block tests)Release Notes
Notes:
fs.open,fs.createReadStream,fs.copyFile,fs.cpand friends now read files inside ASAR archives directly from the archive instead of extracting a temporary copy;fs.opendirandfs.readlinkwork on archives; opening a packed file for writing fails withEACCES.