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
+2 -1
View File
@@ -4,8 +4,9 @@ const router = require('express').Router();
const middleware = require('>/middleware/auth');
router.use('/auth', require('./auth'));
router.use('/token/auth', require('./authtoken'));
router.use('/token/auth', middleware.auth, require('./authtoken'));
router.use('/torrent', middleware.auth, require('./transmission'));
router.use('/search', middleware.auth, require('./search'));
router.use('/user', middleware.auth, require('./user'));
module.exports = router;
+25 -5
View File
@@ -3,10 +3,22 @@
const router = require('express').Router();
const {AuthToken} = require('>/models');
function ownToken(token, req){
if(!token || token.username !== req.user.username){
let error = new Error('AuthTokenNotFound');
error.name = 'AuthTokenNotFound';
error.message = 'Token not found';
error.status = 404;
throw error;
}
return token;
}
router.get('/', async function(req, res, next){
try{
return res.json(await AuthToken.findAll());
return res.json(await AuthToken.findAll({where:{
username: req.user.username
}}));
}catch(error){
next(error);
}
@@ -14,7 +26,7 @@ router.get('/', async function(req, res, next){
router.post('/', async function(req, res, next){
try{
return res.json(await AuthToken.create(req.body));
return res.json(await AuthToken.create({...req.body, username: req.user.username}));
}catch(error){
console.error(error)
next(error);
@@ -23,6 +35,14 @@ router.post('/', async function(req, res, next){
router.get('/user/:username', async function(req, res, next){
try{
if(req.params.username !== req.user.username){
let error = new Error('AuthTokenNotFound');
error.name = 'AuthTokenNotFound';
error.message = 'Token not found';
error.status = 404;
throw error;
}
return res.json(await AuthToken.findAll({where:{
username: req.params.username
}}));
@@ -33,7 +53,7 @@ router.get('/user/:username', async function(req, res, next){
router.get('/:token', async function(req, res, next){
try{
let token = await AuthToken.findByPk(req.params.token)
let token = ownToken(await AuthToken.findByPk(req.params.token), req);
token.dataValues.user = await token.getUser()
return res.json(token);
@@ -44,7 +64,7 @@ router.get('/:token', async function(req, res, next){
router.put('/:token', async function(req, res, next){
try{
let token = await AuthToken.findByPk(req.params.token);
let token = ownToken(await AuthToken.findByPk(req.params.token), req);
await token.update(req.body);
return res.json(token);
}catch(error){
@@ -54,7 +74,7 @@ router.put('/:token', async function(req, res, next){
router.delete('/:token', async function(req, res, next){
try{
let token = await AuthToken.findByPk(req.params.token);
let token = ownToken(await AuthToken.findByPk(req.params.token), req);
await token.destroy();
return res.json({'deleted': true});
+43 -5
View File
@@ -1,19 +1,57 @@
'use static';
'use strict';
const router = require('express').Router();
const path = require('path');
const zlib = require('zlib');
const fs = require('fs');
const https = require('https');
const http = require("http");
const proxy = require('http-proxy-middleware');
const { Auth } = require('>/controller/auth');
const inject = fs.readFileSync('./inject.html', 'utf8');
const mainjs = fs.readFileSync('./static/main.js', 'utf8');
const inject = fs.readFileSync(path.join(__dirname, '..', 'inject.html'), 'utf8');
const mainjs = fs.readFileSync(path.join(__dirname, '..', 'static', 'main.js'), 'utf8');
// Page served to users who are not logged in. It reuses the injected front end
// (jQuery + header partial) so the login dialog is available, but nothing is proxied.
const loginPage = "<html><head><meta name='robots' content='noindex, nofollow'><title>Login</title></head><body>"
+ inject
+ "<script>window.__tbpLoginGate = true;</script>"
+ "</body></html>";
function parseCookies(req){
let out = {};
let header = req.headers.cookie;
if(!header) return out;
for(let pair of header.split(';')){
let idx = pair.indexOf('=');
if(idx < 0) continue;
out[pair.slice(0, idx).trim()] = decodeURIComponent(pair.slice(idx + 1).trim());
}
return out;
}
// Keep the proxy( and everything it serves) out of search engines.
router.get('/robots.txt', function(req, res){
res.type('text/plain').send('User-agent: *\nDisallow: /\n');
});
// Block all proxying for users who are not logged in. Page navigation can not send
// the auth-token header, so the token is read from a cookie set by the front end.
router.use(async function(req, res, next){
res.set('X-Robots-Tag', 'noindex, nofollow');
try{
await Auth.checkToken(parseCookies(req)['auth-token']);
return next();
}catch(error){
return res.status(401).send(loginPage);
}
});
// app.all("/*.js", function(req, res){res.send('')});
router.all('/static/main.js', function(req,res){
res.write(mainjs);
res.end(mainjs);
});
const proxyTarget = {
@@ -70,7 +108,7 @@ router.all("/*", proxy({
// res.set(key, proxyRes.headers[key].toString().replace('http://', 'https://'))
}
let body = new Buffer('');
let body = Buffer.alloc(0);
proxyRes.on('error', function(e){
console.error('ERROR!', e)
});
+24
View File
@@ -0,0 +1,24 @@
'use strict';
const router = require('express').Router();
const search = require('>/controller/search');
// Step 1: fuzzy query -> a few TMDB title candidates( with posters) to confirm.
router.get('/title', async function(req, res, next){
try{
res.json({results: await search.tmdbSearch(req.query.q)});
}catch(error){
next(error);
}
});
// Step 2: confirmed title -> TPB search + LLM-curated release options.
router.post('/releases', async function(req, res, next){
try{
res.json(await search.findReleases(req.body.tmdbId, req.body.mediaType));
}catch(error){
next(error);
}
});
module.exports = router;
+46 -14
View File
@@ -1,12 +1,28 @@
'use static';
'use strict';
const router = require('express').Router();
const {Torrent} = require('>/models');
const organize = require('>/controller/organize');
function authTorrent(torrent, req){
if(torrent && torrent.isPrivate && torrent.added_by !== req.user.username){
let error = new Error('TorrentNotFound');
error.name = 'TorrentNotFound';
error.message = 'Torrent not found';
error.status = 404;
throw error;
}
return torrent;
}
router.get('/', async function(req, res, next){
try{
let username = req.query.username || req.user.username;
let where = {added_by: username};
if(username !== req.user.username) where.isPrivate = false;
res.json({results: await Torrent.findAll({
where:{added_by: req.query.username || req.user.username},
where,
limit: req.query.limit,
offset: req.query.offset,
order: [
@@ -26,14 +42,6 @@ router.post("/", async function(req, res, next){
}
});
router.post("/:hashString", async function(req, res, next){
try{
res.json(await Torrent.migrate(req.params.hashString, req.user.username))
}catch(error){
next(error);
}
});
router.get('/server', async function(req, res, next){
try{
res.json(await Torrent.trClient.sessionStats())
@@ -44,7 +52,7 @@ router.get('/server', async function(req, res, next){
router.get("/:hashString", async function(req, res, next){
try{
let torrent = await Torrent.findByPk(req.params.hashString);
let torrent = authTorrent(await Torrent.findByPk(req.params.hashString), req);
if('latest' in req.query){
torrent = await torrent.getTorrentData();
}
@@ -56,7 +64,7 @@ router.get("/:hashString", async function(req, res, next){
router.delete("/:hashString", async function(req, res, next){
try{
let torrent = await Torrent.findByPk(req.params.hashString);
let torrent = authTorrent(await Torrent.findByPk(req.params.hashString), req);
res.json({result: torrent, activity: await torrent.destroy()});
}catch(error){
@@ -66,7 +74,7 @@ router.delete("/:hashString", async function(req, res, next){
router.post("/:hashString/stop", async function(req, res, next){
try{
let torrent = await Torrent.findByPk(req.params.hashString);
let torrent = authTorrent(await Torrent.findByPk(req.params.hashString), req);
res.json({result: torrent, activity: await torrent.stop()});
}catch(error){
@@ -76,7 +84,7 @@ router.post("/:hashString/stop", async function(req, res, next){
router.post("/:hashString/start", async function(req, res, next){
try{
let torrent = await Torrent.findByPk(req.params.hashString);
let torrent = authTorrent(await Torrent.findByPk(req.params.hashString), req);
res.json({result: torrent, activity: await torrent.start()});
}catch(error){
@@ -84,6 +92,30 @@ router.post("/:hashString/start", async function(req, res, next){
}
});
// Manually (re)run organization for a finished torrent.
router.post("/:hashString/organize", async function(req, res, next){
try{
let torrent = authTorrent(await Torrent.findByPk(req.params.hashString), req);
if(!torrent){ let e = new Error('TorrentNotFound'); e.status = 404; throw e; }
res.json(await organize.fileTorrent(torrent));
}catch(error){
next(error);
}
});
// Correct a wrong match: re-file an already-organized torrent under a chosen TMDB id.
router.post("/:hashString/organize/match", async function(req, res, next){
try{
let torrent = authTorrent(await Torrent.findByPk(req.params.hashString), req);
if(!torrent){ let e = new Error('TorrentNotFound'); e.status = 404; throw e; }
res.json(await organize.refileWithMatch(torrent, req.body.tmdbId, req.body.mediaType));
}catch(error){
next(error);
}
});
module.exports = router;