Skip to content

feat: serve asar file descriptors, streams and copies from the archive - #52833

Merged
MarshallOfSound merged 8 commits into
mainfrom
sam/asar-fd-reads
Aug 22, 2026
Merged

MarshallOfSound merged 8 commits into
mainfrom
sam/asar-fd-reads

Conversation

@MarshallOfSound

Copy link
Copy Markdown
Member

Description of Change

Removes the temp-file extraction (Archive::CopyFileOut) from every fs path except process.dlopen and child_process.execFile*, which need a real path.

  • fs.open/openSync/promises.open on a packed entry return a descriptor dup'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).
  • With ASAR integrity enabled, bytes are only handed out from a block whose hash was just verified (per-reader last-block cache, no shared "validated" bitmap, so in-place tampering after a first read is still caught). A violation now terminates synchronously (process.reallyExit); previously the graceful app.exit() let tampered bytes reach require() first.
  • Opening a packed entry with write flags → EACCES (was: silently wrote to the cached temp copy, poisoning later reads); fchmod/fchown/futimes on such fds → EACCES; writeFileSync fast path routed through the same check.
  • copyFile/copyFileSync/promises.copyFile stream archive→destination (mode flags validated like Node, COPYFILE_EXCL honored, FICLONE_FORCE → ENOTSUP, executable bit preserved). fs.cp/promises.cp now work for directories via Node's own implementation; cpSync natives get archive-aware equivalents.
  • New: fs.opendir* and fs.readlink* for archives (readlink returns the link-relative target). fs.stat follows archive symlinks (so cp({ dereference }) works); bigint stats supported; stats built via getStatsFromBinding (drops the DEP0180 fs.Stats constructor warning); directories/symlinks report 0755/0777 so copies stay traversable.
  • original-fs is 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.
  • Remaining temp copies (dlopen/execFile) are made read-only.
  • Fixes from the audit: fs.exists on an invalid archive returned an Error (truthy) instead of false; readFile validated integrity before checking the read error and ignored short reads; readFileSync returned '' for empty files when given an options object.

Breaking (semantic narrowing, documented in breaking-changes.md): the descriptor is only meaningful through fs; handing it to a native addon / child_process stdio / net.Socket({fd}) is not supported.

Benchmarks

Median of 3 runs on an M-series Mac, testing build, 376 MB archive; "cold" = first access of a distinct entry (the old temp copy was cached per entry after that).

Benchmark before after
cold openSync + read 64 KB + close, 16 MB entry 5.3 ms 0.04 ms
cold createReadStream first 64 KB, 16 MB 5.6 ms 0.12 ms
cold promises.open + read 64 KB, 16 MB 6.0 ms 0.13 ms
cold openSync + read 64 KB, 1 MB 0.45 ms 0.05 ms
cold copyFileSync 16 MB 12.6 ms 3.2 ms
cold createReadStream whole 16 MB 13.5 ms 27 ms (¹)
copyFileSync 64 MB 28.5 ms 8.1 ms
promises.copyFile 64 MB 20.9 ms 12.2 ms
createReadStream 64 MB 252 ms 107 ms
createReadStream 4 MB 5.8 ms 2.5 ms
promises.cp directory (100 × 4 KB) ENOENT 36 ms
temp files left in tmpdir by the run 65 0

¹ 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

  • PR description included and stakeholders cc'd
  • npm test passes (spec/asar-spec.ts 258, spec/asar-integrity-spec.ts 20 incl. new fuse-backed multi-block tests)
  • tests are changed or added
  • relevant documentation is changed or added
  • PR title follows semantic commit guidelines

Release Notes

Notes: fs.open, fs.createReadStream, fs.copyFile, fs.cp and friends now read files inside ASAR archives directly from the archive instead of extracting a temporary copy; fs.opendir and fs.readlink work on archives; opening a packed file for writing fails with EACCES.

