fix: prevent crash from webtorrent _onTorrentId arr2hex(undefined) — closes #110#113
Closed
py-kalki wants to merge 2 commits into
Closed
fix: prevent crash from webtorrent _onTorrentId arr2hex(undefined) — closes #110#113py-kalki wants to merge 2 commits into
py-kalki wants to merge 2 commits into
Conversation
…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.
There was a problem hiding this comment.
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 ifinfoHashcan’t be resolved. - Update
parse-torrenttyping to allowinfoHashto be missing at runtime. - Update
webtorrenttyping to includeTorrent.destroyedused 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 on lines
+107
to
+109
| handlers.onError?.(err); | ||
| this.torrents.delete(id); | ||
| try { torrent.destroy(); } catch {} |
Comment on lines
+114
to
+116
| handlers.onError?.(message(e)); | ||
| this.torrents.delete(id); | ||
| try { torrent.destroy(); } catch {} |
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>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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 anasyncmethod. WhenparseTorrent()resolves to a truthy object but withinfoHash === undefined(e.g. a malformed magnet persisted in a corrupted
queue.json), webtorrentimmediately calls
arr2hex(parsedTorrent.infoHash)without guarding forundefined. TheTypeErroris thrown inside the async function, surfaces asan unhandled promise rejection, and Node 15+ converts that to a fatal exit.
Fix — primary guard in
engine.tsAfter
client.add()returns aTorrentobject, immediately fire a detachedparseTorrent(source).then/catchthat races webtorrent's own_onTorrentId.If
infoHashis missing orparseTorrentrejects, the torrent is destroyedand
onError()is called cleanly before webtorrent can blow up..torrentfile paths (re-seeding from cache) are excluded — they go througha different internal path.
The existing
containUnhandledRejections()inutil/crashlog.tsalready actsas 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.ts—infoHashmarkedstring | undefined(optional),accurately reflecting the runtime behaviour that caused the crash.
webtorrent.d.ts— added missingdestroyed: booleanonTorrent(it exists at runtime; required by the guard's race-check).
Checklist
npm run typecheckis cleannpm testpasses (280/280)HELP_GROUPSandfooterHintsinsrc/ui/keymap.tsStorefield, I updatedmakeStoreinscripts/render-previews-impl.tsfix)