Skip to content

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

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

fix: prevent crash from webtorrent _onTorrentId arr2hex(undefined) — closes #110#114
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.

To prevent race conditions when add() is called rapidly for the same torrent ID, all deletion checks inside .then(), .catch(), and torrent.on("error") verify if (this.torrents.get(id) === torrent) before deleting from the map.

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.

Unit Tests added (src/download/engine.test.ts):

  • Proves onError is called and torrent removed when parseTorrent resolves { infoHash: undefined }.
  • Proves onError is called and torrent removed when parseTorrent rejects.
  • Proves identity check prevents deleting a newer torrent added for the same ID while parseTorrent is settling.

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 (283/283)
  • New logic has a test (vitest)
  • 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 05:24

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 prevents torlnk from crashing shortly after launch by adding an “inner” guard around webtorrent’s Torrent._onTorrentId() behavior when parse-torrent yields a truthy object with a missing infoHash (issue #110). It adds a pre-validation race in TorrentEngine.add() to destroy the torrent and surface a clean error before the upstream unhandled rejection can terminate the process, plus supporting typings and unit tests.

Changes:

  • Add async parseTorrent() pre-validation in TorrentEngine.add() to detect missing/invalid infoHash early and destroy/remove the torrent safely.
  • Add unit tests covering the invalid-infoHash, rejection, and “same id re-add” race scenarios.
  • Update local .d.ts shims for parse-torrent (infoHash optional) and webtorrent (Torrent.destroyed).

Reviewed changes

Copilot reviewed 2 out of 4 changed files in this pull request and generated 1 comment.

File Description
src/download/engine.ts Adds the pre-validation guard and tightens map-deletion checks to avoid racing deletes.
src/download/engine.test.ts Adds mocks and tests validating the guard behavior and the “same id” race safety.
src/parse-torrent.d.ts Updates typing/docs to reflect infoHash can be missing at runtime.
src/webtorrent.d.ts Adds Torrent.destroyed typing 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
AS PER COPILOT

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
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

2 participants