@MarshallOfSound MarshallOfSound added the semver/minor backwards-compatible functionality label Aug 16, 2026
@electron-cation electron-cation Bot added the new-pr 🌱 PR opened recently label Aug 16, 2026
Comment thread spec/asar-spec.ts Dismissed
Comment thread spec/asar-spec.ts Dismissed
Comment thread spec/asar-spec.ts Dismissed
Comment thread spec/asar-spec.ts Dismissed
Comment thread spec/asar-spec.ts Dismissed
Comment thread spec/asar-spec.ts Dismissed
Comment thread spec/asar-spec.ts Dismissed
Comment thread spec/asar-spec.ts Fixed
Comment thread spec/asar-spec.ts Fixed
Comment thread spec/asar-spec.ts Fixed
codebytere-ant

This comment was marked as outdated.

@codebytere codebytere left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread lib/node/asar-fs-wrapper.ts Resolved
Comment thread lib/node/asar-fs-wrapper.ts Resolved
Comment on lines +1781 to +1783
const handle = new binding.FileHandle(reader.fd);
if (openAsarFiles.size > 256) sweepStaleAsarFds();
openAsarFiles.set(reader.fd, { reader, handle: new WeakRef(handle) });

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 reader

the 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).

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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).

Comment thread lib/node/asar-fs-wrapper.ts Resolved
Comment thread lib/node/asar-fs-wrapper.ts Resolved
Comment thread lib/node/asar-fs-wrapper.ts Resolved
@MarshallOfSound

Copy link
Copy Markdown
Member Author

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.

Comment thread spec/asar-spec.ts Dismissed
Comment thread spec/asar-spec.ts Dismissed
Comment thread spec/asar-spec.ts Dismissed
@MarshallOfSound

Copy link
Copy Markdown
Member Author

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 codebytere left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread lib/node/asar-fs-wrapper.ts Resolved
Comment thread docs/breaking-changes.md Resolved
Comment thread lib/node/asar-fs-wrapper.ts Resolved
@0xdevalias

0xdevalias commented Aug 18, 2026 •

Copy link
Copy Markdown

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:

However, #52833 is not a perfect one-for-one replacement. It explicitly leaves child_process.execFile*, process.dlopen, and native-module loading on the temp-copy path because they require a real OS path. So #52833 addresses the issue’s createReadStream case, but apparently does not address #52807’s broader claim that execFile should recover after its cached temp copy disappears.

@MarshallOfSound

Copy link
Copy Markdown
Member Author

@0xdevalias You honestly shouldn't be doing execFile to a path in an ASAR, it likely doesn't work on macOS and it's slow / could be blocked by A/V on Windows. Just unpack the executable.

In a future version of Electron it's more likely we remove the execFile shim for an in-asar executable, rather than fix it to re-validate / always-extract. The "copyFileOut" behavior is not protected by integrity and is fundamentally just kinda bad

@MarshallOfSound
MarshallOfSound marked this pull request as ready for review August 18, 2026 07:13
@MarshallOfSound
MarshallOfSound requested a review from a team as a code owner August 18, 2026 07:13
@codebytere

Copy link
Copy Markdown
Member

API LGTM

@deepak1556 deepak1556 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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_process stdio, 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_fd

@jkleinsc jkleinsc left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

API LGTM

@MarshallOfSound

Copy link
Copy Markdown
Member Author

@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.

Comment thread lib/node/asar-fs-wrapper.ts Resolved
Comment thread lib/node/asar-fs-wrapper.ts Resolved
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.
@MarshallOfSound
MarshallOfSound merged commit 7377022 into main Aug 22, 2026
70 of 71 checks passed
@MarshallOfSound
MarshallOfSound deleted the sam/asar-fd-reads branch August 22, 2026 06:03
@release-clerk

release-clerk Bot commented Aug 22, 2026

Copy link
Copy Markdown

Release Notes Persisted

fs.open, fs.createReadStream, fs.copyFile, fs.cp and friends now read files inside ASAR archives directly from the archive instead of extracting a temporary copy; fs.opendir and fs.readlink work on archives; opening a packed file for writing fails with EACCES.

eliandoran added a commit to TriliumNext/Trilium that referenced this pull request Oct 13, 2026
…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]>
eliandoran added a commit to TriliumNext/Trilium that referenced this pull request Oct 25, 2026
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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

45-x-y api-review/requested 🗳 new-pr 🌱 PR opened recently no-backport semver/minor backwards-compatible functionality

Projects

Status: No status

Development

Successfully merging this pull request may close these issues.

7 participants