Initial YakPanel commit

This commit is contained in:
Niranjan
2026-04-07 02:04:22 +05:30
commit 2826d3e7f3
5359 changed files with 1390724 additions and 0 deletions

View File

@@ -0,0 +1 @@
# YakPanel - Core module

View File

@@ -0,0 +1,88 @@
"""YakPanel - Configuration"""
import os
from typing import Any
from pydantic_settings import BaseSettings
from functools import lru_cache
# Runtime config loaded from DB on startup (overrides Settings)
_runtime_config: dict[str, Any] = {}
class Settings(BaseSettings):
"""Application settings"""
app_name: str = "YakPanel"
app_version: str = "1.0.0"
debug: bool = False
# Paths (Ubuntu/Debian default)
panel_path: str = "/www/server/YakPanel-server"
setup_path: str = "/www/server"
www_root: str = "/www/wwwroot"
www_logs: str = "/www/wwwlogs"
vhost_path: str = "/www/server/panel/vhost"
# Database (use absolute path for SQLite)
database_url: str = "sqlite+aiosqlite:///./data/default.db"
# Redis
redis_url: str = "redis://localhost:6379/0"
# Auth
secret_key: str = "YakPanel-server-secret-change-in-production"
algorithm: str = "HS256"
access_token_expire_minutes: int = 60 * 24 # 24 hours
# Panel
panel_port: int = 8888
webserver_type: str = "nginx" # nginx, apache, openlitespeed
# CORS (comma-separated origins, e.g. https://panel.example.com)
cors_extra_origins: str = ""
# Remote SSH installer (disabled by default — high risk; see docs)
enable_remote_installer: bool = False
remote_install_default_url: str = "https://www.yakpanel.com/YakPanel-server/install.sh"
remote_install_rate_limit_per_ip: int = 10
remote_install_rate_window_minutes: int = 60
# Comma-separated CIDRs; empty = no restriction (e.g. "10.0.0.0/8,192.168.0.0/16")
remote_install_allowed_target_cidrs: str = ""
class Config:
env_file = ".env"
env_file_encoding = "utf-8"
@lru_cache
def get_settings() -> Settings:
return Settings()
def get_runtime_config() -> dict[str, Any]:
"""Get effective panel config (Settings + DB overrides)."""
s = get_settings()
base = {
"panel_port": s.panel_port,
"www_root": s.www_root,
"setup_path": s.setup_path,
"www_logs": s.www_logs,
"vhost_path": s.vhost_path,
"webserver_type": s.webserver_type,
"mysql_root": "",
}
for k, v in _runtime_config.items():
if k in base:
if k == "panel_port":
try:
base[k] = int(v)
except (ValueError, TypeError):
pass
else:
base[k] = v
base["backup_path"] = os.path.join(base["setup_path"], "backup")
return base
def set_runtime_config_overrides(overrides: dict[str, str]) -> None:
"""Set runtime config from DB (called on startup)."""
global _runtime_config
_runtime_config = dict(overrides)

View File

@@ -0,0 +1,97 @@
"""YakPanel - Database configuration"""
import os
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker
from sqlalchemy.orm import DeclarativeBase
from app.core.config import get_settings
settings = get_settings()
# Ensure data directory exists for SQLite
if "sqlite" in settings.database_url:
backend_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
data_dir = os.path.join(backend_dir, "data")
os.makedirs(data_dir, exist_ok=True)
engine = create_async_engine(
settings.database_url,
echo=settings.debug,
)
AsyncSessionLocal = async_sessionmaker(
engine,
class_=AsyncSession,
expire_on_commit=False,
autocommit=False,
autoflush=False,
)
class Base(DeclarativeBase):
"""SQLAlchemy declarative base"""
pass
async def get_db():
"""Dependency for async database sessions"""
async with AsyncSessionLocal() as session:
try:
yield session
await session.commit()
except Exception:
await session.rollback()
raise
finally:
await session.close()
def _run_migrations(conn):
"""Add new columns to existing tables (SQLite)."""
import sqlalchemy
try:
r = conn.execute(sqlalchemy.text("PRAGMA table_info(sites)"))
cols = [row[1] for row in r.fetchall()]
if "php_version" not in cols:
conn.execute(sqlalchemy.text("ALTER TABLE sites ADD COLUMN php_version VARCHAR(16) DEFAULT '74'"))
if "force_https" not in cols:
conn.execute(sqlalchemy.text("ALTER TABLE sites ADD COLUMN force_https INTEGER DEFAULT 0"))
except Exception:
pass
# Create backup_plans if not exists (create_all handles new installs)
try:
conn.execute(sqlalchemy.text("""
CREATE TABLE IF NOT EXISTS backup_plans (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name VARCHAR(128) NOT NULL,
plan_type VARCHAR(32) NOT NULL,
target_id INTEGER NOT NULL,
schedule VARCHAR(64) NOT NULL,
enabled BOOLEAN DEFAULT 1
)
"""))
except Exception:
pass
# Create custom_plugins if not exists
try:
conn.execute(sqlalchemy.text("""
CREATE TABLE IF NOT EXISTS custom_plugins (
id INTEGER PRIMARY KEY AUTOINCREMENT,
plugin_id VARCHAR(64) UNIQUE NOT NULL,
name VARCHAR(128) NOT NULL,
version VARCHAR(32) DEFAULT '1.0',
desc VARCHAR(512) DEFAULT '',
source_url VARCHAR(512) DEFAULT '',
enabled BOOLEAN DEFAULT 1
)
"""))
except Exception:
pass
async def init_db():
"""Initialize database tables"""
import app.models # noqa: F401 - register all models with Base.metadata
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all)
if "sqlite" in str(engine.url):
await conn.run_sync(_run_migrations)

