fix: prevent crash from webtorrent _onTorrentId arr2hex(undefined) — closes #110#114
Open
py-kalki wants to merge 2 commits into
Open
fix: prevent crash from webtorrent _onTorrentId arr2hex(undefined) — closes #110#114py-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 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 inTorrentEngine.add()to detect missing/invalidinfoHashearly and destroy/remove the torrent safely. - Add unit tests covering the invalid-
infoHash, rejection, and “same id re-add” race scenarios. - Update local
.d.tsshims forparse-torrent(infoHashoptional) andwebtorrent(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.
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.
To prevent race conditions when
add()is called rapidly for the same torrent ID, all deletion checks inside.then(),.catch(), andtorrent.on("error")verifyif (this.torrents.get(id) === torrent)before deleting from the map.The existing
containUnhandledRejections()inutil/crashlog.tsalready actsas 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):onErroris called and torrent removed whenparseTorrentresolves{ infoHash: undefined }.onErroris called and torrent removed whenparseTorrentrejects.parseTorrentis settling.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 (283/283)vitest)HELP_GROUPSandfooterHintsinsrc/ui/keymap.tsStorefield, I updatedmakeStoreinscripts/render-previews-impl.tsfix)