Skip to content

fix: prevent crash from webtorrent _onTorrentId arr2hex(undefined) — closes #110#113

Closed
py-kalki wants to merge 2 commits into
baairon:mainfrom
py-kalki:fix/webtorrent-infohash-undefined-crash-v2
Closed

fix: prevent crash from webtorrent _onTorrentId arr2hex(undefined) — closes #110#113
py-kalki wants to merge 2 commits into
baairon:mainfrom
py-kalki:fix/webtorrent-infohash-undefined-crash-v2

Conversation

@py-kalki

Copy link
Copy Markdown
Contributor

What and why

Fixes #110 — torlnk crashes within 2–8 seconds of launch with no user input.

Root cause

Torrent._onTorrentId() in webtorrent ≤2.4.x is an async method. When
parseTorrent() resolves to a truthy object but with infoHash === undefined
(e.g. a malformed magnet persisted in a corrupted queue.json), webtorrent
immediately calls arr2hex(parsedTorrent.infoHash) without guarding for
undefined. The TypeError is thrown inside the async function, surfaces as
an unhandled promise rejection, and Node 15+ converts that to a fatal exit.

Fix — primary guard in engine.ts

After client.add() returns a Torrent object, immediately fire a detached
parseTorrent(source).then/catch that races webtorrent's own _onTorrentId.
If infoHash is missing or parseTorrent rejects, the torrent is destroyed
and onError() is called cleanly before webtorrent can blow up.
.torrent file paths (re-seeding from cache) are excluded — they go through
a different internal path.

The existing containUnhandledRejections() in util/crashlog.ts already acts
as the outer safety net; this PR adds the inner guard that stops the crash at
the source.

Type declaration fixes (no runtime effect):

  • parse-torrent.d.tsinfoHash marked string | undefined (optional),
    accurately reflecting the runtime behaviour that caused the crash.
  • webtorrent.d.ts — added missing destroyed: boolean on Torrent
    (it exists at runtime; required by the guard's race-check).

Checklist

  • npm run typecheck is clean
  • npm test passes (280/280)
  • If I added a key, I updated both HELP_GROUPS and footerHints in src/ui/keymap.ts
  • If I added a Store field, I updated makeStore in scripts/render-previews-impl.ts
  • OS-touching code works on Windows, macOS, and Linux
  • One concern, with a Conventional Commits title (fix)

…aairon#110)

webtorrent's Torrent._onTorrentId() is async. When parseTorrent()
resolves to a truthy object but with infoHash === undefined (e.g. a
malformed magnet surviving in a corrupted queue.json), it calls
arr2hex(undefined) inside the async function, producing an unhandled
promise rejection that kills the process via Node's default handler.

This crash required no user action — a bad entry in the persisted queue
was enough to trigger it within seconds of launch.

Fix (two-layer defence):

1. engine.ts — concurrent pre-validation guard
   After client.add() returns a torrent object, immediately fire a
   detached parseTorrent(source) to race-validate the infoHash before
   webtorrent's own _onTorrentId can blow up. If infoHash is missing or
   parseTorrent rejects, the torrent is destroyed and onError() is called
   cleanly instead. Skips .torrent file paths (re-seed from cache) since
   parseTorrent cannot read local paths in this context.

2. index.tsx — unhandledRejection safety net
   Adds process.on('unhandledRejection', ...) that logs but does NOT
   exit, so any unexpected async rejection from webtorrent internals or
   third-party code is surfaced without killing the TUI. Fatal conditions
   still go through uncaughtException.

Also fixes type declarations:
- parse-torrent.d.ts: infoHash marked optional (string | undefined) to
  accurately reflect the runtime behaviour that caused the crash.
- webtorrent.d.ts: add missing destroyed: boolean property on Torrent
  (required by the pre-validation guard's race-check).

All 267 tests pass. TypeScript type-check clean.
Copilot AI review requested due to automatic review settings July 22, 2026 04:59

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Pull request overview

This PR adds a defensive guard in the download engine to prevent a fatal crash caused by a webtorrent ≤2.4.x bug where _onTorrentId() can call arr2hex(undefined) when parse-torrent produces a truthy result with a missing infoHash. It also updates local type declarations to reflect runtime realities needed by the guard.

Changes:

  • Add an async pre-validation race in TorrentEngine.add() that destroys the torrent and reports a clean error if infoHash can’t be resolved.
  • Update parse-torrent typing to allow infoHash to be missing at runtime.
  • Update webtorrent typing to include Torrent.destroyed used by the guard.

Reviewed changes

Copilot reviewed 1 out of 3 changed files in this pull request and generated 4 comments.

File Description
src/download/engine.ts Adds a detached parseTorrent() race/guard to proactively destroy invalid torrents before webtorrent crashes.
src/parse-torrent.d.ts Marks ParsedTorrent.infoHash as optional to match observed runtime behavior.
src/webtorrent.d.ts Adds missing Torrent.destroyed type used by the new guard logic.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread src/download/engine.ts Outdated
Comment thread src/download/engine.ts
Comment on lines +107 to +109
handlers.onError?.(err);
this.torrents.delete(id);
try { torrent.destroy(); } catch {}
Comment thread src/download/engine.ts
Comment on lines +114 to +116
handlers.onError?.(message(e));
this.torrents.delete(id);
try { torrent.destroy(); } catch {}
Comment thread src/download/engine.ts Outdated
Comment on lines +101 to +118
if (!source.endsWith(".torrent")) {
void parseTorrent(source)
.then((parsed) => {
if (torrent.destroyed) return;
if (!parsed?.infoHash) {
const err = `Invalid torrent source: infoHash could not be resolved (source: ${source.slice(0, 80)})`;
handlers.onError?.(err);
this.torrents.delete(id);
try { torrent.destroy(); } catch {}
}
})
.catch((e: unknown) => {
if (torrent.destroyed) return;
handlers.onError?.(message(e));
this.torrents.delete(id);
try { torrent.destroy(); } catch {}
});
}
as per copilot

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
@baairon baairon closed this Jul 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Crash within seconds of launch: TypeError [ERR_INVALID_ARG_TYPE] in Torrent._onTorrentId / uint8-util arr2hex

3 participants