Harden auth, add AI smart-search and post-download organization

Security & correctness hardening:
- Gate /__api/token/auth behind auth and self-scope every handler to the
  caller (was fully unauthenticated — account-takeover hole).
- Escape LDAP filter values (injection) and reject empty-password binds.
- Enforce per-torrent ownership so private torrents aren't exposed via IDOR.
- Assorted cleanup: fix 'use static' typos, drop dead Torrent.migrate + the
  getTorrentData noUpdate flag, Buffer.alloc, __dirname-relative reads,
  res.statusCode in the error handler, const-scope pubsub.

Login-gated proxy + anti-indexing:
- Block all proxying for logged-out users via an auth-token cookie the front
  end mirrors from its token; serve a local login page instead of hitting TPB.
- robots.txt disallow-all + X-Robots-Tag noindex.

Torrent category:
- Store a normalized category (TV/Movie/Music/Adult/App/Game/Other) mapped
  from the TPB category id; captured at add time (migration).

Smart Search (movies/TV):
- New /__api/search: TMDB title confirm -> scrape piratebay.party HTML ->
  Ollama ranks releases against quality prefs (x265/1080p/~1.5GB/subs,
  prefer uncut) returning a recommended pick, optional warned 4K, and other
  editions. Front-end Smart Search box + dialog feeding the existing add flow.

Post-download organization -> Emby (public Movie/TV only):
- Completion watcher files finished torrents: Ollama parses the release name,
  TMDB canonicalizes title/year, files main video (+subs) into the library
  with edition/quality-aware names (movies + TV SxxExx), stops seeding, and
  triggers an Emby library scan. Low-confidence matches are flagged, not
  mis-filed; correctable via "Fix match". Adds organizedAt/metadata columns.

