Files
tpbproxy/models/ldap/user.js
T
wmantly fd5ef14999 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>
2026-07-01 14:19:13 -04:00

185 lines
3.8 KiB
JavaScript

'use strict';
const {Client, Attribute} = require('ldapts');
const LRUCache = require('lru-native2');
const conf = require('>/conf').ldap;
var userLUR = new LRUCache({
// The maximum age (in milliseconds) of an item.
// The item will be removed if get() is called and the item is too old.
// Default: 0, meaning items will never expire.
maxAge: 60000,
});
const escapeFilterValue = function(value){
return String(value).replace(/[\0()*\\]/g, function(char){
return '\\' + char.charCodeAt(0).toString(16).padStart(2, '0');
});
}
const user_parse = function(data){
if(data[conf.userNameAttribute]){
data.username = data[conf.userNameAttribute];
data.userPassword = undefined;
data.userBacking = "LDAP";
}
return data;
}
var User = {}
User.backing = "LDAP";
User.list = async function(){
try{
const client = new Client({
url: conf.url,
});
await client.bind(conf.bindDN, conf.bindPassword);
const res = await client.search(conf.userBase, {
scope: 'sub',
filter: conf.userFilter,
attributes: ['*', 'createTimestamp', 'modifyTimestamp'],
});
await client.unbind();
return res.searchEntries.map(function(user){return user.uid});
}catch(error){
throw error;
}
};
User.listDetail = async function(){
try{
const client = new Client({
url: conf.url,
});
await client.bind(conf.bindDN, conf.bindPassword);
const res = await client.search(conf.userBase, {
scope: 'sub',
filter: conf.userFilter,
attributes: ['*', 'createTimestamp', 'modifyTimestamp'],
});
await client.unbind();
let users = [];
for(let user of res.searchEntries){
let obj = Object.create(this);
Object.assign(obj, user_parse(user));
users.push(obj);
}
return users;
}catch(error){
throw error;
}
};
User.get = async function(data, key){
try{
if(typeof data !== 'object'){
let uid = data;
data = {};
data.uid = uid;
}
data.searchKey = data.searchKey || key || conf.userNameAttribute;
data.searchValue = data.searchValue || data.uid;
let filter = `(&${conf.userFilter}(${escapeFilterValue(data.searchKey)}=${escapeFilterValue(data.searchValue)}))`;
if(userLUR.get(filter)) return userLUR.get(filter);
const client = new Client({
url: conf.url,
});
await client.bind(conf.bindDN, conf.bindPassword);
const res = await client.search(conf.userBase, {
scope: 'sub',
filter: filter,
attributes: ['*', 'createTimestamp', 'modifyTimestamp'],
});
await client.unbind();
if(res.searchEntries[0]){
let obj = Object.create(this);
Object.assign(obj, user_parse(res.searchEntries[0]));
userLUR.set(filter, obj);
return obj;
}else{
let error = new Error('UserNotFound');
error.name = 'UserNotFound';
error.message = `LDAP:${data.searchValue} does not exists`;
error.status = 404;
throw error;
}
}catch(error){
throw error;
}
};
User.exists = async function(data, key){
// Return true or false if the requested entry exists ignoring error's.
try{
await this.get(data, key);
return true
}catch(error){
return false;
}
};
User.login = async function(data){
try{
if(!data.password){
let error = new Error('LDAPLoginFailed');
error.name = 'LDAPLoginFailed';
error.message = 'Invalid Credentials, login failed.';
error.status = 401;
throw error;
}
let user = await this.get(data.uid || data[conf.userNameAttribute] || data.username);
const client = new Client({
url: conf.url,
});
await client.bind(user.dn, data.password);
await client.unbind();
return user;
}catch(error){
throw error;
}
};
module.exports = {User};
// (async function(){
// try{
// console.log(await User.list());
// console.log(await User.listDetail());
// console.log(await User.get('wmantly'))
// }catch(error){
// console.error(error)
// }
// })()