Download server.js from evidxzone/love: direct link, hf CLI and curl.
- Browser
- Download file 61.6 kB
-
https://huggingface.co/spaces/evidxzone/love/resolve/main/server.js
- Command line
-
hf download hf://spaces/evidxzone/love/server.js
-
curl -L -o server.js https://huggingface.co/spaces/evidxzone/love/resolve/main/server.js
61.6 kB
/**
* ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
* iq4u8 SERVER β Multi-User VPS Dashboard (INSTANCE 2)
* π Security Hardened by: Sherlock π΅οΈ
* π
Date: February 2026
* π‘οΈ Fixes: JWT Auth, Env Secrets, Command Injection,
* CSP Headers, Terminal Jail, Non-Root Container
* β οΈ INSTANCE 2: Separate DB (vps2), separate JWT secret
* ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
*/
require('dotenv').config();
const express = require('express');
const cors = require('cors');
const http = require('http');
const bcrypt = require('bcryptjs');
const multer = require('multer');
const unzipper = require('unzipper');
const WebSocket = require('ws');
const path = require('path');
const fs = require('fs');
const os = require('os');
const crypto = require('crypto');
const { execSync, execFileSync, spawn } = require('child_process');
const mongoose = require('mongoose');
const jwt = require('jsonwebtoken');
const PORT = process.env.PORT || 7860;
// ββ SECRETS (env vars with hardcoded fallbacks for HF Space) ββ
const MONGO_URI = process.env.MONGO_URI || 'mongodb+srv://vps_db_user:lNewpKefIaYU2glK@cluster0.7txstb5.mongodb.net/vps2?retryWrites=true&w=majority&appName=Cluster0';
const JWT_SECRET = process.env.JWT_SECRET || 'iq4u8_server2_jwt_secret_2026_fixed_key';
const OWNER_USERNAME = process.env.OWNER_USERNAME || 'iq4u8';
const OWNER_PASSWORD = process.env.OWNER_PASSWORD || 'Evid@1212';
const OWNER = { username: OWNER_USERNAME, password: OWNER_PASSWORD };
// ββ PERSISTENT STORAGE ββ
const DATA_DIR = '/data';
const BACKUP_DIR = '/app/backup';
const USERS_DIR = path.join(DATA_DIR, 'Users');
// ββ PLANS ββ
const PLANS = {
free: { name: 'Free', price: 40, storage: 500 * 1024 * 1024, ram: 280, cpu: 0.5 },
pro: { name: 'Pro', price: 70, storage: 1000 * 1024 * 1024, ram: 560, cpu: 1 },
ultra: { name: 'Ultra', price: 150, storage: 2000 * 1024 * 1024, ram: 1120, cpu: 2 }
};
const OWNER_LIMITS = { storage: Infinity, ram: 0, cpu: 0 };
// Ensure directories
[DATA_DIR, USERS_DIR, BACKUP_DIR].forEach(d => { if (!fs.existsSync(d)) fs.mkdirSync(d, { recursive: true }); });
// ββ MONGODB SCHEMAS ββ
const userSchema = new mongoose.Schema({
username: { type: String, required: true, unique: true },
usernameLower: { type: String, required: true, unique: true, index: true },
password: { type: String, required: true },
email: { type: String, default: '' },
role: { type: String, default: 'user' },
plan: { type: String, default: 'free' },
status: { type: String, default: 'pending' },
lastIP: { type: String, default: '' },
lastLogin: { type: Number, default: 0 },
trialExpires: { type: Date, default: null },
createdAt: { type: String, default: () => new Date().toISOString() },
referralCode: { type: String, unique: true, sparse: true },
referredBy: { type: String, default: '' },
referralPoints: { type: Number, default: 0 },
referralCredited: { type: Boolean, default: false },
referralMaxPlan: { type: String, default: 'free' }
});
const configSchema = new mongoose.Schema({
key: { type: String, unique: true, required: true },
value: { type: mongoose.Schema.Types.Mixed }
});
const alertSchema = new mongoose.Schema({
message: String, type: { type: String, default: 'warning' },
createdAt: { type: String, default: () => new Date().toISOString() }
});
const User = mongoose.model('User', userSchema);
const Config = mongoose.model('Config', configSchema);
const Alert = mongoose.model('Alert', alertSchema);
// ββ MONGODB CONNECT ββ
let dbReady = false;
function connectMongo() {
mongoose.connect(MONGO_URI, { serverSelectionTimeoutMS: 10000, connectTimeoutMS: 10000 })
.then(async () => {
dbReady = true; console.log('β
MongoDB connected');
// Clean up stale indexes from old schema (googleId, email unique, etc.)
try {
const col = mongoose.connection.collection('users');
const indexes = await col.indexes();
const staleKeys = ['googleId_1', 'email_1', 'picture_1', 'needsSetup_1'];
for (const idx of indexes) {
if (staleKeys.includes(idx.name)) {
await col.dropIndex(idx.name);
console.log('π§Ή Dropped stale index:', idx.name);
}
}
} catch (e) { console.log('Index cleanup skipped:', e.message); }
})
.catch(e => { console.error('β MongoDB failed:', e.message); console.log('π Retrying in 10s...'); setTimeout(connectMongo, 10000); });
}
connectMongo();
mongoose.connection.on('disconnected', () => { dbReady = false; console.log('β οΈ MongoDB disconnected'); });
mongoose.connection.on('reconnected', () => { dbReady = true; console.log('β
MongoDB reconnected'); });
// ββ BACKUP (directory structure only) ββ
function doBackup() {
try {
const bud = path.join(BACKUP_DIR, 'Users');
if (!fs.existsSync(bud)) fs.mkdirSync(bud, { recursive: true });
if (fs.existsSync(USERS_DIR)) {
for (const d of fs.readdirSync(USERS_DIR)) { const t = path.join(bud, d); if (!fs.existsSync(t)) fs.mkdirSync(t, { recursive: true }); }
}
} catch (e) { }
}
setInterval(doBackup, 5 * 60 * 1000);
setTimeout(doBackup, 10000);
// ββ TOKEN & AUTH (JWT-based) ββ
const TOKEN_TTL = '24h';
function mkToken(u) {
return jwt.sign(
{ username: u.username, role: u.role, plan: u.plan || 'free', status: u.status || 'approved' },
JWT_SECRET,
{ expiresIn: TOKEN_TTL }
);
}
function getUser(t) {
if (!t) return null;
try {
const decoded = jwt.verify(t, JWT_SECRET);
return { username: decoded.username, role: decoded.role, plan: decoded.plan, status: decoded.status };
} catch (e) { return null; }
}
function auth(req, res, next) {
const u = getUser(req.headers['x-auth-token'] || req.query.token);
if (u) { req.user = u; return next(); }
res.status(401).json({ error: 'Auth required' });
}
// Rate limiting
const rateLimits = new Map();
function rateLimit(ip, limit = 10, windowMs = 60000) {
const now = Date.now();
const entry = rateLimits.get(ip) || { count: 0, reset: now + windowMs };
if (now > entry.reset) { entry.count = 0; entry.reset = now + windowMs; }
entry.count++;
rateLimits.set(ip, entry);
return entry.count > limit;
}
// Prevent rate-limit Maps from growing unbounded (memory leak)
setInterval(() => {
const now = Date.now();
for (const [ip, entry] of rateLimits) { if (now > entry.reset + 60000) rateLimits.delete(ip); }
for (const [ip, entry] of globalRl) { if (now > entry.r + 60000) globalRl.delete(ip); }
}, 5 * 60 * 1000);
// ββ TERMINAL SESSIONS (declared early β used by cleanPendingUsers & route handlers) ββ
const activeSessions = new Map();
async function getUserPlanAsync(username) {
const u = await User.findOne({ usernameLower: username.toLowerCase() });
return (u && u.plan) ? u.plan : 'free';
}
function getLimits(u) {
if (u.role === 'owner') return OWNER_LIMITS;
return PLANS[u.plan || 'free'] || PLANS.free;
}
function getUserRoot(u) { return u.role === 'owner' ? path.join(USERS_DIR, u.username.replace(/[^a-zA-Z0-9_-]/g, '')) : path.join(USERS_DIR, u.username.replace(/[^a-zA-Z0-9_-]/g, '')); }
function safePath(r, p) { const x = path.resolve(r, p || '.'); return x.startsWith(r) ? x : null; }
function folderSize(dir) { try { const out = execFileSync('du', ['-sb', dir], { encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'] }).trim(); return parseInt(out.split('\t')[0]) || 0; } catch (e) { return 0; } }
function sanitize(str) { return String(str || '').replace(/[<>&"']/g, c => ({ '<': '<', '>': '>', '&': '&', '"': '"', "'": ''' }[c])); }
// ββ OWNER INIT ββ
async function ensureOwner() {
const existing = await User.findOne({ usernameLower: OWNER.username.toLowerCase() });
if (!existing) {
await User.create({ username: OWNER.username, usernameLower: OWNER.username.toLowerCase(), password: bcrypt.hashSync(OWNER.password, 10), role: 'owner', plan: 'ultra', status: 'approved' });
console.log('π Owner account created');
}
const ownerDir = path.join(USERS_DIR, OWNER.username);
if (!fs.existsSync(ownerDir)) fs.mkdirSync(ownerDir, { recursive: true });
const count = await User.countDocuments();
console.log(`π Data: ${DATA_DIR} | π₯ Users: ${count}`);
}
mongoose.connection.once('open', () => ensureOwner());
// ββ 6-HOUR TTL: Auto-delete unapproved users & expired trial users ββ
async function cleanPendingUsers() {
try {
const sixHours = 6 * 60 * 60 * 1000;
const cutoff = new Date(Date.now() - sixHours).toISOString();
// Clean old pending users
const pending = await User.find({ status: 'pending', createdAt: { $lt: cutoff } });
for (const u of pending) {
const userDir = path.join(USERS_DIR, u.username.replace(/[^a-zA-Z0-9_-]/g, ''));
if (fs.existsSync(userDir)) try { fs.rmSync(userDir, { recursive: true, force: true }); } catch (e) { }
const session = activeSessions.get(u.username);
if (session) { try { session.shell.kill(); } catch (e) { } try { session.ws.close(); } catch (e) { } activeSessions.delete(u.username); }
await User.deleteOne({ _id: u._id });
console.log(`ποΈ Auto-deleted pending user: ${u.username}`);
}
// Auto-expire trial users whose trial period has ended
const expiredTrials = await User.find({ status: 'trial', trialExpires: { $lt: new Date() } });
for (const u of expiredTrials) {
u.status = 'pending';
await u.save();
console.log(`β° Trial expired for user: ${u.username}`);
}
if (pending.length) console.log(`π§Ή Cleanup: removed ${pending.length} expired pending user(s)`);
if (expiredTrials.length) console.log(`β° Trial expired: ${expiredTrials.length} user(s) moved to pending`);
} catch (e) { console.error('β Auto-delete cron error:', e.message); }
}
setInterval(cleanPendingUsers, 30 * 60 * 1000);
setTimeout(cleanPendingUsers, 30000);
// ββ ENFORCEMENT SCRIPT (terminal jail β hardened) ββ
// == ENFORCEMENT SCRIPT (terminal jail -- hardened) ==
function writeEnforceScript(username, plan) {
const lim = PLANS[plan] || PLANS.free;
const limitBytes = lim.storage;
const limitMB = Math.round(limitBytes / 1024 / 1024);
const userDir = path.join(USERS_DIR, username.replace(/[^a-zA-Z0-9_-]/g, ''));
const lines = [
'#!/bin/bash',
'_SL=' + limitBytes,
'_SM=' + limitMB,
'_RAM=' + lim.ram,
'_CPU=' + lim.cpu,
'_PLAN="' + plan + '"',
'_HOMEDIR="' + userDir + '"',
'',
'# HARDENED PATH: /usr/bin for basic commands, dangerous ones blocked below',
'export PATH="' + userDir + '/.local/bin:/usr/local/bin:/usr/bin:/bin"',
'',
'# Block dangerous commands via functions',
'wget() { echo "Restricted: wget"; return 1; }',
'curl() { echo "Restricted: curl"; return 1; }',
'apt() { echo "Restricted: apt"; return 1; }',
'apt-get() { echo "Restricted: apt-get"; return 1; }',
'scp() { echo "Restricted: scp"; return 1; }',
'rsync() { echo "Restricted: rsync"; return 1; }',
'dd() { echo "Restricted: dd"; return 1; }',
'nc() { echo "Restricted: nc"; return 1; }',
'ncat() { echo "Restricted: ncat"; return 1; }',
'ssh() { echo "Restricted: ssh"; return 1; }',
'socat() { echo "Restricted: socat"; return 1; }',
'docker() { echo "Restricted: docker"; return 1; }',
'mount() { echo "Restricted: mount"; return 1; }',
'umount() { echo "Restricted: umount"; return 1; }',
'chroot() { echo "Restricted: chroot"; return 1; }',
'su() { echo "Restricted: su"; return 1; }',
'sudo() { echo "Restricted: sudo"; return 1; }',
'passwd() { echo "Restricted: passwd"; return 1; }',
'useradd() { echo "Restricted: useradd"; return 1; }',
'userdel() { echo "Restricted: userdel"; return 1; }',
'pkill() { echo "Restricted: pkill"; return 1; }',
'killall() { echo "Restricted: killall"; return 1; }',
'shutdown() { echo "Restricted: shutdown"; return 1; }',
'reboot() { echo "Restricted: reboot"; return 1; }',
'crontab() { echo "Restricted: crontab"; return 1; }',
'export -f wget curl apt apt-get scp rsync dd nc ncat ssh socat docker mount umount chroot su sudo passwd useradd userdel pkill killall shutdown reboot crontab 2>/dev/null',
'',
"clear() { printf '\\033[2J\\033[H'; }",
'export -f clear 2>/dev/null',
'',
'# Virtualized system commands showing plan limits',
"_udf() { local u=$(du -sb \"$HOME\" 2>/dev/null | awk 'NR==1{print $1}'); u=${u:-0}; local uM=$((u/1024/1024)) av=$(($_SM-uM)); [ \"$av\" -lt 0 ]&&av=0; local pc=$((uM*100/$_SM)); [ \"$pc\" -gt 100 ]&&pc=100; echo \"Filesystem Size Used Avail Use% Mounted on\"; echo \"user-storage ${_SM}M ${uM}M ${av}M ${pc}% $HOME\"; }",
'_ufree() { echo " total used free"; echo "Mem: ${_RAM}Mi --- ---"; echo "Plan: ${_PLAN} | RAM: ${_RAM}MB"; }',
'_ulscpu() { echo "CPU(s): ${_CPU} | Plan: ${_PLAN}"; }',
"alias df='_udf'; alias free='_ufree'; alias lscpu='_ulscpu'",
"alias lsblk='echo Restricted'; alias nproc='echo ${_CPU}'",
"alias htop='echo Restricted'; alias top='echo Restricted'",
'_rcat() { case "$1" in /proc/meminfo|/proc/cpuinfo|/sys/*|/etc/shadow|/etc/passwd) echo "Restricted";; *) /usr/bin/cat "$@";; esac; }',
"alias cat='_rcat'",
'',
'# Directory jail',
'_jail() {',
' local cur=$(pwd 2>/dev/null)',
' case "$cur" in',
' $_HOMEDIR|$_HOMEDIR/*) ;;',
' *) cd "$_HOMEDIR" 2>/dev/null; echo -e "\\e[33mRestricted to home directory\\e[0m" ;;',
' esac',
'}',
'_enforce() {',
' _jail',
" local u=$(du -sb \"$HOME\" 2>/dev/null | awk 'NR==1{print $1}'); u=${u:-0}",
' if [ "$u" -gt "$_SL" ] 2>/dev/null; then',
' local m=$((u/1024/1024))',
' echo -e "\\n\\e[1;31mSTORAGE ${m}MB/${_SM}MB EXCEEDED!\\e[0m"',
' echo -e "\\e[33m Delete files. Write commands blocked.\\e[0m\\n"',
' fi',
'}',
"export PROMPT_COMMAND='_enforce'",
'readonly PROMPT_COMMAND _SL _SM _RAM _CPU _HOMEDIR PATH 2>/dev/null',
];
const script = lines.join('\n');
const sp = '/tmp/.enforce_' + username.replace(/[^a-zA-Z0-9_-]/g, '') + '.sh';
try { fs.writeFileSync(sp, script, { mode: 0o444 }); } catch (e) { }
return sp;
}
// ββ EXPRESS APP ββ
const app = express();
const server = http.createServer(app);
app.use(cors({
origin: ['https://iq4u8.shop', 'http://iq4u8.shop', 'https://www.iq4u8.shop', 'http://www.iq4u8.shop'],
credentials: true,
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'X-Auth-Token']
}));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.set('trust proxy', true);
// ββ URL CLEANING: Strip UTM params ββ
app.use((req, res, next) => {
const url = new URL(req.url, 'http://localhost');
const dirty = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid'];
let cleaned = false;
dirty.forEach(p => { if (url.searchParams.has(p)) { url.searchParams.delete(p); cleaned = true; } });
if (cleaned) return res.redirect(301, url.pathname + (url.search || ''));
next();
});
app.get('/', (req, res) => res.sendFile(path.join(__dirname, 'index.html')));
// π Security audit & hardening by Sherlock
console.log('π‘οΈ Security hardened by Sherlock');
// ββ LAYER 1: SERVER IDENTITY MASKING ββ
app.disable('x-powered-by');
app.use((req, res, next) => {
res.setHeader('Server', 'nginx/1.24.0');
res.removeHeader('X-Powered-By');
next();
});
// ββ LAYER 2: HF PATH & PROBE BLOCKING ββ
app.use((req, res, next) => {
const url = req.url.toLowerCase();
const blockedPaths = [
'/api/spaces', '/api/models', '/api/datasets', '/_next', '/gradio',
'/.git', '/.env', '/.dockerenv', '/spaces/', '/datasets/',
'/api/docker-', '/api/repos/', '/embed/', '/__internal',
'/settings', '/api/who', 'hf.space', 'huggingface'
];
if (blockedPaths.some(p => url.includes(p))) {
return res.status(404).send('Not Found');
}
next();
});
// ββ LAYER 3: STRIP HF-INJECTED HEADERS ββ
app.use((req, res, next) => {
const origWrite = res.writeHead;
res.writeHead = function (...args) {
const hfHeaders = ['x-space-id', 'x-repo-commit', 'x-hf-token', 'x-gradio-version',
'x-space-author', 'x-space-title', 'via', 'x-request-id', 'x-hf-cache',
'x-proxy-by', 'x-space-host', 'x-compute-type', 'x-hardware'];
hfHeaders.forEach(h => res.removeHeader(h));
return origWrite.apply(this, args);
};
next();
});
// ββ LAYER 8: ROBOTS & SCANNER BLOCKING ββ
app.get('/robots.txt', (req, res) => {
res.type('text/plain').send('User-agent: *\nDisallow: /\n');
});
app.use((req, res, next) => {
const url = req.url.toLowerCase();
const scanPaths = ['/wp-admin', '/wp-login', '/xmlrpc', '/wp-content', '/administrator',
'/phpmyadmin', '/pma', '/.well-known/security.txt', '/debug', '/trace',
'/server-status', '/server-info', '/_config', '/actuator', '/console'];
if (scanPaths.some(p => url.startsWith(p))) return res.status(404).send('Not Found');
next();
});
// ββ HEALTH CHECK (locked down β minimal info) ββ
app.get('/healthz', (req, res) => {
res.status(dbReady ? 200 : 503).json({ status: dbReady ? 'ok' : 'starting' });
});
// ββ AAPANEL REVERSE PROXY (no prefix β direct path interception) ββ
const AAPANEL_PORT = 8888;
const https = require('https');
function proxyToPanel(req, res) {
const reqPath = req.originalUrl || req.url;
const baseHeaders = { ...req.headers, host: `127.0.0.1:${AAPANEL_PORT}` };
// Try HTTP first, then HTTPS with self-signed cert
function tryProxy(useHttps) {
const mod = useHttps ? https : http;
const proxyOpts = {
hostname: '127.0.0.1',
port: AAPANEL_PORT,
path: reqPath,
method: req.method,
headers: baseHeaders,
rejectUnauthorized: false // accept self-signed certs
};
const proxyReq = mod.request(proxyOpts, (proxyRes) => {
res.writeHead(proxyRes.statusCode, proxyRes.headers);
proxyRes.pipe(res);
});
proxyReq.on('error', (e) => {
if (!useHttps && (e.code === 'ECONNRESET' || e.code === 'ECONNREFUSED' || e.code === 'HPE_INVALID_CONSTANT')) {
// HTTP failed, try HTTPS
tryProxy(true);
} else {
if (!res.headersSent) res.status(502).json({ error: 'aaPanel not running. Install via terminal: sudo bt' });
}
});
req.pipe(proxyReq);
}
tryProxy(false);
}
// Known aaPanel paths β intercept before VPS routes
const btPaths = ['/static', '/login', '/public', '/site', '/config',
'/ajax', '/system', '/task', '/crontab', '/firewall', '/soft',
'/database', '/ftp', '/monitoring', '/safe', '/logs', '/acme',
'/download', '/upload', '/control', '/plugin', '/ssl', '/btdebug'];
btPaths.forEach(p => app.use(p, proxyToPanel));
// Read security entrance dynamically
try {
const btEntry = fs.readFileSync('/www/server/panel/data/admin_path.pl', 'utf8').trim();
if (btEntry) { app.use('/' + btEntry, proxyToPanel); console.log('π§ aaPanel entry: /' + btEntry); }
} catch (e) { console.log('βΉοΈ aaPanel not installed β /panel proxy skipped'); }
// Also keep /panel as a redirect helper
app.get('/panel', (req, res) => {
try {
const entry = fs.readFileSync('/www/server/panel/data/admin_path.pl', 'utf8').trim();
if (entry) return res.redirect('/' + entry);
} catch (e) { }
res.status(503).json({ error: 'aaPanel not installed. Run install in terminal first.' });
});
// DB readiness check for API routes
app.use('/api', (req, res, next) => {
if (!dbReady) return res.status(503).json({ error: 'Database connecting... please wait and retry' });
next();
});
// ββ SECURITY & IPS ββ
let BANNED_IPS = new Set();
async function loadBanned() { try { const c = await Config.findOne({ key: 'bannedIPs' }); if (c && Array.isArray(c.value)) BANNED_IPS = new Set(c.value); } catch (e) { } }
async function saveBanned() { await Config.findOneAndUpdate({ key: 'bannedIPs' }, { key: 'bannedIPs', value: [...BANNED_IPS] }, { upsert: true }); }
mongoose.connection.once('open', () => loadBanned());
// ββ LAYER 4: HARDENED SECURITY HEADERS ββ
app.use((req, res, next) => {
res.setHeader('X-Content-Type-Options', 'nosniff');
res.setHeader('X-Frame-Options', 'DENY');
res.setHeader('X-XSS-Protection', '1; mode=block');
res.setHeader('Strict-Transport-Security', 'max-age=31536000; includeSubDomains; preload');
res.setHeader('Referrer-Policy', 'strict-origin-when-cross-origin');
res.setHeader('Permissions-Policy', 'camera=(), microphone=(), geolocation=(), display-capture=()');
res.setHeader('X-Permitted-Cross-Domain-Policies', 'none');
// Layer 5: CSP β no platform leaks, no Google/HF references
res.setHeader('Content-Security-Policy', "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://cdn.jsdelivr.net; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com https://cdn.jsdelivr.net; font-src 'self' https://fonts.gstatic.com; connect-src 'self' wss: https:; img-src 'self' data: https:; object-src 'none'; base-uri 'self'; frame-ancestors 'none';");
// Layer 6: Fingerprint response headers β mimic nginx
res.setHeader('X-DNS-Prefetch-Control', 'off');
res.setHeader('Cache-Control', 'private, no-transform');
res.setHeader('X-Download-Options', 'noopen');
next();
});
// Global IP Check & Rate Limit
const globalRl = new Map();
app.use((req, res, next) => {
const ip = req.ip || req.connection.remoteAddress;
if (BANNED_IPS.has(ip)) return res.status(403).send('Access Denied (Banned)');
// Suspicious patterns (SQLi, Path Traversal, etc)
const url = req.url.toLowerCase();
if (url.includes('..') || url.includes('/etc/passwd') || url.includes('select%20') || url.includes('union%20select')) {
console.log(`β οΈ Blocked suspicious request from ${ip}: ${req.url}`);
return res.status(403).send('Blocked');
}
// Global Rate Limit (100 req/min, Auto-ban at 500)
const now = Date.now();
const g = globalRl.get(ip) || { c: 0, r: now + 60000 };
if (now > g.r) { g.c = 0; g.r = now + 60000; }
g.c++;
globalRl.set(ip, g);
if (g.c > 500) {
BANNED_IPS.add(ip); saveBanned();
console.log(`π« Auto-banned IP ${ip} for flooding (${g.c} req/min)`);
return res.status(403).send('IP Banned for flooding');
}
if (g.c > 100 && !req.user) return res.status(429).json({ error: 'Too many requests' });
next();
});
// ββ AUTH ENDPOINTS ββ
function genRefCode(username) {
const chars = 'abcdefghijklmnopqrstuvwxyz0123456789';
let suffix = '';
for (let i = 0; i < 4; i++) suffix += chars[Math.floor(Math.random() * chars.length)];
return username.toLowerCase() + '_' + suffix;
}
app.post('/api/signup', async (req, res) => {
const ip = req.ip || req.connection.remoteAddress;
if (rateLimit(ip, 3, 3600000)) return res.status(429).json({ error: 'Limit exceeded (3/hr)' });
const { username, password, ref } = req.body;
if (!username || !password) return res.status(400).json({ error: 'Missing fields' });
if (password.length < 6) return res.status(400).json({ error: 'Password too weak (min 6 chars)' });
if (!/^[a-zA-Z0-9_-]{7,20}$/.test(username)) return res.status(400).json({ error: 'Username: 7-20 chars, alphanumeric only' });
if (['admin', 'root', 'owner', 'system'].includes(username.toLowerCase())) return res.status(400).json({ error: 'Reserved username' });
try {
const existing = await User.findOne({ usernameLower: username.toLowerCase() });
if (existing) return res.status(400).json({ error: 'Username taken' });
// Validate referral code if provided
let referredBy = '';
if (ref) {
const referrer = await User.findOne({ referralCode: ref });
if (referrer) referredBy = ref;
}
// Generate unique referral code
let referralCode = genRefCode(username);
while (await User.findOne({ referralCode })) { referralCode = genRefCode(username); }
const newUser = await User.create({
username, usernameLower: username.toLowerCase(),
password: bcrypt.hashSync(password, 10),
role: 'user', plan: 'free', status: 'trial', lastIP: ip,
trialExpires: new Date(Date.now() + 3 * 24 * 60 * 60 * 1000),
referralCode, referredBy
});
// Create user directory immediately (trial users get full access)
fs.mkdirSync(path.join(USERS_DIR, username.replace(/[^a-zA-Z0-9_-]/g, '')), { recursive: true });
const token = mkToken(newUser);
res.json({ success: true, newUser: true, token, user: { username: newUser.username, role: newUser.role, plan: newUser.plan, status: newUser.status } });
} catch (e) { console.error('β Signup error:', e.message); res.status(500).json({ error: 'Signup failed. Please try again.' }); }
});
app.post('/api/login', async (req, res) => {
const ip = req.ip || req.connection.remoteAddress;
const { username, password } = req.body;
if (!(username && username.toLowerCase() === OWNER.username.toLowerCase()) && rateLimit(ip, 20, 300000)) return res.status(429).json({ error: 'Too many attempts (20/5min)' });
try {
const u = await User.findOne({ usernameLower: (username || '').toLowerCase() });
if (!u || !bcrypt.compareSync(password, u.password)) return res.status(401).json({ error: 'Invalid credentials' });
// if (u.status === 'pending') return res.json({ success: true, pending: true, message: 'Your account is pending approval. Please wait for owner to approve.' });
if (u.plan === 'banned') return res.status(403).json({ error: 'Account banned' });
u.lastIP = ip; u.lastLogin = Date.now(); await u.save();
fs.mkdirSync(path.join(USERS_DIR, u.username), { recursive: true });
const token = mkToken(u);
res.json({ success: true, token, user: { username: u.username, role: u.role, plan: u.plan, status: u.status } });
} catch (e) { console.error('β Login error:', e.message); res.status(500).json({ error: 'Login failed. Please try again.' }); }
});
app.get('/api/me', async (req, res) => {
const u = getUser(req.headers['x-auth-token'] || req.query.token);
if (!u) return res.json({ loggedIn: false });
// Fetch fresh data from DB to ensure status/plan are up-to-date
try {
const fresh = await User.findOne({ usernameLower: u.username.toLowerCase() });
if (fresh) {
// Auto-expire trial if past expiry date
if (fresh.status === 'trial' && fresh.trialExpires && new Date() > fresh.trialExpires) {
fresh.status = 'pending';
await fresh.save();
}
return res.json({ loggedIn: true, user: { username: fresh.username, role: fresh.role, plan: fresh.plan, status: fresh.status, trialExpires: fresh.trialExpires } });
}
} catch (e) { }
// Fallback to token data if DB fails (unlikely)
res.json({ loggedIn: true, user: u });
});
// ββ DELETE ACCOUNT ββ
app.delete('/api/account', auth, async (req, res) => {
try {
if (req.user.role === 'owner') return res.status(403).json({ error: 'Owner account cannot be deleted' });
await User.deleteOne({ usernameLower: req.user.username.toLowerCase() });
const userDir = path.join(USERS_DIR, req.user.username);
if (fs.existsSync(userDir)) fs.rmSync(userDir, { recursive: true, force: true });
// Remove token
// JWT tokens are stateless β user will be logged out when token expires
res.json({ success: true, message: 'Account deleted' });
} catch (e) { console.error('β Delete account error:', e.message); res.status(500).json({ error: 'Failed to delete account' }); }
});
// ββ ALERT ββ
app.get('/api/alert', async (req, res) => { try { const a = await Alert.findOne().sort({ _id: -1 }); res.json({ alert: a || null }); } catch (e) { res.json({ alert: null }); } });
app.post('/api/alert', auth, async (req, res) => {
if (req.user.role !== 'owner') return res.status(403).json({ error: 'Owner only' });
try {
if (req.body.message) { await Alert.deleteMany({}); await Alert.create({ message: sanitize(req.body.message), type: req.body.type || 'warning' }); }
else await Alert.deleteMany({});
res.json({ success: true });
} catch (e) { res.status(500).json({ error: 'Failed' }); }
});
// ββ SUPPORT CONFIG ββ
app.get('/api/support', auth, async (req, res) => {
try { const c = await Config.findOne({ key: 'support' }); res.json(c ? c.value : { whatsapp: '', telegram: '' }); } catch (e) { res.json({ whatsapp: '', telegram: '' }); }
});
app.put('/api/support', auth, async (req, res) => {
if (req.user.role !== 'owner') return res.status(403).json({ error: 'Owner only' });
try {
const c = await Config.findOne({ key: 'support' }) || { value: {} };
if (req.body.whatsapp !== undefined) c.value.whatsapp = req.body.whatsapp;
if (req.body.telegram !== undefined) c.value.telegram = req.body.telegram;
await Config.findOneAndUpdate({ key: 'support' }, { key: 'support', value: c.value }, { upsert: true });
res.json({ success: true });
} catch (e) { res.status(500).json({ error: 'Failed' }); }
});
// ββ PLANS ββ
app.get('/api/plans', (req, res) => {
const plans = Object.entries(PLANS).map(([k, v]) => ({
id: k, name: v.name, price: v.price,
storage: Math.round(v.storage / 1024 / 1024) + 'MB',
ram: v.ram + 'MB', cpu: v.cpu + ' Core'
}));
res.json({ plans });
});
// ββ RESOURCES ββ
app.get('/api/resources', auth, async (req, res) => {
const lim = getLimits(req.user);
const plan = req.user.role === 'owner' ? 'ultra' : (req.user.plan || 'free');
const userDir = getUserRoot(req.user);
const used = folderSize(userDir);
res.json({
storage: { used, limit: lim.storage, pct: lim.storage === Infinity ? 0 : Math.round((used / lim.storage) * 100) },
ram: { limit: lim.ram }, cpu: { limit: lim.cpu }, role: req.user.role, plan
});
});
// ββ SYSTEM STATS ββ
const statsHistory = [];
function collectStats() {
let totalMem = os.totalmem(), usedMem = totalMem - os.freemem();
try { const mx = fs.readFileSync('/sys/fs/cgroup/memory.max', 'utf8').trim(); if (mx !== 'max') totalMem = parseInt(mx); usedMem = parseInt(fs.readFileSync('/sys/fs/cgroup/memory.current', 'utf8').trim()); }
catch (e) { try { const l = parseInt(fs.readFileSync('/sys/fs/cgroup/memory/memory.limit_in_bytes', 'utf8').trim()); if (l < 1e15) totalMem = l; usedMem = parseInt(fs.readFileSync('/sys/fs/cgroup/memory/memory.usage_in_bytes', 'utf8').trim()); } catch (e2) { } }
const la = os.loadavg()[0]; const cpuPct = Math.min(100, Math.round((la / (os.cpus().length || 1)) * 100));
const ramPct = Math.round((usedMem / totalMem) * 100);
let diskPct = 0;
try { const p = execFileSync('sh', ['-c', "df / | tail -1 | awk '{print $5}'"], { encoding: 'utf8' }).trim(); diskPct = parseInt(p) || 0; } catch (e) { }
statsHistory.push({ cpu: cpuPct, ram: ramPct, disk: diskPct, ts: Date.now() });
if (statsHistory.length > 60) statsHistory.shift();
return { cpuPct, ramPct, diskPct, usedMem, totalMem };
}
setInterval(collectStats, 30000);
setTimeout(collectStats, 2000);
app.get('/api/system', auth, async (req, res) => {
try {
const s = collectStats();
const plan = req.user.role === 'owner' ? 'ultra' : (req.user.plan || 'free');
const up = os.uptime(), d = Math.floor(up / 86400), h = Math.floor((up % 86400) / 3600), m = Math.floor((up % 3600) / 60);
const upStr = (d ? d + 'd ' : '') + (h ? h + 'h ' : '') + m + 'm';
if (req.user.role === 'owner') {
// Owner sees REAL server data
let dU = 'β', dT = 'β', dP = 'β';
try { const p = execFileSync('sh', ['-c', "df -h / | tail -1 | awk '{print $2,$3,$5}'"], { encoding: 'utf8' }).trim().split(' '); dT = p[0]; dU = p[1]; dP = p[2]; } catch (e) { }
const totalUsers = await User.countDocuments();
const cpu = os.cpus();
res.json({
status: 'Active', plan,
uptime: upStr,
ramUsed: (s.usedMem / 1048576).toFixed(0) + 'MB',
ramTotal: (s.totalMem / 1048576).toFixed(0) + 'MB',
ramPct: s.ramPct,
cpuCores: cpu.length, cpuPct: s.cpuPct,
diskUsed: dU, diskTotal: dT, diskPct: parseInt(dP) || 0,
loadAvg: os.loadavg().map(l => l.toFixed(2)).join('/'),
nodeVer: process.version, totalUsers,
platform: os.platform() + ' ' + os.arch(),
role: req.user.role
});
} else {
// Regular users see PLAN limits only
const pl = PLANS[plan] || PLANS.free;
const userDir = getUserRoot(req.user);
const usedBytes = folderSize(userDir);
const usedMB = (usedBytes / (1024 * 1024)).toFixed(1);
const limitMB = (pl.storage / (1024 * 1024)).toFixed(0);
const diskPct = Math.round((usedBytes / pl.storage) * 100);
res.json({
status: 'Active', plan,
uptime: upStr,
ramUsed: 'β', ramTotal: pl.ram + 'MB', ramPct: 0,
cpuCores: pl.cpu, cpuPct: 0,
diskUsed: usedMB + 'MB', diskTotal: limitMB + 'MB', diskPct,
loadAvg: 'β',
platform: 'β',
role: req.user.role
});
}
} catch (e) { res.status(500).json({ error: 'Failed' }); }
});
app.get('/api/stats/history', auth, (req, res) => {
if (req.user.role !== 'owner') return res.json({ history: [] });
res.json({ history: statsHistory });
});
// ββ FILES ββ
app.get('/api/files', auth, (req, res) => {
const root = getUserRoot(req.user), fp = safePath(root, req.query.path || '');
if (!fp) return res.status(403).json({ error: 'Denied' });
try {
if (!fs.existsSync(fp)) return res.json({ files: [], currentPath: req.query.path || '' });
const files = fs.readdirSync(fp).filter(n => !n.startsWith('.')).map(name => {
try { const s = fs.statSync(path.join(fp, name)); return { name, isDir: s.isDirectory(), size: s.size, modified: s.mtime.toISOString() }; }
catch (e) { return { name, isDir: false, size: 0, modified: '' }; }
}).sort((a, b) => (b.isDir - a.isDir) || a.name.localeCompare(b.name));
res.json({ files, currentPath: req.query.path || '' });
} catch (e) { res.status(500).json({ error: 'Failed' }); }
});
const upload = multer({ dest: '/tmp/uploads/', limits: { fileSize: 2000 * 1024 * 1024 } });
app.post('/api/files/upload', auth, upload.array('files', 50), async (req, res) => {
const root = getUserRoot(req.user), dest = safePath(root, req.body.path || '');
if (!dest) return res.status(403).json({ error: 'Denied' });
if (req.user.role !== 'owner') {
const lim = getLimits(req.user);
const used = folderSize(getUserRoot(req.user));
const incoming = (req.files || []).reduce((s, f) => s + f.size, 0);
if (used + incoming > lim.storage) {
for (const f of (req.files || [])) { try { fs.unlinkSync(f.path); } catch (e) { } }
return res.status(400).json({ error: 'Storage limit exceeded' });
}
}
if (!fs.existsSync(dest)) fs.mkdirSync(dest, { recursive: true });
const results = [];
for (const file of (req.files || [])) {
const target = path.join(dest, file.originalname);
try {
fs.renameSync(file.path, target);
results.push({ name: file.originalname, status: 'uploaded' });
} catch (e) { results.push({ name: file.originalname, status: 'failed' }); }
}
res.json({ success: true, results });
});
// ββ Manual Unzip ββ
app.post('/api/files/unzip', auth, async (req, res) => {
const root = getUserRoot(req.user);
const { filePath } = req.body;
if (!filePath) return res.status(400).json({ error: 'Missing path' });
const src = safePath(root, filePath);
if (!src || !src.endsWith('.zip')) return res.status(400).json({ error: 'Not a ZIP file' });
if (!fs.existsSync(src)) return res.status(404).json({ error: 'File not found' });
const exDir = src.replace('.zip', '');
try {
fs.mkdirSync(exDir, { recursive: true });
await fs.createReadStream(src).pipe(unzipper.Extract({ path: exDir })).promise();
if (req.user.role !== 'owner') {
const used = folderSize(getUserRoot(req.user));
if (used > getLimits(req.user).storage) {
fs.rmSync(exDir, { recursive: true, force: true });
return res.status(400).json({ error: 'Storage limit exceeded after extraction' });
}
}
res.json({ success: true, message: 'Extracted to ' + path.basename(exDir) });
} catch (e) { res.status(500).json({ error: 'Extraction failed' }); }
});
// ββ Manual Zip ββ
app.post('/api/files/zip', auth, (req, res) => {
const root = getUserRoot(req.user);
const { filePath } = req.body;
if (!filePath) return res.status(400).json({ error: 'Missing path' });
const src = safePath(root, filePath);
if (!src) return res.status(403).json({ error: 'Denied' });
if (!fs.existsSync(src)) return res.status(404).json({ error: 'File not found' });
const zipDest = src + '.zip';
try {
const srcBase = path.basename(src);
const srcDir = path.dirname(src);
// Fix: Prepend ./ to prevent command injection from filenames starting with -
execFileSync('zip', ['-r', zipDest, './' + srcBase], { cwd: srcDir, encoding: 'utf8' });
res.json({ success: true, message: 'Zipped to ' + path.basename(zipDest) });
} catch (e) { res.status(500).json({ error: 'Zip failed: ' + e.message }); }
});
app.post('/api/files/mkdir', auth, (req, res) => {
const root = getUserRoot(req.user), fp = safePath(root, req.body.path || '');
if (!fp) return res.status(403).json({ error: 'Denied' });
try { fs.mkdirSync(fp, { recursive: true }); res.json({ success: true }); } catch (e) { res.status(500).json({ error: 'Failed' }); }
});
app.delete('/api/files', auth, (req, res) => {
const root = getUserRoot(req.user), fp = safePath(root, req.query.path || '');
if (!fp || fp === root) return res.status(403).json({ error: 'Denied' });
try { const s = fs.statSync(fp); s.isDirectory() ? fs.rmSync(fp, { recursive: true, force: true }) : fs.unlinkSync(fp); res.json({ success: true }); }
catch (e) { res.status(500).json({ error: 'Failed' }); }
});
app.get('/api/files/download', auth, (req, res) => {
const root = getUserRoot(req.user), fp = safePath(root, req.query.path || '');
if (!fp) return res.status(403).json({ error: 'Denied' });
try { if (!fs.existsSync(fp) || fs.statSync(fp).isDirectory()) return res.status(404).json({ error: 'Not found' }); res.download(fp); }
catch (e) { res.status(500).json({ error: 'Failed' }); }
});
// ββ NEW: Rename ββ
app.put('/api/files/rename', auth, (req, res) => {
const root = getUserRoot(req.user);
const { oldPath, newName } = req.body;
if (!oldPath || !newName) return res.status(400).json({ error: 'Missing params' });
if (/[\/\\<>:"|?*]/.test(newName)) return res.status(400).json({ error: 'Invalid filename' });
const src = safePath(root, oldPath);
if (!src || src === root) return res.status(403).json({ error: 'Denied' });
const dest = path.join(path.dirname(src), newName);
if (!dest.startsWith(root)) return res.status(403).json({ error: 'Denied' });
try { fs.renameSync(src, dest); res.json({ success: true }); } catch (e) { res.status(500).json({ error: 'Rename failed' }); }
});
// ββ NEW: Bulk Delete ββ
app.post('/api/files/bulk-delete', auth, (req, res) => {
const root = getUserRoot(req.user);
const { paths } = req.body;
if (!Array.isArray(paths) || !paths.length) return res.status(400).json({ error: 'No paths' });
let deleted = 0;
for (const p of paths) {
const fp = safePath(root, p);
if (!fp || fp === root) continue;
try { const s = fs.statSync(fp); s.isDirectory() ? fs.rmSync(fp, { recursive: true, force: true }) : fs.unlinkSync(fp); deleted++; } catch (e) { }
}
res.json({ success: true, deleted });
});
// ββ NEW: Move ββ
app.post('/api/files/move', auth, (req, res) => {
const root = getUserRoot(req.user);
const { sources, destination } = req.body;
if (!Array.isArray(sources) || !destination) return res.status(400).json({ error: 'Missing params' });
const destDir = safePath(root, destination);
if (!destDir) return res.status(403).json({ error: 'Denied' });
if (!fs.existsSync(destDir)) fs.mkdirSync(destDir, { recursive: true });
let moved = 0;
for (const s of sources) {
const src = safePath(root, s);
if (!src || src === root) continue;
const target = path.join(destDir, path.basename(src));
if (!target.startsWith(root)) continue;
try { fs.renameSync(src, target); moved++; } catch (e) { }
}
res.json({ success: true, moved });
});
// ββ NEW: Copy ββ
app.post('/api/files/copy', auth, (req, res) => {
const root = getUserRoot(req.user);
const { sources, destination } = req.body;
if (!Array.isArray(sources) || !destination) return res.status(400).json({ error: 'Missing params' });
const destDir = safePath(root, destination);
if (!destDir) return res.status(403).json({ error: 'Denied' });
if (!fs.existsSync(destDir)) fs.mkdirSync(destDir, { recursive: true });
let copied = 0;
for (const s of sources) {
const src = safePath(root, s);
if (!src || src === root) continue;
const target = path.join(destDir, path.basename(src));
if (!target.startsWith(root)) continue;
try { fs.cpSync(src, target, { recursive: true }); copied++; } catch (e) { }
}
if (req.user.role !== 'owner') {
const used = folderSize(getUserRoot(req.user));
if (used > getLimits(req.user).storage) return res.status(400).json({ error: 'Storage limit exceeded after copy' });
}
res.json({ success: true, copied });
});
// ββ NEW: Factory Reset ββ
app.post('/api/files/reset', auth, (req, res) => {
const root = getUserRoot(req.user);
try {
if (fs.existsSync(root)) {
const SYSTEM_FILES = ['users.json', 'alert.json', 'config.json', 'Users'];
const items = fs.readdirSync(root);
for (const item of items) {
if (SYSTEM_FILES.includes(item)) continue;
const fp = path.join(root, item);
try { fs.rmSync(fp, { recursive: true, force: true }); } catch (e) { }
}
}
// Kill terminal session
const session = activeSessions.get(req.user.username);
if (session) {
try { session.shell.kill(); } catch (e) { }
try { session.ws.close(); } catch (e) { }
activeSessions.delete(req.user.username);
}
res.json({ success: true, message: 'All files deleted. Terminal reset.' });
} catch (e) { res.status(500).json({ error: 'Reset failed' }); }
});
// ββ USER MANAGEMENT (Owner) ββ
app.get('/api/users', auth, async (req, res) => {
if (req.user.role !== 'owner') return res.status(403).json({ error: 'Owner only' });
const users = await User.find();
const userList = users.map(u => {
const userDir = path.join(USERS_DIR, u.username.replace(/[^a-zA-Z0-9_-]/g, ''));
const storage = fs.existsSync(userDir) ? folderSize(userDir) : 0;
const plan = u.plan || 'free';
const lim = u.role === 'owner' ? OWNER_LIMITS : (PLANS[plan] || PLANS.free);
return {
username: u.username, role: u.role, plan, status: u.status || 'approved',
createdAt: u.createdAt || 'Unknown', storage,
trialExpires: u.trialExpires || null,
lastIP: u.lastIP || 'β',
storageMB: Math.round(storage / 1024 / 1024),
storageLimit: u.role === 'owner' ? 'β' : Math.round(lim.storage / 1024 / 1024) + 'MB',
ramLimit: u.role === 'owner' ? 'β' : lim.ram + 'MB',
cpuLimit: u.role === 'owner' ? 'β' : lim.cpu + ' Core',
price: u.role === 'owner' ? 'β' : 'βΉ' + (PLANS[plan] || PLANS.free).price
};
});
res.json({ users: userList });
});
// ββ CLEAN DATABASE (Owner) ββ
app.post('/api/admin/clean-db', auth, async (req, res) => {
if (req.user.role !== 'owner') return res.status(403).json({ error: 'Owner only' });
try {
// Delete all non-owner users
const deleted = await User.deleteMany({ role: { $ne: 'owner' } });
// Clean user directories
if (fs.existsSync(USERS_DIR)) {
const dirs = fs.readdirSync(USERS_DIR);
for (const d of dirs) {
if (d === OWNER_USERNAME) continue;
const dirPath = path.join(USERS_DIR, d);
try { fs.rmSync(dirPath, { recursive: true, force: true }); } catch (e) { }
}
}
// Kill all terminal sessions except owner
for (const [username, session] of activeSessions) {
if (username === OWNER_USERNAME) continue;
try { session.shell.kill(); } catch (e) { }
try { session.ws.close(); } catch (e) { }
activeSessions.delete(username);
}
// Clear alerts, configs, banned IPs
await Alert.deleteMany({});
BANNED_IPS.clear();
await saveBanned();
res.json({ success: true, message: `Database cleaned. Deleted ${deleted.deletedCount} users.` });
} catch (e) { console.error('Clean DB error:', e.message); res.status(500).json({ error: 'Clean failed' }); }
});
// ββ IP MANAGEMENT (Owner) ββ
app.get('/api/ip/banned', auth, (req, res) => {
if (req.user.role !== 'owner') return res.status(403).json({ error: 'Owner only' });
res.json({ ips: [...BANNED_IPS] });
});
app.post('/api/ip/ban', auth, (req, res) => {
if (req.user.role !== 'owner') return res.status(403).json({ error: 'Owner only' });
const { ip } = req.body;
if (!ip) return res.status(400).json({ error: 'Missing IP' });
if (ip === '::1' || ip === '127.0.0.1' || ip === req.ip) return res.status(400).json({ error: 'Cannot ban yourself/localhost' });
BANNED_IPS.add(ip);
saveBanned();
res.json({ success: true, message: `Banned IP: ${ip}` });
});
app.post('/api/ip/unban', auth, (req, res) => {
if (req.user.role !== 'owner') return res.status(403).json({ error: 'Owner only' });
const { ip } = req.body;
BANNED_IPS.delete(ip);
saveBanned();
res.json({ success: true, message: `Unbanned IP: ${ip}` });
});
app.delete('/api/users/:username', auth, async (req, res) => {
if (req.user.role !== 'owner') return res.status(403).json({ error: 'Owner only' });
const target = req.params.username;
if (target === OWNER.username) return res.status(400).json({ error: 'Cannot delete owner' });
const u = await User.findOne({ username: target });
if (!u) return res.status(404).json({ error: 'User not found' });
await User.deleteOne({ _id: u._id });
const userDir = path.join(USERS_DIR, target.replace(/[^a-zA-Z0-9_-]/g, ''));
if (fs.existsSync(userDir)) try { fs.rmSync(userDir, { recursive: true, force: true }); } catch (e) { }
const session = activeSessions.get(target);
if (session) { try { session.shell.kill(); } catch (e) { } try { session.ws.close(); } catch (e) { } activeSessions.delete(target); }
// JWT tokens are stateless β no need to revoke individual tokens
res.json({ success: true, message: `"${target}" deleted` });
});
// ββ Approve User ββ
app.put('/api/users/:username/approve', auth, async (req, res) => {
if (req.user.role !== 'owner') return res.status(403).json({ error: 'Owner only' });
const u = await User.findOne({ username: req.params.username });
if (!u) return res.status(404).json({ error: 'Not found' });
u.status = 'approved'; await u.save();
// Create user directory on approval
const userDir = path.join(USERS_DIR, u.username.replace(/[^a-zA-Z0-9_-]/g, ''));
fs.mkdirSync(userDir, { recursive: true });
// Attempt referral credit
await creditReferral(u);
res.json({ success: true, message: `"${req.params.username}" approved` });
});
// ββ Reject User ββ
app.put('/api/users/:username/reject', auth, async (req, res) => {
if (req.user.role !== 'owner') return res.status(403).json({ error: 'Owner only' });
const target = req.params.username;
if (target === OWNER.username) return res.status(400).json({ error: 'Cannot reject owner' });
const u = await User.findOne({ username: target });
if (!u) return res.status(404).json({ error: 'Not found' });
await User.deleteOne({ _id: u._id });
const userDir = path.join(USERS_DIR, target.replace(/[^a-zA-Z0-9_-]/g, ''));
if (fs.existsSync(userDir)) try { fs.rmSync(userDir, { recursive: true, force: true }); } catch (e) { }
// JWT tokens are stateless β no need to revoke individual tokens
res.json({ success: true, message: `"${target}" rejected and deleted` });
});
app.put('/api/users/:username/password', auth, async (req, res) => {
if (req.user.role !== 'owner') return res.status(403).json({ error: 'Owner only' });
const { password } = req.body;
if (!password || password.length < 6) return res.status(400).json({ error: '6+ chars' });
const u = await User.findOne({ username: req.params.username });
if (!u) return res.status(404).json({ error: 'Not found' });
u.password = bcrypt.hashSync(password, 10); await u.save();
res.json({ success: true, message: `Password updated for "${req.params.username}"` });
});
app.put('/api/users/:username/plan', auth, async (req, res) => {
if (req.user.role !== 'owner') return res.status(403).json({ error: 'Owner only' });
const { plan } = req.body;
if (!PLANS[plan]) return res.status(400).json({ error: 'Invalid plan' });
const u = await User.findOne({ username: req.params.username });
if (!u) return res.status(404).json({ error: 'Not found' });
u.plan = plan; await u.save();
// Attempt referral credit on upgrade
await creditReferral(u);
res.json({ success: true, message: `Plan set to "${plan}" for "${req.params.username}"` });
});
// Original /api/system removed β duplicate handled above
// ββ REFERRAL SYSTEM ββ
app.get('/api/referral', auth, async (req, res) => {
try {
const u = await User.findOne({ usernameLower: req.user.username.toLowerCase() });
if (!u) return res.status(404).json({ error: 'User not found' });
// Ensure user has a referral code (backfill for existing users)
if (!u.referralCode) {
u.referralCode = genRefCode(u.username);
while (await User.findOne({ referralCode: u.referralCode, _id: { $ne: u._id } })) { u.referralCode = genRefCode(u.username); }
await u.save();
}
// Get referred friends
const friends = await User.find({ referredBy: u.referralCode }).select('username plan status createdAt referralCredited');
const joined = friends.filter(f => f.status === 'approved').length;
const pending = friends.filter(f => f.status === 'pending').length;
res.json({
referralCode: u.referralCode,
referralLink: 'https://iq4u8.shop/join?ref=' + u.referralCode,
points: u.referralPoints || 0,
totalFriends: joined,
pendingFriends: pending,
friends: friends.map(f => ({
username: f.username,
plan: f.plan,
status: f.status,
joinedAt: f.createdAt,
credited: f.referralCredited || false
}))
});
} catch (e) { res.status(500).json({ error: 'Failed to load referral data' }); }
});
async function creditReferral(u) {
if (!u.referredBy || u.status !== 'approved') return;
try {
const referrer = await User.findOne({ referralCode: u.referredBy });
if (!referrer) return;
// Security: Prevent self-referral via same IP (even if different account)
if (referrer.lastIP === u.lastIP) {
console.log(`β οΈ Referral blocked (Same IP): ${referrer.username} -> ${u.username}`);
return;
}
const tierValue = { free: 0, pro: 25, ultra: 100 };
const currentVal = tierValue[u.plan || 'free'] || 0;
const maxVal = tierValue[u.referralMaxPlan || 'free'] || 0;
if (currentVal > maxVal) {
const diff = currentVal - maxVal;
referrer.referralPoints = (referrer.referralPoints || 0) + diff;
await referrer.save();
u.referralMaxPlan = u.plan; // Update highest tier reached
u.referralCredited = true; // Mark legacy flag
await u.save();
console.log(`π Referral: +${diff}pts to ${referrer.username} for ${u.username} (${u.plan})`);
}
} catch (e) { console.error('Referral Logic Error:', e.message); }
}
// (AUTO-DELETE cron consolidated into cleanPendingUsers above β no duplicate needed)
app.get('/api/debug', auth, async (req, res) => {
if (req.user.role !== 'owner') return res.status(403).json({ error: 'Owner only' });
let ps = '', pty = '';
try { ps = execFileSync('ps', ['aux'], { encoding: 'utf8' }); } catch (e) { }
try { require('node-pty'); pty = 'OK'; } catch (e) { pty = 'FAIL: ' + e.message; }
const count = await User.countDocuments();
res.type('text/plain').send('PTY: ' + pty + '\nDATA_DIR: ' + DATA_DIR + '\nUsers: ' + count + '\nDB: MongoDB\n\n' + ps);
});
server.listen(PORT, '0.0.0.0', () => console.log('π Server on ' + PORT));
// ββ TERMINAL ββ
const wss = new WebSocket.Server({ noServer: true });
// activeSessions is declared at the top (after rate limiting) so it's available to cleanPendingUsers & route handlers
server.on('upgrade', async (req, socket, head) => {
const url = new URL(req.url, 'http://localhost');
if (url.pathname !== '/ws/terminal') { socket.destroy(); return; }
const tokenUser = getUser(url.searchParams.get('token'));
if (!tokenUser) { socket.destroy(); return; }
// Fetch fresh status from DB to allow approved users to connect immediately
let freshUser = tokenUser;
try {
const dbUser = await User.findOne({ usernameLower: tokenUser.username.toLowerCase() });
if (dbUser) freshUser = { username: dbUser.username, role: dbUser.role, plan: dbUser.plan, status: dbUser.status };
} catch (e) { }
if (freshUser.status === 'pending') { socket.destroy(); return; }
wss.handleUpgrade(req, socket, head, ws => { ws.user = freshUser; wss.emit('connection', ws, req); });
});
wss.on('connection', (ws) => {
const user = ws.user;
const userDir = getUserRoot(user);
const lim = getLimits(user);
if (!fs.existsSync(userDir)) fs.mkdirSync(userDir, { recursive: true });
console.log(`π₯οΈ Terminal: ${user.username} (${user.role}) β ${userDir}`);
let enforceScriptPath = null;
if (user.role !== 'owner') enforceScriptPath = writeEnforceScript(user.username, user.plan || 'free');
let shell;
const env = { HOME: userDir, USER: user.username, TERM: 'xterm-256color', PATH: process.env.PATH, LANG: 'en_US.UTF-8' };
try {
const pty = require('node-pty');
const shellArgs = (lim.ram > 0) ? ['-c', `ulimit -v ${lim.ram * 1024} 2>/dev/null; exec bash --norc -i`] : [];
shell = pty.spawn('bash', shellArgs, { name: 'xterm-256color', cols: 120, rows: 30, cwd: userDir, env });
activeSessions.set(user.username, { ws, shell, user, userDir });
setTimeout(() => {
shell.write(`export PS1='\\[\\e[1;32m\\]${user.username}\\[\\e[0m\\]@vps:\\[\\e[1;34m\\]\\w\\[\\e[0m\\]\\$ '\r`);
shell.write(`cd ${userDir}\r`);
if (user.role !== 'owner' && enforceScriptPath) shell.write(`source ${enforceScriptPath}\r`);
shell.write('clear\r');
}, 200);
shell.onData(d => { try { if (ws.readyState === 1) ws.send(d); } catch (e) { } });
ws.on('message', msg => { try { const p = JSON.parse(msg.toString()); if (p.type === 'input') shell.write(p.data); else if (p.type === 'resize') shell.resize(p.cols || 120, p.rows || 30); } catch (e) { shell.write(msg.toString()); } });
ws.on('close', () => { activeSessions.delete(user.username); try { shell.kill(); } catch (e) { } });
shell.onExit(() => { activeSessions.delete(user.username); try { ws.close(); } catch (e) { } });
} catch (e) {
console.log('β οΈ PTY fallback:', e.message);
shell = spawn('bash', ['-i'], { cwd: userDir, env, stdio: ['pipe', 'pipe', 'pipe'] });
activeSessions.set(user.username, { ws, shell, user, userDir });
shell.stdout.on('data', d => { try { if (ws.readyState === 1) ws.send(d.toString()); } catch (e) { } });
shell.stderr.on('data', d => { try { if (ws.readyState === 1) ws.send(d.toString()); } catch (e) { } });
ws.on('message', msg => { try { const p = JSON.parse(msg.toString()); if (p.type === 'input') shell.stdin.write(p.data); } catch (e) { shell.stdin.write(msg.toString()); } });
ws.on('close', () => { activeSessions.delete(user.username); try { shell.kill(); } catch (e) { } });
shell.on('exit', () => { activeSessions.delete(user.username); try { ws.close(); } catch (e) { } });
}
});
// Storage monitor
setInterval(() => {
for (const [username, session] of activeSessions.entries()) {
if (!session.user || session.user.role === 'owner') continue;
try {
const used = folderSize(session.userDir);
const lim = getLimits(session.user);
const limitMB = Math.round(lim.storage / 1024 / 1024);
const usedMB = Math.round(used / 1024 / 1024);
if (used > lim.storage * 1.5) {
try { if (session.ws.readyState === 1) session.ws.send('\r\n\x1b[1;31mβ οΈ STORAGE EXCEEDED! Terminal killed.\x1b[0m\r\n'); } catch (e) { }
setTimeout(() => { try { session.shell.kill(); } catch (e) { } try { session.ws.close(); } catch (e) { } activeSessions.delete(username); }, 2000);
} else if (used > lim.storage) {
try { if (session.ws.readyState === 1) session.ws.send('\r\n\x1b[33mβ οΈ Storage: ' + usedMB + 'MB / ' + limitMB + 'MB β Over limit!\x1b[0m\r\n'); } catch (e) { }
}
} catch (e) { }
}
}, 30000);
// ββ LAYER 7: CATCH-ALL β try aaPanel, then 404 ββ
app.use((req, res) => {
// Try proxying to aaPanel for unknown routes
const proxyOpts = {
hostname: '127.0.0.1',
port: AAPANEL_PORT,
path: req.originalUrl || req.url,
method: req.method,
headers: { ...req.headers, host: `127.0.0.1:${AAPANEL_PORT}` }
};
const proxyReq = http.request(proxyOpts, (proxyRes) => {
if (proxyRes.statusCode === 404) {
res.status(404).send('Not Found');
proxyRes.resume();
} else {
res.writeHead(proxyRes.statusCode, proxyRes.headers);
proxyRes.pipe(res);
}
});
proxyReq.on('error', () => {
res.status(404).send('Not Found');
});
req.pipe(proxyReq);
});
app.use((err, req, res, next) => {
console.error('Server error:', err.message);
res.status(500).send('Internal Server Error');
});
/**
* ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
* iq4u8 SERVER β Multi-User VPS Dashboard (INSTANCE 2)
* π Security Hardened by: Sherlock π΅οΈ
* π
Date: February 2026
* π‘οΈ Fixes: JWT Auth, Env Secrets, Command Injection,
* CSP Headers, Terminal Jail, Non-Root Container
* β οΈ INSTANCE 2: Separate DB (vps2), separate JWT secret
* ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
*/
require('dotenv').config();
const express = require('express');
const cors = require('cors');
const http = require('http');
const bcrypt = require('bcryptjs');
const multer = require('multer');
const unzipper = require('unzipper');
const WebSocket = require('ws');
const path = require('path');
const fs = require('fs');
const os = require('os');
const crypto = require('crypto');
const { execSync, execFileSync, spawn } = require('child_process');
const mongoose = require('mongoose');
const jwt = require('jsonwebtoken');
const PORT = process.env.PORT || 7860;
// ββ SECRETS (env vars with hardcoded fallbacks for HF Space) ββ
const MONGO_URI = process.env.MONGO_URI || 'mongodb+srv://vps_db_user:lNewpKefIaYU2glK@cluster0.7txstb5.mongodb.net/vps2?retryWrites=true&w=majority&appName=Cluster0';
const JWT_SECRET = process.env.JWT_SECRET || 'iq4u8_server2_jwt_secret_2026_fixed_key';
const OWNER_USERNAME = process.env.OWNER_USERNAME || 'iq4u8';
const OWNER_PASSWORD = process.env.OWNER_PASSWORD || 'Evid@1212';
const OWNER = { username: OWNER_USERNAME, password: OWNER_PASSWORD };
// ββ PERSISTENT STORAGE ββ
const DATA_DIR = '/data';
const BACKUP_DIR = '/app/backup';
const USERS_DIR = path.join(DATA_DIR, 'Users');
// ββ PLANS ββ
const PLANS = {
free: { name: 'Free', price: 40, storage: 500 * 1024 * 1024, ram: 280, cpu: 0.5 },
pro: { name: 'Pro', price: 70, storage: 1000 * 1024 * 1024, ram: 560, cpu: 1 },
ultra: { name: 'Ultra', price: 150, storage: 2000 * 1024 * 1024, ram: 1120, cpu: 2 }
};
const OWNER_LIMITS = { storage: Infinity, ram: 0, cpu: 0 };
// Ensure directories
[DATA_DIR, USERS_DIR, BACKUP_DIR].forEach(d => { if (!fs.existsSync(d)) fs.mkdirSync(d, { recursive: true }); });
// ββ MONGODB SCHEMAS ββ
const userSchema = new mongoose.Schema({
username: { type: String, required: true, unique: true },
usernameLower: { type: String, required: true, unique: true, index: true },
password: { type: String, required: true },
email: { type: String, default: '' },
role: { type: String, default: 'user' },
plan: { type: String, default: 'free' },
status: { type: String, default: 'pending' },
lastIP: { type: String, default: '' },
lastLogin: { type: Number, default: 0 },
trialExpires: { type: Date, default: null },
createdAt: { type: String, default: () => new Date().toISOString() },
referralCode: { type: String, unique: true, sparse: true },
referredBy: { type: String, default: '' },
referralPoints: { type: Number, default: 0 },
referralCredited: { type: Boolean, default: false },
referralMaxPlan: { type: String, default: 'free' }
});
const configSchema = new mongoose.Schema({
key: { type: String, unique: true, required: true },
value: { type: mongoose.Schema.Types.Mixed }
});
const alertSchema = new mongoose.Schema({
message: String, type: { type: String, default: 'warning' },
createdAt: { type: String, default: () => new Date().toISOString() }
});
const User = mongoose.model('User', userSchema);
const Config = mongoose.model('Config', configSchema);
const Alert = mongoose.model('Alert', alertSchema);
// ββ MONGODB CONNECT ββ
let dbReady = false;
function connectMongo() {
mongoose.connect(MONGO_URI, { serverSelectionTimeoutMS: 10000, connectTimeoutMS: 10000 })
.then(async () => {
dbReady = true; console.log('β
MongoDB connected');
// Clean up stale indexes from old schema (googleId, email unique, etc.)
try {
const col = mongoose.connection.collection('users');
const indexes = await col.indexes();
const staleKeys = ['googleId_1', 'email_1', 'picture_1', 'needsSetup_1'];
for (const idx of indexes) {
if (staleKeys.includes(idx.name)) {
await col.dropIndex(idx.name);
console.log('π§Ή Dropped stale index:', idx.name);
}
}