Buckets:

download
raw
14.5 kB
import asyncio
import json
import os
import pty
import random
import secrets
import select
import signal
import string
import subprocess
import termios
import struct
import fcntl
import shlex
import shutil
import threading
import time
from fastapi import FastAPI, WebSocket, WebSocketDisconnect, Request, Response, HTTPException
from fastapi.staticfiles import StaticFiles
from fastapi.responses import RedirectResponse
import uvicorn
app = FastAPI(title="Zen Terminal")
AUTH_CODE = f"{random.randint(1000, 9999)}-{''.join(random.choices(string.ascii_uppercase, k=4))}"
print(f"\n{'=' * 50}", flush=True)
print(f" *** 2FA CODE (in console/terminal eingeben): {AUTH_CODE} ***", flush=True)
print(f"{'=' * 50}\n", flush=True)
sessions: set[str] = set()
def check_auth(request: Request) -> bool:
token = request.cookies.get("session")
return token in sessions
LOG_DIR = os.environ.get("LOG_DIR", os.path.join(os.path.dirname(__file__), "..", "..", "logs"))
os.makedirs(LOG_DIR, exist_ok=True)
LOG_FILE = os.path.join(LOG_DIR, "terminal_connections.log")
RAMDISK = os.environ.get("RAMDISK", "")
if RAMDISK and os.path.exists(RAMDISK):
print(f" RAM disk active: {RAMDISK} ({LOG_DIR})", flush=True)
def _get_browser_info(request):
return {
"ua": request.headers.get("user-agent", "")[:120],
"lang": request.headers.get("accept-language", "")[:50],
"ref": request.headers.get("referer", "")[:80],
"sec_ch_ua": request.headers.get("sec-ch-ua", "")[:60],
"platform": request.headers.get("sec-ch-ua-platform", "")[:30],
"mobile": request.headers.get("sec-ch-ua-mobile", "")[:10],
}
def _log_connection(ts: str, event: str, ip: str, session_id: str, browser: str = ""):
line = f"[{ts}] {event} ip={ip} session={session_id}"
if browser:
line += f" browser={browser}"
line += "\n"
print(line.strip())
with open(LOG_FILE, "a") as f:
f.write(line)
@app.middleware("http")
async def auth_middleware(request: Request, call_next):
path = request.url.path
if path in ("/login.html", "/health", "/api/visitors", "/api/myip", "/api/whoami"):
if path == "/login.html":
client = request.client.host if request.client else "unknown"
cf = request.headers.get("cf-connecting-ip", "")
xff = request.headers.get("x-forwarded-for", "")
real = cf or xff.split(",")[0].strip() or client
ts = time.strftime("%Y-%m-%d %H:%M:%S")
browser = _get_browser_info(request)
browser_str = f"UA:{browser['ua']} LANG:{browser['lang']}"
_log_connection(ts, "VISIT", real, "-", browser_str)
return await call_next(request)
if path in ("/api/login",):
return await call_next(request)
for prefix in ("/api/tunnel",):
if path.startswith(prefix):
return await call_next(request)
if not check_auth(request):
return RedirectResponse(url="/login.html")
return await call_next(request)
@app.post("/api/login")
async def login(body: dict, response: Response, request: Request):
code = body.get("code", "").strip().upper()
client = request.client.host if request.client else "unknown"
cf = request.headers.get("cf-connecting-ip", "")
xff = request.headers.get("x-forwarded-for", "")
real = cf or xff.split(",")[0].strip() or client
ts = time.strftime("%Y-%m-%d %H:%M:%S")
browser = _get_browser_info(request)
browser_str = f"UA:{browser['ua']} PLAT:{browser['platform']}"
if code == AUTH_CODE:
token = secrets.token_hex(32)
sessions.add(token)
response.set_cookie(key="session", value=token, httponly=True, max_age=86400)
_log_connection(ts, "LOGIN_OK", real, "-", browser_str)
return {"status": "ok"}
_log_connection(ts, "LOGIN_FAIL", real, "-", browser_str)
raise HTTPException(status_code=401, detail="Invalid code")
@app.get("/api/logout")
async def logout(request: Request, response: Response):
token = request.cookies.get("session")
sessions.discard(token)
response.delete_cookie("session")
return {"status": "ok"}
tunnel_processes: dict[str, subprocess.Popen] = {}
class TerminalSession:
def __init__(self):
self.fd = None
self.pid = None
def start(self):
self.pid, self.fd = pty.fork()
if self.pid == 0:
os.environ["TERM"] = "xterm-256color"
os.environ["SHELL"] = os.environ.get("SHELL", "/bin/bash")
subprocess.run([os.environ["SHELL"], "--login"])
os._exit(0)
def resize(self, cols: int, rows: int):
if self.fd:
size = struct.pack("HHHH", rows, cols, 0, 0)
fcntl.ioctl(self.fd, termios.TIOCSWINSZ, size)
def write(self, data: str):
if self.fd:
os.write(self.fd, data.encode())
def read(self) -> str:
if self.fd is None:
return ""
try:
r, _, _ = select.select([self.fd], [], [], 0.01)
if r:
return os.read(self.fd, 4096).decode(errors="replace")
except (OSError, ValueError):
pass
return ""
def close(self):
if self.pid:
try:
os.kill(self.pid, signal.SIGTERM)
except ProcessLookupError:
pass
os.waitpid(self.pid, 0)
if self.fd:
os.close(self.fd)
terminal_sessions: dict[str, TerminalSession] = {}
@app.websocket("/ws/{session_id}")
async def terminal_ws(websocket: WebSocket, session_id: str):
token = websocket.cookies.get("session")
if token not in sessions:
await websocket.close(code=4001)
return
await websocket.accept()
session = TerminalSession()
session.start()
terminal_sessions[session_id] = session
client_host = websocket.client.host if websocket.client else "unknown"
cf_ip = websocket.headers.get("cf-connecting-ip", "")
xff = websocket.headers.get("x-forwarded-for", "")
all_ips = [ip.strip() for ip in (cf_ip, xff.split(",")[0].strip() if xff else "") if ip]
all_ips.append(client_host)
real_ip = all_ips[0] if all_ips else "unknown"
ipv4s = [ip for ip in all_ips if "." in ip]
ipv6s = [ip for ip in all_ips if ":" in ip and "." not in ip]
ip_label = f"IPv4 {ipv4s[0]}" if ipv4s else f"IPv6 {ipv6s[0]}" if ipv6s else real_ip
timestamp = time.strftime("%Y-%m-%d %H:%M:%S")
_log_connection(timestamp, "SHELL", f"{real_ip} ({ip_label})", session_id)
session.write(f"\r\n\x1b[33m⚠️ New connection from \x1b[36m{ip_label}\x1b[33m at {timestamp}\x1b[0m\r\n")
async def reader():
while True:
data = session.read()
if data:
await websocket.send_text(json.dumps({"type": "output", "data": data}))
await asyncio.sleep(0.01)
async def writer():
nonlocal session
try:
async for message in websocket.iter_text():
msg = json.loads(message)
match msg.get("type"):
case "input":
session.write(msg["data"])
case "resize":
session.resize(msg["cols"], msg["rows"])
case "exec":
cmd = msg["data"]
session.write(cmd + "\n")
except WebSocketDisconnect:
pass
try:
await asyncio.gather(reader(), writer())
finally:
timestamp = time.strftime("%Y-%m-%d %H:%M:%S")
_log_connection(timestamp, "DISCONNECT", real_ip, session_id)
session.close()
terminal_sessions.pop(session_id, None)
@app.get("/health")
async def health():
return {"status": "ok"}
@app.get("/api/myip")
async def my_ip(request: Request):
cf = request.headers.get("cf-connecting-ip", "")
xff = request.headers.get("x-forwarded-for", "")
direct = request.client.host if request.client else ""
ip = cf or (xff.split(",")[0].strip() if xff else "") or direct
ip_type = "IPv4" if "." in ip else "IPv6" if ":" in ip else "unknown"
return {
"ip": ip,
"type": ip_type,
"headers": {
"cf-connecting-ip": cf,
"x-forwarded-for": xff,
"remote": direct,
},
}
@app.get("/api/visitors")
@app.get("/api/whoami")
async def whoami(request: Request):
client = request.client.host if request.client else "unknown"
cf = request.headers.get("cf-connecting-ip", "")
xff = request.headers.get("x-forwarded-for", "")
ip = cf or (xff.split(",")[0].strip() if xff else "") or client
ip_type = "IPv4" if "." in ip else "IPv6" if ":" in ip else "unknown"
return {
"ip": ip,
"ip_type": ip_type,
"browser": _get_browser_info(request),
"headers": {
k: v for k, v in request.headers.items() if not k.startswith("x-envoy") and not k.startswith("x-forwarded")
},
}
async def get_visitors(minutes: int = 60):
if not os.path.exists(LOG_FILE):
return {"visitors": []}
entries = []
cutoff = time.time() - minutes * 60
with open(LOG_FILE) as f:
for line in f:
line = line.strip()
if not line:
continue
try:
ts_str = line[1:20]
ts = time.mktime(time.strptime(ts_str, "%Y-%m-%d %H:%M:%S"))
if ts < cutoff:
continue
entries.append(line)
except ValueError:
entries.append(line)
return {"visitors": entries[-100:], "count": len(entries)}
QR_DATA_DIR = "/app/qr_data"
QR_DATA_FILE = f"{QR_DATA_DIR}/qr.json"
@app.get("/api/whatsapp/qr")
async def whatsapp_qr():
if not os.path.exists(QR_DATA_FILE):
return {"qr": None, "connected": False, "status": "no_qr"}
try:
with open(QR_DATA_FILE) as f:
data = json.load(f)
png_path = f"{QR_DATA_DIR}/qr.png"
if os.path.exists(png_path):
with open(png_path, "rb") as f:
import base64
data["qr_png"] = base64.b64encode(f.read()).decode()
return data
except Exception:
return {"qr": None, "connected": False, "status": "error"}
@app.post("/api/exec")
async def exec_command(body: dict, request: Request):
if not check_auth(request):
raise HTTPException(status_code=401, detail="Unauthorized")
cmd = body.get("cmd", "")
try:
result = subprocess.run(
shlex.split(cmd),
capture_output=True,
text=True,
timeout=30,
)
return {
"stdout": result.stdout,
"stderr": result.stderr,
"returncode": result.returncode,
}
except subprocess.TimeoutExpired:
return {"stdout": "", "stderr": "Command timed out", "returncode": -1}
except Exception as e:
return {"stdout": "", "stderr": str(e), "returncode": -1}
@app.post("/api/tunnel")
async def create_tunnel(request: Request):
if not check_auth(request):
raise HTTPException(status_code=401, detail="Unauthorized")
_cleanup_dead_tunnels()
if tunnel_processes:
existing_id = next(iter(tunnel_processes))
existing_url = getattr(app.state, "tunnel_url", None)
return {"id": existing_id, "url": existing_url, "status": "active", "note": "using existing tunnel"}
tunnel_id = "".join(random.choices(string.ascii_lowercase + string.digits, k=8))
target_port = int(os.environ.get("PORT", 8080))
cloudflared = subprocess.Popen(
["cloudflared", "tunnel", "--url", f"http://localhost:{target_port}"],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
tunnel_processes[tunnel_id] = cloudflared
url_found = asyncio.Event()
tunnel_url = None
def extract_url():
nonlocal tunnel_url
for line in iter(cloudflared.stderr.readline, b""):
decoded = line.decode(errors="replace")
if ".trycloudflare.com" in decoded:
start = decoded.index("https://")
end = decoded.index(".trycloudflare.com") + len(".trycloudflare.com")
tunnel_url = decoded[start:end]
app.state.tunnel_url = tunnel_url
url_found.set()
return
threading.Thread(target=extract_url, daemon=True).start()
try:
await asyncio.wait_for(url_found.wait(), timeout=15)
app.state._tunnel_id = tunnel_id
return {"id": tunnel_id, "url": tunnel_url, "status": "active"}
except asyncio.TimeoutError:
return {"id": tunnel_id, "url": None, "status": "connecting"}
def _cleanup_dead_tunnels():
dead = [tid for tid, proc in list(tunnel_processes.items()) if proc.poll() is not None]
for tid in dead:
tunnel_processes.pop(tid, None)
@app.get("/api/tunnel/{tunnel_id}")
async def tunnel_status(tunnel_id: str, request: Request):
if not check_auth(request):
raise HTTPException(status_code=401, detail="Unauthorized")
proc = tunnel_processes.get(tunnel_id)
if not proc:
return {"error": "not found"}
return {"status": "running" if proc.poll() is None else "stopped"}
@app.delete("/api/tunnel/{tunnel_id}")
async def stop_tunnel(tunnel_id: str, request: Request):
if not check_auth(request):
raise HTTPException(status_code=401, detail="Unauthorized")
proc = tunnel_processes.pop(tunnel_id, None)
if proc:
proc.terminate()
return {"status": "stopped"}
return {"error": "not found"}
static_dir = os.path.join(os.path.dirname(__file__), "static")
@app.post("/api/freeramdisk")
async def free_ramdisk(request: Request):
if not check_auth(request):
raise HTTPException(status_code=401, detail="Unauthorized")
result = subprocess.run(["freeramdisk", "-f"], capture_output=True, text=True, timeout=10)
shutil.rmtree(LOG_DIR, ignore_errors=True)
os.makedirs(LOG_DIR, exist_ok=True)
return {
"status": "ok" if result.returncode == 0 else "warn",
"message": f"RAM disk freed: {RAMDISK or 'not set'}",
"log_dir": LOG_DIR,
"cleared": True,
}
app.mount("/", StaticFiles(directory=static_dir, html=True), name="static")
if __name__ == "__main__":
port = int(os.environ.get("PORT", 8080))
uvicorn.run(app, host="0.0.0.0", port=port)

Xet Storage Details

Size:
14.5 kB
·
Xet hash:
b893075a7f984dff404754fe6df0adb8db5bf53eedb4f7a529a52d152570452d

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.