Remote_Cmd / server.js
sayarukshan's picture
Upload 2 files
0267589 verified
const express = require("express");
const { exec } = require("child_process");
const os = require("os");
const path = require("path");
const multer = require("multer");
const fs = require("fs");
const axios = require("axios");
const app = express();
app.use(express.json());
app.use(express.static(path.join(__dirname)));
const MAX_MEM = 90;
const TIMEOUT = 60000;
const BLOCKED_COMMANDS = [
"ollama", "docker build", "docker run", "python train",
"cloudflared tunnel", "cloudflared tunnel --url",
"cloudflared --url", "pip install torch", "yes", ":(){ :|:& }:"
];
let commandHistory = [];
// ===== MEMORY CHECK =====
function getMemoryUsage() {
const total = os.totalmem();
const free = os.freemem();
return Math.round(((total - free) / total) * 100);
}
// ===== HOME PAGE =====
app.get("/", (req, res) => {
res.sendFile(path.join(__dirname, "index.html"));
});
// ===== COMMAND EXECUTION =====
app.post("/run", (req, res) => {
const cmd = req.body?.cmd || req.body?.command;
if (!cmd) return res.json({ error: "command not provided" });
console.log(`[RECEIVED]: ${cmd}`);
if (cmd.trim().toLowerCase() === "log") {
const historyText = commandHistory.length > 0
? commandHistory.map((item, i) => `${i + 1}. [${item.time}] ${item.command}`).join(" | ")
: "History is empty.";
return res.json({ output: historyText.replace(/\n/g, " "), error: "" });
}
if (cmd.trim().toLowerCase() === "clear") {
commandHistory = [];
return res.json({ output: "History cleared.", error: "" });
}
commandHistory.push({ time: new Date().toLocaleTimeString(), command: cmd });
for (const blocked of BLOCKED_COMMANDS) {
if (cmd.includes(blocked)) {
return res.json({ error: "❌ Extremely heavy task blocked." });
}
}
let finalCmd = cmd;
if (cmd.startsWith("apt") && cmd.includes("install") && !cmd.includes("-y")) {
finalCmd += " -y";
}
const memUsage = getMemoryUsage();
if (memUsage > MAX_MEM) console.log(`⚠ High memory usage: ${memUsage}%`);
exec(`timeout ${TIMEOUT / 1000} ${finalCmd}`, { maxBuffer: 5 * 1024 * 1024 }, (error, stdout, stderr) => {
const cleanOutput = (stdout || "").replace(/\n/g, " ").trim();
const cleanError = (stderr || "").replace(/\n/g, " ").trim();
if (error && !stdout && !stderr) {
return res.json({ error: error.message.replace(/\n/g, " ") });
}
res.json({ output: cleanOutput, error: cleanError });
});
});
// ===== UPLOAD TO /app (ROOT) =====
// temp upload
const upload = multer({ dest: "temp/" });
app.post("/upload", upload.single("file"), (req, res) => {
if (!req.file) {
return res.json({ error: "No file uploaded" });
}
const targetPath = path.join(__dirname, req.file.originalname);
fs.rename(req.file.path, targetPath, (err) => {
if (err) {
return res.json({ error: "Upload failed: " + err.message });
}
res.json({ output: `✅ File saved in /app as ${req.file.originalname}` });
});
});
// ===== DOWNLOAD FROM /app =====
app.get("/download", (req, res) => {
const filename = req.query.file;
if (!filename) {
return res.status(400).send("File name required");
}
const filePath = path.join(__dirname, filename);
if (!fs.existsSync(filePath)) {
return res.status(404).send("❌ File not found in /app");
}
res.download(filePath, filename, (err) => {
if (err) {
res.status(500).send("Download failed");
}
});
});
// ===== START SERVER =====
app.listen(7860, () => {
console.log("Server running on port 7860");
});
// ===== AUTO LOG =====
const HF_URL = "http://localhost:7860/run";
setInterval(async () => {
try {
const res = await axios.post(HF_URL, { cmd: "log" });
console.log("🔥 Auto log:", res.data.output || res.data);
} catch (err) {
console.error("⚠ Auto log error:", err.message);
}
}, 120 * 60 * 1000);