Shared helpers: controller/tmdb.js, controller/ollama.js. Config blocks for
tmdb/ollama/search/emby/library/organize (secrets stay in gitignored secrets.js).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-07-01 14:19:13 -04:00
parent b30fe748b2
commit fd5ef14999
21 changed files with 1144 additions and 70 deletions
+129 -2
View File
@@ -185,6 +185,15 @@
<p>
Done! <a href="https://stuff.718it.biz/torrents/{{name}}" target="_blank"> HTTP Link</a>
</p>
{{#organized}}
<p>📁 Filed to <b>{{libraryPath}}</b></p>
{{/organized}}
{{#organizeError}}
<p style="color:#b00">⚠ Not filed: {{organizeError}}</p>
{{/organizeError}}
<button class="ui-button ui-widget ui-corner-all" onclick="tbpFixMatch('{{hashString}}')">
<span class="ui-icon ui-icon-pencil"></span> Fix match
</button>
{{/isFinished}}
<hr />
</li>
@@ -241,6 +250,8 @@
<input type="text" name="hashString" value="{{{hashString}}}" readonly/>
</p>
<input type="hidden" name="category" value="{{{category}}}"/>
<p>
<label for="isPrivate-false" title="The download will appare in the communal download folder">Public:</label>
<input type="radio" name="isPrivate" id="isPrivate-false" value="false" />
@@ -268,11 +279,20 @@
</div>
<!--
<div id="tbp_proxy_search_dialog" title="Smart Search">
<div id="tbp_proxy_search_dialog_body"></div>
</div>
<!--
Injected Header bar
-->
<div id="tbp_proxy_header_right">
<form id="tbp_proxy_search_form" class="tbp_proxy_is_authed" style="display:inline-block; margin-right:.5em;" onsubmit="return false;">
<input type="text" id="tbp_proxy_search_input" placeholder="Smart search movies &amp; TV…" />
<button type="submit" class="ui-button ui-corner-all ui-widget">Search</button>
</form>
<span id="tbp_proxy_torrent_dialog_opener" class="tbp_proxy_is_authed">
<img src="/__static/img/Transmission_Icon.svg" height="22" width="22" style="margin-right: .3em;" />
<span jq-repeat="tbp_proxy_torrent_dialog_opener_status">
@@ -320,6 +340,104 @@
$('#tbp_proxy_torrent_add_dialog').dialog(commonDialogOptions);
/* Smart Search button and dialog */
$('#tbp_proxy_search_dialog').dialog(commonDialogOptions);
// Escape untrusted text before dropping it into HTML.
function tbpEsc(text){ return $('<i>').text(text == null ? '' : text).html(); }
function tbpSearchBody(html){ $('#tbp_proxy_search_dialog_body').html(html); }
// Step 1: render the TMDB title candidates to confirm which one they meant.
// onPick defaults to the search flow; the "Fix match" flow passes its own.
function tbpRenderTitles(results, onPick){
onPick = onPick || tbpFindReleases;
if(!results.length){ tbpSearchBody('<p>No matches found.</p>'); return; }
tbpSearchBody('<p>Which one did you mean?</p>');
results.forEach(function(r){
var poster = r.posterUrl ? '<img src="'+ r.posterUrl +'" width="60" style="vertical-align:middle;margin-right:.5em;"/>' : '';
$('<div class="tbp_search_card" style="cursor:pointer;padding:.4em;border-bottom:1px solid #ccc;"></div>')
.html(poster +'<b>'+ tbpEsc(r.title) +'</b> ('+ tbpEsc(r.year || '?') +') <span style="color:#888">'+ tbpEsc(r.mediaType) +'</span>')
.on('click', function(){ onPick(r); })
.appendTo('#tbp_proxy_search_dialog_body');
});
}
// "Fix match": re-run the title picker for a finished torrent and re-file it under
// the chosen TMDB match via POST /torrent/:hash/organize/match.
window.tbpFixMatch = function(hash){
var item = ($.scope.tbp_proxy_torrent_dialog_torrents || []).filter(function(t){ return t.hashString === hash; })[0];
var query = (item ? item.name : '').replace(/[._]/g, ' ').replace(/\b(19|20)\d\d\b.*/, function(m){ return m.slice(0, 4); }).trim();
openDialog($('#tbp_proxy_search_dialog'));
tbpSearchBody('<p>Searching for a better match…</p>');
app.api.get('search/title?q='+ encodeURIComponent(query || (item ? item.name : '')), function(error, data){
if(error || !data || !data.results){ tbpSearchBody('<p>Search failed. Please try again.</p>'); return; }
tbpRenderTitles(data.results, function(r){
tbpSearchBody('<p>Re-filing as <b>'+ tbpEsc(r.title) +' ('+ tbpEsc(r.year) +')</b>…</p>');
app.api.post('torrent/'+ hash +'/organize/match', { tmdbId: r.tmdbId, mediaType: r.mediaType }, function(err, res){
if(err || !res || res.organized !== true){
tbpSearchBody('<p>Re-file failed: '+ tbpEsc((res && res.message) || err) +'</p>'); return;
}
tbpSearchBody('<p>✓ Re-filed to <b>'+ tbpEsc(res.libraryPath) +'</b>. Emby will re-index.</p>');
});
});
});
};
// Step 2: ask the server( TPB + LLM) for the curated release options.
function tbpFindReleases(title){
tbpSearchBody('<p>Finding the best copies for <b>'+ tbpEsc(title.title) +'</b>…<br/>this can take a few seconds.</p>');
app.api.post('search/releases', { tmdbId: title.tmdbId, mediaType: title.mediaType }, function(error, data){
if(error || !data || !data.options){ tbpSearchBody('<p>Search failed. Please try again.</p>'); return; }
tbpRenderReleases(data);
});
}
// Step 3: render the release cards; a tap feeds the existing add dialog.
function tbpRenderReleases(data){
if(!data.options.length){ tbpSearchBody('<p>No good torrents found for '+ tbpEsc(data.title) +'.</p>'); return; }
tbpSearchBody('<h3>'+ tbpEsc(data.title +' ('+ (data.year || '?') +')') +'</h3>');
data.options.forEach(function(o){
var warn = o.warning ? '<div style="color:#b00;font-weight:bold;">⚠ '+ tbpEsc(o.warning) +'</div>' : '';
var why = o.why ? '<div style="color:#555;font-style:italic;">'+ tbpEsc(o.why) +'</div>' : '';
$('<div class="tbp_search_card" style="cursor:pointer;padding:.5em;border-bottom:1px solid #ccc;"></div>')
.html('<b>'+ tbpEsc(o.label || o.role) +'</b> <span style="color:#888">'+ tbpEsc(o.sizeHuman || '') +' · '+ tbpEsc(o.seeders || 0) +' seeders</span>'
+ '<div style="font-size:.9em">'+ tbpEsc(o.name) +'</div>' + why + warn)
.on('click', function(){ tbpAddRelease(o); })
.appendTo('#tbp_proxy_search_dialog_body');
});
}
// Reuse the existing add flow: fill the torrentAdd scope and open the add dialog.
function tbpAddRelease(o){
$.scope.torrentAdd.update({
magnetLink: o.magnetLink,
name: o.name,
hashString: String(o.info_hash).toLowerCase(),
category: o.category,
});
if(localStorage.getItem('isPrivate') === 'true'){
$('#isPrivate-true').prop('checked', true);
}else{
$('#isPrivate-false').prop('checked', true);
}
$('#tbp_proxy_search_dialog').dialog('close');
openDialog($('#tbp_proxy_torrent_add_dialog'));
}
$('#tbp_proxy_search_form').on('submit', function(){
var q = $('#tbp_proxy_search_input').val();
if(!q) return false;
openDialog($('#tbp_proxy_search_dialog'));
tbpSearchBody('<p>Searching…</p>');
app.api.get('search/title?q='+ encodeURIComponent(q), function(error, data){
if(error || !data || !data.results){ tbpSearchBody('<p>Search failed. Please try again.</p>'); return; }
tbpRenderTitles(data.results);
});
return false;
});
/* Enable tooltips*/
$('#tbp_proxy_header').tooltip({
track: true
@@ -332,10 +450,17 @@
// magnetLink
let magnetLinkParams = new URLSearchParams($(this).data('link'));
// Grab the TPB category id from the /browse/<id> link in this
// torrent's row( listing) or the Type: field( detail page).
let $cat = $(this).closest('tr').find('a[href*="/browse/"]').first();
if(!$cat.length) $cat = $('dd a[href*="/browse/"]').first();
let category = $cat.length ? $cat.attr('href').replace(/.*\/browse\//, '').replace(/\D.*$/, '') : '';
$.scope.torrentAdd.update({
magnetLink: $(this).data('link'),
name: magnetLinkParams.get('dn'),
hashString: magnetLinkParams.get('magnet:?xt').split(':').pop().toLowerCase(),
category: category,
});
if(localStorage.getItem('isPrivate') === 'true'){
@@ -521,7 +646,9 @@
"isActive": [3, 4, 5, 6].includes(torrent.status), // DOWNLOAD_WAIT ,DOWNLOAD, SEED_WAIT, SEED
"isFinished": torrent.isFinished || percentDone === 100,
"createdAtString": moment(torrent.createdAt).fromNow(),
"organized": !!torrent.organizedAt,
"libraryPath": torrent.metadata && torrent.metadata.libraryPath,
"organizeError": torrent.metadata && torrent.metadata.organizeError,
}
}