fd5ef14999
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>
140 lines
5.7 KiB
JavaScript
140 lines
5.7 KiB
JavaScript
'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(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.end(mainjs);
|
|
});
|
|
|
|
const proxyTarget = {
|
|
// target: "https://wtfismyip.com",
|
|
// host: "wtfismyip.com",
|
|
target: 'https://piratebay.party',
|
|
host: 'piratebay.party',
|
|
// target: 'http://172.16.0.1',
|
|
// target: 'http://piratebayo3klnzokct3wt5yyxb2vpebbuyjl7m623iaxmqhsd52coid.onion',
|
|
// host: 'piratebayo3klnzokct3wt5yyxb2vpebbuyjl7m623iaxmqhsd52coid.onion'
|
|
// target: 'https://thepiratebay.org',
|
|
// host: 'thepiratebay.org',
|
|
// target: 'https://www2.thepiratebay3.to',
|
|
// host: 'www2.thepiratebay3.to'
|
|
}
|
|
|
|
function generateRegexForDomain(domain) {
|
|
// Escape special characters in the domain name
|
|
const escapedDomain = domain.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
|
|
// Construct a regular expression pattern to match the domain with optional http(s):// prefix
|
|
const regexPattern = new RegExp(`(?:https?:\\/\\/)?${escapedDomain}`, 'ig');
|
|
|
|
return regexPattern;
|
|
}
|
|
|
|
router.all("/*", proxy({
|
|
target: proxyTarget.target,
|
|
agent: proxyTarget.target.startsWith('https') ? https.globalAgent : http.globalAgent,
|
|
secure: true,
|
|
autoRewrite: true,
|
|
changeOrigin: true,
|
|
followRedirects: true,
|
|
headers: {
|
|
host: proxyTarget.host,
|
|
'Accept-Encoding': 'gzip',
|
|
},
|
|
selfHandleResponse: true, // so that the onProxyRes takes care of sending the response
|
|
onProxyRes: function(proxyRes, req, res){
|
|
|
|
if(proxyRes.statusCode === 403 && proxyRes.headers['content-type'] &&
|
|
proxyRes.headers['content-type'].match('html')
|
|
){
|
|
console.log('403')
|
|
var url = (req.protocol + '://' + req.get('host') + req.originalUrl);
|
|
proxyRes.headers['location'] = url.replace(/\??ckattempt\=\d+/, '');
|
|
proxyRes.statusCode = 307;
|
|
|
|
return res.end()
|
|
}
|
|
|
|
for(let key of Object.keys(proxyRes.headers)){
|
|
if(['content-encoding'].includes(key)) continue;
|
|
// res.set(key, proxyRes.headers[key].toString().replace('http://', 'https://'))
|
|
}
|
|
|
|
let body = Buffer.alloc(0);
|
|
proxyRes.on('error', function(e){
|
|
console.error('ERROR!', e)
|
|
});
|
|
|
|
proxyRes.on('data', function(data){
|
|
body = Buffer.concat([body, data]);
|
|
});
|
|
|
|
proxyRes.on('end', function(){
|
|
// console.log("proxyRes.headers['content-encoding']", proxyRes.headers['content-encoding']);
|
|
body = proxyRes.headers['content-encoding'] === 'gzip' ? zlib.gunzipSync(body).toString('utf8') : body;
|
|
body = proxyRes.headers['content-encoding'] === 'br' ? zlib.brotliDecompressSync(body).toString('utf8') : body;
|
|
if(proxyRes.statusCode === 200 &&
|
|
proxyRes.headers['content-type'] &&
|
|
proxyRes.headers['content-type'].match('html')
|
|
){
|
|
body = body.toString().replace(/<\s*script[^]*?script>/igm, '');
|
|
body = body.replace(generateRegexForDomain(proxyTarget.host), '');
|
|
body = body.replace(/<\s*iframe[^]*?iframe>/igm, '');
|
|
body = body.replace("</html>", '');
|
|
body = body+inject+"</html>";
|
|
}
|
|
res.status(proxyRes.statusCode).end(body);
|
|
});
|
|
|
|
}
|
|
}));
|
|
|
|
module.exports = router; |