View File

@@ -0,0 +1,41 @@
"""YakPanel - Email notifications"""
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from app.core.config import get_runtime_config
def send_email(subject: str, body: str, to: str | None = None) -> tuple[bool, str]:
"""Send email via SMTP. Returns (success, message)."""
cfg = get_runtime_config()
email_to = to or cfg.get("email_to", "").strip()
smtp_server = cfg.get("smtp_server", "").strip()
smtp_port = int(cfg.get("smtp_port") or 587)
smtp_user = cfg.get("smtp_user", "").strip()
smtp_password = cfg.get("smtp_password", "").strip()
if not email_to:
return False, "Email recipient not configured"
if not smtp_server:
return False, "SMTP server not configured"
try:
msg = MIMEMultipart()
msg["Subject"] = subject
msg["From"] = smtp_user or "YakPanel-server@localhost"
msg["To"] = email_to
msg.attach(MIMEText(body, "plain", "utf-8"))
with smtplib.SMTP(smtp_server, smtp_port, timeout=15) as server:
if smtp_user and smtp_password:
server.starttls()
server.login(smtp_user, smtp_password)
server.sendmail(msg["From"], [email_to], msg.as_string())
return True, "Sent"
except smtplib.SMTPAuthenticationError as e:
return False, f"SMTP auth failed: {e}"
except smtplib.SMTPException as e:
return False, str(e)
except Exception as e:
return False, str(e)

View File

@@ -0,0 +1,38 @@
"""YakPanel - Security utilities"""
from datetime import datetime, timedelta
from typing import Optional
from jose import JWTError, jwt
from passlib.context import CryptContext
from app.core.config import get_settings
settings = get_settings()
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
def verify_password(plain_password: str, hashed_password: str) -> bool:
"""Verify a password against its hash"""
return pwd_context.verify(plain_password, hashed_password)
def get_password_hash(password: str) -> str:
"""Hash a password"""
return pwd_context.hash(password)
def create_access_token(data: dict, expires_delta: Optional[timedelta] = None) -> str:
"""Create JWT access token"""
to_encode = data.copy()
if expires_delta:
expire = datetime.utcnow() + expires_delta
else:
expire = datetime.utcnow() + timedelta(minutes=settings.access_token_expire_minutes)
to_encode.update({"exp": expire})
return jwt.encode(to_encode, settings.secret_key, algorithm=settings.algorithm)
def decode_token(token: str) -> Optional[dict]:
"""Decode and validate JWT token"""
try:
return jwt.decode(token, settings.secret_key, algorithms=[settings.algorithm])
except JWTError:
return None

View File

@@ -0,0 +1,112 @@
"""YakPanel - Utility functions (ported from legacy panel public module)"""
import os
import re
import hashlib
import asyncio
import subprocess
import html
from typing import Tuple, Optional
regex_safe_path = re.compile(r"^[\w\s./\-]*$")
def md5(strings: str | bytes) -> str:
"""Generate MD5 hash"""
if isinstance(strings, str):
strings = strings.encode("utf-8")
return hashlib.md5(strings).hexdigest()
def read_file(filename: str, mode: str = "r") -> str | bytes | None:
"""Read file contents"""
if not os.path.exists(filename):
return None
try:
with open(filename, mode, encoding="utf-8" if "b" not in mode else None) as f:
return f.read()
except Exception:
try:
with open(filename, mode) as f:
return f.read()
except Exception:
return None
def write_file(filename: str, content: str | bytes, mode: str = "w+") -> bool:
"""Write content to file"""
try:
os.makedirs(os.path.dirname(filename) or ".", exist_ok=True)
with open(filename, mode, encoding="utf-8" if "b" not in mode else None) as f:
f.write(content)
return True
except Exception:
return False
def xss_decode(text: str) -> str:
"""Decode XSS-encoded text"""
try:
cs = {""": '"', "&quot": '"', "'": "'", "&#x27": "'"}
for k, v in cs.items():
text = text.replace(k, v)
return html.unescape(text)
except Exception:
return text
def path_safe_check(path: str, force: bool = True) -> bool:
"""Validate path for security (no traversal, no dangerous chars)"""
if len(path) > 256:
return False
checks = ["..", "./", "\\", "%", "$", "^", "&", "*", "~", '"', "'", ";", "|", "{", "}", "`"]
for c in checks:
if c in path:
return False
if force and not regex_safe_path.match(path):
return False
return True
async def exec_shell(
cmd: str,
timeout: Optional[float] = None,
cwd: Optional[str] = None,
) -> Tuple[str, str]:
"""Execute shell command asynchronously. Returns (stdout, stderr)."""
proc = await asyncio.create_subprocess_shell(
cmd,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
cwd=cwd,
)
try:
stdout, stderr = await asyncio.wait_for(
proc.communicate(),
timeout=timeout or 300,
)
except asyncio.TimeoutError:
proc.kill()
await proc.wait()
return "", "Timed out"
out = stdout.decode("utf-8", errors="replace") if stdout else ""
err = stderr.decode("utf-8", errors="replace") if stderr else ""
return out, err
def exec_shell_sync(cmd: str, timeout: Optional[float] = None, cwd: Optional[str] = None) -> Tuple[str, str]:
"""Execute shell command synchronously. Returns (stdout, stderr)."""
try:
result = subprocess.run(
cmd,
shell=True,
capture_output=True,
timeout=timeout or 300,
cwd=cwd,
)
out = result.stdout.decode("utf-8", errors="replace") if result.stdout else ""
err = result.stderr.decode("utf-8", errors="replace") if result.stderr else ""
return out, err
except subprocess.TimeoutExpired:
return "", "Timed out"
except Exception as e:
return "", str(e)