#!/usr/bin/env python3 """ HFOS - HuggingFace Operating System for Minecraft (v2.1) Fixed iframe proxy routing, silenced backend logs, robust subprocess, and Repair tools. """ import os import re import sys import json import time import hmac import hashlib import base64 import secrets import shutil import threading import subprocess from collections import deque try: import psutil import httpx from flask import Flask, request, jsonify, Response from flask_cors import CORS except ImportError: subprocess.check_call([sys.executable, "-m", "pip", "install", "flask", "flask-cors", "psutil", "httpx"]) import psutil import httpx from flask import Flask, request, jsonify, Response from flask_cors import CORS # ----------------------------------------------------------------------------- # OS Configuration # ----------------------------------------------------------------------------- BASE_DIR = os.path.abspath(os.environ.get("SERVER_DIR", "/data")) PLUGINS_DIR = os.path.join(BASE_DIR, "plugins") JARS_DIR = os.path.join(BASE_DIR, "jars") CONFIG_PATH = os.path.join(BASE_DIR, "hfos_config.json") SECRET_PATH = os.path.join(BASE_DIR, ".hfos_secret") for d in (BASE_DIR, PLUGINS_DIR, JARS_DIR): os.makedirs(d, exist_ok=True) DEFAULT_JVM = ( "-XX:+UseG1GC -XX:+ParallelRefProcEnabled -XX:MaxGCPauseMillis=200 " "-XX:+UnlockExperimentalVMOptions -XX:+DisableExplicitGC -XX:+AlwaysPreTouch " "-XX:G1NewSizePercent=30 -XX:G1MaxNewSizePercent=40 -XX:G1HeapRegionSize=8M " "-XX:G1ReservePercent=20 -XX:G1MixedGCCountTarget=4 -XX:InitiatingHeapOccupancyPercent=15 " "-XX:G1MixedGCLiveThresholdPercent=90 -XX:SurvivorRatio=32 -XX:+PerfDisableSharedMem " "-XX:MaxTenuringThreshold=1 -Dusing.aikars.flags=https://mcflags.emc.gs " "-Dterminal.jline=false -Dterminal.ansi=true -Dfile.encoding=UTF-8" ) cfg_lock = threading.Lock() def load_config() -> dict: c = { "provider": "purpur", "version": "latest", "jar": "", "memory": "6G", "auto_start": True, "jvm": DEFAULT_JVM, } with cfg_lock: if os.path.exists(CONFIG_PATH): try: c.update(json.load(open(CONFIG_PATH, "r", encoding="utf-8"))) except Exception: pass return c def save_config(c: dict): with cfg_lock: try: json.dump(c, open(CONFIG_PATH, "w", encoding="utf-8"), indent=2) except Exception: pass # ----------------------------------------------------------------------------- # Security & Auth Engine # ----------------------------------------------------------------------------- def get_secret() -> str: if not os.path.exists(SECRET_PATH): open(SECRET_PATH, "w").write(secrets.token_hex(32)) return open(SECRET_PATH, "r").read().strip() def get_admin_pass() -> str: return os.environ.get("PASS", "").strip() or "admin" def gen_token() -> str: payload = f"{secrets.token_hex(8)}:{int(time.time()) + 86400}" sig = hmac.new(get_secret().encode(), payload.encode(), hashlib.sha256).digest() return f"{base64.urlsafe_b64encode(payload.encode()).decode().rstrip('=')}.{base64.urlsafe_b64encode(sig).decode().rstrip('=')}" def verify_token(t: str) -> bool: if not t or "." not in t: return False try: p_b64, s_b64 = t.split(".") p_b64 += "=" * (-len(p_b64) % 4); s_b64 += "=" * (-len(s_b64) % 4) payload = base64.urlsafe_b64decode(p_b64).decode() if time.time() > int(payload.split(":")[1]): return False expected = hmac.new(get_secret().encode(), payload.encode(), hashlib.sha256).digest() return hmac.compare_digest(base64.urlsafe_b64decode(s_b64), expected) except Exception: return False def check_auth(): auth = request.headers.get("Authorization", "").replace("Bearer ", "") if not verify_token(auth): return jsonify({"error": "Unauthorized"}), 401 def safe_path(p: str) -> str: rp = os.path.abspath(os.path.join(BASE_DIR, (p or "").lstrip("/"))) if not rp.startswith(BASE_DIR): raise PermissionError("Path traversal blocked") return rp # ----------------------------------------------------------------------------- # Core Server Engine # ----------------------------------------------------------------------------- class ServerEngine: def __init__(self): self.proc = None self.lock = threading.Lock() self.lines = deque(maxlen=2000) self.after_count = 0 self.start_time = 0 self.players = set() self.active_version = "Unknown" def log(self, msg: str): with self.lock: self.lines.append(msg) self.after_count += 1 # Deliberately NOT using print(msg) here to prevent HuggingFace backend log flooding. def download_jar(self, provider: str, version: str) -> str: self.log(f"[HFOS] Fetching {provider} version {version}...") headers = {"User-Agent": "HFOS/2.1"} if version == "latest": if provider == "purpur": r = httpx.get("https://api.purpurmc.org/v2/purpur", headers=headers, timeout=15) version = r.json()["versions"][-1] elif provider == "paper": r = httpx.get("https://api.papermc.io/v2/projects/paper", headers=headers, timeout=15) version = r.json()["versions"][-1] jar_name = f"{provider}-{version}.jar" jar_path = os.path.join(JARS_DIR, jar_name) if os.path.exists(jar_path): self.log(f"[HFOS] Jar {jar_name} already exists. Skipping download.") return jar_name self.log(f"[HFOS] Downloading {jar_name} (This may take a moment)...") if provider == "purpur": url = f"https://api.purpurmc.org/v2/purpur/{version}/latest/download" else: r = httpx.get(f"https://api.papermc.io/v2/projects/paper/versions/{version}", headers=headers).json() build = r["builds"][-1] r2 = httpx.get(f"https://api.papermc.io/v2/projects/paper/versions/{version}/builds/{build}", headers=headers).json() dl_name = r2["downloads"]["application"]["name"] url = f"https://api.papermc.io/v2/projects/paper/versions/{version}/builds/{build}/downloads/{dl_name}" with httpx.stream("GET", url, headers=headers, follow_redirects=True) as r: r.raise_for_status() with open(jar_path, "wb") as f: for chunk in r.iter_bytes(8192): f.write(chunk) self.log(f"[HFOS] Successfully downloaded {jar_name}.") return jar_name def preflight_check(self): c = load_config() if not c.get("jar") or not os.path.exists(os.path.join(JARS_DIR, c.get("jar", ""))): self.log("[HFOS] No valid Jar found. Auto-provisioning started...") try: jar = self.download_jar(c["provider"], c["version"]) c["jar"] = jar save_config(c) except Exception as e: self.log(f"[HFOS Error] Auto-provisioning failed: {e}") return False with open(os.path.join(BASE_DIR, "eula.txt"), "w") as f: f.write("eula=true\n") sp = os.path.join(BASE_DIR, "server.properties") if not os.path.exists(sp): with open(sp, "w") as f: f.write("server-port=25565\nonline-mode=false\nmotd=Hosted on HFOS\nmax-players=50\n") return True def _reader(self): # text=True in Popen removes the need to decode and avoids buffer warnings for line in iter(self.proc.stdout.readline, ""): if not line: break clean_line = line.rstrip() self.log(clean_line) low = clean_line.lower() v_match = re.search(r"starting minecraft server version\s+([\d.]+)", low) if v_match: self.active_version = v_match.group(1) p_match = re.search(r"\s(\S+)\s+(joined|left) the game", low) if p_match: if p_match.group(2) == "joined": self.players.add(p_match.group(1)) else: self.players.discard(p_match.group(1)) def start(self): if self.proc and self.proc.poll() is None: return "Running" if not self.preflight_check(): return "Failed Preflight" c = load_config() jar_path = os.path.join(JARS_DIR, c["jar"]) # Uses standard Java 25 installed natively from the Dockerfile cmd = ["java", f"-Xmx{c['memory']}", f"-Xms{c['memory']}"] + c["jvm"].split() + ["-jar", jar_path, "--nogui"] self.log(f"[HFOS] Launching Engine: {' '.join(cmd)}") self.players.clear() self.start_time = time.time() # Using text=True prevents the runtime buffer warnings self.proc = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, cwd=BASE_DIR, text=True, bufsize=1) threading.Thread(target=self._reader, daemon=True).start() return "Started" def stop(self): if not self.proc or self.proc.poll() is not None: return self.log("[HFOS] Sending gracefully stop...") try: self.proc.stdin.write("stop\n"); self.proc.stdin.flush() self.proc.wait(15) except Exception: self.proc.kill() self.players.clear() def send(self, cmd: str): if self.proc and self.proc.poll() is None: self.proc.stdin.write(cmd.strip() + "\n"); self.proc.stdin.flush() self.log(f"> {cmd}") engine = ServerEngine() def autostart_worker(): time.sleep(2) if load_config().get("auto_start", True): engine.start() threading.Thread(target=autostart_worker, daemon=True).start() # ----------------------------------------------------------------------------- # Web Application (Flask + API) # ----------------------------------------------------------------------------- app = Flask(__name__) CORS(app) app.config["MAX_CONTENT_LENGTH"] = 2 * 1024 * 1024 * 1024 @app.route("/") def index(): return Response(UI_HTML, mimetype="text/html") @app.post("/api/auth") def auth(): provided_pass = request.form.get("pass", "") if hmac.compare_digest(provided_pass, get_admin_pass()): return jsonify({"token": gen_token()}) return jsonify({"error": "Invalid password"}), 401 @app.before_request def check_requests(): if request.path.startswith("/api/") and request.path != "/api/auth": return check_auth() @app.get("/api/status") def status(): running = engine.proc is not None and engine.proc.poll() is None mem = psutil.virtual_memory() c = load_config() return jsonify({ "running": running, "uptime": int(time.time() - engine.start_time) if running else 0, "players": list(engine.players), "version": engine.active_version if running else c.get("version"), "cpu": psutil.cpu_percent(), "ram_used": mem.used, "ram_total": mem.total, "jar": c.get("jar") }) @app.post("/api/power") def power(): act = request.form.get("action") if act == "start": engine.start() elif act == "stop": threading.Thread(target=engine.stop).start() elif act == "kill": if engine.proc: engine.proc.kill() return jsonify({"ok": True}) @app.get("/api/console") def console(): after = int(request.args.get("after", 0)) with engine.lock: lines = list(engine.lines)[max(0, after - engine.after_count + len(engine.lines)):] idx = engine.after_count return jsonify({"lines": lines, "after": idx}) @app.post("/api/console") def console_send(): engine.send(request.form.get("cmd", "")) return jsonify({"ok": True}) # System Repair Engine (Fixes corrupted library downloads) @app.post("/api/system/repair") def system_repair(): if engine.proc and engine.proc.poll() is None: return jsonify({"error": "Server must be stopped before repairing."}), 400 deleted_items = [] # Delete cache and libraries to force fresh re-download for target in ["cache", "libraries", "versions"]: p = os.path.join(BASE_DIR, target) if os.path.exists(p): shutil.rmtree(p) deleted_items.append(target) engine.log(f"[HFOS System] Repaired environment by clearing: {', '.join(deleted_items)}") return jsonify({"ok": True, "msg": f"Cleared: {', '.join(deleted_items)}"}) # File System API @app.get("/api/fs/list") def fs_list(): p = safe_path(request.args.get("path", "")) if not os.path.isdir(p): return jsonify([]) items = [] for f in os.listdir(p): fp = os.path.join(p, f) is_dir = os.path.isdir(fp) items.append({ "name": f, "is_dir": is_dir, "size": 0 if is_dir else os.path.getsize(fp), "date": os.path.getmtime(fp) }) return jsonify(sorted(items, key=lambda x: (not x["is_dir"], x["name"].lower()))) @app.post("/api/fs/read") def fs_read(): p = safe_path(request.form.get("path", "")) try: return jsonify({"content": open(p, "r", encoding="utf-8").read()}) except Exception as e: return jsonify({"error": str(e)}), 400 @app.post("/api/fs/write") def fs_write(): p = safe_path(request.form.get("path", "")) with open(p, "w", encoding="utf-8") as f: f.write(request.form.get("content", "")) return jsonify({"ok": True}) @app.post("/api/fs/delete") def fs_delete(): p = safe_path(request.form.get("path", "")) if os.path.isdir(p): shutil.rmtree(p) else: os.remove(p) return jsonify({"ok": True}) @app.post("/api/fs/upload") def fs_upload(): p = safe_path(request.form.get("path", "")) file = request.files.get("file") if file: file.save(os.path.join(p, file.filename)) return jsonify({"ok": True}) # Config & Store APIs @app.get("/api/config") def get_config(): return jsonify(load_config()) @app.post("/api/config") def set_config(): c = load_config() for k in c.keys(): if k in request.form: c[k] = request.form[k] save_config(c) return jsonify({"ok": True}) @app.post("/api/plugins/install_url") def plugins_install_url(): url = request.form.get("url", "").strip() if not url: return jsonify({"error": "Empty URL provided."}), 400 try: if url.endswith(".jar"): fname = url.split("/")[-1] dl_url = url elif "modrinth.com/" in url: match = re.search(r'modrinth\.com/(?:plugin|project)/([^/?#]+)', url) if not match: return jsonify({"error": "Invalid Modrinth URL format."}), 400 slug = match.group(1) versions = httpx.get(f"https://api.modrinth.com/v2/project/{slug}/version", headers={"User-Agent":"HFOS/2.1"}).json() if not versions: return jsonify({"error": "No files found for this Modrinth project."}), 404 file_info = versions[0]["files"][0] dl_url = file_info["url"] fname = file_info["filename"] else: return jsonify({"error": "Unsupported URL format."}), 400 engine.log(f"[HFOS] Fetching plugin from: {dl_url}") with httpx.stream("GET", dl_url, follow_redirects=True, headers={"User-Agent":"HFOS/2.1"}) as r: r.raise_for_status() with open(os.path.join(PLUGINS_DIR, fname), "wb") as f: for chunk in r.iter_bytes(8192): f.write(chunk) engine.log(f"[HFOS] Installed plugin: {fname}") return jsonify({"ok": True, "file": fname}) except Exception as e: return jsonify({"error": str(e)}), 500 # ----------------------------------------------------------------------------- # OS Frontend GUI (Mobile Responsive + Fixed Network Routing) # ----------------------------------------------------------------------------- UI_HTML = """ HFOS - Mobile Native Controller
🚀 HFOS

HFOS Secure Login

Enter your environment password.

""" if __name__ == "__main__": port = int(os.environ.get("PORT", 7860)) app.run(host="0.0.0.0", port=port, threaded=True)