Add complete project structure and all files
This commit is contained in:
1
backend/app/__init__.py
Normal file
1
backend/app/__init__.py
Normal file
@@ -0,0 +1 @@
|
||||
# пустой, но нужен для пакета
|
||||
22
backend/app/api/__init__.py
Normal file
22
backend/app/api/__init__.py
Normal file
@@ -0,0 +1,22 @@
|
||||
# API routers
|
||||
from . import auth
|
||||
from . import dashboard
|
||||
from . import proxmox
|
||||
from . import templates
|
||||
from . import ipam
|
||||
from . import logs
|
||||
from . import settings
|
||||
from . import notifications
|
||||
from . import users
|
||||
|
||||
__all__ = [
|
||||
"auth",
|
||||
"dashboard",
|
||||
"proxmox",
|
||||
"templates",
|
||||
"ipam",
|
||||
"logs",
|
||||
"settings",
|
||||
"notifications",
|
||||
"users"
|
||||
]
|
||||
473
backend/app/api/auth.py
Normal file
473
backend/app/api/auth.py
Normal file
@@ -0,0 +1,473 @@
|
||||
from datetime import datetime, timedelta
|
||||
from fastapi import APIRouter, Depends, HTTPException, status, Request, Form
|
||||
from fastapi.responses import HTMLResponse, RedirectResponse
|
||||
from fastapi.templating import Jinja2Templates
|
||||
from sqlalchemy.orm import Session
|
||||
from loguru import logger
|
||||
|
||||
from ..db import get_db
|
||||
from ..models import User
|
||||
from ..schemas import UserCreate, UserResponse, LoginRequest, Token
|
||||
from ..auth import (
|
||||
get_password_hash,
|
||||
verify_password,
|
||||
create_access_token,
|
||||
get_current_user,
|
||||
get_current_active_admin,
|
||||
get_client_ip,
|
||||
get_current_session_token
|
||||
)
|
||||
from ..config import settings, utcnow
|
||||
from ..logging_service import LoggingService
|
||||
from ..template_helpers import add_i18n_context
|
||||
from ..services.security_service import SecurityService
|
||||
|
||||
router = APIRouter()
|
||||
templates = Jinja2Templates(directory="app/templates")
|
||||
|
||||
|
||||
@router.get("/login", response_class=HTMLResponse, include_in_schema=False)
|
||||
def login_page(request: Request):
|
||||
"""Login page"""
|
||||
context = {
|
||||
"request": request,
|
||||
"panel_name": settings.PANEL_NAME,
|
||||
"version": settings.VERSION,
|
||||
}
|
||||
context = add_i18n_context(request, context)
|
||||
return templates.TemplateResponse("login.html", context)
|
||||
|
||||
|
||||
@router.post("/api/auth/login", response_model=Token)
|
||||
def login(login_data: LoginRequest, request: Request, db: Session = Depends(get_db)):
|
||||
"""
|
||||
Authenticate user and return JWT token with session management
|
||||
"""
|
||||
# Get client info
|
||||
client_ip = get_client_ip(request)
|
||||
user_agent = request.headers.get("user-agent", "")[:500]
|
||||
|
||||
# Check if IP is blocked
|
||||
is_blocked, block_reason = SecurityService.is_ip_blocked(db, client_ip)
|
||||
if is_blocked:
|
||||
logger.warning(f"Blocked IP {client_ip} attempted login: {block_reason}")
|
||||
SecurityService.record_login_attempt(
|
||||
db, client_ip, login_data.username, False, "IP blocked", user_agent
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail=f"Access denied: {block_reason}"
|
||||
)
|
||||
|
||||
# Check for brute force
|
||||
should_block, reason = SecurityService.check_brute_force(db, client_ip, login_data.username)
|
||||
if should_block:
|
||||
block_duration = SecurityService.get_setting_int(db, "ip_block_duration_minutes", 60)
|
||||
SecurityService.block_ip(db, client_ip, reason, "system", block_duration)
|
||||
SecurityService.record_login_attempt(
|
||||
db, client_ip, login_data.username, False, "Brute force detected", user_agent
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Too many failed attempts. IP blocked temporarily."
|
||||
)
|
||||
|
||||
# Find user
|
||||
user = db.query(User).filter(User.username == login_data.username).first()
|
||||
|
||||
if not user:
|
||||
SecurityService.record_login_attempt(
|
||||
db, client_ip, login_data.username, False, "User not found", user_agent
|
||||
)
|
||||
LoggingService.log_auth(
|
||||
db=db,
|
||||
action="login_failed",
|
||||
username=login_data.username,
|
||||
ip_address=client_ip,
|
||||
success=False,
|
||||
error_message="User not found",
|
||||
user_agent=user_agent
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Incorrect username or password",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
|
||||
# Check if account is locked
|
||||
is_locked, locked_until = SecurityService.is_account_locked(user)
|
||||
if is_locked:
|
||||
SecurityService.record_login_attempt(
|
||||
db, client_ip, login_data.username, False, "Account locked", user_agent
|
||||
)
|
||||
LoggingService.log_auth(
|
||||
db=db,
|
||||
action="login_blocked",
|
||||
username=login_data.username,
|
||||
ip_address=client_ip,
|
||||
success=False,
|
||||
error_message="Account locked",
|
||||
user_agent=user_agent,
|
||||
user_id=user.id
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail=f"Account is locked until {locked_until.strftime('%H:%M:%S')}"
|
||||
)
|
||||
|
||||
# Verify password
|
||||
if not verify_password(login_data.password, user.hashed_password):
|
||||
SecurityService.record_login_attempt(
|
||||
db, client_ip, login_data.username, False, "Wrong password", user_agent
|
||||
)
|
||||
|
||||
# Increment failed attempts
|
||||
was_locked = SecurityService.increment_failed_attempts(db, user)
|
||||
|
||||
LoggingService.log_auth(
|
||||
db=db,
|
||||
action="login_failed",
|
||||
username=login_data.username,
|
||||
ip_address=client_ip,
|
||||
success=False,
|
||||
error_message="Incorrect password" + (" - account locked" if was_locked else ""),
|
||||
user_agent=user_agent,
|
||||
user_id=user.id
|
||||
)
|
||||
|
||||
if was_locked:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Account locked due to too many failed attempts"
|
||||
)
|
||||
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Incorrect username or password",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
|
||||
# Check if user is active
|
||||
if not user.is_active:
|
||||
SecurityService.record_login_attempt(
|
||||
db, client_ip, login_data.username, False, "Account disabled", user_agent
|
||||
)
|
||||
LoggingService.log_auth(
|
||||
db=db,
|
||||
action="login_blocked",
|
||||
username=login_data.username,
|
||||
ip_address=client_ip,
|
||||
success=False,
|
||||
error_message="Account disabled",
|
||||
user_agent=user_agent,
|
||||
user_id=user.id
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="User account is disabled"
|
||||
)
|
||||
|
||||
# SUCCESS - Reset failed attempts
|
||||
SecurityService.reset_failed_attempts(db, user)
|
||||
|
||||
# Create session
|
||||
session, was_other_terminated = SecurityService.create_session(
|
||||
db, user, client_ip, user_agent
|
||||
)
|
||||
|
||||
# Update last login
|
||||
user.last_login = utcnow()
|
||||
db.commit()
|
||||
|
||||
# Create access token with session binding
|
||||
session_timeout = SecurityService.get_setting_int(db, "session_timeout_minutes", 60)
|
||||
access_token_expires = timedelta(minutes=session_timeout)
|
||||
access_token = create_access_token(
|
||||
data={"sub": user.username},
|
||||
session_token=session.session_token,
|
||||
expires_delta=access_token_expires
|
||||
)
|
||||
|
||||
# Record successful login
|
||||
SecurityService.record_login_attempt(
|
||||
db, client_ip, login_data.username, True, None, user_agent
|
||||
)
|
||||
|
||||
# Log successful login
|
||||
LoggingService.log_auth(
|
||||
db=db,
|
||||
action="login",
|
||||
username=user.username,
|
||||
ip_address=client_ip,
|
||||
success=True,
|
||||
user_agent=user_agent,
|
||||
user_id=user.id,
|
||||
details={"session_id": session.id, "other_session_terminated": was_other_terminated}
|
||||
)
|
||||
|
||||
logger.info(f"User {user.username} logged in from {client_ip}" +
|
||||
(" (other session terminated)" if was_other_terminated else ""))
|
||||
|
||||
return {
|
||||
"access_token": access_token,
|
||||
"token_type": "bearer",
|
||||
"session_id": session.id,
|
||||
"other_session_terminated": was_other_terminated
|
||||
}
|
||||
|
||||
|
||||
@router.post("/api/auth/logout")
|
||||
def logout(
|
||||
request: Request,
|
||||
current_user: User = Depends(get_current_user),
|
||||
session_token: str = Depends(get_current_session_token),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""Logout user and terminate current session only"""
|
||||
client_ip = get_client_ip(request)
|
||||
|
||||
# Terminate only current session (allow multiple sessions)
|
||||
if session_token:
|
||||
SecurityService.terminate_session(db, session_token)
|
||||
|
||||
LoggingService.log_auth(
|
||||
db=db,
|
||||
action="logout",
|
||||
username=current_user.username,
|
||||
ip_address=client_ip,
|
||||
success=True,
|
||||
user_id=current_user.id
|
||||
)
|
||||
|
||||
logger.info(f"User {current_user.username} logged out")
|
||||
return {"message": "Successfully logged out"}
|
||||
|
||||
|
||||
@router.get("/api/auth/me")
|
||||
def get_current_user_info(current_user: User = Depends(get_current_user)):
|
||||
"""Get current user information with permissions"""
|
||||
permissions = {}
|
||||
if current_user.role:
|
||||
permissions = current_user.role.permissions or {}
|
||||
elif current_user.is_admin:
|
||||
# Admin has all permissions
|
||||
from ..services.security_service import SecurityService
|
||||
all_perms = SecurityService.get_all_permissions()
|
||||
for category, perms in all_perms.items():
|
||||
for perm in perms:
|
||||
permissions[perm] = True
|
||||
|
||||
return {
|
||||
"id": current_user.id,
|
||||
"username": current_user.username,
|
||||
"email": current_user.email,
|
||||
"full_name": current_user.full_name,
|
||||
"is_admin": current_user.is_admin,
|
||||
"is_active": current_user.is_active,
|
||||
"role": {
|
||||
"id": current_user.role.id if current_user.role else None,
|
||||
"name": current_user.role.name if current_user.role else ("admin" if current_user.is_admin else "user"),
|
||||
"display_name": current_user.role.display_name if current_user.role else ("Administrator" if current_user.is_admin else "User")
|
||||
},
|
||||
"permissions": permissions,
|
||||
"require_password_change": current_user.require_password_change,
|
||||
"last_login": current_user.last_login.isoformat() if current_user.last_login else None,
|
||||
"created_at": current_user.created_at.isoformat() if current_user.created_at else None
|
||||
}
|
||||
|
||||
|
||||
@router.get("/api/auth/sessions")
|
||||
def get_my_sessions(current_user: User = Depends(get_current_user), db: Session = Depends(get_db)):
|
||||
"""Get current user's active sessions"""
|
||||
sessions = SecurityService.get_user_sessions(db, current_user.id)
|
||||
return [{
|
||||
"id": s.id,
|
||||
"ip_address": s.ip_address,
|
||||
"device_info": s.device_info,
|
||||
"created_at": s.created_at.isoformat() if s.created_at else None,
|
||||
"last_activity": s.last_activity.isoformat() if s.last_activity else None,
|
||||
"expires_at": s.expires_at.isoformat() if s.expires_at else None
|
||||
} for s in sessions]
|
||||
|
||||
|
||||
@router.post("/api/auth/register", response_model=UserResponse, status_code=status.HTTP_201_CREATED)
|
||||
def register_user(
|
||||
user_data: UserCreate,
|
||||
request: Request,
|
||||
db: Session = Depends(get_db),
|
||||
current_admin: User = Depends(get_current_active_admin)
|
||||
):
|
||||
"""
|
||||
Register a new user (admin only)
|
||||
"""
|
||||
client_ip = get_client_ip(request)
|
||||
|
||||
# Check if username already exists
|
||||
if db.query(User).filter(User.username == user_data.username).first():
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Username already registered"
|
||||
)
|
||||
|
||||
# Check if email already exists
|
||||
if db.query(User).filter(User.email == user_data.email).first():
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Email already registered"
|
||||
)
|
||||
|
||||
# Validate password
|
||||
is_valid, errors = SecurityService.validate_password(db, user_data.password)
|
||||
if not is_valid:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="; ".join(errors)
|
||||
)
|
||||
|
||||
# Create new user
|
||||
hashed_password = get_password_hash(user_data.password)
|
||||
new_user = User(
|
||||
username=user_data.username,
|
||||
email=user_data.email,
|
||||
full_name=user_data.full_name,
|
||||
hashed_password=hashed_password,
|
||||
is_active=True,
|
||||
is_admin=False,
|
||||
last_password_change=utcnow()
|
||||
)
|
||||
|
||||
db.add(new_user)
|
||||
db.commit()
|
||||
db.refresh(new_user)
|
||||
|
||||
LoggingService.log_auth(
|
||||
db=db,
|
||||
action="user_created",
|
||||
username=current_admin.username,
|
||||
ip_address=client_ip,
|
||||
success=True,
|
||||
user_id=current_admin.id,
|
||||
details={"new_user": new_user.username}
|
||||
)
|
||||
|
||||
logger.info(f"New user registered: {new_user.username} by admin {current_admin.username}")
|
||||
|
||||
return new_user
|
||||
|
||||
|
||||
@router.get("/api/users", response_model=list[UserResponse])
|
||||
def list_users(
|
||||
db: Session = Depends(get_db),
|
||||
current_admin: User = Depends(get_current_active_admin)
|
||||
):
|
||||
"""
|
||||
List all users (admin only)
|
||||
"""
|
||||
users = db.query(User).all()
|
||||
return users
|
||||
|
||||
|
||||
@router.delete("/api/users/{user_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||
def delete_user(
|
||||
user_id: int,
|
||||
request: Request,
|
||||
db: Session = Depends(get_db),
|
||||
current_admin: User = Depends(get_current_active_admin)
|
||||
):
|
||||
"""
|
||||
Delete a user (admin only)
|
||||
"""
|
||||
client_ip = get_client_ip(request)
|
||||
user = db.query(User).filter(User.id == user_id).first()
|
||||
|
||||
if not user:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="User not found"
|
||||
)
|
||||
|
||||
# Prevent deleting yourself
|
||||
if user.id == current_admin.id:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Cannot delete your own account"
|
||||
)
|
||||
|
||||
username = user.username
|
||||
|
||||
# Terminate sessions before deletion
|
||||
SecurityService.terminate_all_user_sessions(db, user_id)
|
||||
|
||||
db.delete(user)
|
||||
db.commit()
|
||||
|
||||
LoggingService.log_auth(
|
||||
db=db,
|
||||
action="user_deleted",
|
||||
username=current_admin.username,
|
||||
ip_address=client_ip,
|
||||
success=True,
|
||||
user_id=current_admin.id,
|
||||
details={"deleted_user": username}
|
||||
)
|
||||
|
||||
logger.info(f"User {username} deleted by admin {current_admin.username}")
|
||||
|
||||
return None
|
||||
|
||||
|
||||
@router.post("/api/auth/change-password")
|
||||
def change_password(
|
||||
old_password: str = Form(...),
|
||||
new_password: str = Form(...),
|
||||
request: Request = None,
|
||||
current_user: User = Depends(get_current_user),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""
|
||||
Change user password
|
||||
"""
|
||||
client_ip = get_client_ip(request) if request else "unknown"
|
||||
|
||||
# Verify old password
|
||||
if not verify_password(old_password, current_user.hashed_password):
|
||||
LoggingService.log_auth(
|
||||
db=db,
|
||||
action="password_change_failed",
|
||||
username=current_user.username,
|
||||
ip_address=client_ip,
|
||||
success=False,
|
||||
error_message="Incorrect current password",
|
||||
user_id=current_user.id
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Incorrect password"
|
||||
)
|
||||
|
||||
# Validate new password
|
||||
is_valid, errors = SecurityService.validate_password(db, new_password)
|
||||
if not is_valid:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="; ".join(errors)
|
||||
)
|
||||
|
||||
# Update password
|
||||
current_user.hashed_password = get_password_hash(new_password)
|
||||
current_user.last_password_change = utcnow()
|
||||
current_user.require_password_change = False
|
||||
db.commit()
|
||||
|
||||
LoggingService.log_auth(
|
||||
db=db,
|
||||
action="password_changed",
|
||||
username=current_user.username,
|
||||
ip_address=client_ip,
|
||||
success=True,
|
||||
user_id=current_user.id
|
||||
)
|
||||
|
||||
logger.info(f"User {current_user.username} changed password")
|
||||
|
||||
return {"message": "Password changed successfully"}
|
||||
53
backend/app/api/dashboard.py
Normal file
53
backend/app/api/dashboard.py
Normal file
@@ -0,0 +1,53 @@
|
||||
from fastapi import APIRouter, Depends, Request
|
||||
from fastapi.responses import HTMLResponse, RedirectResponse
|
||||
from fastapi.templating import Jinja2Templates
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..db import get_db
|
||||
from ..models import ProxmoxServer
|
||||
from ..template_helpers import add_i18n_context
|
||||
|
||||
router = APIRouter()
|
||||
templates = Jinja2Templates(directory="app/templates")
|
||||
|
||||
|
||||
@router.get("/", response_class=HTMLResponse, include_in_schema=False)
|
||||
@router.get("/dashboard", response_class=HTMLResponse, include_in_schema=False)
|
||||
def dashboard(request: Request, db: Session = Depends(get_db)):
|
||||
total_servers = db.query(ProxmoxServer).count()
|
||||
online_servers = db.query(ProxmoxServer).filter(ProxmoxServer.is_online == True).count()
|
||||
offline_servers = db.query(ProxmoxServer).filter(ProxmoxServer.is_online == False).count()
|
||||
|
||||
recent_servers = db.query(ProxmoxServer).order_by(ProxmoxServer.id.desc()).limit(6).all()
|
||||
|
||||
stats = {
|
||||
"total_servers": total_servers,
|
||||
"online_servers": online_servers,
|
||||
"offline_servers": offline_servers,
|
||||
}
|
||||
|
||||
lang = request.cookies.get("language", "en")
|
||||
from ..i18n import t
|
||||
|
||||
context = {
|
||||
"request": request,
|
||||
"stats": stats,
|
||||
"recent_servers": recent_servers,
|
||||
"page_title": t('nav_dashboard', lang),
|
||||
}
|
||||
context = add_i18n_context(request, context)
|
||||
|
||||
return templates.TemplateResponse("dashboard.html", context)
|
||||
|
||||
|
||||
@router.get("/containers", response_class=HTMLResponse, include_in_schema=False)
|
||||
def containers(request: Request):
|
||||
lang = request.cookies.get("language", "en")
|
||||
from ..i18n import t
|
||||
|
||||
context = {
|
||||
"request": request,
|
||||
"page_title": t('nav_docker', lang),
|
||||
}
|
||||
context = add_i18n_context(request, context)
|
||||
return templates.TemplateResponse("containers.html", context)
|
||||
898
backend/app/api/ipam.py
Normal file
898
backend/app/api/ipam.py
Normal file
@@ -0,0 +1,898 @@
|
||||
"""
|
||||
IPAM API Routes
|
||||
IP Address Management endpoints for networks, pools, and allocations.
|
||||
"""
|
||||
|
||||
import logging
|
||||
from typing import List, Optional
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Request
|
||||
from fastapi.responses import HTMLResponse
|
||||
from fastapi.templating import Jinja2Templates
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..db import get_db
|
||||
from ..models import IPAMNetwork, IPAMPool, IPAMAllocation, IPAMHistory, ProxmoxServer, User, VMInstance
|
||||
from ..schemas import (
|
||||
IPAMNetworkCreate, IPAMNetworkUpdate, IPAMNetworkResponse, IPAMNetworkStats,
|
||||
IPAMPoolCreate, IPAMPoolUpdate, IPAMPoolResponse,
|
||||
IPAMAllocationCreate, IPAMAllocationUpdate, IPAMAllocationResponse,
|
||||
IPAMHistoryResponse, IPAMAutoAllocateRequest
|
||||
)
|
||||
from ..ipam_service import IPAMService
|
||||
from ..auth import get_current_user, PermissionChecker
|
||||
from ..template_helpers import add_i18n_context
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
router = APIRouter()
|
||||
templates = Jinja2Templates(directory="app/templates")
|
||||
|
||||
|
||||
# ==================== HTML Pages ====================
|
||||
|
||||
@router.get("/", response_class=HTMLResponse, include_in_schema=False)
|
||||
async def ipam_dashboard(request: Request):
|
||||
"""IPAM Dashboard page"""
|
||||
from ..i18n import t
|
||||
lang = request.cookies.get("language", "en")
|
||||
|
||||
context = {
|
||||
"request": request,
|
||||
"page_title": t('nav_ipam', lang),
|
||||
}
|
||||
context = add_i18n_context(request, context)
|
||||
return templates.TemplateResponse("ipam_dashboard.html", context)
|
||||
|
||||
|
||||
@router.get("/networks", response_class=HTMLResponse, include_in_schema=False)
|
||||
async def ipam_networks_page(request: Request):
|
||||
"""IPAM Networks management page"""
|
||||
from ..i18n import t
|
||||
lang = request.cookies.get("language", "en")
|
||||
|
||||
context = {
|
||||
"request": request,
|
||||
"page_title": t('nav_ipam', lang),
|
||||
}
|
||||
context = add_i18n_context(request, context)
|
||||
return templates.TemplateResponse("ipam_networks.html", context)
|
||||
|
||||
|
||||
@router.get("/network/{network_id}", response_class=HTMLResponse, include_in_schema=False)
|
||||
async def ipam_network_detail(request: Request, network_id: int):
|
||||
"""IPAM Network detail page with IP grid"""
|
||||
from ..i18n import t
|
||||
lang = request.cookies.get("language", "en")
|
||||
|
||||
context = {
|
||||
"request": request,
|
||||
"network_id": network_id,
|
||||
"page_title": t('nav_ipam', lang),
|
||||
}
|
||||
context = add_i18n_context(request, context)
|
||||
return templates.TemplateResponse("ipam_network_detail.html", context)
|
||||
|
||||
|
||||
@router.get("/allocations", response_class=HTMLResponse, include_in_schema=False)
|
||||
async def ipam_allocations_page(request: Request):
|
||||
"""IPAM Allocations page"""
|
||||
from ..i18n import t
|
||||
lang = request.cookies.get("language", "en")
|
||||
|
||||
context = {
|
||||
"request": request,
|
||||
"page_title": t('nav_ipam', lang),
|
||||
}
|
||||
context = add_i18n_context(request, context)
|
||||
return templates.TemplateResponse("ipam_allocations.html", context)
|
||||
|
||||
|
||||
@router.get("/history", response_class=HTMLResponse, include_in_schema=False)
|
||||
async def ipam_history_page(request: Request):
|
||||
"""IPAM History page"""
|
||||
from ..i18n import t
|
||||
lang = request.cookies.get("language", "en")
|
||||
|
||||
context = {
|
||||
"request": request,
|
||||
"page_title": t('nav_ipam', lang),
|
||||
}
|
||||
context = add_i18n_context(request, context)
|
||||
return templates.TemplateResponse("ipam_history.html", context)
|
||||
|
||||
|
||||
# ==================== Network API ====================
|
||||
|
||||
@router.get("/api/networks", response_model=List[IPAMNetworkResponse])
|
||||
async def get_networks(
|
||||
is_active: Optional[bool] = None,
|
||||
proxmox_server_id: Optional[int] = None,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(PermissionChecker("ipam.view"))
|
||||
):
|
||||
"""Get all IPAM networks"""
|
||||
query = db.query(IPAMNetwork)
|
||||
|
||||
if is_active is not None:
|
||||
query = query.filter(IPAMNetwork.is_active == is_active)
|
||||
|
||||
if proxmox_server_id:
|
||||
query = query.filter(IPAMNetwork.proxmox_server_id == proxmox_server_id)
|
||||
|
||||
networks = query.order_by(IPAMNetwork.name).all()
|
||||
|
||||
# Get server names for networks
|
||||
server_ids = [n.proxmox_server_id for n in networks if n.proxmox_server_id]
|
||||
servers = {}
|
||||
if server_ids:
|
||||
server_records = db.query(ProxmoxServer).filter(ProxmoxServer.id.in_(server_ids)).all()
|
||||
servers = {s.id: s.name for s in server_records}
|
||||
|
||||
# Add computed stats to each network
|
||||
ipam = IPAMService(db)
|
||||
result = []
|
||||
for network in networks:
|
||||
stats = ipam.get_network_stats(network.id)
|
||||
network_dict = {
|
||||
**network.__dict__,
|
||||
'total_ips': stats.get('total_ips', 0),
|
||||
'used_ips': stats.get('allocated_ips', 0) + stats.get('reserved_ips', 0),
|
||||
'available_ips': stats.get('available_ips', 0),
|
||||
'utilization_percent': stats.get('utilization_percent', 0),
|
||||
'server_name': servers.get(network.proxmox_server_id) if network.proxmox_server_id else None
|
||||
}
|
||||
result.append(network_dict)
|
||||
|
||||
return result
|
||||
|
||||
|
||||
@router.get("/api/networks/{network_id}", response_model=IPAMNetworkResponse)
|
||||
async def get_network(
|
||||
network_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(PermissionChecker("ipam.view"))
|
||||
):
|
||||
"""Get a specific IPAM network"""
|
||||
network = db.query(IPAMNetwork).filter(IPAMNetwork.id == network_id).first()
|
||||
if not network:
|
||||
raise HTTPException(status_code=404, detail="Network not found")
|
||||
|
||||
ipam = IPAMService(db)
|
||||
stats = ipam.get_network_stats(network_id)
|
||||
|
||||
return {
|
||||
**network.__dict__,
|
||||
'total_ips': stats.get('total_ips', 0),
|
||||
'used_ips': stats.get('allocated_ips', 0) + stats.get('reserved_ips', 0),
|
||||
'available_ips': stats.get('available_ips', 0),
|
||||
'utilization_percent': stats.get('utilization_percent', 0)
|
||||
}
|
||||
|
||||
|
||||
@router.get("/api/networks/{network_id}/stats", response_model=IPAMNetworkStats)
|
||||
async def get_network_stats(
|
||||
network_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(PermissionChecker("ipam.view"))
|
||||
):
|
||||
"""Get detailed statistics for a network"""
|
||||
ipam = IPAMService(db)
|
||||
stats = ipam.get_network_stats(network_id)
|
||||
|
||||
if not stats:
|
||||
raise HTTPException(status_code=404, detail="Network not found")
|
||||
|
||||
return stats
|
||||
|
||||
|
||||
@router.get("/api/networks/{network_id}/ip-map")
|
||||
async def get_network_ip_map(
|
||||
network_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(PermissionChecker("ipam.view"))
|
||||
):
|
||||
"""Get IP address map for visualization"""
|
||||
ipam = IPAMService(db)
|
||||
ip_map = ipam.get_network_ip_map(network_id)
|
||||
|
||||
if not ip_map:
|
||||
network = db.query(IPAMNetwork).filter(IPAMNetwork.id == network_id).first()
|
||||
if not network:
|
||||
raise HTTPException(status_code=404, detail="Network not found")
|
||||
|
||||
return {"network_id": network_id, "ip_map": ip_map}
|
||||
|
||||
|
||||
@router.post("/api/networks", response_model=IPAMNetworkResponse)
|
||||
async def create_network(
|
||||
network_data: IPAMNetworkCreate,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(PermissionChecker("ipam.manage"))
|
||||
):
|
||||
"""Create a new IPAM network"""
|
||||
# Check for duplicate network CIDR
|
||||
existing = db.query(IPAMNetwork).filter(IPAMNetwork.network == network_data.network).first()
|
||||
if existing:
|
||||
raise HTTPException(status_code=400, detail=f"Network {network_data.network} already exists")
|
||||
|
||||
network = IPAMNetwork(**network_data.model_dump())
|
||||
db.add(network)
|
||||
db.commit()
|
||||
db.refresh(network)
|
||||
|
||||
logger.info(f"User {current_user.username} created network {network.name} ({network.network})")
|
||||
return network
|
||||
|
||||
|
||||
@router.put("/api/networks/{network_id}", response_model=IPAMNetworkResponse)
|
||||
async def update_network(
|
||||
network_id: int,
|
||||
network_data: IPAMNetworkUpdate,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(PermissionChecker("ipam.manage"))
|
||||
):
|
||||
"""Update an IPAM network"""
|
||||
network = db.query(IPAMNetwork).filter(IPAMNetwork.id == network_id).first()
|
||||
if not network:
|
||||
raise HTTPException(status_code=404, detail="Network not found")
|
||||
|
||||
update_data = network_data.model_dump(exclude_unset=True)
|
||||
for field, value in update_data.items():
|
||||
setattr(network, field, value)
|
||||
|
||||
db.commit()
|
||||
db.refresh(network)
|
||||
|
||||
logger.info(f"User {current_user.username} updated network {network.name}")
|
||||
return network
|
||||
|
||||
|
||||
@router.delete("/api/networks/{network_id}")
|
||||
async def delete_network(
|
||||
network_id: int,
|
||||
force: bool = False,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(PermissionChecker("ipam.manage"))
|
||||
):
|
||||
"""Delete an IPAM network"""
|
||||
network = db.query(IPAMNetwork).filter(IPAMNetwork.id == network_id).first()
|
||||
if not network:
|
||||
raise HTTPException(status_code=404, detail="Network not found")
|
||||
|
||||
# Check for existing allocations
|
||||
alloc_count = db.query(IPAMAllocation).filter(IPAMAllocation.network_id == network_id).count()
|
||||
if alloc_count > 0 and not force:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Network has {alloc_count} allocations. Use force=true to delete anyway."
|
||||
)
|
||||
|
||||
# Delete related data
|
||||
db.query(IPAMAllocation).filter(IPAMAllocation.network_id == network_id).delete()
|
||||
db.query(IPAMPool).filter(IPAMPool.network_id == network_id).delete()
|
||||
db.query(IPAMHistory).filter(IPAMHistory.network_id == network_id).delete()
|
||||
db.delete(network)
|
||||
db.commit()
|
||||
|
||||
logger.info(f"User {current_user.username} deleted network {network.name}")
|
||||
return {"message": f"Network {network.name} deleted"}
|
||||
|
||||
|
||||
# ==================== Pool API ====================
|
||||
|
||||
@router.get("/api/pools", response_model=List[IPAMPoolResponse])
|
||||
async def get_pools(
|
||||
network_id: Optional[int] = None,
|
||||
is_active: Optional[bool] = None,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(PermissionChecker("ipam.view"))
|
||||
):
|
||||
"""Get all IP pools"""
|
||||
query = db.query(IPAMPool)
|
||||
|
||||
if network_id:
|
||||
query = query.filter(IPAMPool.network_id == network_id)
|
||||
|
||||
if is_active is not None:
|
||||
query = query.filter(IPAMPool.is_active == is_active)
|
||||
|
||||
pools = query.order_by(IPAMPool.network_id, IPAMPool.range_start).all()
|
||||
|
||||
# Add stats to each pool
|
||||
ipam = IPAMService(db)
|
||||
result = []
|
||||
for pool in pools:
|
||||
stats = ipam.get_pool_stats(pool.id)
|
||||
pool_dict = {
|
||||
**pool.__dict__,
|
||||
'total_ips': stats.get('total_ips', 0),
|
||||
'used_ips': stats.get('used_ips', 0),
|
||||
'available_ips': stats.get('available_ips', 0)
|
||||
}
|
||||
result.append(pool_dict)
|
||||
|
||||
return result
|
||||
|
||||
|
||||
@router.post("/api/pools", response_model=IPAMPoolResponse)
|
||||
async def create_pool(
|
||||
pool_data: IPAMPoolCreate,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(PermissionChecker("ipam.manage"))
|
||||
):
|
||||
"""Create a new IP pool"""
|
||||
# Validate network exists
|
||||
network = db.query(IPAMNetwork).filter(IPAMNetwork.id == pool_data.network_id).first()
|
||||
if not network:
|
||||
raise HTTPException(status_code=404, detail="Network not found")
|
||||
|
||||
# Validate range
|
||||
ipam = IPAMService(db)
|
||||
is_valid, error = ipam.validate_pool_range(
|
||||
pool_data.network_id,
|
||||
pool_data.range_start,
|
||||
pool_data.range_end
|
||||
)
|
||||
if not is_valid:
|
||||
raise HTTPException(status_code=400, detail=error)
|
||||
|
||||
pool = IPAMPool(**pool_data.model_dump())
|
||||
db.add(pool)
|
||||
db.commit()
|
||||
db.refresh(pool)
|
||||
|
||||
logger.info(f"User {current_user.username} created pool {pool.name} in network {network.name}")
|
||||
return pool
|
||||
|
||||
|
||||
@router.put("/api/pools/{pool_id}", response_model=IPAMPoolResponse)
|
||||
async def update_pool(
|
||||
pool_id: int,
|
||||
pool_data: IPAMPoolUpdate,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(PermissionChecker("ipam.manage"))
|
||||
):
|
||||
"""Update an IP pool"""
|
||||
pool = db.query(IPAMPool).filter(IPAMPool.id == pool_id).first()
|
||||
if not pool:
|
||||
raise HTTPException(status_code=404, detail="Pool not found")
|
||||
|
||||
# Validate new range if provided
|
||||
update_data = pool_data.model_dump(exclude_unset=True)
|
||||
if 'range_start' in update_data or 'range_end' in update_data:
|
||||
ipam = IPAMService(db)
|
||||
is_valid, error = ipam.validate_pool_range(
|
||||
pool.network_id,
|
||||
update_data.get('range_start', pool.range_start),
|
||||
update_data.get('range_end', pool.range_end),
|
||||
exclude_pool_id=pool_id
|
||||
)
|
||||
if not is_valid:
|
||||
raise HTTPException(status_code=400, detail=error)
|
||||
|
||||
for field, value in update_data.items():
|
||||
setattr(pool, field, value)
|
||||
|
||||
db.commit()
|
||||
db.refresh(pool)
|
||||
|
||||
logger.info(f"User {current_user.username} updated pool {pool.name}")
|
||||
return pool
|
||||
|
||||
|
||||
@router.delete("/api/pools/{pool_id}")
|
||||
async def delete_pool(
|
||||
pool_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(PermissionChecker("ipam.manage"))
|
||||
):
|
||||
"""Delete an IP pool"""
|
||||
pool = db.query(IPAMPool).filter(IPAMPool.id == pool_id).first()
|
||||
if not pool:
|
||||
raise HTTPException(status_code=404, detail="Pool not found")
|
||||
|
||||
# Update allocations to remove pool reference
|
||||
db.query(IPAMAllocation).filter(IPAMAllocation.pool_id == pool_id).update({IPAMAllocation.pool_id: None})
|
||||
db.delete(pool)
|
||||
db.commit()
|
||||
|
||||
logger.info(f"User {current_user.username} deleted pool {pool.name}")
|
||||
return {"message": f"Pool {pool.name} deleted"}
|
||||
|
||||
|
||||
# ==================== Allocation API ====================
|
||||
|
||||
@router.get("/api/allocations", response_model=List[IPAMAllocationResponse])
|
||||
async def get_allocations(
|
||||
network_id: Optional[int] = None,
|
||||
pool_id: Optional[int] = None,
|
||||
status: Optional[str] = None,
|
||||
resource_type: Optional[str] = None,
|
||||
search: Optional[str] = None,
|
||||
limit: int = Query(default=100, le=1000),
|
||||
offset: int = 0,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(PermissionChecker("ipam.view"))
|
||||
):
|
||||
"""Get IP allocations with filtering"""
|
||||
query = db.query(IPAMAllocation)
|
||||
|
||||
if network_id:
|
||||
query = query.filter(IPAMAllocation.network_id == network_id)
|
||||
|
||||
if pool_id:
|
||||
query = query.filter(IPAMAllocation.pool_id == pool_id)
|
||||
|
||||
if status:
|
||||
query = query.filter(IPAMAllocation.status == status)
|
||||
|
||||
if resource_type:
|
||||
query = query.filter(IPAMAllocation.resource_type == resource_type)
|
||||
|
||||
if search:
|
||||
search_filter = f"%{search}%"
|
||||
query = query.filter(
|
||||
(IPAMAllocation.ip_address.like(search_filter)) |
|
||||
(IPAMAllocation.resource_name.like(search_filter)) |
|
||||
(IPAMAllocation.hostname.like(search_filter))
|
||||
)
|
||||
|
||||
allocations = query.order_by(IPAMAllocation.ip_address).offset(offset).limit(limit).all()
|
||||
|
||||
# Add network/pool names
|
||||
networks = {n.id: n.name for n in db.query(IPAMNetwork).all()}
|
||||
pools = {p.id: p.name for p in db.query(IPAMPool).all()}
|
||||
|
||||
result = []
|
||||
for alloc in allocations:
|
||||
alloc_dict = {
|
||||
**alloc.__dict__,
|
||||
'network_name': networks.get(alloc.network_id),
|
||||
'pool_name': pools.get(alloc.pool_id) if alloc.pool_id else None
|
||||
}
|
||||
result.append(alloc_dict)
|
||||
|
||||
return result
|
||||
|
||||
|
||||
@router.get("/api/allocations/{allocation_id}", response_model=IPAMAllocationResponse)
|
||||
async def get_allocation(
|
||||
allocation_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(PermissionChecker("ipam.view"))
|
||||
):
|
||||
"""Get a specific allocation"""
|
||||
allocation = db.query(IPAMAllocation).filter(IPAMAllocation.id == allocation_id).first()
|
||||
if not allocation:
|
||||
raise HTTPException(status_code=404, detail="Allocation not found")
|
||||
|
||||
network = db.query(IPAMNetwork).filter(IPAMNetwork.id == allocation.network_id).first()
|
||||
pool = db.query(IPAMPool).filter(IPAMPool.id == allocation.pool_id).first() if allocation.pool_id else None
|
||||
|
||||
return {
|
||||
**allocation.__dict__,
|
||||
'network_name': network.name if network else None,
|
||||
'pool_name': pool.name if pool else None
|
||||
}
|
||||
|
||||
|
||||
@router.post("/api/allocations", response_model=IPAMAllocationResponse)
|
||||
async def create_allocation(
|
||||
alloc_data: IPAMAllocationCreate,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(PermissionChecker("ipam.manage"))
|
||||
):
|
||||
"""Manually create an IP allocation"""
|
||||
ipam = IPAMService(db)
|
||||
allocation, error = ipam.allocate_ip(
|
||||
ip_address=alloc_data.ip_address,
|
||||
network_id=alloc_data.network_id,
|
||||
pool_id=alloc_data.pool_id,
|
||||
resource_type=alloc_data.resource_type,
|
||||
resource_id=alloc_data.resource_id,
|
||||
resource_name=alloc_data.resource_name,
|
||||
hostname=alloc_data.hostname,
|
||||
fqdn=alloc_data.fqdn,
|
||||
mac_address=alloc_data.mac_address,
|
||||
proxmox_server_id=alloc_data.proxmox_server_id,
|
||||
proxmox_vmid=alloc_data.proxmox_vmid,
|
||||
proxmox_node=alloc_data.proxmox_node,
|
||||
allocation_type=alloc_data.allocation_type,
|
||||
status=alloc_data.status,
|
||||
allocated_by=current_user.username,
|
||||
notes=alloc_data.notes
|
||||
)
|
||||
|
||||
if error:
|
||||
raise HTTPException(status_code=400, detail=error)
|
||||
|
||||
return allocation
|
||||
|
||||
|
||||
@router.post("/api/allocations/auto", response_model=IPAMAllocationResponse)
|
||||
async def auto_allocate_ip(
|
||||
request: IPAMAutoAllocateRequest,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(PermissionChecker("ipam.manage"))
|
||||
):
|
||||
"""Automatically allocate the next available IP"""
|
||||
ipam = IPAMService(db)
|
||||
allocation, error = ipam.auto_allocate_ip(
|
||||
network_id=request.network_id,
|
||||
pool_id=request.pool_id,
|
||||
resource_type=request.resource_type,
|
||||
resource_id=request.resource_id,
|
||||
resource_name=request.resource_name,
|
||||
hostname=request.hostname,
|
||||
allocated_by=current_user.username,
|
||||
notes=request.notes
|
||||
)
|
||||
|
||||
if error:
|
||||
raise HTTPException(status_code=400, detail=error)
|
||||
|
||||
return allocation
|
||||
|
||||
|
||||
@router.put("/api/allocations/{allocation_id}", response_model=IPAMAllocationResponse)
|
||||
async def update_allocation(
|
||||
allocation_id: int,
|
||||
alloc_data: IPAMAllocationUpdate,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(PermissionChecker("ipam.manage"))
|
||||
):
|
||||
"""Update an allocation"""
|
||||
allocation = db.query(IPAMAllocation).filter(IPAMAllocation.id == allocation_id).first()
|
||||
if not allocation:
|
||||
raise HTTPException(status_code=404, detail="Allocation not found")
|
||||
|
||||
ipam = IPAMService(db)
|
||||
updated, error = ipam.update_allocation(
|
||||
allocation.ip_address,
|
||||
updated_by=current_user.username,
|
||||
**alloc_data.model_dump(exclude_unset=True)
|
||||
)
|
||||
|
||||
if error:
|
||||
raise HTTPException(status_code=400, detail=error)
|
||||
|
||||
return updated
|
||||
|
||||
|
||||
@router.delete("/api/allocations/{allocation_id}")
|
||||
async def delete_allocation(
|
||||
allocation_id: int,
|
||||
reason: Optional[str] = None,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(PermissionChecker("ipam.manage"))
|
||||
):
|
||||
"""Release/delete an IP allocation"""
|
||||
allocation = db.query(IPAMAllocation).filter(IPAMAllocation.id == allocation_id).first()
|
||||
if not allocation:
|
||||
raise HTTPException(status_code=404, detail="Allocation not found")
|
||||
|
||||
ipam = IPAMService(db)
|
||||
success, error = ipam.release_ip(
|
||||
allocation.ip_address,
|
||||
released_by=current_user.username,
|
||||
reason=reason
|
||||
)
|
||||
|
||||
if not success:
|
||||
raise HTTPException(status_code=400, detail=error)
|
||||
|
||||
return {"message": f"IP {allocation.ip_address} released"}
|
||||
|
||||
|
||||
@router.get("/api/allocations/next-available/{network_id}")
|
||||
async def get_next_available_ip(
|
||||
network_id: int,
|
||||
pool_id: Optional[int] = None,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(PermissionChecker("ipam.view"))
|
||||
):
|
||||
"""Get the next available IP in a network (without allocating)"""
|
||||
ipam = IPAMService(db)
|
||||
ip = ipam.get_next_available_ip(network_id, pool_id)
|
||||
|
||||
if not ip:
|
||||
raise HTTPException(status_code=404, detail="No available IP addresses")
|
||||
|
||||
return {"next_available_ip": ip}
|
||||
|
||||
|
||||
# ==================== History API ====================
|
||||
|
||||
@router.get("/api/history", response_model=List[IPAMHistoryResponse])
|
||||
async def get_history(
|
||||
network_id: Optional[int] = None,
|
||||
ip_address: Optional[str] = None,
|
||||
action: Optional[str] = None,
|
||||
limit: int = Query(default=100, le=500),
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(PermissionChecker("ipam.view"))
|
||||
):
|
||||
"""Get IPAM history"""
|
||||
query = db.query(IPAMHistory)
|
||||
|
||||
if network_id:
|
||||
query = query.filter(IPAMHistory.network_id == network_id)
|
||||
|
||||
if ip_address:
|
||||
query = query.filter(IPAMHistory.ip_address == ip_address)
|
||||
|
||||
if action:
|
||||
query = query.filter(IPAMHistory.action == action)
|
||||
|
||||
return query.order_by(IPAMHistory.performed_at.desc()).limit(limit).all()
|
||||
|
||||
|
||||
@router.get("/api/history/ip/{ip_address}", response_model=List[IPAMHistoryResponse])
|
||||
async def get_ip_history(
|
||||
ip_address: str,
|
||||
limit: int = Query(default=50, le=200),
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(PermissionChecker("ipam.view"))
|
||||
):
|
||||
"""Get history for a specific IP address"""
|
||||
ipam = IPAMService(db)
|
||||
return ipam.get_ip_history(ip_address, limit)
|
||||
|
||||
|
||||
# ==================== Utility API ====================
|
||||
|
||||
@router.get("/api/conflicts")
|
||||
async def detect_conflicts(
|
||||
network_id: Optional[int] = None,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(PermissionChecker("ipam.view"))
|
||||
):
|
||||
"""Detect IP address conflicts"""
|
||||
ipam = IPAMService(db)
|
||||
conflicts = ipam.detect_conflicts(network_id)
|
||||
return {"conflicts": conflicts, "count": len(conflicts)}
|
||||
|
||||
|
||||
@router.get("/api/summary")
|
||||
async def get_ipam_summary(
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(PermissionChecker("ipam.view"))
|
||||
):
|
||||
"""Get overall IPAM summary"""
|
||||
networks_count = db.query(IPAMNetwork).filter(IPAMNetwork.is_active == True).count()
|
||||
pools_count = db.query(IPAMPool).filter(IPAMPool.is_active == True).count()
|
||||
|
||||
total_allocated = db.query(IPAMAllocation).filter(IPAMAllocation.status == 'allocated').count()
|
||||
total_reserved = db.query(IPAMAllocation).filter(IPAMAllocation.status == 'reserved').count()
|
||||
|
||||
# Count by resource type
|
||||
vm_count = db.query(IPAMAllocation).filter(IPAMAllocation.resource_type == 'vm').count()
|
||||
lxc_count = db.query(IPAMAllocation).filter(IPAMAllocation.resource_type == 'lxc').count()
|
||||
physical_count = db.query(IPAMAllocation).filter(IPAMAllocation.resource_type == 'physical').count()
|
||||
|
||||
# Recent activity
|
||||
recent_allocations = db.query(IPAMHistory).filter(
|
||||
IPAMHistory.action == 'allocated'
|
||||
).order_by(IPAMHistory.performed_at.desc()).limit(5).all()
|
||||
|
||||
return {
|
||||
'networks_count': networks_count,
|
||||
'pools_count': pools_count,
|
||||
'total_allocated': total_allocated,
|
||||
'total_reserved': total_reserved,
|
||||
'vm_count': vm_count,
|
||||
'lxc_count': lxc_count,
|
||||
'physical_count': physical_count,
|
||||
'recent_allocations': [
|
||||
{
|
||||
'ip': h.ip_address,
|
||||
'resource': h.resource_name,
|
||||
'by': h.performed_by,
|
||||
'at': h.performed_at.isoformat() if h.performed_at else None
|
||||
} for h in recent_allocations
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
# ==================== Maintenance API ====================
|
||||
|
||||
@router.get("/api/orphans")
|
||||
async def get_orphan_allocations(
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(PermissionChecker("ipam.manage"))
|
||||
):
|
||||
"""
|
||||
Get orphan IPAM allocations - IPs allocated to VMs that no longer exist.
|
||||
"""
|
||||
orphans = []
|
||||
|
||||
# 1. Allocations with proxmox_vmid but VM doesn't exist or is deleted
|
||||
allocations_with_vmid = db.query(IPAMAllocation).filter(
|
||||
IPAMAllocation.proxmox_vmid.isnot(None),
|
||||
IPAMAllocation.proxmox_server_id.isnot(None),
|
||||
IPAMAllocation.status.in_(['allocated', 'reserved'])
|
||||
).all()
|
||||
|
||||
for alloc in allocations_with_vmid:
|
||||
vm = db.query(VMInstance).filter(
|
||||
VMInstance.vmid == alloc.proxmox_vmid,
|
||||
VMInstance.server_id == alloc.proxmox_server_id,
|
||||
VMInstance.deleted_at.is_(None)
|
||||
).first()
|
||||
|
||||
if not vm:
|
||||
orphans.append({
|
||||
'id': alloc.id,
|
||||
'ip_address': alloc.ip_address,
|
||||
'resource_name': alloc.resource_name,
|
||||
'resource_type': alloc.resource_type,
|
||||
'proxmox_vmid': alloc.proxmox_vmid,
|
||||
'proxmox_server_id': alloc.proxmox_server_id,
|
||||
'reason': 'VM/LXC not found or deleted'
|
||||
})
|
||||
|
||||
# 2. Allocations to non-existent servers
|
||||
allocations_with_server = db.query(IPAMAllocation).filter(
|
||||
IPAMAllocation.proxmox_server_id.isnot(None),
|
||||
IPAMAllocation.status.in_(['allocated', 'reserved'])
|
||||
).all()
|
||||
|
||||
server_ids = {a.proxmox_server_id for a in allocations_with_server}
|
||||
existing_servers = {s.id for s in db.query(ProxmoxServer.id).filter(ProxmoxServer.id.in_(server_ids)).all()}
|
||||
|
||||
for alloc in allocations_with_server:
|
||||
if alloc.proxmox_server_id not in existing_servers:
|
||||
# Check if not already in orphans
|
||||
if not any(o['id'] == alloc.id for o in orphans):
|
||||
orphans.append({
|
||||
'id': alloc.id,
|
||||
'ip_address': alloc.ip_address,
|
||||
'resource_name': alloc.resource_name,
|
||||
'resource_type': alloc.resource_type,
|
||||
'proxmox_vmid': alloc.proxmox_vmid,
|
||||
'proxmox_server_id': alloc.proxmox_server_id,
|
||||
'reason': f'Server {alloc.proxmox_server_id} not found'
|
||||
})
|
||||
|
||||
return {
|
||||
'orphans': orphans,
|
||||
'count': len(orphans)
|
||||
}
|
||||
|
||||
|
||||
@router.post("/api/cleanup-orphans")
|
||||
async def cleanup_orphan_allocations(
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(PermissionChecker("ipam.manage"))
|
||||
):
|
||||
"""
|
||||
Clean up orphan IPAM allocations - release IPs for VMs that no longer exist.
|
||||
"""
|
||||
ipam = IPAMService(db)
|
||||
released = []
|
||||
errors = []
|
||||
|
||||
# Get orphans
|
||||
orphans_result = await get_orphan_allocations(db, current_user)
|
||||
orphans = orphans_result['orphans']
|
||||
|
||||
for orphan in orphans:
|
||||
try:
|
||||
success, error = ipam.release_ip(
|
||||
ip_address=orphan['ip_address'],
|
||||
released_by=current_user.username,
|
||||
reason=f"Orphan cleanup: {orphan['reason']}"
|
||||
)
|
||||
if success:
|
||||
released.append(orphan['ip_address'])
|
||||
logger.info(f"Released orphan IP {orphan['ip_address']} by {current_user.username}")
|
||||
else:
|
||||
errors.append({'ip': orphan['ip_address'], 'error': error})
|
||||
except Exception as e:
|
||||
errors.append({'ip': orphan['ip_address'], 'error': str(e)})
|
||||
|
||||
return {
|
||||
'released': released,
|
||||
'released_count': len(released),
|
||||
'errors': errors,
|
||||
'error_count': len(errors)
|
||||
}
|
||||
|
||||
|
||||
@router.get("/api/unlinked")
|
||||
async def get_unlinked_allocations(
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(PermissionChecker("ipam.manage"))
|
||||
):
|
||||
"""
|
||||
Get IPAM allocations without proxmox_vmid that can be linked to existing VMs by name.
|
||||
"""
|
||||
unlinked = []
|
||||
|
||||
# Allocations without proxmox_vmid
|
||||
allocations = db.query(IPAMAllocation).filter(
|
||||
IPAMAllocation.proxmox_vmid.is_(None),
|
||||
IPAMAllocation.status.in_(['allocated', 'reserved'])
|
||||
).all()
|
||||
|
||||
for alloc in allocations:
|
||||
# Try to find matching VM by name
|
||||
vm = db.query(VMInstance).filter(
|
||||
VMInstance.name.ilike(alloc.resource_name),
|
||||
VMInstance.deleted_at.is_(None)
|
||||
).first()
|
||||
|
||||
unlinked.append({
|
||||
'id': alloc.id,
|
||||
'ip_address': alloc.ip_address,
|
||||
'resource_name': alloc.resource_name,
|
||||
'resource_type': alloc.resource_type,
|
||||
'can_link': vm is not None,
|
||||
'suggested_vmid': vm.vmid if vm else None,
|
||||
'suggested_server_id': vm.server_id if vm else None,
|
||||
'suggested_server_name': None # Will be filled below
|
||||
})
|
||||
|
||||
if vm:
|
||||
server = db.query(ProxmoxServer).filter(ProxmoxServer.id == vm.server_id).first()
|
||||
unlinked[-1]['suggested_server_name'] = server.name if server else None
|
||||
|
||||
return {
|
||||
'unlinked': unlinked,
|
||||
'count': len(unlinked),
|
||||
'linkable_count': sum(1 for u in unlinked if u['can_link'])
|
||||
}
|
||||
|
||||
|
||||
@router.post("/api/link-allocations")
|
||||
async def link_allocations_to_vms(
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(PermissionChecker("ipam.manage"))
|
||||
):
|
||||
"""
|
||||
Link IPAM allocations to real VMs by matching resource_name.
|
||||
"""
|
||||
linked = []
|
||||
not_found = []
|
||||
|
||||
# Get unlinked allocations
|
||||
allocations = db.query(IPAMAllocation).filter(
|
||||
IPAMAllocation.proxmox_vmid.is_(None),
|
||||
IPAMAllocation.status.in_(['allocated', 'reserved'])
|
||||
).all()
|
||||
|
||||
for alloc in allocations:
|
||||
# Find VM by name (case-insensitive)
|
||||
vm = db.query(VMInstance).filter(
|
||||
VMInstance.name.ilike(alloc.resource_name),
|
||||
VMInstance.deleted_at.is_(None)
|
||||
).first()
|
||||
|
||||
if vm:
|
||||
# Update allocation with VM info
|
||||
alloc.proxmox_vmid = vm.vmid
|
||||
alloc.proxmox_server_id = vm.server_id
|
||||
alloc.resource_id = vm.vmid
|
||||
|
||||
linked.append({
|
||||
'ip_address': alloc.ip_address,
|
||||
'resource_name': alloc.resource_name,
|
||||
'vmid': vm.vmid,
|
||||
'server_id': vm.server_id
|
||||
})
|
||||
logger.info(f"Linked IP {alloc.ip_address} to VM {vm.vmid} on server {vm.server_id}")
|
||||
else:
|
||||
not_found.append({
|
||||
'ip_address': alloc.ip_address,
|
||||
'resource_name': alloc.resource_name
|
||||
})
|
||||
|
||||
if linked:
|
||||
db.commit()
|
||||
|
||||
return {
|
||||
'linked': linked,
|
||||
'linked_count': len(linked),
|
||||
'not_found': not_found,
|
||||
'not_found_count': len(not_found)
|
||||
}
|
||||
|
||||
226
backend/app/api/logs.py
Normal file
226
backend/app/api/logs.py
Normal file
@@ -0,0 +1,226 @@
|
||||
"""
|
||||
Logs API endpoints
|
||||
View and manage audit logs
|
||||
"""
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Optional, List
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Request
|
||||
from fastapi.responses import HTMLResponse
|
||||
from fastapi.templating import Jinja2Templates
|
||||
from sqlalchemy.orm import Session
|
||||
from pydantic import BaseModel
|
||||
|
||||
from ..db import get_db
|
||||
from ..auth import get_current_user, PermissionChecker
|
||||
from ..models import User, AuditLog
|
||||
from ..logging_service import LoggingService
|
||||
from ..template_helpers import add_i18n_context
|
||||
|
||||
|
||||
router = APIRouter()
|
||||
templates = Jinja2Templates(directory="app/templates")
|
||||
|
||||
|
||||
# ==================== Schemas ====================
|
||||
|
||||
class LogResponse(BaseModel):
|
||||
id: int
|
||||
level: str
|
||||
category: str
|
||||
action: str
|
||||
message: str
|
||||
username: Optional[str] = None
|
||||
ip_address: Optional[str] = None
|
||||
user_agent: Optional[str] = None
|
||||
resource_type: Optional[str] = None
|
||||
resource_id: Optional[str] = None
|
||||
resource_name: Optional[str] = None
|
||||
details: Optional[dict] = None
|
||||
request_method: Optional[str] = None
|
||||
request_path: Optional[str] = None
|
||||
response_status: Optional[int] = None
|
||||
duration_ms: Optional[int] = None
|
||||
success: bool
|
||||
error_message: Optional[str] = None
|
||||
created_at: datetime
|
||||
# Enhanced logging fields
|
||||
request_id: Optional[str] = None
|
||||
session_id: Optional[str] = None
|
||||
geo_location: Optional[str] = None
|
||||
server_id: Optional[int] = None
|
||||
server_name: Optional[str] = None
|
||||
node_name: Optional[str] = None
|
||||
request_body: Optional[dict] = None
|
||||
response_body: Optional[dict] = None
|
||||
query_params: Optional[str] = None
|
||||
error_traceback: Optional[str] = None
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
|
||||
class LogsListResponse(BaseModel):
|
||||
logs: List[LogResponse]
|
||||
total: int
|
||||
page: int
|
||||
limit: int
|
||||
pages: int
|
||||
|
||||
|
||||
class LogStatsResponse(BaseModel):
|
||||
period_hours: int
|
||||
total: int
|
||||
by_level: dict
|
||||
by_category: dict
|
||||
errors_count: int
|
||||
failed_logins: int
|
||||
recent_errors: List[dict]
|
||||
|
||||
|
||||
# ==================== HTML Endpoints ====================
|
||||
|
||||
@router.get("/", response_class=HTMLResponse)
|
||||
async def logs_page(request: Request):
|
||||
"""Render logs page"""
|
||||
from ..i18n import t
|
||||
lang = request.cookies.get("language", "ru")
|
||||
context = {
|
||||
"request": request,
|
||||
"title": t("nav_logs", lang),
|
||||
"page_title": f"📋 {t('system_logs', lang)}"
|
||||
}
|
||||
context = add_i18n_context(request, context)
|
||||
return templates.TemplateResponse("logs.html", context)
|
||||
|
||||
|
||||
# ==================== API Endpoints ====================
|
||||
|
||||
@router.get("/api/logs", response_model=LogsListResponse)
|
||||
async def get_logs(
|
||||
level: Optional[str] = Query(None, description="Filter by log level"),
|
||||
category: Optional[str] = Query(None, description="Filter by category"),
|
||||
username: Optional[str] = Query(None, description="Filter by username"),
|
||||
ip: Optional[str] = Query(None, description="Filter by IP address"),
|
||||
resource_type: Optional[str] = Query(None, description="Filter by resource type"),
|
||||
resource_id: Optional[str] = Query(None, description="Filter by resource ID"),
|
||||
date_from: Optional[str] = Query(None, description="Filter from date (YYYY-MM-DD)"),
|
||||
date_to: Optional[str] = Query(None, description="Filter to date (YYYY-MM-DD)"),
|
||||
search: Optional[str] = Query(None, description="Search in message"),
|
||||
page: int = Query(1, ge=1, description="Page number"),
|
||||
limit: int = Query(50, ge=1, le=500, description="Items per page"),
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(PermissionChecker("logs.view"))
|
||||
):
|
||||
"""Get logs with filtering and pagination"""
|
||||
|
||||
# Parse dates
|
||||
parsed_date_from = None
|
||||
parsed_date_to = None
|
||||
|
||||
if date_from:
|
||||
try:
|
||||
parsed_date_from = datetime.strptime(date_from, "%Y-%m-%d")
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=400, detail="Invalid date_from format. Use YYYY-MM-DD")
|
||||
|
||||
if date_to:
|
||||
try:
|
||||
parsed_date_to = datetime.strptime(date_to, "%Y-%m-%d") + timedelta(days=1) # Include the whole day
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=400, detail="Invalid date_to format. Use YYYY-MM-DD")
|
||||
|
||||
# Calculate offset
|
||||
offset = (page - 1) * limit
|
||||
|
||||
# Get logs
|
||||
logs, total = LoggingService.get_logs(
|
||||
db=db,
|
||||
level=level,
|
||||
category=category,
|
||||
username=username,
|
||||
ip_address=ip,
|
||||
resource_type=resource_type,
|
||||
resource_id=resource_id,
|
||||
date_from=parsed_date_from,
|
||||
date_to=parsed_date_to,
|
||||
search=search,
|
||||
limit=limit,
|
||||
offset=offset
|
||||
)
|
||||
|
||||
# Calculate total pages
|
||||
pages = (total + limit - 1) // limit if total > 0 else 1
|
||||
|
||||
return LogsListResponse(
|
||||
logs=[LogResponse.model_validate(log) for log in logs],
|
||||
total=total,
|
||||
page=page,
|
||||
limit=limit,
|
||||
pages=pages
|
||||
)
|
||||
|
||||
|
||||
@router.get("/api/stats", response_model=LogStatsResponse)
|
||||
async def get_log_stats(
|
||||
hours: int = Query(24, ge=1, le=720, description="Period in hours"),
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(PermissionChecker("logs.view"))
|
||||
):
|
||||
"""Get log statistics for the specified period"""
|
||||
stats = LoggingService.get_stats(db, hours=hours)
|
||||
return LogStatsResponse(**stats)
|
||||
|
||||
|
||||
@router.delete("/api/logs")
|
||||
async def cleanup_logs(
|
||||
days: int = Query(30, ge=1, le=365, description="Delete logs older than this many days"),
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(PermissionChecker("logs.delete"))
|
||||
):
|
||||
"""Delete old logs (admin only)"""
|
||||
if not current_user.is_admin:
|
||||
raise HTTPException(status_code=403, detail="Only admins can delete logs")
|
||||
|
||||
deleted = LoggingService.cleanup_old_logs(db, days=days)
|
||||
|
||||
# Log this action
|
||||
LoggingService.log(
|
||||
db=db,
|
||||
level=LoggingService.WARNING,
|
||||
category=LoggingService.SYSTEM,
|
||||
action="logs_cleanup",
|
||||
message=f"Удалено {deleted} логов старше {days} дней",
|
||||
username=current_user.username
|
||||
)
|
||||
|
||||
return {"deleted": deleted, "message": f"Удалено {deleted} логов старше {days} дней"}
|
||||
|
||||
|
||||
@router.get("/api/levels")
|
||||
async def get_log_levels():
|
||||
"""Get available log levels"""
|
||||
return {
|
||||
"levels": [
|
||||
{"value": "debug", "label": "Debug", "color": "#6c757d"},
|
||||
{"value": "info", "label": "Info", "color": "#0dcaf0"},
|
||||
{"value": "warning", "label": "Warning", "color": "#ffc107"},
|
||||
{"value": "error", "label": "Error", "color": "#dc3545"},
|
||||
{"value": "critical", "label": "Critical", "color": "#dc3545"}
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
@router.get("/api/categories")
|
||||
async def get_log_categories():
|
||||
"""Get available log categories"""
|
||||
return {
|
||||
"categories": [
|
||||
{"value": "auth", "label": "🔐 Авторизация"},
|
||||
{"value": "proxmox", "label": "🖥️ Proxmox"},
|
||||
{"value": "ipam", "label": "🌐 IPAM"},
|
||||
{"value": "system", "label": "⚙️ Система"},
|
||||
{"value": "api", "label": "🔌 API"},
|
||||
{"value": "docker", "label": "🐳 Docker"}
|
||||
]
|
||||
}
|
||||
253
backend/app/api/notifications.py
Normal file
253
backend/app/api/notifications.py
Normal file
@@ -0,0 +1,253 @@
|
||||
"""
|
||||
API routes for notifications
|
||||
"""
|
||||
|
||||
from typing import List, Optional
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..db import get_db
|
||||
from ..auth import get_current_user, PermissionChecker
|
||||
from ..models import User
|
||||
from ..services.notification_service import NotificationService
|
||||
from ..schemas import (
|
||||
NotificationResponse,
|
||||
NotificationListResponse,
|
||||
NotificationUpdate,
|
||||
NotificationPreferenceResponse,
|
||||
NotificationPreferenceUpdate
|
||||
)
|
||||
|
||||
router = APIRouter(prefix="/api/notifications", tags=["notifications"])
|
||||
|
||||
|
||||
@router.get("/", response_model=NotificationListResponse)
|
||||
async def get_notifications(
|
||||
unread_only: bool = Query(False, description="Only unread notifications"),
|
||||
level: Optional[str] = Query(None, description="Filter by level: critical, warning, info, success"),
|
||||
limit: int = Query(50, ge=1, le=100),
|
||||
offset: int = Query(0, ge=0),
|
||||
current_user: User = Depends(PermissionChecker("notifications.manage")),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""
|
||||
Get user notifications with filters
|
||||
|
||||
- **unread_only**: Return only unread notifications
|
||||
- **level**: Filter by notification level
|
||||
- **limit**: Maximum number of notifications (1-100)
|
||||
- **offset**: Offset for pagination
|
||||
"""
|
||||
notifications, total = NotificationService.get_user_notifications(
|
||||
db,
|
||||
user_id=current_user.id,
|
||||
unread_only=unread_only,
|
||||
level=level,
|
||||
limit=limit,
|
||||
offset=offset
|
||||
)
|
||||
|
||||
unread_count = NotificationService.get_unread_count(db, current_user.id)
|
||||
|
||||
return {
|
||||
"total": total,
|
||||
"unread_count": unread_count,
|
||||
"notifications": [n.to_dict() for n in notifications]
|
||||
}
|
||||
|
||||
|
||||
@router.get("/unread-count")
|
||||
async def get_unread_count(
|
||||
current_user: User = Depends(PermissionChecker("notifications.manage")),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""Get count of unread notifications"""
|
||||
count = NotificationService.get_unread_count(db, current_user.id)
|
||||
return {"count": count}
|
||||
|
||||
|
||||
@router.patch("/{notification_id}/read", response_model=NotificationResponse)
|
||||
async def mark_notification_as_read(
|
||||
notification_id: int,
|
||||
current_user: User = Depends(PermissionChecker("notifications.manage")),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""Mark notification as read"""
|
||||
notification = NotificationService.mark_as_read(
|
||||
db,
|
||||
notification_id=notification_id,
|
||||
user_id=current_user.id
|
||||
)
|
||||
|
||||
if not notification:
|
||||
raise HTTPException(status_code=404, detail="Notification not found")
|
||||
|
||||
return notification.to_dict()
|
||||
|
||||
|
||||
@router.post("/mark-all-read")
|
||||
async def mark_all_notifications_as_read(
|
||||
current_user: User = Depends(PermissionChecker("notifications.manage")),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""Mark all notifications as read"""
|
||||
count = NotificationService.mark_all_as_read(db, current_user.id)
|
||||
return {"message": f"{count} notifications marked as read"}
|
||||
|
||||
|
||||
@router.delete("/{notification_id}")
|
||||
async def delete_notification(
|
||||
notification_id: int,
|
||||
current_user: User = Depends(PermissionChecker("notifications.manage")),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""Delete a notification"""
|
||||
success = NotificationService.delete_notification(
|
||||
db,
|
||||
notification_id=notification_id,
|
||||
user_id=current_user.id
|
||||
)
|
||||
|
||||
if not success:
|
||||
raise HTTPException(status_code=404, detail="Notification not found")
|
||||
|
||||
return {"message": "Notification deleted"}
|
||||
|
||||
|
||||
@router.delete("/read/all")
|
||||
async def delete_all_read_notifications(
|
||||
current_user: User = Depends(PermissionChecker("notifications.manage")),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""Delete all read notifications"""
|
||||
count = NotificationService.delete_all_read(db, current_user.id)
|
||||
return {"message": f"{count} notifications deleted"}
|
||||
|
||||
|
||||
# Preferences endpoints
|
||||
|
||||
@router.get("/preferences", response_model=NotificationPreferenceResponse)
|
||||
async def get_notification_preferences(
|
||||
current_user: User = Depends(PermissionChecker("notifications.manage")),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""Get user notification preferences"""
|
||||
prefs = NotificationService.get_user_preferences(db, current_user.id)
|
||||
return prefs.to_dict()
|
||||
|
||||
|
||||
@router.put("/preferences", response_model=NotificationPreferenceResponse)
|
||||
async def update_notification_preferences(
|
||||
prefs_data: NotificationPreferenceUpdate,
|
||||
current_user: User = Depends(PermissionChecker("notifications.manage")),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""Update user notification preferences"""
|
||||
prefs = NotificationService.update_user_preferences(
|
||||
db,
|
||||
user_id=current_user.id,
|
||||
prefs_data=prefs_data
|
||||
)
|
||||
return prefs.to_dict()
|
||||
|
||||
|
||||
# ============================================
|
||||
# Channel management endpoints
|
||||
# ============================================
|
||||
|
||||
@router.get("/channels/status")
|
||||
async def get_channels_status(
|
||||
current_user: User = Depends(PermissionChecker("notifications.manage")),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""
|
||||
Get status of all notification channels
|
||||
|
||||
Returns configuration and status for:
|
||||
- Email (SMTP)
|
||||
- Telegram
|
||||
- In-app notifications
|
||||
"""
|
||||
status = await NotificationService.get_channels_status(db, current_user.id)
|
||||
return status
|
||||
|
||||
|
||||
@router.post("/test")
|
||||
async def send_test_notification(
|
||||
channel: str = Query("all", description="Channel to test: all, email, telegram, inapp"),
|
||||
current_user: User = Depends(PermissionChecker("notifications.manage")),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""
|
||||
Send a test notification through specified channel(s)
|
||||
|
||||
- **channel**: Which channel to test (all, email, telegram, inapp)
|
||||
"""
|
||||
if channel not in ["all", "email", "telegram", "inapp"]:
|
||||
raise HTTPException(status_code=400, detail="Invalid channel. Use: all, email, telegram, inapp")
|
||||
|
||||
results = await NotificationService.send_test_notification(db, current_user.id, channel)
|
||||
return results
|
||||
|
||||
|
||||
@router.post("/telegram/verify")
|
||||
async def verify_telegram_chat(
|
||||
chat_id: str = Query(..., description="Telegram chat ID to verify"),
|
||||
current_user: User = Depends(PermissionChecker("notifications.manage")),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""
|
||||
Verify Telegram chat ID and save to preferences
|
||||
|
||||
Steps to get your chat_id:
|
||||
1. Start a conversation with @userinfobot in Telegram
|
||||
2. It will tell you your chat ID
|
||||
3. Make sure you've sent /start to your notification bot first
|
||||
"""
|
||||
from ..services.notification_channels import get_telegram_channel
|
||||
|
||||
tg_ch = get_telegram_channel()
|
||||
if not tg_ch.is_configured():
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="Telegram бот не настроен. Добавьте токен в Настройки → Уведомления."
|
||||
)
|
||||
|
||||
# Try to send test message
|
||||
success = await tg_ch.verify_chat_id(chat_id)
|
||||
|
||||
if not success:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="Failed to send message to this chat_id. Make sure you've started the bot with /start"
|
||||
)
|
||||
|
||||
# Save chat_id to preferences
|
||||
prefs = NotificationService.get_user_preferences(db, current_user.id)
|
||||
prefs.telegram_chat_id = chat_id
|
||||
prefs.telegram_enabled = True
|
||||
db.commit()
|
||||
|
||||
return {
|
||||
"success": True,
|
||||
"message": "Telegram verified and enabled!",
|
||||
"chat_id": chat_id
|
||||
}
|
||||
|
||||
|
||||
@router.get("/telegram/bot-info")
|
||||
async def get_telegram_bot_info(
|
||||
current_user: User = Depends(PermissionChecker("notifications.manage"))
|
||||
):
|
||||
"""Get information about the configured Telegram bot"""
|
||||
from ..services.notification_channels import get_telegram_channel
|
||||
|
||||
tg_ch = get_telegram_channel()
|
||||
if not tg_ch.is_configured():
|
||||
return {"configured": False, "bot_info": None}
|
||||
|
||||
bot_info = await tg_ch.get_bot_info()
|
||||
return {
|
||||
"configured": True,
|
||||
"bot_info": bot_info
|
||||
}
|
||||
5418
backend/app/api/proxmox.py
Normal file
5418
backend/app/api/proxmox.py
Normal file
File diff suppressed because it is too large
Load Diff
754
backend/app/api/settings.py
Normal file
754
backend/app/api/settings.py
Normal file
@@ -0,0 +1,754 @@
|
||||
"""
|
||||
Settings API endpoints
|
||||
User account settings and panel configuration
|
||||
"""
|
||||
|
||||
from datetime import datetime
|
||||
from fastapi import APIRouter, Depends, HTTPException, status, Request, Query
|
||||
from fastapi.responses import HTMLResponse, Response
|
||||
from fastapi.templating import Jinja2Templates
|
||||
from sqlalchemy.orm import Session
|
||||
from pydantic import BaseModel, EmailStr, Field
|
||||
from typing import Optional
|
||||
|
||||
from ..db import get_db
|
||||
from ..models import User, PanelSettings
|
||||
from ..auth import get_current_user, get_current_user_optional, get_password_hash, verify_password, PermissionChecker
|
||||
from ..logging_service import LoggingService
|
||||
from ..template_helpers import add_i18n_context
|
||||
from ..i18n import I18nService, t
|
||||
from ..services.logo_service import LogoService
|
||||
from ..services.update_service import (
|
||||
get_current_version,
|
||||
check_for_updates,
|
||||
perform_update,
|
||||
get_update_status,
|
||||
reset_update_status
|
||||
)
|
||||
|
||||
|
||||
def get_local_time() -> str:
|
||||
"""Get current local time formatted string"""
|
||||
return datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
||||
|
||||
|
||||
router = APIRouter()
|
||||
templates = Jinja2Templates(directory="app/templates")
|
||||
|
||||
|
||||
# ==================== Helper Functions ====================
|
||||
|
||||
def get_setting(db: Session, key: str, default: str = None) -> str:
|
||||
"""Get setting value from database"""
|
||||
setting = db.query(PanelSettings).filter(PanelSettings.key == key).first()
|
||||
if setting:
|
||||
return setting.value
|
||||
return default
|
||||
|
||||
|
||||
def set_setting(db: Session, key: str, value: str, description: str = None):
|
||||
"""Set setting value in database"""
|
||||
setting = db.query(PanelSettings).filter(PanelSettings.key == key).first()
|
||||
if setting:
|
||||
setting.value = value
|
||||
if description:
|
||||
setting.description = description
|
||||
else:
|
||||
setting = PanelSettings(key=key, value=value, description=description)
|
||||
db.add(setting)
|
||||
db.commit()
|
||||
|
||||
|
||||
# ==================== Schemas ====================
|
||||
|
||||
class UpdateProfileRequest(BaseModel):
|
||||
full_name: Optional[str] = Field(None, max_length=100)
|
||||
email: Optional[EmailStr] = None
|
||||
|
||||
|
||||
class ChangePasswordRequest(BaseModel):
|
||||
current_password: str = Field(..., min_length=1)
|
||||
new_password: str = Field(..., min_length=6)
|
||||
confirm_password: str = Field(..., min_length=6)
|
||||
|
||||
|
||||
class PanelSettingsResponse(BaseModel):
|
||||
panel_name: str
|
||||
refresh_interval: int # seconds
|
||||
log_retention_days: int
|
||||
language: str # ru or en
|
||||
|
||||
|
||||
class UpdatePanelSettingsRequest(BaseModel):
|
||||
refresh_interval: Optional[int] = Field(None, ge=1, le=60)
|
||||
log_retention_days: Optional[int] = Field(None, ge=1, le=365)
|
||||
language: Optional[str] = Field(None, pattern='^(ru|en)$')
|
||||
|
||||
|
||||
# ==================== Logo Protection ====================
|
||||
|
||||
@router.get("/api/logo.png")
|
||||
async def get_protected_logo():
|
||||
"""
|
||||
Get protected logo image.
|
||||
Returns the verified original logo or a fallback if tampered.
|
||||
"""
|
||||
logo_bytes = LogoService.get_logo_bytes()
|
||||
return Response(
|
||||
content=logo_bytes,
|
||||
media_type="image/png",
|
||||
headers={
|
||||
"Cache-Control": "public, max-age=3600",
|
||||
"X-Logo-Protected": "true"
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
# ==================== HTML Pages ====================
|
||||
|
||||
@router.get("/", response_class=HTMLResponse)
|
||||
async def settings_page(
|
||||
request: Request,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: Optional[User] = Depends(get_current_user_optional)
|
||||
):
|
||||
"""Render settings page"""
|
||||
from ..template_helpers import get_language
|
||||
lang = get_language(request)
|
||||
context = {
|
||||
"request": request,
|
||||
"title": t("nav_settings", lang),
|
||||
"page_title": f"⚙️ {t('nav_settings', lang)}",
|
||||
"current_user": current_user
|
||||
}
|
||||
# Add i18n context
|
||||
context = add_i18n_context(request, context)
|
||||
|
||||
return templates.TemplateResponse("settings.html", context)
|
||||
|
||||
|
||||
# ==================== User Account Settings ====================
|
||||
|
||||
@router.get("/api/profile")
|
||||
async def get_profile(
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Get current user profile"""
|
||||
return {
|
||||
"id": current_user.id,
|
||||
"username": current_user.username,
|
||||
"email": current_user.email,
|
||||
"full_name": current_user.full_name,
|
||||
"is_admin": current_user.is_admin,
|
||||
"is_active": current_user.is_active,
|
||||
"created_at": current_user.created_at.isoformat() if current_user.created_at else None,
|
||||
"last_login": current_user.last_login.isoformat() if current_user.last_login else None
|
||||
}
|
||||
|
||||
|
||||
@router.put("/api/profile")
|
||||
async def update_profile(
|
||||
data: UpdateProfileRequest,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Update user profile"""
|
||||
updated_fields = []
|
||||
|
||||
if data.full_name is not None:
|
||||
current_user.full_name = data.full_name
|
||||
updated_fields.append("full_name")
|
||||
|
||||
if data.email is not None:
|
||||
# Check if email is already taken by another user
|
||||
existing = db.query(User).filter(
|
||||
User.email == data.email,
|
||||
User.id != current_user.id
|
||||
).first()
|
||||
if existing:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Email уже используется другим пользователем"
|
||||
)
|
||||
current_user.email = data.email
|
||||
updated_fields.append("email")
|
||||
|
||||
if updated_fields:
|
||||
db.commit()
|
||||
db.refresh(current_user)
|
||||
|
||||
# Log profile update
|
||||
LoggingService.log(
|
||||
db=db,
|
||||
level=LoggingService.INFO,
|
||||
category=LoggingService.AUTH,
|
||||
action="profile_update",
|
||||
message=f"Пользователь {current_user.username} обновил профиль: {', '.join(updated_fields)}",
|
||||
username=current_user.username,
|
||||
user_id=current_user.id
|
||||
)
|
||||
|
||||
return {
|
||||
"message": "Профиль обновлён",
|
||||
"updated_fields": updated_fields
|
||||
}
|
||||
|
||||
|
||||
@router.post("/api/change-password")
|
||||
async def change_password(
|
||||
data: ChangePasswordRequest,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Change user password"""
|
||||
|
||||
# Verify current password
|
||||
if not verify_password(data.current_password, current_user.hashed_password):
|
||||
LoggingService.log(
|
||||
db=db,
|
||||
level=LoggingService.WARNING,
|
||||
category=LoggingService.AUTH,
|
||||
action="password_change_failed",
|
||||
message=f"Неудачная попытка смены пароля (неверный текущий пароль)",
|
||||
username=current_user.username,
|
||||
user_id=current_user.id,
|
||||
success=False
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Неверный текущий пароль"
|
||||
)
|
||||
|
||||
# Check new password confirmation
|
||||
if data.new_password != data.confirm_password:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Новые пароли не совпадают"
|
||||
)
|
||||
|
||||
# Update password
|
||||
current_user.hashed_password = get_password_hash(data.new_password)
|
||||
db.commit()
|
||||
|
||||
# Log password change
|
||||
LoggingService.log(
|
||||
db=db,
|
||||
level=LoggingService.INFO,
|
||||
category=LoggingService.AUTH,
|
||||
action="password_change",
|
||||
message=f"Пользователь {current_user.username} изменил пароль",
|
||||
username=current_user.username,
|
||||
user_id=current_user.id,
|
||||
success=True
|
||||
)
|
||||
|
||||
return {"message": "Пароль успешно изменён"}
|
||||
|
||||
|
||||
# ==================== Panel Settings ====================
|
||||
|
||||
@router.get("/api/panel", response_model=PanelSettingsResponse)
|
||||
async def get_panel_settings(
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(PermissionChecker("settings.view"))
|
||||
):
|
||||
"""Get panel settings"""
|
||||
from ..config import settings
|
||||
|
||||
# Get settings from database or use defaults
|
||||
refresh_interval = get_setting(db, "refresh_interval", "5")
|
||||
log_retention_days = get_setting(db, "log_retention_days", "30")
|
||||
language = get_setting(db, "language", "ru")
|
||||
|
||||
return {
|
||||
"panel_name": settings.PANEL_NAME,
|
||||
"refresh_interval": int(refresh_interval),
|
||||
"log_retention_days": int(log_retention_days),
|
||||
"language": language
|
||||
}
|
||||
|
||||
|
||||
@router.put("/api/panel")
|
||||
async def update_panel_settings(
|
||||
data: UpdatePanelSettingsRequest,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(PermissionChecker("settings.panel"))
|
||||
):
|
||||
"""Update panel settings (requires settings.panel permission)"""
|
||||
updated_fields = []
|
||||
|
||||
# Save settings to database
|
||||
if data.refresh_interval is not None:
|
||||
set_setting(db, "refresh_interval", str(data.refresh_interval), "Интервал обновления данных (секунды)")
|
||||
updated_fields.append(f"refresh_interval={data.refresh_interval}")
|
||||
|
||||
if data.log_retention_days is not None:
|
||||
set_setting(db, "log_retention_days", str(data.log_retention_days), "Срок хранения логов (дни)")
|
||||
updated_fields.append(f"log_retention_days={data.log_retention_days}")
|
||||
|
||||
if data.language is not None:
|
||||
set_setting(db, "language", data.language, "Язык интерфейса панели")
|
||||
updated_fields.append(f"language={data.language}")
|
||||
|
||||
if updated_fields:
|
||||
# Log settings change
|
||||
LoggingService.log(
|
||||
db=db,
|
||||
level=LoggingService.INFO,
|
||||
category=LoggingService.SYSTEM,
|
||||
action="panel_settings_update",
|
||||
message=f"Администратор {current_user.username} обновил настройки панели: {', '.join(updated_fields)}",
|
||||
username=current_user.username,
|
||||
user_id=current_user.id,
|
||||
details=data.dict(exclude_none=True)
|
||||
)
|
||||
|
||||
return {
|
||||
"message": "Настройки панели обновлены",
|
||||
"updated_fields": updated_fields
|
||||
}
|
||||
|
||||
|
||||
@router.post("/api/cleanup-logs")
|
||||
async def cleanup_old_logs(
|
||||
days: int = 30,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Manually cleanup old logs (admin only)"""
|
||||
|
||||
if not current_user.is_admin:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Только администраторы могут очищать логи"
|
||||
)
|
||||
|
||||
deleted = LoggingService.cleanup_old_logs(db, days=days)
|
||||
|
||||
# Log the cleanup action
|
||||
LoggingService.log(
|
||||
db=db,
|
||||
level=LoggingService.WARNING,
|
||||
category=LoggingService.SYSTEM,
|
||||
action="logs_cleanup",
|
||||
message=f"Администратор {current_user.username} очистил {deleted} логов старше {days} дней",
|
||||
username=current_user.username,
|
||||
user_id=current_user.id,
|
||||
details={"deleted_count": deleted, "older_than_days": days}
|
||||
)
|
||||
|
||||
return {
|
||||
"message": f"Удалено {deleted} логов старше {days} дней",
|
||||
"deleted": deleted
|
||||
}
|
||||
|
||||
|
||||
# ==================== Translations API ====================
|
||||
|
||||
@router.get("/api/translations/{lang}")
|
||||
async def get_translations(lang: str):
|
||||
"""Get all translations for specific language"""
|
||||
if lang not in ["ru", "en"]:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Unsupported language. Use 'ru' or 'en'"
|
||||
)
|
||||
|
||||
return I18nService.get_all(lang)
|
||||
|
||||
|
||||
# ==================== Security Settings API ====================
|
||||
|
||||
class SecuritySettingsRequest(BaseModel):
|
||||
single_session_enabled: Optional[bool] = None
|
||||
|
||||
|
||||
@router.get("/api/security-settings")
|
||||
async def get_security_settings(
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Get security settings (admin only)"""
|
||||
|
||||
if not current_user.is_admin:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Только администраторы могут просматривать настройки безопасности"
|
||||
)
|
||||
|
||||
from ..services.security_service import SecurityService
|
||||
|
||||
return {
|
||||
"single_session_enabled": SecurityService.get_setting_bool(db, "single_session_enabled", False)
|
||||
}
|
||||
|
||||
|
||||
@router.put("/api/security-settings")
|
||||
async def update_security_settings(
|
||||
data: SecuritySettingsRequest,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Update security settings (admin only)"""
|
||||
|
||||
if not current_user.is_admin:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Только администраторы могут изменять настройки безопасности"
|
||||
)
|
||||
|
||||
from ..services.security_service import SecurityService
|
||||
|
||||
updated_fields = []
|
||||
|
||||
if data.single_session_enabled is not None:
|
||||
SecurityService.update_setting(db, "single_session_enabled", str(data.single_session_enabled).lower())
|
||||
updated_fields.append(f"single_session_enabled={data.single_session_enabled}")
|
||||
|
||||
if updated_fields:
|
||||
# Log settings change
|
||||
LoggingService.log(
|
||||
db=db,
|
||||
level=LoggingService.INFO,
|
||||
category=LoggingService.AUTH,
|
||||
action="security_settings_update",
|
||||
message=f"Администратор {current_user.username} обновил настройки безопасности: {', '.join(updated_fields)}",
|
||||
username=current_user.username,
|
||||
user_id=current_user.id,
|
||||
details=data.model_dump(exclude_none=True)
|
||||
)
|
||||
|
||||
return {
|
||||
"message": "Настройки безопасности обновлены",
|
||||
"updated_fields": updated_fields
|
||||
}
|
||||
|
||||
|
||||
# ==================== Notification Channel Settings API ====================
|
||||
|
||||
class SMTPSettingsRequest(BaseModel):
|
||||
smtp_host: Optional[str] = Field(None, max_length=255)
|
||||
smtp_port: Optional[int] = Field(None, ge=1, le=65535)
|
||||
smtp_user: Optional[str] = Field(None, max_length=255)
|
||||
smtp_password: Optional[str] = Field(None, max_length=255)
|
||||
smtp_from: Optional[str] = Field(None, max_length=255)
|
||||
smtp_tls: Optional[bool] = None
|
||||
|
||||
|
||||
class TelegramSettingsRequest(BaseModel):
|
||||
telegram_bot_token: Optional[str] = Field(None, max_length=255)
|
||||
|
||||
|
||||
@router.get("/api/notification-channels")
|
||||
async def get_notification_channel_settings(
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Get notification channel settings (admin only)"""
|
||||
|
||||
if not current_user.is_admin:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Только администраторы могут просматривать настройки уведомлений"
|
||||
)
|
||||
|
||||
return {
|
||||
"smtp": {
|
||||
"host": get_setting(db, "smtp_host", ""),
|
||||
"port": int(get_setting(db, "smtp_port", "587") or "587"),
|
||||
"user": get_setting(db, "smtp_user", ""),
|
||||
"password": "***" if get_setting(db, "smtp_password") else "",
|
||||
"from": get_setting(db, "smtp_from", ""),
|
||||
"tls": get_setting(db, "smtp_tls", "true").lower() == "true"
|
||||
},
|
||||
"telegram": {
|
||||
"bot_token": "***" if get_setting(db, "telegram_bot_token") else "",
|
||||
"configured": bool(get_setting(db, "telegram_bot_token"))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@router.put("/api/notification-channels/smtp")
|
||||
async def update_smtp_settings(
|
||||
data: SMTPSettingsRequest,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Update SMTP settings (admin only)"""
|
||||
|
||||
if not current_user.is_admin:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Только администраторы могут изменять настройки SMTP"
|
||||
)
|
||||
|
||||
updated_fields = []
|
||||
|
||||
if data.smtp_host is not None:
|
||||
set_setting(db, "smtp_host", data.smtp_host, "SMTP сервер")
|
||||
updated_fields.append("smtp_host")
|
||||
|
||||
if data.smtp_port is not None:
|
||||
set_setting(db, "smtp_port", str(data.smtp_port), "SMTP порт")
|
||||
updated_fields.append("smtp_port")
|
||||
|
||||
if data.smtp_user is not None:
|
||||
set_setting(db, "smtp_user", data.smtp_user, "SMTP пользователь")
|
||||
updated_fields.append("smtp_user")
|
||||
|
||||
if data.smtp_password is not None:
|
||||
set_setting(db, "smtp_password", data.smtp_password, "SMTP пароль")
|
||||
updated_fields.append("smtp_password")
|
||||
|
||||
if data.smtp_from is not None:
|
||||
set_setting(db, "smtp_from", data.smtp_from, "Email отправителя")
|
||||
updated_fields.append("smtp_from")
|
||||
|
||||
if data.smtp_tls is not None:
|
||||
set_setting(db, "smtp_tls", str(data.smtp_tls).lower(), "Использовать TLS")
|
||||
updated_fields.append("smtp_tls")
|
||||
|
||||
if updated_fields:
|
||||
# Reload notification channels
|
||||
from ..services.notification_channels import reload_notification_channels
|
||||
reload_notification_channels()
|
||||
|
||||
# Log settings change
|
||||
LoggingService.log(
|
||||
db=db,
|
||||
level=LoggingService.INFO,
|
||||
category=LoggingService.SYSTEM,
|
||||
action="smtp_settings_update",
|
||||
message=f"Администратор {current_user.username} обновил настройки SMTP: {', '.join(updated_fields)}",
|
||||
username=current_user.username,
|
||||
user_id=current_user.id
|
||||
)
|
||||
|
||||
return {
|
||||
"message": "Настройки SMTP обновлены",
|
||||
"updated_fields": updated_fields
|
||||
}
|
||||
|
||||
|
||||
@router.put("/api/notification-channels/telegram")
|
||||
async def update_telegram_settings(
|
||||
data: TelegramSettingsRequest,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Update Telegram bot settings (admin only)"""
|
||||
|
||||
if not current_user.is_admin:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Только администраторы могут изменять настройки Telegram"
|
||||
)
|
||||
|
||||
updated_fields = []
|
||||
|
||||
if data.telegram_bot_token is not None:
|
||||
set_setting(db, "telegram_bot_token", data.telegram_bot_token, "Токен Telegram бота")
|
||||
updated_fields.append("telegram_bot_token")
|
||||
|
||||
if updated_fields:
|
||||
# Reload notification channels
|
||||
from ..services.notification_channels import reload_notification_channels
|
||||
reload_notification_channels()
|
||||
|
||||
# Log settings change
|
||||
LoggingService.log(
|
||||
db=db,
|
||||
level=LoggingService.INFO,
|
||||
category=LoggingService.SYSTEM,
|
||||
action="telegram_settings_update",
|
||||
message=f"Администратор {current_user.username} обновил настройки Telegram",
|
||||
username=current_user.username,
|
||||
user_id=current_user.id
|
||||
)
|
||||
|
||||
return {
|
||||
"message": "Настройки Telegram обновлены",
|
||||
"updated_fields": updated_fields
|
||||
}
|
||||
|
||||
|
||||
@router.post("/api/notification-channels/smtp/test")
|
||||
async def test_smtp_connection(
|
||||
test_email: str = Query(..., description="Email для отправки тестового письма"),
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Test SMTP connection by sending a test email (admin only)"""
|
||||
|
||||
if not current_user.is_admin:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Только администраторы могут тестировать SMTP"
|
||||
)
|
||||
|
||||
from ..services.notification_channels import get_email_channel
|
||||
|
||||
email_channel = get_email_channel()
|
||||
if not email_channel.is_configured():
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="SMTP не настроен. Заполните все необходимые поля."
|
||||
)
|
||||
|
||||
success = await email_channel.send(
|
||||
to_email=test_email,
|
||||
subject="🔧 Тестовое письмо - PVEmanager",
|
||||
body=f"Тестовое письмо от PVEmanager.\n\nВремя: {get_local_time()}\nОтправлено пользователем: {current_user.username}",
|
||||
html_body=f"""
|
||||
<div style="font-family: Arial, sans-serif; padding: 20px; background: #1a1a2e; color: #fff;">
|
||||
<h2 style="color: #667eea;">🔧 Тестовое письмо</h2>
|
||||
<p>SMTP настройки работают корректно!</p>
|
||||
<p>Время: {get_local_time()}</p>
|
||||
<p>Отправлено пользователем: {current_user.username}</p>
|
||||
<hr style="border-color: #333;">
|
||||
<p style="color: #888; font-size: 12px;">PVEmanager</p>
|
||||
</div>
|
||||
"""
|
||||
)
|
||||
|
||||
if success:
|
||||
LoggingService.log(
|
||||
db=db,
|
||||
level=LoggingService.INFO,
|
||||
category=LoggingService.SYSTEM,
|
||||
action="smtp_test",
|
||||
message=f"Администратор {current_user.username} отправил тестовое письмо на {test_email}",
|
||||
username=current_user.username,
|
||||
user_id=current_user.id
|
||||
)
|
||||
return {"success": True, "message": f"Тестовое письмо отправлено на {test_email}"}
|
||||
else:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail="Не удалось отправить тестовое письмо. Проверьте настройки SMTP."
|
||||
)
|
||||
|
||||
|
||||
@router.post("/api/notification-channels/telegram/test")
|
||||
async def test_telegram_bot(
|
||||
chat_id: str = Query(..., description="Telegram Chat ID для отправки тестового сообщения"),
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Test Telegram bot by sending a test message (admin only)"""
|
||||
|
||||
if not current_user.is_admin:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Только администраторы могут тестировать Telegram бота"
|
||||
)
|
||||
|
||||
from ..services.notification_channels import get_telegram_channel, get_local_time
|
||||
|
||||
tg_channel = get_telegram_channel()
|
||||
if not tg_channel.is_configured():
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Telegram бот не настроен. Укажите токен бота."
|
||||
)
|
||||
|
||||
success = await tg_channel.send(
|
||||
chat_id=chat_id,
|
||||
message=f"🔧 <b>Тестовое сообщение</b>\n\nTelegram бот работает корректно!\n\n🕐 Время: {get_local_time()}\n👤 Отправлено: {current_user.username}\n\n🖥️ <i>PVEmanager</i>",
|
||||
parse_mode="HTML"
|
||||
)
|
||||
|
||||
if success:
|
||||
LoggingService.log(
|
||||
db=db,
|
||||
level=LoggingService.INFO,
|
||||
category=LoggingService.SYSTEM,
|
||||
action="telegram_test",
|
||||
message=f"Администратор {current_user.username} отправил тестовое сообщение в Telegram (chat_id: {chat_id})",
|
||||
username=current_user.username,
|
||||
user_id=current_user.id
|
||||
)
|
||||
return {"success": True, "message": f"Тестовое сообщение отправлено в Telegram (chat_id: {chat_id})"}
|
||||
else:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail="Не удалось отправить тестовое сообщение. Проверьте токен бота и chat_id."
|
||||
)
|
||||
|
||||
|
||||
# ==================== System Updates ====================
|
||||
|
||||
@router.get("/api/version")
|
||||
async def get_version():
|
||||
"""Get current panel version"""
|
||||
return {"version": get_current_version()}
|
||||
|
||||
|
||||
@router.get("/api/updates/check")
|
||||
async def check_updates(
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(PermissionChecker("settings.manage"))
|
||||
):
|
||||
"""Check for available updates (admin only)"""
|
||||
result = await check_for_updates()
|
||||
|
||||
LoggingService.log(
|
||||
db=db,
|
||||
level=LoggingService.INFO,
|
||||
category=LoggingService.SYSTEM,
|
||||
action="update_check",
|
||||
message=f"Проверка обновлений: текущая {result['current_version']}, последняя {result.get('latest_version', 'unknown')}",
|
||||
username=current_user.username,
|
||||
user_id=current_user.id
|
||||
)
|
||||
|
||||
return result
|
||||
|
||||
|
||||
@router.get("/api/updates/status")
|
||||
async def updates_status():
|
||||
"""Get current update status (no auth required for banner check)"""
|
||||
return get_update_status()
|
||||
|
||||
|
||||
@router.post("/api/updates/perform")
|
||||
async def perform_system_update(
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(PermissionChecker("settings.manage"))
|
||||
):
|
||||
"""Perform system update (admin only)"""
|
||||
|
||||
LoggingService.log(
|
||||
db=db,
|
||||
level=LoggingService.WARNING,
|
||||
category=LoggingService.SYSTEM,
|
||||
action="update_start",
|
||||
message=f"Администратор {current_user.username} запустил обновление системы",
|
||||
username=current_user.username,
|
||||
user_id=current_user.id
|
||||
)
|
||||
|
||||
result = await perform_update()
|
||||
|
||||
if not result["success"]:
|
||||
LoggingService.log(
|
||||
db=db,
|
||||
level=LoggingService.ERROR,
|
||||
category=LoggingService.SYSTEM,
|
||||
action="update_failed",
|
||||
message=f"Ошибка обновления: {result.get('error')}",
|
||||
username=current_user.username,
|
||||
user_id=current_user.id
|
||||
)
|
||||
|
||||
return result
|
||||
|
||||
|
||||
@router.post("/api/updates/reset")
|
||||
async def reset_update(
|
||||
current_user: User = Depends(PermissionChecker("settings.manage"))
|
||||
):
|
||||
"""Reset update status (admin only)"""
|
||||
reset_update_status()
|
||||
return {"success": True, "message": "Update status reset"}
|
||||
|
||||
926
backend/app/api/templates.py
Normal file
926
backend/app/api/templates.py
Normal file
@@ -0,0 +1,926 @@
|
||||
"""
|
||||
API endpoints for OS Templates management
|
||||
Allows creating VM templates, groups, and deploying VMs from templates
|
||||
"""
|
||||
|
||||
from fastapi import APIRouter, Depends, Request, HTTPException, status
|
||||
from fastapi.responses import HTMLResponse, JSONResponse
|
||||
from fastapi.templating import Jinja2Templates
|
||||
from sqlalchemy.orm import Session
|
||||
from loguru import logger
|
||||
from typing import List
|
||||
|
||||
from ..db import get_db
|
||||
from ..models import ProxmoxServer, OSTemplateGroup, OSTemplate, VMInstance, User
|
||||
from ..schemas import (
|
||||
OSTemplateGroupCreate, OSTemplateGroupUpdate, OSTemplateGroupResponse,
|
||||
OSTemplateCreate, OSTemplateUpdate, OSTemplateResponse, OSTemplateWithGroup,
|
||||
VMDeployRequest, VMDeployResponse
|
||||
)
|
||||
from ..proxmox_client import ProxmoxClient
|
||||
from ..api.proxmox import get_next_vmid, save_vm_instance, get_vm_instance
|
||||
from ..auth import get_current_user, PermissionChecker
|
||||
from ..ipam_service import IPAMService
|
||||
from ..logging_service import LoggingService
|
||||
from ..template_helpers import add_i18n_context
|
||||
|
||||
router = APIRouter()
|
||||
templates = Jinja2Templates(directory="app/templates")
|
||||
|
||||
|
||||
# ==================== HTML Pages ====================
|
||||
|
||||
@router.get("/", response_class=HTMLResponse, include_in_schema=False)
|
||||
def templates_page(request: Request, db: Session = Depends(get_db)):
|
||||
"""Страница управления OS шаблонами"""
|
||||
from ..i18n import t
|
||||
lang = request.cookies.get("language", "en")
|
||||
|
||||
proxmox_servers = db.query(ProxmoxServer).all()
|
||||
template_groups = db.query(OSTemplateGroup).order_by(OSTemplateGroup.sort_order).all()
|
||||
os_templates = db.query(OSTemplate).order_by(OSTemplate.sort_order).all()
|
||||
|
||||
context = {
|
||||
"request": request,
|
||||
"proxmox_servers": proxmox_servers,
|
||||
"template_groups": template_groups,
|
||||
"os_templates": os_templates,
|
||||
"page_title": t('nav_templates', lang),
|
||||
}
|
||||
context = add_i18n_context(request, context)
|
||||
return templates.TemplateResponse("os_templates.html", context)
|
||||
|
||||
|
||||
# ==================== Template Groups CRUD ====================
|
||||
|
||||
@router.get("/api/groups", response_model=List[OSTemplateGroupResponse])
|
||||
def list_template_groups(
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(PermissionChecker("templates.view"))
|
||||
):
|
||||
"""Получить список всех групп шаблонов"""
|
||||
groups = db.query(OSTemplateGroup).order_by(OSTemplateGroup.sort_order).all()
|
||||
return groups
|
||||
|
||||
|
||||
@router.post("/api/groups", response_model=OSTemplateGroupResponse, status_code=status.HTTP_201_CREATED)
|
||||
def create_template_group(
|
||||
group_data: OSTemplateGroupCreate,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(PermissionChecker("templates.manage"))
|
||||
):
|
||||
"""Создать новую группу шаблонов"""
|
||||
# Check if group with same name exists
|
||||
existing = db.query(OSTemplateGroup).filter(OSTemplateGroup.name == group_data.name).first()
|
||||
if existing:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail=f"Группа с именем '{group_data.name}' уже существует"
|
||||
)
|
||||
|
||||
group = OSTemplateGroup(**group_data.model_dump())
|
||||
db.add(group)
|
||||
db.commit()
|
||||
db.refresh(group)
|
||||
|
||||
logger.info(f"User {current_user.username} created template group: {group.name}")
|
||||
return group
|
||||
|
||||
|
||||
@router.get("/api/groups/{group_id}", response_model=OSTemplateGroupResponse)
|
||||
def get_template_group(
|
||||
group_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(PermissionChecker("templates.view"))
|
||||
):
|
||||
"""Получить группу шаблонов по ID"""
|
||||
group = db.query(OSTemplateGroup).filter(OSTemplateGroup.id == group_id).first()
|
||||
if not group:
|
||||
raise HTTPException(status_code=404, detail="Группа шаблонов не найдена")
|
||||
return group
|
||||
|
||||
|
||||
@router.put("/api/groups/{group_id}", response_model=OSTemplateGroupResponse)
|
||||
def update_template_group(
|
||||
group_id: int,
|
||||
group_data: OSTemplateGroupUpdate,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(PermissionChecker("templates.manage"))
|
||||
):
|
||||
"""Обновить группу шаблонов"""
|
||||
group = db.query(OSTemplateGroup).filter(OSTemplateGroup.id == group_id).first()
|
||||
if not group:
|
||||
raise HTTPException(status_code=404, detail="Группа шаблонов не найдена")
|
||||
|
||||
update_data = group_data.model_dump(exclude_unset=True)
|
||||
for field, value in update_data.items():
|
||||
setattr(group, field, value)
|
||||
|
||||
db.commit()
|
||||
db.refresh(group)
|
||||
|
||||
logger.info(f"User {current_user.username} updated template group: {group.name}")
|
||||
return group
|
||||
|
||||
|
||||
@router.delete("/api/groups/{group_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||
def delete_template_group(
|
||||
group_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(PermissionChecker("templates.manage"))
|
||||
):
|
||||
"""Удалить группу шаблонов"""
|
||||
group = db.query(OSTemplateGroup).filter(OSTemplateGroup.id == group_id).first()
|
||||
if not group:
|
||||
raise HTTPException(status_code=404, detail="Группа шаблонов не найдена")
|
||||
|
||||
# Check if there are templates in this group
|
||||
templates_count = db.query(OSTemplate).filter(OSTemplate.group_id == group_id).count()
|
||||
if templates_count > 0:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail=f"Невозможно удалить группу: в ней {templates_count} шаблон(ов)"
|
||||
)
|
||||
|
||||
logger.info(f"User {current_user.username} deleted template group: {group.name}")
|
||||
db.delete(group)
|
||||
db.commit()
|
||||
return None
|
||||
|
||||
|
||||
# ==================== OS Templates CRUD ====================
|
||||
|
||||
@router.get("/api/templates", response_model=List[OSTemplateWithGroup])
|
||||
def list_os_templates(
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(PermissionChecker("templates.view")),
|
||||
group_id: int = None,
|
||||
server_id: int = None,
|
||||
active_only: bool = True
|
||||
):
|
||||
"""Получить список всех OS шаблонов с информацией о группе"""
|
||||
query = db.query(OSTemplate)
|
||||
|
||||
if group_id:
|
||||
query = query.filter(OSTemplate.group_id == group_id)
|
||||
if server_id:
|
||||
query = query.filter(OSTemplate.server_id == server_id)
|
||||
if active_only:
|
||||
query = query.filter(OSTemplate.is_active == True)
|
||||
|
||||
os_templates = query.order_by(OSTemplate.sort_order).all()
|
||||
|
||||
# Enrich with group and server info
|
||||
result = []
|
||||
for template in os_templates:
|
||||
group = db.query(OSTemplateGroup).filter(OSTemplateGroup.id == template.group_id).first()
|
||||
server = db.query(ProxmoxServer).filter(ProxmoxServer.id == template.server_id).first()
|
||||
|
||||
template_dict = {
|
||||
**template.__dict__,
|
||||
'group_name': group.name if group else None,
|
||||
'group_icon': group.icon if group else None,
|
||||
'server_name': server.name if server else None,
|
||||
}
|
||||
# Remove SQLAlchemy internal state
|
||||
template_dict.pop('_sa_instance_state', None)
|
||||
result.append(template_dict)
|
||||
|
||||
return result
|
||||
|
||||
|
||||
@router.post("/api/templates", response_model=OSTemplateResponse, status_code=status.HTTP_201_CREATED)
|
||||
def create_os_template(
|
||||
template_data: OSTemplateCreate,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(PermissionChecker("templates.manage"))
|
||||
):
|
||||
"""Создать новый OS шаблон"""
|
||||
# Validate group exists
|
||||
group = db.query(OSTemplateGroup).filter(OSTemplateGroup.id == template_data.group_id).first()
|
||||
if not group:
|
||||
raise HTTPException(status_code=404, detail="Группа шаблонов не найдена")
|
||||
|
||||
# Validate server exists
|
||||
server = db.query(ProxmoxServer).filter(ProxmoxServer.id == template_data.server_id).first()
|
||||
if not server:
|
||||
raise HTTPException(status_code=404, detail="Proxmox сервер не найден")
|
||||
|
||||
# Check if template with same VMID on same server exists
|
||||
existing = db.query(OSTemplate).filter(
|
||||
OSTemplate.server_id == template_data.server_id,
|
||||
OSTemplate.vmid == template_data.vmid
|
||||
).first()
|
||||
if existing:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail=f"Шаблон с VMID {template_data.vmid} уже существует для этого сервера"
|
||||
)
|
||||
|
||||
template = OSTemplate(**template_data.model_dump())
|
||||
db.add(template)
|
||||
db.commit()
|
||||
db.refresh(template)
|
||||
|
||||
logger.info(f"User {current_user.username} created OS template: {template.name} (VMID: {template.vmid})")
|
||||
return template
|
||||
|
||||
|
||||
@router.get("/api/templates/{template_id}", response_model=OSTemplateWithGroup)
|
||||
def get_os_template(
|
||||
template_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(PermissionChecker("templates.view"))
|
||||
):
|
||||
"""Получить OS шаблон по ID"""
|
||||
template = db.query(OSTemplate).filter(OSTemplate.id == template_id).first()
|
||||
if not template:
|
||||
raise HTTPException(status_code=404, detail="Шаблон не найден")
|
||||
|
||||
group = db.query(OSTemplateGroup).filter(OSTemplateGroup.id == template.group_id).first()
|
||||
server = db.query(ProxmoxServer).filter(ProxmoxServer.id == template.server_id).first()
|
||||
|
||||
template_dict = {
|
||||
**template.__dict__,
|
||||
'group_name': group.name if group else None,
|
||||
'group_icon': group.icon if group else None,
|
||||
'server_name': server.name if server else None,
|
||||
}
|
||||
template_dict.pop('_sa_instance_state', None)
|
||||
|
||||
return template_dict
|
||||
|
||||
|
||||
@router.put("/api/templates/{template_id}", response_model=OSTemplateResponse)
|
||||
def update_os_template(
|
||||
template_id: int,
|
||||
template_data: OSTemplateUpdate,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(PermissionChecker("templates.manage"))
|
||||
):
|
||||
"""Обновить OS шаблон"""
|
||||
template = db.query(OSTemplate).filter(OSTemplate.id == template_id).first()
|
||||
if not template:
|
||||
raise HTTPException(status_code=404, detail="Шаблон не найден")
|
||||
|
||||
update_data = template_data.model_dump(exclude_unset=True)
|
||||
|
||||
# Validate group if changing
|
||||
if 'group_id' in update_data:
|
||||
group = db.query(OSTemplateGroup).filter(OSTemplateGroup.id == update_data['group_id']).first()
|
||||
if not group:
|
||||
raise HTTPException(status_code=404, detail="Группа шаблонов не найдена")
|
||||
|
||||
# Validate server if changing
|
||||
if 'server_id' in update_data:
|
||||
server = db.query(ProxmoxServer).filter(ProxmoxServer.id == update_data['server_id']).first()
|
||||
if not server:
|
||||
raise HTTPException(status_code=404, detail="Proxmox сервер не найден")
|
||||
|
||||
for field, value in update_data.items():
|
||||
setattr(template, field, value)
|
||||
|
||||
db.commit()
|
||||
db.refresh(template)
|
||||
|
||||
logger.info(f"User {current_user.username} updated OS template: {template.name}")
|
||||
return template
|
||||
|
||||
|
||||
@router.delete("/api/templates/{template_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||
def delete_os_template(
|
||||
template_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(PermissionChecker("templates.manage"))
|
||||
):
|
||||
"""Удалить OS шаблон"""
|
||||
template = db.query(OSTemplate).filter(OSTemplate.id == template_id).first()
|
||||
if not template:
|
||||
raise HTTPException(status_code=404, detail="Шаблон не найден")
|
||||
|
||||
logger.info(f"User {current_user.username} deleted OS template: {template.name} (VMID: {template.vmid})")
|
||||
db.delete(template)
|
||||
db.commit()
|
||||
return None
|
||||
|
||||
|
||||
# ==================== Proxmox Templates Discovery ====================
|
||||
|
||||
@router.get("/api/discover/{server_id}")
|
||||
def discover_proxmox_templates(
|
||||
server_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(PermissionChecker("templates.view"))
|
||||
):
|
||||
"""
|
||||
Обнаружить все VM-шаблоны на Proxmox сервере.
|
||||
Возвращает список шаблонов, которые можно добавить.
|
||||
"""
|
||||
server = db.query(ProxmoxServer).filter(ProxmoxServer.id == server_id).first()
|
||||
if not server:
|
||||
raise HTTPException(status_code=404, detail="Proxmox сервер не найден")
|
||||
|
||||
try:
|
||||
if server.use_password:
|
||||
client = ProxmoxClient(
|
||||
host=server.ip_address,
|
||||
user=server.api_user,
|
||||
password=server.password,
|
||||
verify_ssl=server.verify_ssl
|
||||
)
|
||||
else:
|
||||
client = ProxmoxClient(
|
||||
host=server.ip_address,
|
||||
user=server.api_user,
|
||||
token_name=server.api_token_name,
|
||||
token_value=server.api_token_value,
|
||||
verify_ssl=server.verify_ssl
|
||||
)
|
||||
|
||||
if not client.is_connected():
|
||||
raise HTTPException(status_code=503, detail="Не удалось подключиться к Proxmox серверу")
|
||||
|
||||
# Get templates - фильтруем по hostname ноды если это кластер
|
||||
node_filter = None
|
||||
if server.hostname and server.hostname != server.ip_address:
|
||||
node_filter = server.hostname
|
||||
|
||||
proxmox_templates = client.get_templates(node=node_filter)
|
||||
|
||||
# Get already added templates для ЭТОГО сервера
|
||||
existing_vmids = set(
|
||||
t.vmid for t in db.query(OSTemplate).filter(OSTemplate.server_id == server_id).all()
|
||||
)
|
||||
|
||||
result = []
|
||||
for tpl in proxmox_templates:
|
||||
result.append({
|
||||
'vmid': tpl.get('vmid'),
|
||||
'name': tpl.get('name', f"Template-{tpl.get('vmid')}"),
|
||||
'node': tpl.get('node'),
|
||||
'status': tpl.get('status'),
|
||||
'maxmem': tpl.get('maxmem', 0),
|
||||
'maxdisk': tpl.get('maxdisk', 0),
|
||||
'already_added': tpl.get('vmid') in existing_vmids
|
||||
})
|
||||
|
||||
return JSONResponse(content={
|
||||
'server_id': server_id,
|
||||
'server_name': server.name,
|
||||
'templates': result
|
||||
})
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error discovering templates on {server.name}: {e}")
|
||||
raise HTTPException(status_code=500, detail=f"Ошибка обнаружения шаблонов: {str(e)}")
|
||||
|
||||
|
||||
# ==================== Auto-Import Templates ====================
|
||||
|
||||
# Маппинг ключевых слов на группы
|
||||
# Иконки используют CSS классы для адаптации к теме
|
||||
OS_GROUP_MAPPING = {
|
||||
'ubuntu': {'name': 'Ubuntu', 'icon': '<i class="fa-brands fa-ubuntu os-icon os-icon-ubuntu"></i>', 'order': 1},
|
||||
'debian': {'name': 'Debian', 'icon': '<i class="fa-brands fa-debian os-icon os-icon-debian"></i>', 'order': 2},
|
||||
'centos': {'name': 'CentOS', 'icon': '<i class="fa-brands fa-centos os-icon os-icon-centos"></i>', 'order': 3},
|
||||
'rocky': {'name': 'Rocky Linux', 'icon': '<span class="os-icon-rocky-svg"></span>', 'order': 4},
|
||||
'alma': {'name': 'AlmaLinux', 'icon': '<span class="os-icon-alma-svg"></span>', 'order': 5},
|
||||
'almalinux': {'name': 'AlmaLinux', 'icon': '<span class="os-icon-alma-svg"></span>', 'order': 5},
|
||||
'fedora': {'name': 'Fedora', 'icon': '<i class="fa-brands fa-fedora os-icon os-icon-fedora"></i>', 'order': 6},
|
||||
'rhel': {'name': 'RHEL', 'icon': '<i class="fa-brands fa-redhat os-icon os-icon-rhel"></i>', 'order': 7},
|
||||
'oracle': {'name': 'Oracle Linux', 'icon': '<i class="fa-brands fa-linux os-icon os-icon-oracle"></i>', 'order': 8},
|
||||
'suse': {'name': 'openSUSE', 'icon': '<i class="fa-brands fa-suse os-icon os-icon-suse"></i>', 'order': 9},
|
||||
'opensuse': {'name': 'openSUSE', 'icon': '<i class="fa-brands fa-suse os-icon os-icon-suse"></i>', 'order': 9},
|
||||
'arch': {'name': 'Arch Linux', 'icon': '<i class="fa-brands fa-linux os-icon os-icon-arch"></i>', 'order': 10},
|
||||
'gentoo': {'name': 'Gentoo', 'icon': '<i class="fa-brands fa-linux os-icon os-icon-gentoo"></i>', 'order': 11},
|
||||
'alpine': {'name': 'Alpine', 'icon': '<i class="fa-brands fa-linux os-icon os-icon-alpine"></i>', 'order': 12},
|
||||
'windows': {'name': 'Windows', 'icon': '<i class="fa-brands fa-windows os-icon os-icon-windows"></i>', 'order': 20},
|
||||
'win': {'name': 'Windows', 'icon': '<i class="fa-brands fa-windows os-icon os-icon-windows"></i>', 'order': 20},
|
||||
'freebsd': {'name': 'FreeBSD', 'icon': '<i class="fa-brands fa-freebsd os-icon os-icon-freebsd"></i>', 'order': 30},
|
||||
'openbsd': {'name': 'OpenBSD', 'icon': '<i class="fa-brands fa-linux os-icon os-icon-openbsd"></i>', 'order': 31},
|
||||
'other': {'name': 'Other', 'icon': '<i class="fa-solid fa-compact-disc os-icon os-icon-other"></i>', 'order': 99},
|
||||
}
|
||||
|
||||
|
||||
def detect_os_group(template_name: str) -> dict:
|
||||
"""Определить группу ОС по имени шаблона"""
|
||||
name_lower = template_name.lower()
|
||||
|
||||
for keyword, group_info in OS_GROUP_MAPPING.items():
|
||||
if keyword in name_lower:
|
||||
return group_info
|
||||
|
||||
return OS_GROUP_MAPPING['other']
|
||||
|
||||
|
||||
@router.post("/api/auto-import/{server_id}")
|
||||
def auto_import_templates(
|
||||
server_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(PermissionChecker("templates.manage"))
|
||||
):
|
||||
"""
|
||||
Автоматический импорт шаблонов с Proxmox сервера.
|
||||
Автоматически определяет группу ОС и назначает порядок сортировки.
|
||||
Глобальная сортировка: Ubuntu 0-3, CentOS 4-5 и т.д.
|
||||
"""
|
||||
server = db.query(ProxmoxServer).filter(ProxmoxServer.id == server_id).first()
|
||||
if not server:
|
||||
raise HTTPException(status_code=404, detail="Proxmox сервер не найден")
|
||||
|
||||
try:
|
||||
# Подключаемся к Proxmox
|
||||
if server.use_password:
|
||||
client = ProxmoxClient(
|
||||
host=server.ip_address,
|
||||
user=server.api_user,
|
||||
password=server.password,
|
||||
verify_ssl=server.verify_ssl
|
||||
)
|
||||
else:
|
||||
client = ProxmoxClient(
|
||||
host=server.ip_address,
|
||||
user=server.api_user,
|
||||
token_name=server.api_token_name,
|
||||
token_value=server.api_token_value,
|
||||
verify_ssl=server.verify_ssl
|
||||
)
|
||||
|
||||
if not client.is_connected():
|
||||
raise HTTPException(status_code=503, detail="Не удалось подключиться к Proxmox серверу")
|
||||
|
||||
# Фильтруем по ноде если это кластер
|
||||
node_filter = None
|
||||
if server.hostname and server.hostname != server.ip_address:
|
||||
node_filter = server.hostname
|
||||
|
||||
# Получаем шаблоны только с этой ноды
|
||||
proxmox_templates = client.get_templates(node=node_filter)
|
||||
|
||||
# Получаем уже добавленные шаблоны для ЭТОГО сервера
|
||||
existing_vmids = set(
|
||||
t.vmid for t in db.query(OSTemplate).filter(OSTemplate.server_id == server_id).all()
|
||||
)
|
||||
|
||||
# Кеш групп: name -> group
|
||||
groups_cache = {}
|
||||
for group in db.query(OSTemplateGroup).all():
|
||||
groups_cache[group.name] = group
|
||||
|
||||
# Группируем шаблоны по ОС
|
||||
templates_by_group = {} # group_name -> [templates]
|
||||
|
||||
for tpl in proxmox_templates:
|
||||
vmid = tpl.get('vmid')
|
||||
if vmid in existing_vmids:
|
||||
continue # Пропускаем уже добавленные
|
||||
|
||||
template_name = tpl.get('name', f"Template-{vmid}")
|
||||
group_info = detect_os_group(template_name)
|
||||
group_name = group_info['name']
|
||||
|
||||
if group_name not in templates_by_group:
|
||||
templates_by_group[group_name] = {
|
||||
'info': group_info,
|
||||
'templates': []
|
||||
}
|
||||
|
||||
templates_by_group[group_name]['templates'].append({
|
||||
'vmid': vmid,
|
||||
'name': template_name,
|
||||
'node': tpl.get('node'),
|
||||
'maxmem': tpl.get('maxmem', 0),
|
||||
'maxdisk': tpl.get('maxdisk', 0),
|
||||
})
|
||||
|
||||
# Создаём группы и шаблоны с ГЛОБАЛЬНОЙ сортировкой
|
||||
imported = []
|
||||
global_sort_order = 0 # Глобальный счётчик для всех шаблонов
|
||||
|
||||
# Сортируем группы по их порядку (Ubuntu=1, Debian=2, CentOS=3...)
|
||||
sorted_groups = sorted(
|
||||
templates_by_group.items(),
|
||||
key=lambda x: x[1]['info']['order']
|
||||
)
|
||||
|
||||
for group_name, group_data in sorted_groups:
|
||||
group_info = group_data['info']
|
||||
group_templates = group_data['templates']
|
||||
|
||||
# Получаем или создаём группу
|
||||
if group_name not in groups_cache:
|
||||
# Получаем максимальный sort_order для групп
|
||||
max_group_order = db.query(OSTemplateGroup).count()
|
||||
|
||||
new_group = OSTemplateGroup(
|
||||
name=group_name,
|
||||
icon=group_info['icon'],
|
||||
description=f"Шаблоны {group_name}",
|
||||
sort_order=group_info['order'], # Используем порядок из маппинга
|
||||
is_active=True
|
||||
)
|
||||
db.add(new_group)
|
||||
db.flush()
|
||||
groups_cache[group_name] = new_group
|
||||
logger.info(f"Created new group: {group_name}")
|
||||
|
||||
group = groups_cache[group_name]
|
||||
|
||||
# Сортируем шаблоны по имени для консистентности
|
||||
group_templates.sort(key=lambda x: x['name'])
|
||||
|
||||
# Добавляем шаблоны с ГЛОБАЛЬНЫМ sort_order
|
||||
for idx, tpl in enumerate(group_templates):
|
||||
# Определяем дефолтные значения из размера шаблона
|
||||
default_memory = max(1024, (tpl.get('maxmem', 0) // (1024 * 1024)) or 1024)
|
||||
default_disk = max(10, (tpl.get('maxdisk', 0) // (1024 * 1024 * 1024)) or 10)
|
||||
|
||||
template = OSTemplate(
|
||||
group_id=group.id,
|
||||
server_id=server_id,
|
||||
name=tpl['name'],
|
||||
vmid=tpl['vmid'],
|
||||
node=tpl.get('node'),
|
||||
source_node=tpl.get('node'),
|
||||
default_cores=2,
|
||||
default_memory=default_memory,
|
||||
default_disk=default_disk,
|
||||
min_cores=1,
|
||||
min_memory=512,
|
||||
min_disk=5,
|
||||
is_active=True,
|
||||
sort_order=global_sort_order # ГЛОБАЛЬНАЯ сортировка
|
||||
)
|
||||
|
||||
db.add(template)
|
||||
imported.append({
|
||||
'vmid': tpl['vmid'],
|
||||
'name': tpl['name'],
|
||||
'group': group_name,
|
||||
'sort_order': global_sort_order
|
||||
})
|
||||
global_sort_order += 1 # Увеличиваем глобальный счётчик
|
||||
|
||||
db.commit()
|
||||
|
||||
logger.info(f"User {current_user.username} auto-imported {len(imported)} templates from {server.name}")
|
||||
|
||||
return JSONResponse(content={
|
||||
'success': True,
|
||||
'server_id': server_id,
|
||||
'server_name': server.name,
|
||||
'imported_count': len(imported),
|
||||
'templates': imported,
|
||||
'groups_created': [g for g in templates_by_group.keys() if g not in groups_cache]
|
||||
})
|
||||
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error(f"Error auto-importing templates from {server.name}: {e}")
|
||||
db.rollback()
|
||||
raise HTTPException(status_code=500, detail=f"Ошибка импорта шаблонов: {str(e)}")
|
||||
|
||||
|
||||
# ==================== VM Deployment ====================
|
||||
|
||||
@router.post("/api/deploy", response_model=VMDeployResponse)
|
||||
async def deploy_vm_from_template(
|
||||
deploy_data: VMDeployRequest,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(PermissionChecker("vms.create"))
|
||||
):
|
||||
"""
|
||||
Развернуть новую VM из шаблона.
|
||||
Клонирует шаблон и настраивает параметры VM.
|
||||
Поддерживает развертывание на любую ноду кластера (cross-node deployment).
|
||||
"""
|
||||
# Get template
|
||||
template = db.query(OSTemplate).filter(OSTemplate.id == deploy_data.template_id).first()
|
||||
if not template:
|
||||
raise HTTPException(status_code=404, detail="Шаблон не найден")
|
||||
|
||||
if not template.is_active:
|
||||
raise HTTPException(status_code=400, detail="Шаблон неактивен")
|
||||
|
||||
# Get server
|
||||
server = db.query(ProxmoxServer).filter(ProxmoxServer.id == template.server_id).first()
|
||||
if not server:
|
||||
raise HTTPException(status_code=404, detail="Proxmox сервер не найден")
|
||||
|
||||
# Validate resources
|
||||
cores = deploy_data.cores or template.default_cores
|
||||
memory = deploy_data.memory or template.default_memory
|
||||
disk = deploy_data.disk or template.default_disk
|
||||
|
||||
if cores < template.min_cores:
|
||||
raise HTTPException(status_code=400, detail=f"Минимум {template.min_cores} ядер CPU")
|
||||
if memory < template.min_memory:
|
||||
raise HTTPException(status_code=400, detail=f"Минимум {template.min_memory} MB памяти")
|
||||
if disk < template.min_disk:
|
||||
raise HTTPException(status_code=400, detail=f"Минимум {template.min_disk} GB диска")
|
||||
|
||||
try:
|
||||
# Connect to Proxmox
|
||||
if server.use_password:
|
||||
client = ProxmoxClient(
|
||||
host=server.ip_address,
|
||||
user=server.api_user,
|
||||
password=server.password,
|
||||
verify_ssl=server.verify_ssl
|
||||
)
|
||||
else:
|
||||
client = ProxmoxClient(
|
||||
host=server.ip_address,
|
||||
user=server.api_user,
|
||||
token_name=server.api_token_name,
|
||||
token_value=server.api_token_value,
|
||||
verify_ssl=server.verify_ssl
|
||||
)
|
||||
|
||||
if not client.is_connected():
|
||||
raise HTTPException(status_code=503, detail="Не удалось подключиться к Proxmox серверу")
|
||||
|
||||
# Determine source node (where template exists) and target node (where to deploy)
|
||||
source_node = template.get_source_node()
|
||||
target_node = deploy_data.target_node or source_node
|
||||
|
||||
# Check if template exists on source node
|
||||
template_vmid = template.vmid
|
||||
template_status = client.get_vm_status(source_node, template_vmid)
|
||||
|
||||
if not template_status:
|
||||
# Try to find the template on other nodes
|
||||
found = client.find_template_on_nodes(template_vmid)
|
||||
if found:
|
||||
source_node = found['node']
|
||||
logger.info(f"Template {template_vmid} found on alternative node: {source_node}")
|
||||
else:
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail=f"Шаблон VMID {template_vmid} не найден. Проверьте настройки шаблона."
|
||||
)
|
||||
|
||||
# For shared storage: template is accessible from all nodes
|
||||
# For local storage: template needs to be on the target node or replicated
|
||||
#
|
||||
# In a cluster with shared storage, we can clone from source_node
|
||||
# but specify target_node for the new VM
|
||||
clone_from_node = source_node
|
||||
clone_template_vmid = template_vmid
|
||||
|
||||
# Log cross-node deployment
|
||||
if target_node and target_node != source_node:
|
||||
logger.info(f"Cross-node deployment: template on {source_node}, target node {target_node}")
|
||||
|
||||
# Get next VMID from database (range 10000-19999) or use provided VMID
|
||||
if deploy_data.vmid:
|
||||
# Используем указанный VMID (для переустановки)
|
||||
new_vmid = deploy_data.vmid
|
||||
logger.info(f"Using provided VMID: {new_vmid} for reinstall")
|
||||
else:
|
||||
# Генерируем новый случайный VMID для новой VM
|
||||
new_vmid = get_next_vmid(db, server.id)
|
||||
logger.info(f"Generated new VMID: {new_vmid} for server {server.id}")
|
||||
|
||||
# Clone VM from template
|
||||
# For shared storage: clone from source node, target specifies where VM will run
|
||||
clone_upid = client.clone_vm_from_template(
|
||||
node=clone_from_node,
|
||||
template_vmid=clone_template_vmid,
|
||||
new_vmid=new_vmid,
|
||||
name=deploy_data.name,
|
||||
full_clone=True,
|
||||
description=f"Deployed from template {template.name} by {current_user.username}",
|
||||
target_storage=deploy_data.target_storage,
|
||||
target_node=target_node if target_node != clone_from_node else None
|
||||
)
|
||||
|
||||
if not clone_upid:
|
||||
raise HTTPException(status_code=500, detail="Ошибка клонирования VM")
|
||||
|
||||
# Wait for clone to complete
|
||||
clone_success = client.wait_for_task(clone_from_node, clone_upid, timeout=300)
|
||||
if not clone_success:
|
||||
raise HTTPException(status_code=500, detail="Таймаут клонирования VM")
|
||||
|
||||
# Use target_node for all subsequent operations
|
||||
deploy_node = target_node
|
||||
|
||||
# IPAM Integration - Auto-allocate IP if network specified but no IP provided
|
||||
allocated_ip = deploy_data.ip_address
|
||||
ipam_allocation = None
|
||||
|
||||
if deploy_data.ipam_network_id and not deploy_data.ip_address:
|
||||
ipam = IPAMService(db)
|
||||
ipam_allocation, error = ipam.auto_allocate_ip(
|
||||
network_id=deploy_data.ipam_network_id,
|
||||
pool_id=deploy_data.ipam_pool_id,
|
||||
resource_type='vm',
|
||||
resource_name=deploy_data.name,
|
||||
proxmox_server_id=server.id,
|
||||
proxmox_vmid=new_vmid,
|
||||
proxmox_node=deploy_node,
|
||||
allocated_by=current_user.username,
|
||||
notes=f"Auto-allocated for VM deployment from template {template.name}"
|
||||
)
|
||||
if error:
|
||||
logger.error(f"IPAM auto-allocation failed: {error}")
|
||||
# Continue without IPAM - let user know
|
||||
else:
|
||||
allocated_ip = ipam_allocation.ip_address
|
||||
logger.info(f"IPAM allocated IP {allocated_ip} for VM {deploy_data.name}")
|
||||
# Get gateway from network if not provided
|
||||
if not deploy_data.gateway:
|
||||
from ..models import IPAMNetwork
|
||||
network = db.query(IPAMNetwork).filter(IPAMNetwork.id == deploy_data.ipam_network_id).first()
|
||||
if network and network.gateway:
|
||||
deploy_data.gateway = network.gateway
|
||||
elif deploy_data.ip_address and deploy_data.ipam_network_id:
|
||||
# Register manually specified IP in IPAM
|
||||
ipam = IPAMService(db)
|
||||
ipam_allocation, error = ipam.allocate_ip(
|
||||
ip_address=deploy_data.ip_address,
|
||||
network_id=deploy_data.ipam_network_id,
|
||||
pool_id=deploy_data.ipam_pool_id,
|
||||
resource_type='vm',
|
||||
resource_name=deploy_data.name,
|
||||
proxmox_server_id=server.id,
|
||||
proxmox_vmid=new_vmid,
|
||||
proxmox_node=deploy_node,
|
||||
allocated_by=current_user.username,
|
||||
notes=f"Manually assigned for VM deployment from template {template.name}"
|
||||
)
|
||||
if error:
|
||||
logger.warning(f"IPAM registration failed for manually specified IP: {error}")
|
||||
|
||||
# Configure VM
|
||||
ip_config = None
|
||||
if allocated_ip:
|
||||
if deploy_data.gateway:
|
||||
ip_config = f"ip={allocated_ip}/24,gw={deploy_data.gateway}"
|
||||
else:
|
||||
ip_config = f"ip={allocated_ip}/24"
|
||||
elif allocated_ip is None:
|
||||
ip_config = "ip=dhcp"
|
||||
|
||||
config_success = client.configure_vm(
|
||||
node=deploy_node,
|
||||
vmid=new_vmid,
|
||||
cores=cores,
|
||||
memory=memory,
|
||||
disk_size=disk, # configure_vm will compare with current disk size
|
||||
network_bridge=deploy_data.network_bridge,
|
||||
cloud_init_user=deploy_data.cloud_init_user,
|
||||
cloud_init_password=deploy_data.cloud_init_password,
|
||||
ssh_keys=deploy_data.ssh_keys,
|
||||
ip_config=ip_config,
|
||||
onboot=deploy_data.onboot
|
||||
)
|
||||
|
||||
if not config_success:
|
||||
logger.warning(f"VM {new_vmid} created but configuration may be incomplete")
|
||||
|
||||
# Start VM if requested
|
||||
if deploy_data.start_after_create:
|
||||
client.start_vm(deploy_node, new_vmid)
|
||||
|
||||
# Enable High Availability if requested (cluster only)
|
||||
ha_enabled = False
|
||||
if deploy_data.enable_ha:
|
||||
try:
|
||||
if client.is_cluster():
|
||||
ha_result = client.add_to_ha(vmid=new_vmid, vm_type='vm', max_restart=3, max_relocate=3)
|
||||
if ha_result.get('success'):
|
||||
ha_enabled = True
|
||||
logger.info(f"HA enabled for VM {new_vmid}")
|
||||
else:
|
||||
logger.warning(f"Failed to enable HA for VM {new_vmid}: {ha_result.get('error')}")
|
||||
else:
|
||||
logger.warning(f"HA requested but server {server.name} is not in a cluster")
|
||||
except Exception as ha_error:
|
||||
logger.error(f"Error enabling HA for VM {new_vmid}: {ha_error}")
|
||||
|
||||
# Save VM configuration to database with owner
|
||||
save_vm_instance(
|
||||
db=db,
|
||||
server_id=server.id,
|
||||
vmid=new_vmid,
|
||||
node=deploy_node,
|
||||
vm_type='qemu',
|
||||
name=deploy_data.name,
|
||||
cores=cores,
|
||||
memory=memory,
|
||||
disk_size=disk,
|
||||
ip_address=allocated_ip,
|
||||
ip_prefix=24,
|
||||
gateway=deploy_data.gateway,
|
||||
cloud_init_user=deploy_data.cloud_init_user,
|
||||
cloud_init_password=deploy_data.cloud_init_password,
|
||||
ssh_keys=deploy_data.ssh_keys,
|
||||
template_id=template.id,
|
||||
template_name=template.name,
|
||||
description=f"Deployed from template {template.name}",
|
||||
owner_id=current_user.id # VPS-style user isolation
|
||||
)
|
||||
|
||||
logger.info(f"User {current_user.username} deployed VM {new_vmid} ({deploy_data.name}) from template {template.name}")
|
||||
|
||||
# Log VM deployment to audit
|
||||
LoggingService.log_proxmox_action(
|
||||
db=db,
|
||||
action="create",
|
||||
resource_type="vm",
|
||||
resource_id=new_vmid,
|
||||
username=current_user.username,
|
||||
resource_name=deploy_data.name,
|
||||
server_id=server.id,
|
||||
server_name=server.name,
|
||||
node_name=deploy_node,
|
||||
details={
|
||||
"template_id": template.id,
|
||||
"template_name": template.name,
|
||||
"source_node": source_node if source_node != deploy_node else None,
|
||||
"cores": cores,
|
||||
"memory": memory,
|
||||
"disk": disk,
|
||||
"ip_address": allocated_ip,
|
||||
"ha_enabled": ha_enabled
|
||||
},
|
||||
success=True
|
||||
)
|
||||
|
||||
return VMDeployResponse(
|
||||
success=True,
|
||||
vmid=new_vmid,
|
||||
name=deploy_data.name,
|
||||
node=deploy_node,
|
||||
server_id=server.id,
|
||||
task_upid=clone_upid,
|
||||
message=f"VM {deploy_data.name} успешно создана (VMID: {new_vmid})"
|
||||
)
|
||||
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as e:
|
||||
# Log failed deployment
|
||||
LoggingService.log_proxmox_action(
|
||||
db=db,
|
||||
action="create",
|
||||
resource_type="vm",
|
||||
resource_id=deploy_data.vmid,
|
||||
username=current_user.username,
|
||||
resource_name=deploy_data.name,
|
||||
server_id=server.id if server else None,
|
||||
server_name=server.name if server else None,
|
||||
node_name=deploy_node if 'deploy_node' in locals() else None,
|
||||
details={
|
||||
"template_id": template.id if template else None,
|
||||
"template_name": template.name if template else None
|
||||
},
|
||||
success=False,
|
||||
error_message=str(e)
|
||||
)
|
||||
logger.error(f"Error deploying VM from template {template.id}: {e}")
|
||||
raise HTTPException(status_code=500, detail=f"Ошибка развертывания VM: {str(e)}")
|
||||
|
||||
|
||||
# ==================== Quick Deploy (for UI) ====================
|
||||
|
||||
@router.get("/api/quick-deploy/{template_id}")
|
||||
def get_quick_deploy_info(
|
||||
template_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(PermissionChecker("templates.view"))
|
||||
):
|
||||
"""Получить информацию для быстрого развертывания VM"""
|
||||
template = db.query(OSTemplate).filter(OSTemplate.id == template_id).first()
|
||||
if not template:
|
||||
raise HTTPException(status_code=404, detail="Шаблон не найден")
|
||||
|
||||
group = db.query(OSTemplateGroup).filter(OSTemplateGroup.id == template.group_id).first()
|
||||
server = db.query(ProxmoxServer).filter(ProxmoxServer.id == template.server_id).first()
|
||||
|
||||
return JSONResponse(content={
|
||||
'template': {
|
||||
'id': template.id,
|
||||
'name': template.name,
|
||||
'vmid': template.vmid,
|
||||
'node': template.node,
|
||||
'description': template.description,
|
||||
'default_cores': template.default_cores,
|
||||
'default_memory': template.default_memory,
|
||||
'default_disk': template.default_disk,
|
||||
'min_cores': template.min_cores,
|
||||
'min_memory': template.min_memory,
|
||||
'min_disk': template.min_disk,
|
||||
},
|
||||
'group': {
|
||||
'name': group.name if group else None,
|
||||
'icon': group.icon if group else None,
|
||||
},
|
||||
'server': {
|
||||
'id': server.id if server else None,
|
||||
'name': server.name if server else None,
|
||||
}
|
||||
})
|
||||
986
backend/app/api/users.py
Normal file
986
backend/app/api/users.py
Normal file
@@ -0,0 +1,986 @@
|
||||
"""
|
||||
Users and Roles Management API
|
||||
"""
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
from typing import List, Optional
|
||||
from fastapi import APIRouter, Depends, HTTPException, status, Request
|
||||
from fastapi.responses import HTMLResponse
|
||||
from fastapi.templating import Jinja2Templates
|
||||
from sqlalchemy.orm import Session
|
||||
from pydantic import BaseModel, Field, EmailStr
|
||||
from loguru import logger
|
||||
|
||||
from ..db import get_db
|
||||
from ..models import User, Role
|
||||
from ..auth import (
|
||||
get_password_hash,
|
||||
get_current_user,
|
||||
get_current_active_admin,
|
||||
PermissionChecker,
|
||||
get_client_ip
|
||||
)
|
||||
from ..config import utcnow
|
||||
from ..services.security_service import SecurityService
|
||||
from ..logging_service import LoggingService
|
||||
from ..template_helpers import add_i18n_context
|
||||
|
||||
|
||||
router = APIRouter()
|
||||
templates = Jinja2Templates(directory="app/templates")
|
||||
|
||||
|
||||
# ==================== HTML Pages ====================
|
||||
|
||||
@router.get("/users", response_class=HTMLResponse, include_in_schema=False)
|
||||
async def users_page(request: Request, db: Session = Depends(get_db)):
|
||||
"""Users management page (admin only) - auth checked on frontend"""
|
||||
from ..i18n import t
|
||||
lang = request.cookies.get("language", "en")
|
||||
|
||||
context = {
|
||||
"request": request,
|
||||
"page_title": t('nav_users', lang),
|
||||
}
|
||||
context = add_i18n_context(request, context)
|
||||
return templates.TemplateResponse("users.html", context)
|
||||
|
||||
|
||||
# ==================== Schemas ====================
|
||||
|
||||
class RoleBase(BaseModel):
|
||||
name: str = Field(..., min_length=2, max_length=50)
|
||||
display_name: str = Field(..., min_length=2, max_length=100)
|
||||
description: Optional[str] = None
|
||||
permissions: dict = Field(default_factory=dict)
|
||||
|
||||
|
||||
class RoleCreate(RoleBase):
|
||||
pass
|
||||
|
||||
|
||||
class RoleUpdate(BaseModel):
|
||||
display_name: Optional[str] = Field(None, min_length=2, max_length=100)
|
||||
description: Optional[str] = None
|
||||
permissions: Optional[dict] = None
|
||||
is_active: Optional[bool] = None
|
||||
|
||||
|
||||
class RoleResponse(BaseModel):
|
||||
id: int
|
||||
name: str
|
||||
display_name: str
|
||||
description: Optional[str]
|
||||
permissions: dict
|
||||
is_system: bool
|
||||
is_active: bool
|
||||
created_at: datetime
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
|
||||
class UserCreate(BaseModel):
|
||||
username: str = Field(..., min_length=3, max_length=50)
|
||||
email: EmailStr
|
||||
password: str = Field(..., min_length=6)
|
||||
full_name: Optional[str] = Field(None, max_length=100)
|
||||
role_id: Optional[int] = None
|
||||
is_active: bool = True
|
||||
is_admin: bool = False
|
||||
|
||||
|
||||
class UserUpdate(BaseModel):
|
||||
email: Optional[EmailStr] = None
|
||||
full_name: Optional[str] = Field(None, max_length=100)
|
||||
role_id: Optional[int] = None
|
||||
is_active: Optional[bool] = None
|
||||
is_admin: Optional[bool] = None
|
||||
require_password_change: Optional[bool] = None
|
||||
|
||||
|
||||
class UserResponse(BaseModel):
|
||||
id: int
|
||||
username: str
|
||||
email: str
|
||||
full_name: Optional[str]
|
||||
is_active: bool
|
||||
is_admin: bool
|
||||
role_id: Optional[int]
|
||||
role_name: Optional[str] = None
|
||||
failed_login_attempts: int = 0
|
||||
locked_until: Optional[datetime] = None
|
||||
last_login: Optional[datetime] = None
|
||||
created_at: datetime
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
|
||||
class PasswordChange(BaseModel):
|
||||
new_password: str = Field(..., min_length=6)
|
||||
|
||||
|
||||
class SecuritySettingsUpdate(BaseModel):
|
||||
max_login_attempts: Optional[int] = Field(None, ge=1, le=20)
|
||||
lockout_duration_minutes: Optional[int] = Field(None, ge=1, le=1440)
|
||||
session_timeout_minutes: Optional[int] = Field(None, ge=5, le=1440)
|
||||
ip_block_threshold: Optional[int] = Field(None, ge=1, le=100)
|
||||
ip_block_duration_minutes: Optional[int] = Field(None, ge=1, le=10080)
|
||||
password_min_length: Optional[int] = Field(None, ge=6, le=50)
|
||||
password_require_uppercase: Optional[bool] = None
|
||||
password_require_lowercase: Optional[bool] = None
|
||||
password_require_numbers: Optional[bool] = None
|
||||
password_require_special: Optional[bool] = None
|
||||
|
||||
|
||||
# ==================== HTML Pages ====================
|
||||
|
||||
@router.get("/", response_class=HTMLResponse)
|
||||
async def users_page(
|
||||
request: Request,
|
||||
current_user: User = Depends(PermissionChecker("users.view"))
|
||||
):
|
||||
"""Render users management page"""
|
||||
from ..i18n import t
|
||||
lang = request.cookies.get("language", "en")
|
||||
|
||||
context = {
|
||||
"request": request,
|
||||
"page_title": t('nav_users', lang),
|
||||
}
|
||||
context = add_i18n_context(request, context)
|
||||
return templates.TemplateResponse("users.html", context)
|
||||
|
||||
|
||||
# ==================== Role API ====================
|
||||
|
||||
@router.get("/api/roles", response_model=List[RoleResponse])
|
||||
async def list_roles(
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(PermissionChecker("roles.view"))
|
||||
):
|
||||
"""Get all roles"""
|
||||
roles = SecurityService.get_all_roles(db, include_inactive=True)
|
||||
return roles
|
||||
|
||||
|
||||
@router.get("/api/roles/{role_id}", response_model=RoleResponse)
|
||||
async def get_role(
|
||||
role_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(PermissionChecker("roles.view"))
|
||||
):
|
||||
"""Get role by ID"""
|
||||
role = db.query(Role).filter(Role.id == role_id).first()
|
||||
if not role:
|
||||
raise HTTPException(status_code=404, detail="Role not found")
|
||||
return role
|
||||
|
||||
|
||||
@router.post("/api/roles", response_model=RoleResponse, status_code=201)
|
||||
async def create_role(
|
||||
role_data: RoleCreate,
|
||||
request: Request,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(PermissionChecker("roles.manage"))
|
||||
):
|
||||
"""Create a new role"""
|
||||
# Check if role name exists
|
||||
existing = db.query(Role).filter(Role.name == role_data.name.lower()).first()
|
||||
if existing:
|
||||
raise HTTPException(status_code=400, detail="Role name already exists")
|
||||
|
||||
role = SecurityService.create_role(
|
||||
db=db,
|
||||
name=role_data.name,
|
||||
display_name=role_data.display_name,
|
||||
description=role_data.description,
|
||||
permissions=role_data.permissions
|
||||
)
|
||||
|
||||
LoggingService.log(
|
||||
db=db,
|
||||
level=LoggingService.INFO,
|
||||
category=LoggingService.AUTH,
|
||||
action="role_created",
|
||||
message=f"Role '{role.name}' created by {current_user.username}",
|
||||
username=current_user.username,
|
||||
user_id=current_user.id,
|
||||
ip_address=get_client_ip(request),
|
||||
resource_type="role",
|
||||
resource_id=str(role.id),
|
||||
resource_name=role.name
|
||||
)
|
||||
|
||||
return role
|
||||
|
||||
|
||||
@router.put("/api/roles/{role_id}", response_model=RoleResponse)
|
||||
async def update_role(
|
||||
role_id: int,
|
||||
role_data: RoleUpdate,
|
||||
request: Request,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(PermissionChecker("roles.manage"))
|
||||
):
|
||||
"""Update a role"""
|
||||
role = db.query(Role).filter(Role.id == role_id).first()
|
||||
if not role:
|
||||
raise HTTPException(status_code=404, detail="Role not found")
|
||||
|
||||
# Update fields
|
||||
if role_data.display_name is not None:
|
||||
role.display_name = role_data.display_name
|
||||
if role_data.description is not None:
|
||||
role.description = role_data.description
|
||||
if role_data.permissions is not None:
|
||||
role.permissions = role_data.permissions
|
||||
if role_data.is_active is not None:
|
||||
role.is_active = role_data.is_active
|
||||
|
||||
role.updated_at = utcnow()
|
||||
db.commit()
|
||||
db.refresh(role)
|
||||
|
||||
LoggingService.log(
|
||||
db=db,
|
||||
level=LoggingService.INFO,
|
||||
category=LoggingService.AUTH,
|
||||
action="role_updated",
|
||||
message=f"Role '{role.name}' updated by {current_user.username}",
|
||||
username=current_user.username,
|
||||
user_id=current_user.id,
|
||||
ip_address=get_client_ip(request),
|
||||
resource_type="role",
|
||||
resource_id=str(role.id),
|
||||
resource_name=role.name
|
||||
)
|
||||
|
||||
return role
|
||||
|
||||
|
||||
@router.delete("/api/roles/{role_id}")
|
||||
async def delete_role(
|
||||
role_id: int,
|
||||
request: Request,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(PermissionChecker("roles.manage"))
|
||||
):
|
||||
"""Delete a role"""
|
||||
success, message = SecurityService.delete_role(db, role_id)
|
||||
if not success:
|
||||
raise HTTPException(status_code=400, detail=message)
|
||||
|
||||
LoggingService.log(
|
||||
db=db,
|
||||
level=LoggingService.WARNING,
|
||||
category=LoggingService.AUTH,
|
||||
action="role_deleted",
|
||||
message=f"Role ID {role_id} deleted by {current_user.username}",
|
||||
username=current_user.username,
|
||||
user_id=current_user.id,
|
||||
ip_address=get_client_ip(request),
|
||||
resource_type="role",
|
||||
resource_id=str(role_id)
|
||||
)
|
||||
|
||||
return {"message": "Role deleted"}
|
||||
|
||||
|
||||
@router.get("/api/permissions")
|
||||
async def get_all_permissions(
|
||||
current_user: User = Depends(PermissionChecker("roles.view"))
|
||||
):
|
||||
"""Get all available permissions (legacy format for backwards compatibility)"""
|
||||
return SecurityService.get_all_permissions()
|
||||
|
||||
|
||||
@router.get("/api/permissions/v2")
|
||||
async def get_all_permissions_v2(
|
||||
current_user: User = Depends(PermissionChecker("roles.view"))
|
||||
):
|
||||
"""
|
||||
Get all available permissions in new format.
|
||||
Returns permissions grouped by category with resource:action codes.
|
||||
"""
|
||||
return SecurityService.get_all_permissions_v2()
|
||||
|
||||
|
||||
# ==================== User API ====================
|
||||
|
||||
@router.get("/api/users", response_model=List[UserResponse])
|
||||
async def list_users(
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(PermissionChecker("users.view"))
|
||||
):
|
||||
"""Get all users"""
|
||||
users = db.query(User).order_by(User.username).all()
|
||||
|
||||
# Add role_name
|
||||
result = []
|
||||
for user in users:
|
||||
user_dict = {
|
||||
"id": user.id,
|
||||
"username": user.username,
|
||||
"email": user.email,
|
||||
"full_name": user.full_name,
|
||||
"is_active": user.is_active,
|
||||
"is_admin": user.is_admin,
|
||||
"role_id": user.role_id,
|
||||
"role_name": user.role.display_name if user.role else ("Administrator" if user.is_admin else "User"),
|
||||
"failed_login_attempts": user.failed_login_attempts or 0,
|
||||
"locked_until": user.locked_until,
|
||||
"last_login": user.last_login,
|
||||
"created_at": user.created_at
|
||||
}
|
||||
result.append(user_dict)
|
||||
|
||||
return result
|
||||
|
||||
|
||||
@router.get("/api/users/{user_id}", response_model=UserResponse)
|
||||
async def get_user(
|
||||
user_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(PermissionChecker("users.view"))
|
||||
):
|
||||
"""Get user by ID"""
|
||||
user = db.query(User).filter(User.id == user_id).first()
|
||||
if not user:
|
||||
raise HTTPException(status_code=404, detail="User not found")
|
||||
|
||||
return {
|
||||
"id": user.id,
|
||||
"username": user.username,
|
||||
"email": user.email,
|
||||
"full_name": user.full_name,
|
||||
"is_active": user.is_active,
|
||||
"is_admin": user.is_admin,
|
||||
"role_id": user.role_id,
|
||||
"role_name": user.role.display_name if user.role else None,
|
||||
"failed_login_attempts": user.failed_login_attempts or 0,
|
||||
"locked_until": user.locked_until,
|
||||
"last_login": user.last_login,
|
||||
"created_at": user.created_at
|
||||
}
|
||||
|
||||
|
||||
@router.post("/api/users", response_model=UserResponse, status_code=201)
|
||||
async def create_user(
|
||||
user_data: UserCreate,
|
||||
request: Request,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(PermissionChecker("users.create"))
|
||||
):
|
||||
"""Create a new user"""
|
||||
# Check username
|
||||
if db.query(User).filter(User.username == user_data.username).first():
|
||||
raise HTTPException(status_code=400, detail="Username already exists")
|
||||
|
||||
# Check email
|
||||
if db.query(User).filter(User.email == user_data.email).first():
|
||||
raise HTTPException(status_code=400, detail="Email already exists")
|
||||
|
||||
# Validate password
|
||||
is_valid, errors = SecurityService.validate_password(db, user_data.password)
|
||||
if not is_valid:
|
||||
raise HTTPException(status_code=400, detail="; ".join(errors))
|
||||
|
||||
# Validate role
|
||||
if user_data.role_id:
|
||||
role = db.query(Role).filter(Role.id == user_data.role_id).first()
|
||||
if not role:
|
||||
raise HTTPException(status_code=400, detail="Invalid role")
|
||||
|
||||
# Create user
|
||||
user = User(
|
||||
username=user_data.username,
|
||||
email=user_data.email,
|
||||
hashed_password=get_password_hash(user_data.password),
|
||||
full_name=user_data.full_name,
|
||||
role_id=user_data.role_id,
|
||||
is_active=user_data.is_active,
|
||||
is_admin=user_data.is_admin,
|
||||
last_password_change=utcnow()
|
||||
)
|
||||
|
||||
db.add(user)
|
||||
db.commit()
|
||||
db.refresh(user)
|
||||
|
||||
LoggingService.log(
|
||||
db=db,
|
||||
level=LoggingService.INFO,
|
||||
category=LoggingService.AUTH,
|
||||
action="user_created",
|
||||
message=f"User '{user.username}' created by {current_user.username}",
|
||||
username=current_user.username,
|
||||
user_id=current_user.id,
|
||||
ip_address=get_client_ip(request),
|
||||
resource_type="user",
|
||||
resource_id=str(user.id),
|
||||
resource_name=user.username
|
||||
)
|
||||
|
||||
return {
|
||||
"id": user.id,
|
||||
"username": user.username,
|
||||
"email": user.email,
|
||||
"full_name": user.full_name,
|
||||
"is_active": user.is_active,
|
||||
"is_admin": user.is_admin,
|
||||
"role_id": user.role_id,
|
||||
"role_name": user.role.display_name if user.role else None,
|
||||
"failed_login_attempts": 0,
|
||||
"locked_until": None,
|
||||
"last_login": None,
|
||||
"created_at": user.created_at
|
||||
}
|
||||
|
||||
|
||||
@router.put("/api/users/{user_id}", response_model=UserResponse)
|
||||
async def update_user(
|
||||
user_id: int,
|
||||
user_data: UserUpdate,
|
||||
request: Request,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(PermissionChecker("users.edit"))
|
||||
):
|
||||
"""Update a user"""
|
||||
user = db.query(User).filter(User.id == user_id).first()
|
||||
if not user:
|
||||
raise HTTPException(status_code=404, detail="User not found")
|
||||
|
||||
# Prevent editing admin by non-admin
|
||||
if user.is_admin and not current_user.is_admin:
|
||||
raise HTTPException(status_code=403, detail="Cannot edit admin user")
|
||||
|
||||
# Update fields
|
||||
if user_data.email is not None:
|
||||
# Check email uniqueness
|
||||
existing = db.query(User).filter(User.email == user_data.email, User.id != user_id).first()
|
||||
if existing:
|
||||
raise HTTPException(status_code=400, detail="Email already exists")
|
||||
user.email = user_data.email
|
||||
|
||||
if user_data.full_name is not None:
|
||||
user.full_name = user_data.full_name
|
||||
|
||||
if user_data.role_id is not None:
|
||||
role = db.query(Role).filter(Role.id == user_data.role_id).first()
|
||||
if not role:
|
||||
raise HTTPException(status_code=400, detail="Invalid role")
|
||||
user.role_id = user_data.role_id
|
||||
|
||||
if user_data.is_active is not None:
|
||||
# Cannot deactivate yourself
|
||||
if user_id == current_user.id and not user_data.is_active:
|
||||
raise HTTPException(status_code=400, detail="Cannot deactivate yourself")
|
||||
user.is_active = user_data.is_active
|
||||
|
||||
# Terminate sessions if deactivating
|
||||
if not user_data.is_active:
|
||||
SecurityService.terminate_all_user_sessions(db, user_id)
|
||||
|
||||
if user_data.require_password_change is not None:
|
||||
user.require_password_change = user_data.require_password_change
|
||||
|
||||
if user_data.is_admin is not None:
|
||||
# Only admin can change admin status
|
||||
if not current_user.is_admin:
|
||||
raise HTTPException(status_code=403, detail="Only admin can change admin status")
|
||||
# Cannot remove own admin status
|
||||
if user_id == current_user.id and not user_data.is_admin:
|
||||
raise HTTPException(status_code=400, detail="Cannot remove your own admin status")
|
||||
user.is_admin = user_data.is_admin
|
||||
|
||||
user.updated_at = utcnow()
|
||||
db.commit()
|
||||
db.refresh(user)
|
||||
|
||||
LoggingService.log(
|
||||
db=db,
|
||||
level=LoggingService.INFO,
|
||||
category=LoggingService.AUTH,
|
||||
action="user_updated",
|
||||
message=f"User '{user.username}' updated by {current_user.username}",
|
||||
username=current_user.username,
|
||||
user_id=current_user.id,
|
||||
ip_address=get_client_ip(request),
|
||||
resource_type="user",
|
||||
resource_id=str(user.id),
|
||||
resource_name=user.username
|
||||
)
|
||||
|
||||
return {
|
||||
"id": user.id,
|
||||
"username": user.username,
|
||||
"email": user.email,
|
||||
"full_name": user.full_name,
|
||||
"is_active": user.is_active,
|
||||
"is_admin": user.is_admin,
|
||||
"role_id": user.role_id,
|
||||
"role_name": user.role.display_name if user.role else None,
|
||||
"failed_login_attempts": user.failed_login_attempts or 0,
|
||||
"locked_until": user.locked_until,
|
||||
"last_login": user.last_login,
|
||||
"created_at": user.created_at
|
||||
}
|
||||
|
||||
|
||||
@router.delete("/api/users/{user_id}")
|
||||
async def delete_user(
|
||||
user_id: int,
|
||||
request: Request,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(PermissionChecker("users.delete"))
|
||||
):
|
||||
"""Delete a user"""
|
||||
user = db.query(User).filter(User.id == user_id).first()
|
||||
if not user:
|
||||
raise HTTPException(status_code=404, detail="User not found")
|
||||
|
||||
# Cannot delete yourself
|
||||
if user_id == current_user.id:
|
||||
raise HTTPException(status_code=400, detail="Cannot delete yourself")
|
||||
|
||||
# Cannot delete admin
|
||||
if user.is_admin:
|
||||
raise HTTPException(status_code=400, detail="Cannot delete admin user")
|
||||
|
||||
username = user.username
|
||||
|
||||
# Terminate all sessions
|
||||
SecurityService.terminate_all_user_sessions(db, user_id)
|
||||
|
||||
db.delete(user)
|
||||
db.commit()
|
||||
|
||||
LoggingService.log(
|
||||
db=db,
|
||||
level=LoggingService.WARNING,
|
||||
category=LoggingService.AUTH,
|
||||
action="user_deleted",
|
||||
message=f"User '{username}' deleted by {current_user.username}",
|
||||
username=current_user.username,
|
||||
user_id=current_user.id,
|
||||
ip_address=get_client_ip(request),
|
||||
resource_type="user",
|
||||
resource_id=str(user_id),
|
||||
resource_name=username
|
||||
)
|
||||
|
||||
return {"message": "User deleted"}
|
||||
|
||||
|
||||
@router.post("/api/users/{user_id}/reset-password")
|
||||
async def reset_user_password(
|
||||
user_id: int,
|
||||
password_data: PasswordChange,
|
||||
request: Request,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(PermissionChecker("users.edit"))
|
||||
):
|
||||
"""Reset user password (admin action)"""
|
||||
user = db.query(User).filter(User.id == user_id).first()
|
||||
if not user:
|
||||
raise HTTPException(status_code=404, detail="User not found")
|
||||
|
||||
# Validate password
|
||||
is_valid, errors = SecurityService.validate_password(db, password_data.new_password)
|
||||
if not is_valid:
|
||||
raise HTTPException(status_code=400, detail="; ".join(errors))
|
||||
|
||||
user.hashed_password = get_password_hash(password_data.new_password)
|
||||
user.last_password_change = utcnow()
|
||||
user.require_password_change = True # Force password change on next login
|
||||
user.failed_login_attempts = 0
|
||||
user.locked_until = None
|
||||
db.commit()
|
||||
|
||||
# Terminate all sessions
|
||||
SecurityService.terminate_all_user_sessions(db, user_id)
|
||||
|
||||
LoggingService.log(
|
||||
db=db,
|
||||
level=LoggingService.WARNING,
|
||||
category=LoggingService.AUTH,
|
||||
action="password_reset",
|
||||
message=f"Password reset for user '{user.username}' by {current_user.username}",
|
||||
username=current_user.username,
|
||||
user_id=current_user.id,
|
||||
ip_address=get_client_ip(request),
|
||||
resource_type="user",
|
||||
resource_id=str(user.id),
|
||||
resource_name=user.username
|
||||
)
|
||||
|
||||
return {"message": "Password reset successfully"}
|
||||
|
||||
|
||||
@router.post("/api/users/{user_id}/unlock")
|
||||
async def unlock_user(
|
||||
user_id: int,
|
||||
request: Request,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(PermissionChecker("users.edit"))
|
||||
):
|
||||
"""Unlock a locked user account"""
|
||||
user = db.query(User).filter(User.id == user_id).first()
|
||||
if not user:
|
||||
raise HTTPException(status_code=404, detail="User not found")
|
||||
|
||||
user.failed_login_attempts = 0
|
||||
user.locked_until = None
|
||||
db.commit()
|
||||
|
||||
LoggingService.log(
|
||||
db=db,
|
||||
level=LoggingService.INFO,
|
||||
category=LoggingService.AUTH,
|
||||
action="user_unlocked",
|
||||
message=f"User '{user.username}' unlocked by {current_user.username}",
|
||||
username=current_user.username,
|
||||
user_id=current_user.id,
|
||||
ip_address=get_client_ip(request),
|
||||
resource_type="user",
|
||||
resource_id=str(user.id),
|
||||
resource_name=user.username
|
||||
)
|
||||
|
||||
return {"message": "User unlocked"}
|
||||
|
||||
|
||||
@router.post("/api/users/{user_id}/terminate-sessions")
|
||||
async def terminate_user_sessions(
|
||||
user_id: int,
|
||||
request: Request,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(PermissionChecker("users.edit"))
|
||||
):
|
||||
"""Terminate all sessions for a user"""
|
||||
user = db.query(User).filter(User.id == user_id).first()
|
||||
if not user:
|
||||
raise HTTPException(status_code=404, detail="User not found")
|
||||
|
||||
count = SecurityService.terminate_all_user_sessions(db, user_id)
|
||||
|
||||
LoggingService.log(
|
||||
db=db,
|
||||
level=LoggingService.INFO,
|
||||
category=LoggingService.AUTH,
|
||||
action="sessions_terminated",
|
||||
message=f"Terminated {count} sessions for user '{user.username}' by {current_user.username}",
|
||||
username=current_user.username,
|
||||
user_id=current_user.id,
|
||||
ip_address=get_client_ip(request),
|
||||
resource_type="user",
|
||||
resource_id=str(user.id),
|
||||
resource_name=user.username
|
||||
)
|
||||
|
||||
return {"message": f"Terminated {count} sessions"}
|
||||
|
||||
|
||||
# ==================== Security Settings API ====================
|
||||
|
||||
@router.get("/api/security/settings")
|
||||
async def get_security_settings(
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(PermissionChecker("settings.security"))
|
||||
):
|
||||
"""Get security settings"""
|
||||
return {
|
||||
"max_login_attempts": SecurityService.get_setting_int(db, "max_login_attempts", 5),
|
||||
"lockout_duration_minutes": SecurityService.get_setting_int(db, "lockout_duration_minutes", 30),
|
||||
"session_timeout_minutes": SecurityService.get_setting_int(db, "session_timeout_minutes", 60),
|
||||
"ip_block_threshold": SecurityService.get_setting_int(db, "ip_block_threshold", 10),
|
||||
"ip_block_duration_minutes": SecurityService.get_setting_int(db, "ip_block_duration_minutes", 60),
|
||||
"password_min_length": SecurityService.get_setting_int(db, "password_min_length", 8),
|
||||
"password_require_uppercase": SecurityService.get_setting_bool(db, "password_require_uppercase", True),
|
||||
"password_require_lowercase": SecurityService.get_setting_bool(db, "password_require_lowercase", True),
|
||||
"password_require_numbers": SecurityService.get_setting_bool(db, "password_require_numbers", True),
|
||||
"password_require_special": SecurityService.get_setting_bool(db, "password_require_special", False),
|
||||
}
|
||||
|
||||
|
||||
@router.put("/api/security/settings")
|
||||
async def update_security_settings(
|
||||
settings_data: SecuritySettingsUpdate,
|
||||
request: Request,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(PermissionChecker("settings.security"))
|
||||
):
|
||||
"""Update security settings"""
|
||||
updated = []
|
||||
|
||||
for key, value in settings_data.model_dump(exclude_unset=True).items():
|
||||
SecurityService.update_setting(db, key, str(value).lower() if isinstance(value, bool) else str(value))
|
||||
updated.append(key)
|
||||
|
||||
if updated:
|
||||
LoggingService.log(
|
||||
db=db,
|
||||
level=LoggingService.INFO,
|
||||
category=LoggingService.AUTH,
|
||||
action="security_settings_updated",
|
||||
message=f"Security settings updated by {current_user.username}: {', '.join(updated)}",
|
||||
username=current_user.username,
|
||||
user_id=current_user.id,
|
||||
ip_address=get_client_ip(request)
|
||||
)
|
||||
|
||||
return {"message": "Settings updated", "updated": updated}
|
||||
|
||||
|
||||
# ==================== Blocked IPs API ====================
|
||||
|
||||
@router.get("/api/security/blocked-ips")
|
||||
async def list_blocked_ips(
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(PermissionChecker("settings.security"))
|
||||
):
|
||||
"""Get list of blocked IPs"""
|
||||
from ..models import BlockedIP
|
||||
blocked = db.query(BlockedIP).order_by(BlockedIP.blocked_at.desc()).all()
|
||||
return [{
|
||||
"id": ip.id,
|
||||
"ip_address": ip.ip_address,
|
||||
"reason": ip.reason,
|
||||
"blocked_by": ip.blocked_by,
|
||||
"blocked_at": ip.blocked_at.isoformat() if ip.blocked_at else None,
|
||||
"expires_at": ip.expires_at.isoformat() if ip.expires_at else None,
|
||||
"is_permanent": ip.is_permanent,
|
||||
"attempts_count": ip.attempts_count,
|
||||
"is_active": ip.is_blocked()
|
||||
} for ip in blocked]
|
||||
|
||||
|
||||
@router.delete("/api/security/blocked-ips/{ip_address:path}")
|
||||
async def unblock_ip(
|
||||
ip_address: str,
|
||||
request: Request,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(PermissionChecker("settings.security"))
|
||||
):
|
||||
"""Unblock an IP address"""
|
||||
if SecurityService.unblock_ip(db, ip_address):
|
||||
LoggingService.log(
|
||||
db=db,
|
||||
level=LoggingService.INFO,
|
||||
category=LoggingService.AUTH,
|
||||
action="ip_unblocked",
|
||||
message=f"IP {ip_address} unblocked by {current_user.username}",
|
||||
username=current_user.username,
|
||||
user_id=current_user.id,
|
||||
ip_address=get_client_ip(request)
|
||||
)
|
||||
return {"message": f"IP {ip_address} unblocked"}
|
||||
|
||||
raise HTTPException(status_code=404, detail="IP not found in blocked list")
|
||||
|
||||
|
||||
# ==================== Sessions API ====================
|
||||
|
||||
@router.get("/api/sessions")
|
||||
async def list_sessions(
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(PermissionChecker("users.view"))
|
||||
):
|
||||
"""Get list of active sessions"""
|
||||
from ..models import ActiveSession
|
||||
|
||||
sessions = db.query(ActiveSession).filter(
|
||||
ActiveSession.expires_at > utcnow()
|
||||
).order_by(ActiveSession.last_activity.desc()).all()
|
||||
|
||||
result = []
|
||||
for session in sessions:
|
||||
user = db.query(User).filter(User.id == session.user_id).first()
|
||||
result.append({
|
||||
"id": session.id,
|
||||
"user_id": session.user_id,
|
||||
"username": user.username if user else "Unknown",
|
||||
"ip_address": session.ip_address,
|
||||
"device_info": session.device_info,
|
||||
"created_at": session.created_at.isoformat() if session.created_at else None,
|
||||
"last_activity": session.last_activity.isoformat() if session.last_activity else None,
|
||||
"expires_at": session.expires_at.isoformat() if session.expires_at else None,
|
||||
})
|
||||
|
||||
return result
|
||||
|
||||
|
||||
@router.delete("/api/sessions/{session_id}")
|
||||
async def terminate_session(
|
||||
session_id: int,
|
||||
request: Request,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(PermissionChecker("users.edit"))
|
||||
):
|
||||
"""Terminate a specific session"""
|
||||
from ..models import ActiveSession
|
||||
|
||||
session = db.query(ActiveSession).filter(ActiveSession.id == session_id).first()
|
||||
if not session:
|
||||
raise HTTPException(status_code=404, detail="Session not found")
|
||||
|
||||
db.delete(session)
|
||||
db.commit()
|
||||
|
||||
LoggingService.log(
|
||||
db=db,
|
||||
level=LoggingService.INFO,
|
||||
category=LoggingService.AUTH,
|
||||
action="session_terminated",
|
||||
message=f"Session {session_id} terminated by {current_user.username}",
|
||||
username=current_user.username,
|
||||
user_id=current_user.id,
|
||||
ip_address=get_client_ip(request)
|
||||
)
|
||||
|
||||
return {"message": "Session terminated"}
|
||||
|
||||
|
||||
@router.post("/api/sessions/terminate-all")
|
||||
async def terminate_all_sessions(
|
||||
request: Request,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(PermissionChecker("users.edit"))
|
||||
):
|
||||
"""Terminate all sessions except current user's"""
|
||||
from ..models import ActiveSession
|
||||
|
||||
# Delete all sessions except current user's
|
||||
deleted = db.query(ActiveSession).filter(
|
||||
ActiveSession.user_id != current_user.id
|
||||
).delete()
|
||||
db.commit()
|
||||
|
||||
LoggingService.log(
|
||||
db=db,
|
||||
level=LoggingService.WARNING,
|
||||
category=LoggingService.AUTH,
|
||||
action="all_sessions_terminated",
|
||||
message=f"All sessions ({deleted}) terminated by {current_user.username}",
|
||||
username=current_user.username,
|
||||
user_id=current_user.id,
|
||||
ip_address=get_client_ip(request)
|
||||
)
|
||||
|
||||
return {"message": f"Terminated {deleted} sessions"}
|
||||
|
||||
|
||||
# ==================== Security Events API ====================
|
||||
|
||||
@router.get("/api/security/events")
|
||||
async def list_security_events(
|
||||
limit: int = 50,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(PermissionChecker("settings.security"))
|
||||
):
|
||||
"""Get security events from logs"""
|
||||
from ..models import AuditLog
|
||||
|
||||
# Get auth-related logs
|
||||
events = db.query(AuditLog).filter(
|
||||
AuditLog.category == "auth"
|
||||
).order_by(AuditLog.created_at.desc()).limit(limit).all()
|
||||
|
||||
return [{
|
||||
"id": event.id,
|
||||
"event_type": event.action,
|
||||
"ip_address": event.ip_address,
|
||||
"username": event.username,
|
||||
"message": event.message,
|
||||
"created_at": event.created_at.isoformat() if event.created_at else None,
|
||||
} for event in events]
|
||||
|
||||
|
||||
# ==================== Block IP API ====================
|
||||
|
||||
@router.post("/api/security/blocked-ips")
|
||||
async def block_ip(
|
||||
ip_data: dict,
|
||||
request: Request,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(PermissionChecker("settings.security"))
|
||||
):
|
||||
"""Block an IP address manually"""
|
||||
from ..models import BlockedIP
|
||||
|
||||
ip_address = ip_data.get("ip_address")
|
||||
reason = ip_data.get("reason", "Manual block")
|
||||
duration_minutes = ip_data.get("duration_minutes")
|
||||
|
||||
if not ip_address:
|
||||
raise HTTPException(status_code=400, detail="IP address is required")
|
||||
|
||||
# Check if already blocked
|
||||
existing = db.query(BlockedIP).filter(BlockedIP.ip_address == ip_address).first()
|
||||
if existing:
|
||||
raise HTTPException(status_code=400, detail="IP is already blocked")
|
||||
|
||||
# Calculate expiry
|
||||
expires_at = None
|
||||
is_permanent = True
|
||||
if duration_minutes:
|
||||
expires_at = utcnow() + timedelta(minutes=int(duration_minutes))
|
||||
is_permanent = False
|
||||
|
||||
blocked_ip = BlockedIP(
|
||||
ip_address=ip_address,
|
||||
reason=reason,
|
||||
blocked_by=current_user.username,
|
||||
blocked_at=utcnow(),
|
||||
expires_at=expires_at,
|
||||
is_permanent=is_permanent
|
||||
)
|
||||
db.add(blocked_ip)
|
||||
db.commit()
|
||||
|
||||
LoggingService.log(
|
||||
db=db,
|
||||
level=LoggingService.WARNING,
|
||||
category=LoggingService.AUTH,
|
||||
action="ip_blocked_manual",
|
||||
message=f"IP {ip_address} blocked manually by {current_user.username}: {reason}",
|
||||
username=current_user.username,
|
||||
user_id=current_user.id,
|
||||
ip_address=get_client_ip(request)
|
||||
)
|
||||
|
||||
return {"message": f"IP {ip_address} blocked", "id": blocked_ip.id}
|
||||
|
||||
|
||||
@router.delete("/api/security/blocked-ips/{blocked_id}")
|
||||
async def unblock_ip_by_id(
|
||||
blocked_id: int,
|
||||
request: Request,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(PermissionChecker("settings.security"))
|
||||
):
|
||||
"""Unblock an IP address by ID"""
|
||||
from ..models import BlockedIP
|
||||
|
||||
blocked_ip = db.query(BlockedIP).filter(BlockedIP.id == blocked_id).first()
|
||||
if not blocked_ip:
|
||||
raise HTTPException(status_code=404, detail="Blocked IP not found")
|
||||
|
||||
ip_address = blocked_ip.ip_address
|
||||
db.delete(blocked_ip)
|
||||
db.commit()
|
||||
|
||||
LoggingService.log(
|
||||
db=db,
|
||||
level=LoggingService.INFO,
|
||||
category=LoggingService.AUTH,
|
||||
action="ip_unblocked",
|
||||
message=f"IP {ip_address} unblocked by {current_user.username}",
|
||||
username=current_user.username,
|
||||
user_id=current_user.id,
|
||||
ip_address=get_client_ip(request)
|
||||
)
|
||||
|
||||
return {"message": f"IP {ip_address} unblocked"}
|
||||
224
backend/app/auth.py
Normal file
224
backend/app/auth.py
Normal file
@@ -0,0 +1,224 @@
|
||||
"""
|
||||
Authentication module with enhanced security
|
||||
"""
|
||||
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Optional
|
||||
from functools import wraps
|
||||
import jwt
|
||||
from passlib.context import CryptContext
|
||||
from fastapi import Depends, HTTPException, status, Request
|
||||
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
||||
from sqlalchemy.orm import Session, joinedload
|
||||
|
||||
from .config import settings
|
||||
from .db import get_db
|
||||
from .models import User
|
||||
|
||||
# Password hashing
|
||||
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
||||
|
||||
# JWT Bearer token
|
||||
security = HTTPBearer()
|
||||
|
||||
|
||||
def verify_password(plain_password: str, hashed_password: str) -> bool:
|
||||
"""Verify a password against a 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, session_token: str = None, expires_delta: Optional[timedelta] = None) -> str:
|
||||
"""Create JWT access token with optional session binding"""
|
||||
to_encode = data.copy()
|
||||
now = datetime.now(timezone.utc)
|
||||
if expires_delta:
|
||||
expire = now + expires_delta
|
||||
else:
|
||||
expire = now + timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
|
||||
|
||||
to_encode.update({
|
||||
"exp": expire,
|
||||
"iat": now
|
||||
})
|
||||
|
||||
# Include session token for validation
|
||||
if session_token:
|
||||
to_encode["session"] = session_token
|
||||
|
||||
encoded_jwt = jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM)
|
||||
return encoded_jwt
|
||||
|
||||
|
||||
def decode_access_token(token: str) -> Optional[dict]:
|
||||
"""Decode JWT access token"""
|
||||
try:
|
||||
payload = jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM])
|
||||
return payload
|
||||
except jwt.ExpiredSignatureError:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Token has expired",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
except jwt.PyJWTError:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Could not validate credentials",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
|
||||
|
||||
def get_current_user(
|
||||
credentials: HTTPAuthorizationCredentials = Depends(security),
|
||||
db: Session = Depends(get_db)
|
||||
) -> User:
|
||||
"""Get current authenticated user with session validation"""
|
||||
token = credentials.credentials
|
||||
payload = decode_access_token(token)
|
||||
|
||||
username: str = payload.get("sub")
|
||||
session_token: str = payload.get("session")
|
||||
|
||||
if username is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Could not validate credentials",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
|
||||
# Validate session if present
|
||||
if session_token:
|
||||
from .services.security_service import SecurityService
|
||||
session = SecurityService.validate_session(db, session_token)
|
||||
if not session:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Session expired or invalid. Please login again.",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
|
||||
user = db.query(User).options(joinedload(User.role)).filter(User.username == username).first()
|
||||
if user is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="User not found",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
|
||||
if not user.is_active:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="User account is disabled"
|
||||
)
|
||||
|
||||
# Check if account is locked
|
||||
if user.is_locked():
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Account is locked. Please try again later."
|
||||
)
|
||||
|
||||
return user
|
||||
|
||||
|
||||
def get_current_session_token(
|
||||
credentials: HTTPAuthorizationCredentials = Depends(security)
|
||||
) -> str:
|
||||
"""Get current session token from JWT"""
|
||||
token = credentials.credentials
|
||||
payload = decode_access_token(token)
|
||||
return payload.get("session")
|
||||
|
||||
|
||||
def get_current_active_admin(current_user: User = Depends(get_current_user)) -> User:
|
||||
"""Get current active admin user"""
|
||||
if not current_user.is_admin and (not current_user.role or current_user.role.name != "admin"):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Administrator access required"
|
||||
)
|
||||
return current_user
|
||||
|
||||
|
||||
class PermissionChecker:
|
||||
"""
|
||||
Dependency for checking permissions.
|
||||
Usage: Depends(PermissionChecker("vms.create"))
|
||||
|
||||
Supports both legacy (vms.create) and new (vm:create) permission formats.
|
||||
"""
|
||||
def __init__(self, permission: str):
|
||||
self.permission = permission
|
||||
|
||||
def __call__(self, current_user: User = Depends(get_current_user)) -> User:
|
||||
# Use new RBAC engine
|
||||
from .rbac import PermissionEngine
|
||||
|
||||
if not PermissionEngine.has_permission(current_user, self.permission):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail=f"Permission denied: {self.permission}"
|
||||
)
|
||||
return current_user
|
||||
|
||||
|
||||
def check_permission(user: User, permission: str) -> bool:
|
||||
"""Check if user has specific permission"""
|
||||
from .rbac import PermissionEngine
|
||||
return PermissionEngine.has_permission(user, permission)
|
||||
|
||||
|
||||
def require_permission(user: User, permission: str) -> None:
|
||||
"""Require user to have specific permission, raise 403 if not"""
|
||||
from .rbac import PermissionEngine
|
||||
PermissionEngine.check_permission(user, permission)
|
||||
|
||||
|
||||
def get_client_ip(request: Request) -> str:
|
||||
"""Get client IP from request, handling proxies"""
|
||||
# Try X-Forwarded-For first (from nginx/proxy)
|
||||
forwarded = request.headers.get("x-forwarded-for")
|
||||
if forwarded:
|
||||
return forwarded.split(",")[0].strip()
|
||||
|
||||
# Try X-Real-IP
|
||||
real_ip = request.headers.get("x-real-ip")
|
||||
if real_ip:
|
||||
return real_ip
|
||||
|
||||
# Fall back to direct client
|
||||
if request.client:
|
||||
return request.client.host
|
||||
|
||||
return "unknown"
|
||||
|
||||
|
||||
# Optional auth - allows both authenticated and anonymous access
|
||||
class OptionalHTTPBearer(HTTPBearer):
|
||||
async def __call__(self, request: Request):
|
||||
try:
|
||||
return await super().__call__(request)
|
||||
except HTTPException:
|
||||
return None
|
||||
|
||||
|
||||
optional_security = OptionalHTTPBearer()
|
||||
|
||||
|
||||
def get_current_user_optional(
|
||||
credentials: Optional[HTTPAuthorizationCredentials] = Depends(optional_security),
|
||||
db: Session = Depends(get_db)
|
||||
) -> Optional[User]:
|
||||
"""Get current user if authenticated, None otherwise"""
|
||||
if credentials is None:
|
||||
return None
|
||||
|
||||
try:
|
||||
return get_current_user(credentials, db)
|
||||
except HTTPException:
|
||||
return None
|
||||
87
backend/app/config.py
Normal file
87
backend/app/config.py
Normal file
@@ -0,0 +1,87 @@
|
||||
import os
|
||||
from typing import Optional
|
||||
from pydantic_settings import BaseSettings
|
||||
from pydantic import Field
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def get_version() -> str:
|
||||
"""Read version from VERSION file"""
|
||||
# Try multiple locations for VERSION file
|
||||
possible_paths = [
|
||||
Path(__file__).parent.parent.parent.parent / "VERSION", # Development
|
||||
Path(__file__).parent.parent / "VERSION", # Docker /app/VERSION
|
||||
Path("/app/VERSION"), # Docker absolute
|
||||
]
|
||||
for version_file in possible_paths:
|
||||
if version_file.exists():
|
||||
return version_file.read_text().strip()
|
||||
return "1.7.0"
|
||||
|
||||
|
||||
class Settings(BaseSettings):
|
||||
# Panel name - configurable but not shown in UI by default
|
||||
PANEL_NAME: str = Field(default="PVEmanager", env="PANEL_NAME")
|
||||
VERSION: str = Field(default_factory=get_version)
|
||||
DEBUG: bool = Field(default=False, env="DEBUG")
|
||||
|
||||
# Database settings
|
||||
DB_HOST: str = Field(default="localhost", env="DB_HOST")
|
||||
DB_PORT: int = Field(default=5432, env="DB_PORT")
|
||||
DB_USER: str = Field(default="serverpanel", env="DB_USER")
|
||||
DB_PASSWORD: str = Field(default="serverpanel", env="DB_PASSWORD")
|
||||
DB_NAME: str = Field(default="serverpanel", env="DB_NAME")
|
||||
DATABASE_URL: Optional[str] = Field(default=None, env="DATABASE_URL")
|
||||
|
||||
# Security settings
|
||||
SECRET_KEY: str = Field(default="your-secret-key-here", env="SECRET_KEY")
|
||||
ALGORITHM: str = "HS256"
|
||||
ACCESS_TOKEN_EXPIRE_MINUTES: int = Field(default=480, env="ACCESS_TOKEN_EXPIRE_MINUTES") # 8 hours
|
||||
|
||||
# Logging settings
|
||||
LOG_LEVEL: str = Field(default="INFO", env="LOG_LEVEL")
|
||||
LOG_FILE: str = Field(default="logs/app.log", env="LOG_FILE")
|
||||
|
||||
# SSH settings
|
||||
SSH_TIMEOUT: int = Field(default=10, env="SSH_TIMEOUT")
|
||||
DEFAULT_SSH_USER: str = Field(default="root", env="DEFAULT_SSH_USER")
|
||||
DEFAULT_SSH_PORT: int = Field(default=22, env="DEFAULT_SSH_PORT")
|
||||
|
||||
# Timezone
|
||||
TZ: str = Field(default="UTC", env="TZ")
|
||||
|
||||
model_config = {
|
||||
"env_file": ".env",
|
||||
"env_file_encoding": "utf-8",
|
||||
"case_sensitive": False,
|
||||
}
|
||||
|
||||
@property
|
||||
def SQLALCHEMY_DATABASE_URI(self) -> str:
|
||||
if self.DATABASE_URL:
|
||||
return self.DATABASE_URL.replace("postgresql://", "postgresql+psycopg2://")
|
||||
return (
|
||||
f"postgresql+psycopg2://{self.DB_USER}:"
|
||||
f"{self.DB_PASSWORD}@{self.DB_HOST}:"
|
||||
f"{self.DB_PORT}/{self.DB_NAME}"
|
||||
)
|
||||
|
||||
@property
|
||||
def get_db_url(self) -> str:
|
||||
"""Get database URL for alembic and other tools"""
|
||||
return self.SQLALCHEMY_DATABASE_URI
|
||||
|
||||
|
||||
settings = Settings()
|
||||
|
||||
|
||||
# Timezone-aware datetime helper
|
||||
from datetime import datetime, timezone
|
||||
|
||||
def utcnow() -> datetime:
|
||||
"""Get current UTC time as timezone-aware datetime.
|
||||
|
||||
Use this instead of datetime.utcnow() to avoid timezone issues
|
||||
with PostgreSQL columns that have timezone=True.
|
||||
"""
|
||||
return datetime.now(timezone.utc)
|
||||
152
backend/app/db.py
Normal file
152
backend/app/db.py
Normal file
@@ -0,0 +1,152 @@
|
||||
import logging
|
||||
from typing import Generator, AsyncGenerator
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
from sqlalchemy import create_engine, event
|
||||
from sqlalchemy.orm import declarative_base, sessionmaker, Session
|
||||
from sqlalchemy.pool import StaticPool
|
||||
from sqlalchemy.engine import Engine
|
||||
import time
|
||||
|
||||
from .config import settings
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Configure SQLAlchemy engine with connection pooling
|
||||
engine = create_engine(
|
||||
settings.SQLALCHEMY_DATABASE_URI,
|
||||
echo=settings.DEBUG,
|
||||
pool_size=10,
|
||||
max_overflow=20,
|
||||
pool_pre_ping=True, # Validates connections before use
|
||||
pool_recycle=3600, # Recycle connections every hour
|
||||
connect_args={
|
||||
"connect_timeout": 10,
|
||||
"application_name": settings.PANEL_NAME,
|
||||
}
|
||||
)
|
||||
|
||||
# Add connection event listeners for monitoring
|
||||
@event.listens_for(Engine, "before_cursor_execute")
|
||||
def before_cursor_execute(conn, cursor, statement, parameters, context, executemany):
|
||||
context._query_start_time = time.time()
|
||||
if settings.DEBUG:
|
||||
logger.debug("Start Query: %s", statement)
|
||||
|
||||
|
||||
@event.listens_for(Engine, "after_cursor_execute")
|
||||
def after_cursor_execute(conn, cursor, statement, parameters, context, executemany):
|
||||
total = time.time() - context._query_start_time
|
||||
if settings.DEBUG:
|
||||
logger.debug("Query Complete in %.3f seconds", total)
|
||||
if total > 1.0: # Log slow queries
|
||||
logger.warning("Slow query detected (%.3f seconds): %s", total, statement)
|
||||
|
||||
|
||||
SessionLocal = sessionmaker(
|
||||
autocommit=False,
|
||||
autoflush=False,
|
||||
bind=engine,
|
||||
)
|
||||
|
||||
Base = declarative_base()
|
||||
|
||||
|
||||
def get_db() -> Generator[Session, None, None]:
|
||||
"""Dependency to get database session"""
|
||||
db = SessionLocal()
|
||||
try:
|
||||
yield db
|
||||
except Exception as e:
|
||||
logger.error(f"Database session error: {e}")
|
||||
db.rollback()
|
||||
raise
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def get_async_db() -> AsyncGenerator[Session, None]:
|
||||
"""Async context manager for database session"""
|
||||
db = SessionLocal()
|
||||
try:
|
||||
yield db
|
||||
db.commit()
|
||||
except Exception as e:
|
||||
logger.error(f"Database session error: {e}")
|
||||
db.rollback()
|
||||
raise
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
def init_db() -> None:
|
||||
"""Initialize database tables"""
|
||||
try:
|
||||
Base.metadata.create_all(bind=engine)
|
||||
logger.info("Database initialized successfully")
|
||||
|
||||
# Initialize default panel settings if not exist
|
||||
init_default_settings()
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to initialize database: {e}")
|
||||
raise
|
||||
|
||||
|
||||
def init_default_settings() -> None:
|
||||
"""Initialize default panel settings"""
|
||||
try:
|
||||
from .models import PanelSettings
|
||||
|
||||
db = SessionLocal()
|
||||
try:
|
||||
# Check if settings already exist
|
||||
existing = db.query(PanelSettings).count()
|
||||
if existing > 0:
|
||||
logger.info(f"Panel settings already initialized ({existing} settings found)")
|
||||
return
|
||||
|
||||
# Add default settings
|
||||
defaults = [
|
||||
PanelSettings(
|
||||
key="refresh_interval",
|
||||
value="5",
|
||||
description="Интервал обновления данных на панели (секунды)"
|
||||
),
|
||||
PanelSettings(
|
||||
key="log_retention_days",
|
||||
value="30",
|
||||
description="Срок хранения логов перед автоматической очисткой (дни)"
|
||||
),
|
||||
PanelSettings(
|
||||
key="language",
|
||||
value="ru",
|
||||
description="Язык интерфейса панели (ru/en)"
|
||||
),
|
||||
]
|
||||
|
||||
for setting in defaults:
|
||||
db.add(setting)
|
||||
|
||||
db.commit()
|
||||
logger.info(f"Added {len(defaults)} default panel settings")
|
||||
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
except Exception as e:
|
||||
logger.warning(f"Failed to initialize default settings: {e}")
|
||||
# Don't raise - this is not critical for app startup
|
||||
|
||||
|
||||
def check_db_connection() -> bool:
|
||||
"""Check if database connection is working"""
|
||||
try:
|
||||
with engine.connect() as conn:
|
||||
from sqlalchemy import text
|
||||
conn.execute(text("SELECT 1"))
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.error(f"Database connection check failed: {e}")
|
||||
return False
|
||||
4619
backend/app/i18n.py
Normal file
4619
backend/app/i18n.py
Normal file
File diff suppressed because it is too large
Load Diff
819
backend/app/ipam_service.py
Normal file
819
backend/app/ipam_service.py
Normal file
@@ -0,0 +1,819 @@
|
||||
"""
|
||||
IPAM Service - IP Address Management Service
|
||||
Provides functions for managing IP addresses, networks, pools, and allocations.
|
||||
"""
|
||||
|
||||
import ipaddress
|
||||
import logging
|
||||
from typing import List, Optional, Dict, Any, Tuple
|
||||
from datetime import datetime, timezone
|
||||
from sqlalchemy.orm import Session
|
||||
from sqlalchemy import and_, or_
|
||||
|
||||
from .models import IPAMNetwork, IPAMPool, IPAMAllocation, IPAMHistory
|
||||
|
||||
|
||||
def utcnow() -> datetime:
|
||||
"""Get current UTC time as timezone-aware datetime"""
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class IPAMService:
|
||||
"""Service class for IP Address Management operations"""
|
||||
|
||||
def __init__(self, db: Session):
|
||||
self.db = db
|
||||
|
||||
# ==================== Network Operations ====================
|
||||
|
||||
def get_network_stats(self, network_id: int) -> Dict[str, Any]:
|
||||
"""
|
||||
Get statistics for a network including IP utilization.
|
||||
|
||||
Args:
|
||||
network_id: Network ID
|
||||
|
||||
Returns:
|
||||
Dictionary with network statistics
|
||||
"""
|
||||
network = self.db.query(IPAMNetwork).filter(IPAMNetwork.id == network_id).first()
|
||||
if not network:
|
||||
return {}
|
||||
|
||||
# Parse network CIDR
|
||||
try:
|
||||
net = ipaddress.ip_network(network.network, strict=False)
|
||||
# Exclude network and broadcast addresses for usable IPs
|
||||
total_ips = net.num_addresses - 2 if net.num_addresses > 2 else net.num_addresses
|
||||
except ValueError:
|
||||
total_ips = 0
|
||||
|
||||
# Count allocations by status and type
|
||||
allocations = self.db.query(IPAMAllocation).filter(
|
||||
IPAMAllocation.network_id == network_id
|
||||
).all()
|
||||
|
||||
allocated_ips = len([a for a in allocations if a.status == 'allocated'])
|
||||
reserved_ips = len([a for a in allocations if a.status == 'reserved'])
|
||||
|
||||
vms_count = len([a for a in allocations if a.resource_type == 'vm'])
|
||||
lxc_count = len([a for a in allocations if a.resource_type == 'lxc'])
|
||||
physical_count = len([a for a in allocations if a.resource_type == 'physical'])
|
||||
other_count = len([a for a in allocations if a.resource_type not in ('vm', 'lxc', 'physical', None)])
|
||||
|
||||
pools_count = self.db.query(IPAMPool).filter(
|
||||
IPAMPool.network_id == network_id,
|
||||
IPAMPool.is_active == True
|
||||
).count()
|
||||
|
||||
available_ips = total_ips - allocated_ips - reserved_ips
|
||||
utilization = (allocated_ips + reserved_ips) / total_ips * 100 if total_ips > 0 else 0
|
||||
|
||||
return {
|
||||
'network_id': network_id,
|
||||
'network_name': network.name,
|
||||
'network_cidr': network.network,
|
||||
'total_ips': total_ips,
|
||||
'allocated_ips': allocated_ips,
|
||||
'reserved_ips': reserved_ips,
|
||||
'available_ips': available_ips,
|
||||
'utilization_percent': round(utilization, 2),
|
||||
'pools_count': pools_count,
|
||||
'vms_count': vms_count,
|
||||
'lxc_count': lxc_count,
|
||||
'physical_count': physical_count,
|
||||
'other_count': other_count
|
||||
}
|
||||
|
||||
def get_network_ip_map(self, network_id: int) -> List[Dict[str, Any]]:
|
||||
"""
|
||||
Get a map of all IP addresses in a network with their status.
|
||||
|
||||
Args:
|
||||
network_id: Network ID
|
||||
|
||||
Returns:
|
||||
List of IP address info dictionaries
|
||||
"""
|
||||
network = self.db.query(IPAMNetwork).filter(IPAMNetwork.id == network_id).first()
|
||||
if not network:
|
||||
return []
|
||||
|
||||
try:
|
||||
net = ipaddress.ip_network(network.network, strict=False)
|
||||
except ValueError:
|
||||
return []
|
||||
|
||||
# Get all allocations for this network
|
||||
allocations = {
|
||||
a.ip_address: a for a in
|
||||
self.db.query(IPAMAllocation).filter(IPAMAllocation.network_id == network_id).all()
|
||||
}
|
||||
|
||||
ip_map = []
|
||||
for ip in net.hosts(): # Excludes network and broadcast
|
||||
ip_str = str(ip)
|
||||
allocation = allocations.get(ip_str)
|
||||
|
||||
# Check if this is the gateway
|
||||
is_gateway = ip_str == network.gateway
|
||||
|
||||
ip_info = {
|
||||
'ip_address': ip_str,
|
||||
'is_gateway': is_gateway,
|
||||
'status': 'gateway' if is_gateway else (allocation.status if allocation else 'available'),
|
||||
'resource_type': allocation.resource_type if allocation else None,
|
||||
'resource_name': allocation.resource_name if allocation else None,
|
||||
'hostname': allocation.hostname if allocation else None,
|
||||
'allocation_id': allocation.id if allocation else None,
|
||||
'proxmox_vmid': allocation.proxmox_vmid if allocation else None,
|
||||
'last_seen': allocation.last_seen.isoformat() if allocation and allocation.last_seen else None
|
||||
}
|
||||
ip_map.append(ip_info)
|
||||
|
||||
return ip_map
|
||||
|
||||
# ==================== IP Allocation Operations ====================
|
||||
|
||||
def get_next_available_ip(
|
||||
self,
|
||||
network_id: int,
|
||||
pool_id: Optional[int] = None,
|
||||
prefer_sequential: bool = True
|
||||
) -> Optional[str]:
|
||||
"""
|
||||
Get the next available IP address from a network or specific pool.
|
||||
|
||||
Args:
|
||||
network_id: Network ID
|
||||
pool_id: Optional specific pool ID
|
||||
prefer_sequential: If True, prefer sequential IPs; if False, can use any gap
|
||||
|
||||
Returns:
|
||||
Available IP address string or None if no IPs available
|
||||
"""
|
||||
network = self.db.query(IPAMNetwork).filter(
|
||||
IPAMNetwork.id == network_id,
|
||||
IPAMNetwork.is_active == True
|
||||
).first()
|
||||
|
||||
if not network:
|
||||
logger.warning(f"Network {network_id} not found or inactive")
|
||||
return None
|
||||
|
||||
# Get pool(s) to search
|
||||
if pool_id:
|
||||
pools = self.db.query(IPAMPool).filter(
|
||||
IPAMPool.id == pool_id,
|
||||
IPAMPool.network_id == network_id,
|
||||
IPAMPool.is_active == True,
|
||||
IPAMPool.auto_assign == True
|
||||
).all()
|
||||
else:
|
||||
pools = self.db.query(IPAMPool).filter(
|
||||
IPAMPool.network_id == network_id,
|
||||
IPAMPool.is_active == True,
|
||||
IPAMPool.auto_assign == True
|
||||
).order_by(IPAMPool.id).all()
|
||||
|
||||
if not pools:
|
||||
logger.warning(f"No active auto-assign pools found for network {network_id}")
|
||||
return None
|
||||
|
||||
# Get all allocated IPs in this network
|
||||
allocated_ips = set(
|
||||
a.ip_address for a in
|
||||
self.db.query(IPAMAllocation).filter(
|
||||
IPAMAllocation.network_id == network_id,
|
||||
IPAMAllocation.status.in_(['allocated', 'reserved'])
|
||||
).all()
|
||||
)
|
||||
|
||||
# Also exclude gateway
|
||||
if network.gateway:
|
||||
allocated_ips.add(network.gateway)
|
||||
|
||||
# Search through pools for available IP
|
||||
for pool in pools:
|
||||
try:
|
||||
start_ip = ipaddress.ip_address(pool.range_start)
|
||||
end_ip = ipaddress.ip_address(pool.range_end)
|
||||
|
||||
for ip_int in range(int(start_ip), int(end_ip) + 1):
|
||||
ip = str(ipaddress.ip_address(ip_int))
|
||||
if ip not in allocated_ips:
|
||||
logger.info(f"Found available IP: {ip} in pool {pool.name}")
|
||||
return ip
|
||||
|
||||
except ValueError as e:
|
||||
logger.error(f"Invalid IP range in pool {pool.id}: {e}")
|
||||
continue
|
||||
|
||||
logger.warning(f"No available IPs found in network {network_id}")
|
||||
return None
|
||||
|
||||
def allocate_ip(
|
||||
self,
|
||||
ip_address: str,
|
||||
network_id: int,
|
||||
pool_id: Optional[int] = None,
|
||||
resource_type: Optional[str] = None,
|
||||
resource_id: Optional[int] = None,
|
||||
resource_name: Optional[str] = None,
|
||||
hostname: Optional[str] = None,
|
||||
fqdn: Optional[str] = None,
|
||||
mac_address: Optional[str] = None,
|
||||
proxmox_server_id: Optional[int] = None,
|
||||
proxmox_vmid: Optional[int] = None,
|
||||
proxmox_node: Optional[str] = None,
|
||||
allocation_type: str = "static",
|
||||
status: str = "allocated",
|
||||
allocated_by: Optional[str] = None,
|
||||
notes: Optional[str] = None
|
||||
) -> Tuple[Optional[IPAMAllocation], Optional[str]]:
|
||||
"""
|
||||
Allocate an IP address.
|
||||
|
||||
Args:
|
||||
ip_address: IP address to allocate
|
||||
network_id: Network ID
|
||||
... other optional parameters
|
||||
|
||||
Returns:
|
||||
Tuple of (allocation object, error message)
|
||||
"""
|
||||
# Validate IP is not already allocated
|
||||
existing = self.db.query(IPAMAllocation).filter(
|
||||
IPAMAllocation.ip_address == ip_address
|
||||
).first()
|
||||
|
||||
if existing:
|
||||
return None, f"IP {ip_address} is already allocated to {existing.resource_name or 'unknown'}"
|
||||
|
||||
# Validate IP belongs to the network
|
||||
network = self.db.query(IPAMNetwork).filter(IPAMNetwork.id == network_id).first()
|
||||
if not network:
|
||||
return None, f"Network {network_id} not found"
|
||||
|
||||
try:
|
||||
net = ipaddress.ip_network(network.network, strict=False)
|
||||
ip = ipaddress.ip_address(ip_address)
|
||||
if ip not in net:
|
||||
return None, f"IP {ip_address} is not within network {network.network}"
|
||||
except ValueError as e:
|
||||
return None, f"Invalid IP or network: {e}"
|
||||
|
||||
# Check if IP is the gateway
|
||||
if ip_address == network.gateway:
|
||||
return None, f"IP {ip_address} is the gateway for this network"
|
||||
|
||||
# Auto-detect pool if not specified
|
||||
if not pool_id:
|
||||
pools = self.db.query(IPAMPool).filter(
|
||||
IPAMPool.network_id == network_id,
|
||||
IPAMPool.is_active == True
|
||||
).all()
|
||||
|
||||
for pool in pools:
|
||||
try:
|
||||
start = ipaddress.ip_address(pool.range_start)
|
||||
end = ipaddress.ip_address(pool.range_end)
|
||||
if start <= ip <= end:
|
||||
pool_id = pool.id
|
||||
break
|
||||
except ValueError:
|
||||
continue
|
||||
|
||||
# Build FQDN if not provided
|
||||
if not fqdn and hostname and network.dns_domain:
|
||||
fqdn = f"{hostname}.{network.dns_domain}"
|
||||
|
||||
# Create allocation
|
||||
allocation = IPAMAllocation(
|
||||
network_id=network_id,
|
||||
pool_id=pool_id,
|
||||
ip_address=ip_address,
|
||||
mac_address=mac_address,
|
||||
resource_type=resource_type,
|
||||
resource_id=resource_id,
|
||||
resource_name=resource_name,
|
||||
proxmox_server_id=proxmox_server_id,
|
||||
proxmox_vmid=proxmox_vmid,
|
||||
proxmox_node=proxmox_node,
|
||||
status=status,
|
||||
allocation_type=allocation_type,
|
||||
hostname=hostname,
|
||||
fqdn=fqdn,
|
||||
allocated_by=allocated_by,
|
||||
notes=notes
|
||||
)
|
||||
|
||||
self.db.add(allocation)
|
||||
|
||||
# Log to history
|
||||
self._log_history(
|
||||
ip_address=ip_address,
|
||||
network_id=network_id,
|
||||
action="allocated",
|
||||
new_value={
|
||||
'resource_type': resource_type,
|
||||
'resource_name': resource_name,
|
||||
'status': status
|
||||
},
|
||||
resource_type=resource_type,
|
||||
resource_id=resource_id,
|
||||
resource_name=resource_name,
|
||||
performed_by=allocated_by
|
||||
)
|
||||
|
||||
self.db.commit()
|
||||
self.db.refresh(allocation)
|
||||
|
||||
logger.info(f"Allocated IP {ip_address} to {resource_name or 'unknown'} by {allocated_by or 'system'}")
|
||||
return allocation, None
|
||||
|
||||
def auto_allocate_ip(
|
||||
self,
|
||||
network_id: int,
|
||||
pool_id: Optional[int] = None,
|
||||
resource_type: Optional[str] = None,
|
||||
resource_id: Optional[int] = None,
|
||||
resource_name: Optional[str] = None,
|
||||
hostname: Optional[str] = None,
|
||||
proxmox_server_id: Optional[int] = None,
|
||||
proxmox_vmid: Optional[int] = None,
|
||||
proxmox_node: Optional[str] = None,
|
||||
allocated_by: Optional[str] = None,
|
||||
notes: Optional[str] = None
|
||||
) -> Tuple[Optional[IPAMAllocation], Optional[str]]:
|
||||
"""
|
||||
Automatically allocate the next available IP address.
|
||||
|
||||
Returns:
|
||||
Tuple of (allocation object, error message)
|
||||
"""
|
||||
ip_address = self.get_next_available_ip(network_id, pool_id)
|
||||
|
||||
if not ip_address:
|
||||
return None, f"No available IP addresses in network {network_id}"
|
||||
|
||||
return self.allocate_ip(
|
||||
ip_address=ip_address,
|
||||
network_id=network_id,
|
||||
pool_id=pool_id,
|
||||
resource_type=resource_type,
|
||||
resource_id=resource_id,
|
||||
resource_name=resource_name,
|
||||
hostname=hostname,
|
||||
proxmox_server_id=proxmox_server_id,
|
||||
proxmox_vmid=proxmox_vmid,
|
||||
proxmox_node=proxmox_node,
|
||||
allocated_by=allocated_by,
|
||||
notes=notes
|
||||
)
|
||||
|
||||
def release_ip(
|
||||
self,
|
||||
ip_address: str,
|
||||
released_by: Optional[str] = None,
|
||||
reason: Optional[str] = None
|
||||
) -> Tuple[bool, Optional[str]]:
|
||||
"""
|
||||
Release an IP address allocation.
|
||||
|
||||
Args:
|
||||
ip_address: IP address to release
|
||||
released_by: Username performing the release
|
||||
reason: Reason for release
|
||||
|
||||
Returns:
|
||||
Tuple of (success, error message)
|
||||
"""
|
||||
allocation = self.db.query(IPAMAllocation).filter(
|
||||
IPAMAllocation.ip_address == ip_address
|
||||
).first()
|
||||
|
||||
if not allocation:
|
||||
return False, f"IP {ip_address} is not allocated"
|
||||
|
||||
# Store old data for history
|
||||
old_data = {
|
||||
'resource_type': allocation.resource_type,
|
||||
'resource_name': allocation.resource_name,
|
||||
'status': allocation.status,
|
||||
'proxmox_vmid': allocation.proxmox_vmid
|
||||
}
|
||||
|
||||
# Log to history before deletion
|
||||
self._log_history(
|
||||
ip_address=ip_address,
|
||||
network_id=allocation.network_id,
|
||||
action="released",
|
||||
old_value=old_data,
|
||||
resource_type=allocation.resource_type,
|
||||
resource_id=allocation.resource_id,
|
||||
resource_name=allocation.resource_name,
|
||||
performed_by=released_by,
|
||||
notes=reason
|
||||
)
|
||||
|
||||
self.db.delete(allocation)
|
||||
self.db.commit()
|
||||
|
||||
logger.info(f"Released IP {ip_address} by {released_by or 'system'}")
|
||||
return True, None
|
||||
|
||||
def release_ip_by_vmid(
|
||||
self,
|
||||
proxmox_server_id: int,
|
||||
proxmox_vmid: int,
|
||||
released_by: Optional[str] = None,
|
||||
reason: Optional[str] = None
|
||||
) -> Tuple[bool, Optional[str]]:
|
||||
"""
|
||||
Release IP allocation by Proxmox VM/container ID.
|
||||
Used when VM/container is deleted.
|
||||
|
||||
Args:
|
||||
proxmox_server_id: Proxmox server ID
|
||||
proxmox_vmid: VM/container ID
|
||||
released_by: Username performing the release
|
||||
reason: Reason for release
|
||||
|
||||
Returns:
|
||||
Tuple of (success, error message or released IP)
|
||||
"""
|
||||
# First try to find by proxmox_server_id and proxmox_vmid
|
||||
allocation = self.find_allocation_by_resource(proxmox_server_id, proxmox_vmid)
|
||||
|
||||
# Fallback: search by resource_id if proxmox fields are not set
|
||||
if not allocation:
|
||||
allocation = self.db.query(IPAMAllocation).filter(
|
||||
IPAMAllocation.resource_id == proxmox_vmid,
|
||||
IPAMAllocation.status.in_(['allocated', 'reserved'])
|
||||
).first()
|
||||
if allocation:
|
||||
logger.debug(f"Found allocation by resource_id={proxmox_vmid} (legacy)")
|
||||
|
||||
if not allocation:
|
||||
logger.debug(f"No IPAM allocation found for server {proxmox_server_id}, vmid {proxmox_vmid}")
|
||||
return False, None # Not an error, just no allocation to release
|
||||
|
||||
ip_address = allocation.ip_address
|
||||
success, error = self.release_ip(ip_address, released_by, reason)
|
||||
|
||||
if success:
|
||||
logger.info(f"Auto-released IP {ip_address} for deleted VM/container {proxmox_vmid}")
|
||||
return True, ip_address
|
||||
|
||||
return False, error
|
||||
|
||||
def update_allocation(
|
||||
self,
|
||||
ip_address: str,
|
||||
updated_by: Optional[str] = None,
|
||||
**kwargs
|
||||
) -> Tuple[Optional[IPAMAllocation], Optional[str]]:
|
||||
"""
|
||||
Update an existing IP allocation.
|
||||
|
||||
Args:
|
||||
ip_address: IP address to update
|
||||
updated_by: Username performing update
|
||||
**kwargs: Fields to update
|
||||
|
||||
Returns:
|
||||
Tuple of (updated allocation, error message)
|
||||
"""
|
||||
allocation = self.db.query(IPAMAllocation).filter(
|
||||
IPAMAllocation.ip_address == ip_address
|
||||
).first()
|
||||
|
||||
if not allocation:
|
||||
return None, f"IP {ip_address} is not allocated"
|
||||
|
||||
# Store old values for history
|
||||
old_value = {}
|
||||
new_value = {}
|
||||
|
||||
allowed_fields = [
|
||||
'pool_id', 'mac_address', 'resource_type', 'resource_id', 'resource_name',
|
||||
'proxmox_server_id', 'proxmox_vmid', 'proxmox_node', 'status', 'allocation_type',
|
||||
'hostname', 'fqdn', 'dns_ptr_record', 'expires_at', 'notes', 'last_seen'
|
||||
]
|
||||
|
||||
for field, value in kwargs.items():
|
||||
if field in allowed_fields and hasattr(allocation, field):
|
||||
old_val = getattr(allocation, field)
|
||||
if old_val != value:
|
||||
old_value[field] = old_val
|
||||
new_value[field] = value
|
||||
setattr(allocation, field, value)
|
||||
|
||||
if old_value:
|
||||
self._log_history(
|
||||
ip_address=ip_address,
|
||||
network_id=allocation.network_id,
|
||||
action="modified",
|
||||
old_value=old_value,
|
||||
new_value=new_value,
|
||||
resource_type=allocation.resource_type,
|
||||
resource_id=allocation.resource_id,
|
||||
resource_name=allocation.resource_name,
|
||||
performed_by=updated_by
|
||||
)
|
||||
|
||||
self.db.commit()
|
||||
self.db.refresh(allocation)
|
||||
|
||||
return allocation, None
|
||||
|
||||
def find_allocation_by_resource(
|
||||
self,
|
||||
proxmox_server_id: int,
|
||||
proxmox_vmid: int
|
||||
) -> Optional[IPAMAllocation]:
|
||||
"""Find active allocation by Proxmox VM/container"""
|
||||
return self.db.query(IPAMAllocation).filter(
|
||||
IPAMAllocation.proxmox_server_id == proxmox_server_id,
|
||||
IPAMAllocation.proxmox_vmid == proxmox_vmid,
|
||||
IPAMAllocation.status.in_(['allocated', 'reserved'])
|
||||
).first()
|
||||
|
||||
def release_all_by_server(self, proxmox_server_id: int, released_by: str = None) -> int:
|
||||
"""
|
||||
Release all IP allocations for a Proxmox server.
|
||||
Used when server is deleted.
|
||||
|
||||
Args:
|
||||
proxmox_server_id: Proxmox server ID
|
||||
released_by: Username performing the release
|
||||
|
||||
Returns:
|
||||
Number of released allocations
|
||||
"""
|
||||
allocations = self.db.query(IPAMAllocation).filter(
|
||||
IPAMAllocation.proxmox_server_id == proxmox_server_id,
|
||||
IPAMAllocation.status.in_(['allocated', 'reserved'])
|
||||
).all()
|
||||
|
||||
released_count = 0
|
||||
for alloc in allocations:
|
||||
try:
|
||||
self._log_history(
|
||||
ip_address=alloc.ip_address,
|
||||
network_id=alloc.network_id,
|
||||
action="released",
|
||||
old_value={
|
||||
'resource_type': alloc.resource_type,
|
||||
'resource_name': alloc.resource_name,
|
||||
'proxmox_vmid': alloc.proxmox_vmid
|
||||
},
|
||||
resource_type=alloc.resource_type,
|
||||
resource_id=alloc.resource_id,
|
||||
resource_name=alloc.resource_name,
|
||||
performed_by=released_by,
|
||||
notes=f"Proxmox server {proxmox_server_id} deleted"
|
||||
)
|
||||
self.db.delete(alloc)
|
||||
released_count += 1
|
||||
logger.info(f"Released IP {alloc.ip_address} (server {proxmox_server_id} deleted)")
|
||||
except Exception as e:
|
||||
logger.warning(f"Failed to release IP {alloc.ip_address}: {e}")
|
||||
|
||||
if released_count > 0:
|
||||
self.db.commit()
|
||||
|
||||
return released_count
|
||||
|
||||
# ==================== Pool Operations ====================
|
||||
|
||||
def get_pool_stats(self, pool_id: int) -> Dict[str, Any]:
|
||||
"""Get statistics for a pool"""
|
||||
pool = self.db.query(IPAMPool).filter(IPAMPool.id == pool_id).first()
|
||||
if not pool:
|
||||
return {}
|
||||
|
||||
try:
|
||||
start = ipaddress.ip_address(pool.range_start)
|
||||
end = ipaddress.ip_address(pool.range_end)
|
||||
total_ips = int(end) - int(start) + 1
|
||||
except ValueError:
|
||||
total_ips = 0
|
||||
|
||||
used_ips = self.db.query(IPAMAllocation).filter(
|
||||
IPAMAllocation.pool_id == pool_id,
|
||||
IPAMAllocation.status.in_(['allocated', 'reserved'])
|
||||
).count()
|
||||
|
||||
return {
|
||||
'pool_id': pool_id,
|
||||
'pool_name': pool.name,
|
||||
'total_ips': total_ips,
|
||||
'used_ips': used_ips,
|
||||
'available_ips': total_ips - used_ips
|
||||
}
|
||||
|
||||
def validate_pool_range(
|
||||
self,
|
||||
network_id: int,
|
||||
range_start: str,
|
||||
range_end: str,
|
||||
exclude_pool_id: Optional[int] = None
|
||||
) -> Tuple[bool, Optional[str]]:
|
||||
"""
|
||||
Validate that a pool range is valid and doesn't overlap with existing pools.
|
||||
|
||||
Returns:
|
||||
Tuple of (is_valid, error_message)
|
||||
"""
|
||||
network = self.db.query(IPAMNetwork).filter(IPAMNetwork.id == network_id).first()
|
||||
if not network:
|
||||
return False, "Network not found"
|
||||
|
||||
try:
|
||||
net = ipaddress.ip_network(network.network, strict=False)
|
||||
start = ipaddress.ip_address(range_start)
|
||||
end = ipaddress.ip_address(range_end)
|
||||
except ValueError as e:
|
||||
return False, f"Invalid IP format: {e}"
|
||||
|
||||
# Validate range is within network
|
||||
if start not in net or end not in net:
|
||||
return False, f"Range must be within network {network.network}"
|
||||
|
||||
# Validate start <= end
|
||||
if start > end:
|
||||
return False, "Range start must be less than or equal to range end"
|
||||
|
||||
# Check for overlaps with existing pools
|
||||
existing_pools = self.db.query(IPAMPool).filter(
|
||||
IPAMPool.network_id == network_id,
|
||||
IPAMPool.id != exclude_pool_id if exclude_pool_id else True
|
||||
).all()
|
||||
|
||||
for pool in existing_pools:
|
||||
try:
|
||||
pool_start = ipaddress.ip_address(pool.range_start)
|
||||
pool_end = ipaddress.ip_address(pool.range_end)
|
||||
|
||||
# Check overlap
|
||||
if not (end < pool_start or start > pool_end):
|
||||
return False, f"Range overlaps with existing pool '{pool.name}' ({pool.range_start}-{pool.range_end})"
|
||||
except ValueError:
|
||||
continue
|
||||
|
||||
return True, None
|
||||
|
||||
# ==================== Sync & Scan Operations ====================
|
||||
|
||||
def sync_from_proxmox_vm(
|
||||
self,
|
||||
network_id: int,
|
||||
proxmox_server_id: int,
|
||||
vmid: int,
|
||||
vm_name: str,
|
||||
vm_type: str,
|
||||
ip_address: str,
|
||||
node: str,
|
||||
mac_address: Optional[str] = None,
|
||||
synced_by: str = "system"
|
||||
) -> Tuple[Optional[IPAMAllocation], Optional[str]]:
|
||||
"""
|
||||
Sync/create allocation for a Proxmox VM.
|
||||
Called when discovering VMs from Proxmox.
|
||||
"""
|
||||
# Check if already allocated
|
||||
existing = self.db.query(IPAMAllocation).filter(
|
||||
IPAMAllocation.ip_address == ip_address
|
||||
).first()
|
||||
|
||||
if existing:
|
||||
# Update existing allocation
|
||||
if existing.proxmox_vmid != vmid or existing.proxmox_server_id != proxmox_server_id:
|
||||
return self.update_allocation(
|
||||
ip_address,
|
||||
updated_by=synced_by,
|
||||
proxmox_server_id=proxmox_server_id,
|
||||
proxmox_vmid=vmid,
|
||||
proxmox_node=node,
|
||||
resource_type=vm_type,
|
||||
resource_name=vm_name,
|
||||
mac_address=mac_address,
|
||||
last_seen=utcnow()
|
||||
)
|
||||
else:
|
||||
# Just update last_seen
|
||||
existing.last_seen = utcnow()
|
||||
self.db.commit()
|
||||
return existing, None
|
||||
|
||||
# Create new allocation
|
||||
return self.allocate_ip(
|
||||
ip_address=ip_address,
|
||||
network_id=network_id,
|
||||
resource_type=vm_type,
|
||||
resource_name=vm_name,
|
||||
proxmox_server_id=proxmox_server_id,
|
||||
proxmox_vmid=vmid,
|
||||
proxmox_node=node,
|
||||
mac_address=mac_address,
|
||||
allocated_by=synced_by,
|
||||
notes="Auto-synced from Proxmox"
|
||||
)
|
||||
|
||||
def detect_conflicts(self, network_id: Optional[int] = None) -> List[Dict[str, Any]]:
|
||||
"""
|
||||
Detect IP address conflicts.
|
||||
|
||||
Returns:
|
||||
List of conflict info dictionaries
|
||||
"""
|
||||
# This would typically involve scanning the network
|
||||
# For now, we check for duplicate allocations
|
||||
conflicts = []
|
||||
|
||||
query = self.db.query(IPAMAllocation)
|
||||
if network_id:
|
||||
query = query.filter(IPAMAllocation.network_id == network_id)
|
||||
|
||||
allocations = query.all()
|
||||
|
||||
# Group by IP
|
||||
ip_groups = {}
|
||||
for alloc in allocations:
|
||||
if alloc.ip_address not in ip_groups:
|
||||
ip_groups[alloc.ip_address] = []
|
||||
ip_groups[alloc.ip_address].append(alloc)
|
||||
|
||||
# Find duplicates
|
||||
for ip, allocs in ip_groups.items():
|
||||
if len(allocs) > 1:
|
||||
conflicts.append({
|
||||
'ip_address': ip,
|
||||
'type': 'duplicate_allocation',
|
||||
'allocations': [
|
||||
{
|
||||
'id': a.id,
|
||||
'resource_name': a.resource_name,
|
||||
'resource_type': a.resource_type,
|
||||
'proxmox_vmid': a.proxmox_vmid
|
||||
} for a in allocs
|
||||
]
|
||||
})
|
||||
|
||||
return conflicts
|
||||
|
||||
# ==================== History Operations ====================
|
||||
|
||||
def _log_history(
|
||||
self,
|
||||
ip_address: str,
|
||||
network_id: Optional[int],
|
||||
action: str,
|
||||
old_value: Optional[Dict] = None,
|
||||
new_value: Optional[Dict] = None,
|
||||
resource_type: Optional[str] = None,
|
||||
resource_id: Optional[int] = None,
|
||||
resource_name: Optional[str] = None,
|
||||
performed_by: Optional[str] = None,
|
||||
notes: Optional[str] = None
|
||||
):
|
||||
"""Log an action to IPAM history"""
|
||||
history = IPAMHistory(
|
||||
ip_address=ip_address,
|
||||
network_id=network_id,
|
||||
action=action,
|
||||
old_value=old_value,
|
||||
new_value=new_value,
|
||||
resource_type=resource_type,
|
||||
resource_id=resource_id,
|
||||
resource_name=resource_name,
|
||||
performed_by=performed_by or "system",
|
||||
notes=notes
|
||||
)
|
||||
self.db.add(history)
|
||||
|
||||
def get_ip_history(
|
||||
self,
|
||||
ip_address: str,
|
||||
limit: int = 50
|
||||
) -> List[IPAMHistory]:
|
||||
"""Get history for a specific IP address"""
|
||||
return self.db.query(IPAMHistory).filter(
|
||||
IPAMHistory.ip_address == ip_address
|
||||
).order_by(IPAMHistory.performed_at.desc()).limit(limit).all()
|
||||
|
||||
def get_recent_history(
|
||||
self,
|
||||
network_id: Optional[int] = None,
|
||||
limit: int = 100
|
||||
) -> List[IPAMHistory]:
|
||||
"""Get recent IPAM history"""
|
||||
query = self.db.query(IPAMHistory)
|
||||
if network_id:
|
||||
query = query.filter(IPAMHistory.network_id == network_id)
|
||||
return query.order_by(IPAMHistory.performed_at.desc()).limit(limit).all()
|
||||
34
backend/app/language_middleware.py
Normal file
34
backend/app/language_middleware.py
Normal file
@@ -0,0 +1,34 @@
|
||||
"""
|
||||
Language middleware
|
||||
Detects user language from settings and adds to request state
|
||||
"""
|
||||
|
||||
from fastapi import Request
|
||||
from starlette.middleware.base import BaseHTTPMiddleware
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from .db import SessionLocal
|
||||
from .models import PanelSettings
|
||||
|
||||
|
||||
class LanguageMiddleware(BaseHTTPMiddleware):
|
||||
"""Middleware to detect and set language"""
|
||||
|
||||
async def dispatch(self, request: Request, call_next):
|
||||
# Get language from database settings
|
||||
lang = "ru" # default
|
||||
|
||||
try:
|
||||
db = SessionLocal()
|
||||
setting = db.query(PanelSettings).filter(PanelSettings.key == "language").first()
|
||||
if setting:
|
||||
lang = setting.value
|
||||
db.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# Store language in request state
|
||||
request.state.lang = lang
|
||||
|
||||
response = await call_next(request)
|
||||
return response
|
||||
218
backend/app/logging_middleware.py
Normal file
218
backend/app/logging_middleware.py
Normal file
@@ -0,0 +1,218 @@
|
||||
"""
|
||||
HTTP Request Logging Middleware
|
||||
Automatically logs all API requests to the audit log with enhanced details
|
||||
"""
|
||||
|
||||
import time
|
||||
import uuid
|
||||
import json
|
||||
from typing import Callable, Optional
|
||||
from fastapi import Request, Response
|
||||
from starlette.middleware.base import BaseHTTPMiddleware
|
||||
from starlette.types import ASGIApp
|
||||
from loguru import logger
|
||||
|
||||
from .db import SessionLocal
|
||||
from .logging_service import LoggingService
|
||||
|
||||
|
||||
class RequestLoggingMiddleware(BaseHTTPMiddleware):
|
||||
"""Middleware to log all HTTP requests with enhanced details"""
|
||||
|
||||
# Paths to exclude from detailed logging (too verbose)
|
||||
EXCLUDE_PATHS = [
|
||||
"/health",
|
||||
"/favicon.ico",
|
||||
"/static/",
|
||||
]
|
||||
|
||||
# Paths that should only log errors (to reduce noise)
|
||||
QUIET_PATHS = [
|
||||
"/api/logs", # Don't log requests to view logs
|
||||
"/api/virtual-machines", # High frequency polling
|
||||
]
|
||||
|
||||
# Paths to log request body (important operations)
|
||||
LOG_BODY_PATHS = [
|
||||
"/api/proxmox/",
|
||||
"/api/auth/",
|
||||
"/api/users/",
|
||||
"/api/ipam/",
|
||||
"/api/settings/",
|
||||
]
|
||||
|
||||
# Max body size to log (bytes)
|
||||
MAX_BODY_SIZE = 10000
|
||||
|
||||
def __init__(self, app: ASGIApp, enable_api_logging: bool = True):
|
||||
super().__init__(app)
|
||||
self.enable_api_logging = enable_api_logging
|
||||
|
||||
async def dispatch(self, request: Request, call_next: Callable) -> Response:
|
||||
# Skip excluded paths
|
||||
path = request.url.path
|
||||
for excluded in self.EXCLUDE_PATHS:
|
||||
if path.startswith(excluded):
|
||||
return await call_next(request)
|
||||
|
||||
# Generate unique request ID for correlation
|
||||
request_id = str(uuid.uuid4())
|
||||
|
||||
# Store request ID in state for use in handlers
|
||||
request.state.request_id = request_id
|
||||
|
||||
# Record start time
|
||||
start_time = time.time()
|
||||
|
||||
# Get client info
|
||||
client_ip = self._get_client_ip(request)
|
||||
user_agent = request.headers.get("user-agent", "")[:500]
|
||||
|
||||
# Try to get username and session from token
|
||||
username = None
|
||||
session_id = None
|
||||
user_id = None
|
||||
try:
|
||||
auth_header = request.headers.get("authorization", "")
|
||||
if auth_header.startswith("Bearer "):
|
||||
token = auth_header[7:]
|
||||
# Extract session ID from token (first 16 chars of hash)
|
||||
import hashlib
|
||||
session_id = hashlib.sha256(token.encode()).hexdigest()[:16]
|
||||
except:
|
||||
pass
|
||||
|
||||
# Capture request body for important operations
|
||||
request_body = None
|
||||
should_log_body = any(path.startswith(p) for p in self.LOG_BODY_PATHS)
|
||||
if should_log_body and request.method in ["POST", "PUT", "PATCH"]:
|
||||
try:
|
||||
body_bytes = await request.body()
|
||||
if len(body_bytes) <= self.MAX_BODY_SIZE:
|
||||
try:
|
||||
request_body = json.loads(body_bytes)
|
||||
except:
|
||||
request_body = {"_raw": body_bytes.decode('utf-8', errors='replace')[:1000]}
|
||||
except:
|
||||
pass
|
||||
|
||||
# Get query params
|
||||
query_params = str(request.query_params) if request.query_params else None
|
||||
|
||||
# Process request
|
||||
response = await call_next(request)
|
||||
|
||||
# Calculate duration
|
||||
duration_ms = int((time.time() - start_time) * 1000)
|
||||
|
||||
# Determine if we should log this request
|
||||
should_log = self.enable_api_logging
|
||||
|
||||
# Check quiet paths - only log errors or slow requests
|
||||
for quiet_path in self.QUIET_PATHS:
|
||||
if path.startswith(quiet_path):
|
||||
should_log = response.status_code >= 400 or duration_ms > 5000
|
||||
break
|
||||
|
||||
# Log to database (async-safe)
|
||||
if should_log and (path.startswith("/api/") or path.startswith("/proxmox/") or path.startswith("/ipam/")):
|
||||
try:
|
||||
db = SessionLocal()
|
||||
try:
|
||||
error_message = None
|
||||
error_traceback = None
|
||||
if response.status_code >= 400:
|
||||
error_message = f"HTTP {response.status_code}"
|
||||
|
||||
# Determine log level
|
||||
level = LoggingService.DEBUG
|
||||
if response.status_code >= 500:
|
||||
level = LoggingService.ERROR
|
||||
elif response.status_code >= 400:
|
||||
level = LoggingService.WARNING
|
||||
elif duration_ms > 3000:
|
||||
level = LoggingService.WARNING # Slow requests
|
||||
|
||||
# Determine action from path and method
|
||||
action = self._get_action_from_request(request.method, path)
|
||||
|
||||
# Create detailed message
|
||||
message = f"{request.method} {path}"
|
||||
if duration_ms > 1000:
|
||||
message += f" (slow: {duration_ms}ms)"
|
||||
message += f" -> {response.status_code}"
|
||||
|
||||
LoggingService.log(
|
||||
db=db,
|
||||
level=level,
|
||||
category=LoggingService.API,
|
||||
action=action,
|
||||
message=message,
|
||||
request_id=request_id,
|
||||
session_id=session_id,
|
||||
username=username,
|
||||
user_id=user_id,
|
||||
ip_address=client_ip,
|
||||
user_agent=user_agent,
|
||||
request_method=request.method,
|
||||
request_path=path,
|
||||
query_params=query_params,
|
||||
request_body=request_body,
|
||||
response_status=response.status_code,
|
||||
duration_ms=duration_ms,
|
||||
success=response.status_code < 400,
|
||||
error_message=error_message,
|
||||
error_traceback=error_traceback
|
||||
)
|
||||
finally:
|
||||
db.close()
|
||||
except Exception as e:
|
||||
logger.warning(f"Failed to log API request: {e}")
|
||||
|
||||
# Add request ID to response headers for debugging
|
||||
response.headers["X-Request-ID"] = request_id
|
||||
|
||||
return response
|
||||
|
||||
def _get_client_ip(self, request: Request) -> str:
|
||||
"""Extract client IP from request, considering proxies"""
|
||||
# Check X-Forwarded-For header (from reverse proxy)
|
||||
forwarded_for = request.headers.get("x-forwarded-for")
|
||||
if forwarded_for:
|
||||
return forwarded_for.split(",")[0].strip()
|
||||
|
||||
# Check X-Real-IP header
|
||||
real_ip = request.headers.get("x-real-ip")
|
||||
if real_ip:
|
||||
return real_ip
|
||||
|
||||
# Fall back to direct client IP
|
||||
if request.client:
|
||||
return request.client.host
|
||||
|
||||
return "unknown"
|
||||
|
||||
def _get_action_from_request(self, method: str, path: str) -> str:
|
||||
"""Determine action name from HTTP method and path"""
|
||||
# Map method to basic action
|
||||
method_actions = {
|
||||
"GET": "read",
|
||||
"POST": "create",
|
||||
"PUT": "update",
|
||||
"PATCH": "update",
|
||||
"DELETE": "delete"
|
||||
}
|
||||
base_action = method_actions.get(method, method.lower())
|
||||
|
||||
# Try to extract resource from path
|
||||
path_parts = path.strip("/").split("/")
|
||||
if len(path_parts) >= 2:
|
||||
resource = path_parts[1] if path_parts[0] in ["api", "proxmox", "ipam"] else path_parts[0]
|
||||
# Handle specific actions in path
|
||||
if len(path_parts) >= 3:
|
||||
last_part = path_parts[-1]
|
||||
if last_part in ["start", "stop", "restart", "shutdown", "clone", "migrate", "backup", "console"]:
|
||||
return f"{resource}_{last_part}"
|
||||
return f"{resource}_{base_action}"
|
||||
|
||||
return f"api_{base_action}"
|
||||
559
backend/app/logging_service.py
Normal file
559
backend/app/logging_service.py
Normal file
@@ -0,0 +1,559 @@
|
||||
"""
|
||||
Logging Service for PVEmanager
|
||||
Provides centralized logging functionality for audit, system, and API events
|
||||
"""
|
||||
|
||||
import uuid
|
||||
import traceback
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Optional, Dict, Any, List
|
||||
from sqlalchemy.orm import Session
|
||||
from sqlalchemy import desc, and_, or_
|
||||
from loguru import logger
|
||||
|
||||
from .models import AuditLog
|
||||
|
||||
|
||||
def utcnow() -> datetime:
|
||||
"""Get current UTC time as timezone-aware datetime"""
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
class LoggingService:
|
||||
"""Centralized logging service for the application"""
|
||||
|
||||
# Log levels
|
||||
DEBUG = "debug"
|
||||
INFO = "info"
|
||||
WARNING = "warning"
|
||||
ERROR = "error"
|
||||
CRITICAL = "critical"
|
||||
|
||||
# Log categories
|
||||
AUTH = "auth"
|
||||
PROXMOX = "proxmox"
|
||||
IPAM = "ipam"
|
||||
SYSTEM = "system"
|
||||
API = "api"
|
||||
DOCKER = "docker"
|
||||
|
||||
# Sensitive fields to mask in logs
|
||||
SENSITIVE_FIELDS = {'password', 'token', 'secret', 'api_key', 'apikey', 'access_token', 'refresh_token'}
|
||||
|
||||
@staticmethod
|
||||
def generate_request_id() -> str:
|
||||
"""Generate a unique request ID"""
|
||||
return str(uuid.uuid4())
|
||||
|
||||
@staticmethod
|
||||
def mask_sensitive_data(data: Any, depth: int = 0) -> Any:
|
||||
"""Mask sensitive fields in data for safe logging"""
|
||||
if depth > 10: # Prevent infinite recursion
|
||||
return data
|
||||
|
||||
if isinstance(data, dict):
|
||||
masked = {}
|
||||
for key, value in data.items():
|
||||
key_lower = key.lower()
|
||||
if any(sensitive in key_lower for sensitive in LoggingService.SENSITIVE_FIELDS):
|
||||
masked[key] = "***MASKED***"
|
||||
else:
|
||||
masked[key] = LoggingService.mask_sensitive_data(value, depth + 1)
|
||||
return masked
|
||||
elif isinstance(data, list):
|
||||
return [LoggingService.mask_sensitive_data(item, depth + 1) for item in data]
|
||||
return data
|
||||
|
||||
@staticmethod
|
||||
def truncate_data(data: Any, max_size: int = 5000) -> Any:
|
||||
"""Truncate large data for storage"""
|
||||
if data is None:
|
||||
return None
|
||||
if isinstance(data, str):
|
||||
if len(data) > max_size:
|
||||
return data[:max_size] + f"... (truncated, {len(data)} total chars)"
|
||||
return data
|
||||
if isinstance(data, dict):
|
||||
import json
|
||||
json_str = json.dumps(data)
|
||||
if len(json_str) > max_size:
|
||||
return {"_truncated": True, "_size": len(json_str), "_preview": json_str[:500]}
|
||||
return data
|
||||
return data
|
||||
|
||||
@staticmethod
|
||||
def log(
|
||||
db: Session,
|
||||
level: str,
|
||||
category: str,
|
||||
action: str,
|
||||
message: str,
|
||||
user_id: Optional[int] = None,
|
||||
username: Optional[str] = None,
|
||||
ip_address: Optional[str] = None,
|
||||
user_agent: Optional[str] = None,
|
||||
resource_type: Optional[str] = None,
|
||||
resource_id: Optional[str] = None,
|
||||
resource_name: Optional[str] = None,
|
||||
details: Optional[Dict[str, Any]] = None,
|
||||
request_method: Optional[str] = None,
|
||||
request_path: Optional[str] = None,
|
||||
response_status: Optional[int] = None,
|
||||
duration_ms: Optional[int] = None,
|
||||
success: bool = True,
|
||||
error_message: Optional[str] = None,
|
||||
# New enhanced fields
|
||||
request_id: Optional[str] = None,
|
||||
session_id: Optional[str] = None,
|
||||
geo_location: Optional[str] = None,
|
||||
server_id: Optional[int] = None,
|
||||
server_name: Optional[str] = None,
|
||||
node_name: Optional[str] = None,
|
||||
request_body: Optional[Dict[str, Any]] = None,
|
||||
response_body: Optional[Dict[str, Any]] = None,
|
||||
query_params: Optional[str] = None,
|
||||
error_traceback: Optional[str] = None
|
||||
) -> AuditLog:
|
||||
"""
|
||||
Create a new audit log entry with enhanced details
|
||||
|
||||
Args:
|
||||
db: Database session
|
||||
level: Log level (debug, info, warning, error, critical)
|
||||
category: Log category (auth, proxmox, ipam, system, api)
|
||||
action: Action performed (login, vm_start, etc.)
|
||||
message: Human-readable message
|
||||
user_id: User ID (optional)
|
||||
username: Username (optional)
|
||||
ip_address: Client IP address (optional)
|
||||
user_agent: Client user agent (optional)
|
||||
resource_type: Type of resource (vm, container, etc.)
|
||||
resource_id: ID of the resource
|
||||
resource_name: Name of the resource
|
||||
details: Additional details as JSON
|
||||
request_method: HTTP method
|
||||
request_path: HTTP path
|
||||
response_status: HTTP response status code
|
||||
duration_ms: Request duration in milliseconds
|
||||
success: Whether the action was successful
|
||||
error_message: Error message if failed
|
||||
request_id: Unique request ID for correlation
|
||||
session_id: User session ID
|
||||
geo_location: Geographic location from IP
|
||||
server_id: Proxmox server ID
|
||||
server_name: Proxmox server name
|
||||
node_name: Proxmox node name
|
||||
request_body: Request body (sensitive data masked)
|
||||
response_body: Response body (truncated)
|
||||
query_params: Query string parameters
|
||||
error_traceback: Stack trace for errors
|
||||
|
||||
Returns:
|
||||
Created AuditLog instance
|
||||
"""
|
||||
try:
|
||||
# Mask sensitive data in request body
|
||||
safe_request_body = None
|
||||
if request_body:
|
||||
safe_request_body = LoggingService.mask_sensitive_data(request_body)
|
||||
safe_request_body = LoggingService.truncate_data(safe_request_body)
|
||||
|
||||
# Truncate response body
|
||||
safe_response_body = LoggingService.truncate_data(response_body) if response_body else None
|
||||
|
||||
# Mask sensitive data in details
|
||||
safe_details = LoggingService.mask_sensitive_data(details) if details else None
|
||||
|
||||
log_entry = AuditLog(
|
||||
level=level,
|
||||
category=category,
|
||||
action=action,
|
||||
message=message,
|
||||
request_id=request_id,
|
||||
session_id=session_id,
|
||||
user_id=user_id,
|
||||
username=username,
|
||||
ip_address=ip_address,
|
||||
user_agent=user_agent,
|
||||
geo_location=geo_location,
|
||||
resource_type=resource_type,
|
||||
resource_id=str(resource_id) if resource_id else None,
|
||||
resource_name=resource_name,
|
||||
server_id=server_id,
|
||||
server_name=server_name,
|
||||
node_name=node_name,
|
||||
details=safe_details,
|
||||
request_body=safe_request_body,
|
||||
response_body=safe_response_body,
|
||||
request_method=request_method,
|
||||
request_path=request_path,
|
||||
query_params=query_params,
|
||||
response_status=response_status,
|
||||
duration_ms=duration_ms,
|
||||
success=success,
|
||||
error_message=error_message,
|
||||
error_traceback=error_traceback
|
||||
)
|
||||
db.add(log_entry)
|
||||
db.commit()
|
||||
db.refresh(log_entry)
|
||||
|
||||
# Also log to file/console via loguru with request_id for correlation
|
||||
log_method = getattr(logger, level, logger.info)
|
||||
log_prefix = f"[{request_id[:8]}] " if request_id else ""
|
||||
log_method(f"{log_prefix}[{category.upper()}] {action}: {message}")
|
||||
|
||||
return log_entry
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to create audit log: {e}")
|
||||
db.rollback()
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def log_auth(
|
||||
db: Session,
|
||||
action: str,
|
||||
username: str,
|
||||
ip_address: str,
|
||||
success: bool = True,
|
||||
error_message: Optional[str] = None,
|
||||
user_agent: Optional[str] = None,
|
||||
user_id: Optional[int] = None,
|
||||
details: Optional[Dict[str, Any]] = None
|
||||
) -> AuditLog:
|
||||
"""Log authentication events"""
|
||||
level = LoggingService.INFO if success else LoggingService.WARNING
|
||||
message = f"User '{username}' {action}"
|
||||
if not success:
|
||||
message += f" failed: {error_message}"
|
||||
|
||||
return LoggingService.log(
|
||||
db=db,
|
||||
level=level,
|
||||
category=LoggingService.AUTH,
|
||||
action=action,
|
||||
message=message,
|
||||
user_id=user_id,
|
||||
username=username,
|
||||
ip_address=ip_address,
|
||||
user_agent=user_agent,
|
||||
success=success,
|
||||
error_message=error_message,
|
||||
details=details
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def log_proxmox_action(
|
||||
db: Session,
|
||||
action: str,
|
||||
resource_type: str,
|
||||
resource_id: Any,
|
||||
username: Optional[str] = None,
|
||||
resource_name: Optional[str] = None,
|
||||
details: Optional[Dict[str, Any]] = None,
|
||||
success: bool = True,
|
||||
error_message: Optional[str] = None,
|
||||
ip_address: Optional[str] = None,
|
||||
server_id: Optional[int] = None,
|
||||
server_name: Optional[str] = None,
|
||||
node_name: Optional[str] = None,
|
||||
request_id: Optional[str] = None,
|
||||
error_traceback: Optional[str] = None
|
||||
) -> AuditLog:
|
||||
"""Log Proxmox actions (VM/Container operations)"""
|
||||
level = LoggingService.INFO if success else LoggingService.ERROR
|
||||
|
||||
action_messages = {
|
||||
"start": "started",
|
||||
"stop": "stopped",
|
||||
"restart": "restarted",
|
||||
"shutdown": "shutdown",
|
||||
"delete": "deleted",
|
||||
"create": "created",
|
||||
"clone": "cloned",
|
||||
"migrate": "migrated",
|
||||
"backup": "backup created",
|
||||
"restore": "restored",
|
||||
"snapshot": "snapshot created",
|
||||
"resize": "disk resized",
|
||||
"console": "console accessed",
|
||||
"config_update": "config updated"
|
||||
}
|
||||
|
||||
action_text = action_messages.get(action, action)
|
||||
type_text = "VM" if resource_type == "vm" else "Container" if resource_type == "container" else resource_type
|
||||
|
||||
message = f"{type_text} {resource_id}"
|
||||
if resource_name:
|
||||
message += f" ({resource_name})"
|
||||
message += f" {action_text}"
|
||||
if node_name:
|
||||
message += f" on node {node_name}"
|
||||
if server_name:
|
||||
message += f" [{server_name}]"
|
||||
if username:
|
||||
message += f" by {username}"
|
||||
|
||||
if not success:
|
||||
message += f" - ERROR: {error_message}"
|
||||
|
||||
# Enhance details with server context
|
||||
enhanced_details = details.copy() if details else {}
|
||||
if server_id:
|
||||
enhanced_details['server_id'] = server_id
|
||||
if server_name:
|
||||
enhanced_details['server_name'] = server_name
|
||||
if node_name:
|
||||
enhanced_details['node'] = node_name
|
||||
|
||||
return LoggingService.log(
|
||||
db=db,
|
||||
level=level,
|
||||
category=LoggingService.PROXMOX,
|
||||
action=f"{resource_type}_{action}",
|
||||
message=message,
|
||||
username=username,
|
||||
ip_address=ip_address,
|
||||
resource_type=resource_type,
|
||||
resource_id=resource_id,
|
||||
resource_name=resource_name,
|
||||
server_id=server_id,
|
||||
server_name=server_name,
|
||||
node_name=node_name,
|
||||
details=enhanced_details,
|
||||
success=success,
|
||||
error_message=error_message,
|
||||
request_id=request_id,
|
||||
error_traceback=error_traceback
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def log_ipam_action(
|
||||
db: Session,
|
||||
action: str,
|
||||
resource_type: str,
|
||||
resource_id: Any,
|
||||
username: Optional[str] = None,
|
||||
resource_name: Optional[str] = None,
|
||||
details: Optional[Dict[str, Any]] = None,
|
||||
ip_address: Optional[str] = None
|
||||
) -> AuditLog:
|
||||
"""Log IPAM actions"""
|
||||
action_messages = {
|
||||
"allocate": "выделен IP адрес",
|
||||
"release": "освобождён IP адрес",
|
||||
"create_network": "создана сеть",
|
||||
"delete_network": "удалена сеть",
|
||||
"create_pool": "создан пул адресов",
|
||||
"delete_pool": "удалён пул адресов"
|
||||
}
|
||||
|
||||
message = action_messages.get(action, action)
|
||||
if resource_name:
|
||||
message += f": {resource_name}"
|
||||
if username:
|
||||
message += f" (пользователь: {username})"
|
||||
|
||||
return LoggingService.log(
|
||||
db=db,
|
||||
level=LoggingService.INFO,
|
||||
category=LoggingService.IPAM,
|
||||
action=action,
|
||||
message=message,
|
||||
username=username,
|
||||
ip_address=ip_address,
|
||||
resource_type=resource_type,
|
||||
resource_id=resource_id,
|
||||
resource_name=resource_name,
|
||||
details=details
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def log_api_request(
|
||||
db: Session,
|
||||
method: str,
|
||||
path: str,
|
||||
status_code: int,
|
||||
duration_ms: int,
|
||||
ip_address: Optional[str] = None,
|
||||
username: Optional[str] = None,
|
||||
user_agent: Optional[str] = None,
|
||||
error_message: Optional[str] = None
|
||||
) -> AuditLog:
|
||||
"""Log API requests"""
|
||||
level = LoggingService.DEBUG
|
||||
if status_code >= 500:
|
||||
level = LoggingService.ERROR
|
||||
elif status_code >= 400:
|
||||
level = LoggingService.WARNING
|
||||
|
||||
success = status_code < 400
|
||||
message = f"{method} {path} - {status_code} ({duration_ms}ms)"
|
||||
|
||||
return LoggingService.log(
|
||||
db=db,
|
||||
level=level,
|
||||
category=LoggingService.API,
|
||||
action="api_request",
|
||||
message=message,
|
||||
username=username,
|
||||
ip_address=ip_address,
|
||||
user_agent=user_agent,
|
||||
request_method=method,
|
||||
request_path=path,
|
||||
response_status=status_code,
|
||||
duration_ms=duration_ms,
|
||||
success=success,
|
||||
error_message=error_message
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def log_system(
|
||||
db: Session,
|
||||
action: str,
|
||||
message: str,
|
||||
level: str = "info",
|
||||
details: Optional[Dict[str, Any]] = None
|
||||
) -> AuditLog:
|
||||
"""Log system events"""
|
||||
return LoggingService.log(
|
||||
db=db,
|
||||
level=level,
|
||||
category=LoggingService.SYSTEM,
|
||||
action=action,
|
||||
message=message,
|
||||
details=details
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def get_logs(
|
||||
db: Session,
|
||||
level: Optional[str] = None,
|
||||
category: Optional[str] = None,
|
||||
username: Optional[str] = None,
|
||||
ip_address: Optional[str] = None,
|
||||
resource_type: Optional[str] = None,
|
||||
resource_id: Optional[str] = None,
|
||||
date_from: Optional[datetime] = None,
|
||||
date_to: Optional[datetime] = None,
|
||||
search: Optional[str] = None,
|
||||
request_id: Optional[str] = None,
|
||||
limit: int = 100,
|
||||
offset: int = 0
|
||||
) -> tuple[List[AuditLog], int]:
|
||||
"""
|
||||
Get logs with filtering
|
||||
|
||||
Returns:
|
||||
Tuple of (logs list, total count)
|
||||
"""
|
||||
query = db.query(AuditLog)
|
||||
|
||||
# Apply filters
|
||||
if level:
|
||||
query = query.filter(AuditLog.level == level)
|
||||
if category:
|
||||
query = query.filter(AuditLog.category == category)
|
||||
if username:
|
||||
query = query.filter(AuditLog.username.ilike(f"%{username}%"))
|
||||
if ip_address:
|
||||
query = query.filter(AuditLog.ip_address.ilike(f"%{ip_address}%"))
|
||||
if resource_type:
|
||||
query = query.filter(AuditLog.resource_type == resource_type)
|
||||
if resource_id:
|
||||
query = query.filter(AuditLog.resource_id == resource_id)
|
||||
if date_from:
|
||||
query = query.filter(AuditLog.created_at >= date_from)
|
||||
if date_to:
|
||||
query = query.filter(AuditLog.created_at <= date_to)
|
||||
if request_id:
|
||||
query = query.filter(AuditLog.request_id == request_id)
|
||||
if search:
|
||||
query = query.filter(
|
||||
or_(
|
||||
AuditLog.message.ilike(f"%{search}%"),
|
||||
AuditLog.action.ilike(f"%{search}%"),
|
||||
AuditLog.resource_name.ilike(f"%{search}%"),
|
||||
AuditLog.request_id.ilike(f"%{search}%")
|
||||
)
|
||||
)
|
||||
|
||||
# Get total count
|
||||
total = query.count()
|
||||
|
||||
# Apply pagination and ordering
|
||||
logs = query.order_by(desc(AuditLog.created_at)).offset(offset).limit(limit).all()
|
||||
|
||||
return logs, total
|
||||
|
||||
@staticmethod
|
||||
def get_stats(db: Session, hours: int = 24) -> Dict[str, Any]:
|
||||
"""Get log statistics for the specified period"""
|
||||
from sqlalchemy import func
|
||||
|
||||
since = utcnow() - timedelta(hours=hours)
|
||||
|
||||
# Total logs
|
||||
total = db.query(AuditLog).filter(AuditLog.created_at >= since).count()
|
||||
|
||||
# By level
|
||||
by_level = {}
|
||||
for level in ['debug', 'info', 'warning', 'error', 'critical']:
|
||||
count = db.query(AuditLog).filter(
|
||||
and_(AuditLog.created_at >= since, AuditLog.level == level)
|
||||
).count()
|
||||
by_level[level] = count
|
||||
|
||||
# By category
|
||||
by_category = {}
|
||||
for category in ['auth', 'proxmox', 'ipam', 'system', 'api', 'docker']:
|
||||
count = db.query(AuditLog).filter(
|
||||
and_(AuditLog.created_at >= since, AuditLog.category == category)
|
||||
).count()
|
||||
by_category[category] = count
|
||||
|
||||
# Recent errors
|
||||
errors = db.query(AuditLog).filter(
|
||||
and_(
|
||||
AuditLog.created_at >= since,
|
||||
AuditLog.level.in_(['error', 'critical'])
|
||||
)
|
||||
).order_by(desc(AuditLog.created_at)).limit(5).all()
|
||||
|
||||
# Failed logins
|
||||
failed_logins = db.query(AuditLog).filter(
|
||||
and_(
|
||||
AuditLog.created_at >= since,
|
||||
AuditLog.category == 'auth',
|
||||
AuditLog.success == False
|
||||
)
|
||||
).count()
|
||||
|
||||
return {
|
||||
"period_hours": hours,
|
||||
"total": total,
|
||||
"by_level": by_level,
|
||||
"by_category": by_category,
|
||||
"errors_count": by_level.get('error', 0) + by_level.get('critical', 0),
|
||||
"failed_logins": failed_logins,
|
||||
"recent_errors": [
|
||||
{
|
||||
"id": e.id,
|
||||
"level": e.level,
|
||||
"category": e.category,
|
||||
"action": e.action,
|
||||
"message": e.message,
|
||||
"created_at": e.created_at.isoformat() if e.created_at else None
|
||||
}
|
||||
for e in errors
|
||||
]
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def cleanup_old_logs(db: Session, days: int = 30) -> int:
|
||||
"""Delete logs older than specified days"""
|
||||
cutoff = utcnow() - timedelta(days=days)
|
||||
deleted = db.query(AuditLog).filter(AuditLog.created_at < cutoff).delete()
|
||||
db.commit()
|
||||
logger.info(f"Cleaned up {deleted} audit logs older than {days} days")
|
||||
return deleted
|
||||
257
backend/app/main.py
Normal file
257
backend/app/main.py
Normal file
@@ -0,0 +1,257 @@
|
||||
import logging
|
||||
import os
|
||||
from contextlib import asynccontextmanager
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import FastAPI, Request, HTTPException
|
||||
from fastapi.responses import RedirectResponse, JSONResponse
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
from fastapi.exception_handlers import http_exception_handler
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.templating import Jinja2Templates
|
||||
from loguru import logger
|
||||
|
||||
from .config import settings
|
||||
from .db import Base, engine, init_db, check_db_connection
|
||||
from .api import dashboard as dashboard_router
|
||||
from .api import proxmox as proxmox_router
|
||||
from .api import auth as auth_router
|
||||
from .api import templates as templates_router
|
||||
from .api import ipam as ipam_router
|
||||
from .api import logs as logs_router
|
||||
from .api import settings as settings_router
|
||||
from .api import notifications as notifications_router
|
||||
from .api import users as users_router
|
||||
from .logging_middleware import RequestLoggingMiddleware
|
||||
from .language_middleware import LanguageMiddleware
|
||||
from .i18n import I18nService
|
||||
from .template_helpers import add_i18n_context
|
||||
|
||||
|
||||
# Configure logging
|
||||
def setup_logging():
|
||||
"""Setup application logging"""
|
||||
log_dir = Path("logs")
|
||||
log_dir.mkdir(exist_ok=True)
|
||||
|
||||
# Remove default logger
|
||||
logger.remove()
|
||||
|
||||
# Add console logging
|
||||
logger.add(
|
||||
sink=lambda msg: print(msg, end=""),
|
||||
level=settings.LOG_LEVEL,
|
||||
format="<green>{time:YYYY-MM-DD HH:mm:ss}</green> | <level>{level: <8}</level> | <cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> - <level>{message}</level>"
|
||||
)
|
||||
|
||||
# Add file logging
|
||||
logger.add(
|
||||
settings.LOG_FILE,
|
||||
level=settings.LOG_LEVEL,
|
||||
format="{time:YYYY-MM-DD HH:mm:ss} | {level: <8} | {name}:{function}:{line} - {message}",
|
||||
rotation="10 MB",
|
||||
retention="30 days",
|
||||
compression="zip"
|
||||
)
|
||||
|
||||
# Intercept standard logging
|
||||
class InterceptHandler(logging.Handler):
|
||||
def emit(self, record):
|
||||
try:
|
||||
level = logger.level(record.levelname).name
|
||||
except ValueError:
|
||||
level = record.levelno
|
||||
|
||||
frame, depth = logging.currentframe(), 2
|
||||
while frame.f_code.co_filename == logging.__file__:
|
||||
frame = frame.f_back
|
||||
depth += 1
|
||||
|
||||
logger.opt(depth=depth, exception=record.exc_info).log(level, record.getMessage())
|
||||
|
||||
logging.basicConfig(handlers=[InterceptHandler()], level=0, force=True)
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
"""Application lifespan handler"""
|
||||
logger.info(f"Starting {settings.PANEL_NAME}")
|
||||
|
||||
# Setup logging
|
||||
setup_logging()
|
||||
|
||||
# Check database connection
|
||||
if not check_db_connection():
|
||||
logger.error("Database connection failed!")
|
||||
raise Exception("Cannot connect to database")
|
||||
|
||||
# Initialize database
|
||||
try:
|
||||
init_db()
|
||||
logger.info("Database initialized successfully")
|
||||
except Exception as e:
|
||||
logger.error(f"Database initialization failed: {e}")
|
||||
raise
|
||||
|
||||
# Run database migrations automatically
|
||||
try:
|
||||
import sys
|
||||
from pathlib import Path
|
||||
import importlib.util
|
||||
|
||||
# Add migrations directory to path
|
||||
migrations_path = Path(__file__).parent.parent / 'migrations'
|
||||
sys.path.insert(0, str(migrations_path))
|
||||
|
||||
from .db import engine
|
||||
|
||||
# Load and run unified migrations
|
||||
spec = importlib.util.spec_from_file_location(
|
||||
"migrations",
|
||||
migrations_path / "migrations.py"
|
||||
)
|
||||
migrations_module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(migrations_module)
|
||||
migrations_module.run_all_migrations(engine)
|
||||
logger.info("Database migrations completed")
|
||||
|
||||
except Exception as e:
|
||||
logger.warning(f"Migration check failed: {e}")
|
||||
|
||||
# Start background monitoring worker
|
||||
try:
|
||||
from .workers.monitoring_worker import start_monitoring_worker
|
||||
scheduler = start_monitoring_worker()
|
||||
logger.info("Background monitoring worker started")
|
||||
except Exception as e:
|
||||
logger.warning(f"Background worker startup failed: {e}")
|
||||
|
||||
logger.info("Application startup complete")
|
||||
yield
|
||||
|
||||
# Cleanup
|
||||
try:
|
||||
if 'scheduler' in locals():
|
||||
scheduler.shutdown()
|
||||
logger.info("Background worker stopped")
|
||||
except Exception as e:
|
||||
logger.warning(f"Background worker shutdown failed: {e}")
|
||||
|
||||
logger.info("Application shutdown")
|
||||
|
||||
|
||||
def create_app() -> FastAPI:
|
||||
"""Create FastAPI application"""
|
||||
app = FastAPI(
|
||||
title=settings.PANEL_NAME,
|
||||
description="Server management panel with Proxmox integration",
|
||||
lifespan=lifespan,
|
||||
debug=settings.DEBUG
|
||||
)
|
||||
|
||||
# Add CORS middleware
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=["*"], # In production, specify exact origins
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
# Add request logging middleware
|
||||
app.add_middleware(RequestLoggingMiddleware, enable_api_logging=True)
|
||||
|
||||
# Add language detection middleware
|
||||
app.add_middleware(LanguageMiddleware)
|
||||
|
||||
# Templates
|
||||
templates = Jinja2Templates(directory="app/templates")
|
||||
|
||||
|
||||
|
||||
# Custom exception handler
|
||||
@app.exception_handler(Exception)
|
||||
async def global_exception_handler(request: Request, exc: Exception):
|
||||
logger.error(f"Unhandled exception: {exc}", exc_info=True)
|
||||
return JSONResponse(
|
||||
status_code=500,
|
||||
content={"detail": "Internal server error"}
|
||||
)
|
||||
|
||||
@app.exception_handler(HTTPException)
|
||||
async def custom_http_exception_handler(request: Request, exc: HTTPException):
|
||||
logger.warning(f"HTTP exception: {exc.status_code} - {exc.detail}")
|
||||
return await http_exception_handler(request, exc)
|
||||
|
||||
# Health check endpoint
|
||||
@app.get("/health")
|
||||
async def health_check():
|
||||
"""Health check endpoint"""
|
||||
db_healthy = check_db_connection()
|
||||
return {
|
||||
"status": "healthy" if db_healthy else "unhealthy",
|
||||
"version": settings.VERSION,
|
||||
"database": "connected" if db_healthy else "disconnected"
|
||||
}
|
||||
|
||||
# Root redirect
|
||||
@app.get("/", include_in_schema=False)
|
||||
async def root():
|
||||
return RedirectResponse(url="/dashboard", status_code=302)
|
||||
|
||||
# Legacy redirect for old /servers URL
|
||||
@app.get("/servers", include_in_schema=False)
|
||||
async def servers_redirect():
|
||||
return RedirectResponse(url="/proxmox/vms", status_code=301)
|
||||
|
||||
# Direct access to /vms - now shows Proxmox servers
|
||||
@app.get("/vms", include_in_schema=False)
|
||||
async def vms_redirect():
|
||||
return RedirectResponse(url="/proxmox/vms", status_code=301)
|
||||
|
||||
# Virtual Machines list page
|
||||
@app.get("/virtual-machines", include_in_schema=False)
|
||||
async def virtual_machines_page(request: Request):
|
||||
"""Virtual Machines list page"""
|
||||
from .i18n import t
|
||||
lang = request.cookies.get("language", "ru")
|
||||
|
||||
context = {
|
||||
"request": request,
|
||||
"page_title": t('nav_vms', lang),
|
||||
}
|
||||
context = add_i18n_context(request, context)
|
||||
return templates.TemplateResponse("virtual_machines.html", context)
|
||||
|
||||
# Virtual Machine detail page
|
||||
@app.get("/virtual-machines/{server_id}/{vmid}", include_in_schema=False)
|
||||
async def virtual_machine_detail_page(request: Request, server_id: int, vmid: int, type: str = "qemu", node: str = ""):
|
||||
"""Virtual Machine detail page"""
|
||||
return RedirectResponse(url=f"/proxmox/server/{server_id}/instance/{vmid}?type={type}&node={node}", status_code=302)
|
||||
|
||||
# API for virtual machines list (proxy to proxmox router)
|
||||
@app.get("/api/virtual-machines")
|
||||
async def api_virtual_machines(request: Request):
|
||||
"""Proxy to proxmox virtual-machines API"""
|
||||
return RedirectResponse(url="/proxmox/api/virtual-machines", status_code=307)
|
||||
|
||||
# Include routers
|
||||
app.include_router(auth_router.router, tags=["auth"])
|
||||
app.include_router(dashboard_router.router, tags=["dashboard"])
|
||||
app.include_router(proxmox_router.router, prefix="/proxmox", tags=["proxmox"])
|
||||
app.include_router(templates_router.router, prefix="/templates", tags=["templates"])
|
||||
app.include_router(ipam_router.router, prefix="/ipam", tags=["ipam"])
|
||||
app.include_router(logs_router.router, prefix="/logs", tags=["logs"])
|
||||
app.include_router(settings_router.router, prefix="/settings", tags=["settings"])
|
||||
app.include_router(notifications_router.router, tags=["notifications"])
|
||||
app.include_router(users_router.router, prefix="/admin", tags=["users", "admin"])
|
||||
|
||||
# Mount static files for noVNC
|
||||
static_dir = Path(__file__).parent / "static"
|
||||
if static_dir.exists():
|
||||
app.mount("/static", StaticFiles(directory=str(static_dir)), name="static")
|
||||
|
||||
return app
|
||||
|
||||
|
||||
app = create_app()
|
||||
844
backend/app/models.py
Normal file
844
backend/app/models.py
Normal file
@@ -0,0 +1,844 @@
|
||||
from sqlalchemy import Boolean, Column, Integer, BigInteger, String, DateTime, Text, Index, JSON, ForeignKey
|
||||
from sqlalchemy.sql import func
|
||||
from sqlalchemy.orm import relationship
|
||||
from datetime import datetime, timezone
|
||||
from typing import Optional
|
||||
|
||||
from .db import Base
|
||||
|
||||
|
||||
def utcnow() -> datetime:
|
||||
"""Get current UTC time as timezone-aware datetime"""
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
# ==================== RBAC Models ====================
|
||||
|
||||
class Role(Base):
|
||||
"""User roles with permissions"""
|
||||
__tablename__ = "roles"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
name = Column(String(50), unique=True, nullable=False, index=True)
|
||||
display_name = Column(String(100), nullable=False)
|
||||
description = Column(Text, nullable=True)
|
||||
permissions = Column(JSON, nullable=False, default={})
|
||||
is_system = Column(Boolean, default=False, nullable=False) # System roles can't be deleted
|
||||
is_active = Column(Boolean, default=True, nullable=False)
|
||||
|
||||
created_at = Column(DateTime(timezone=True), server_default=func.now(), nullable=False)
|
||||
updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now(), nullable=False)
|
||||
|
||||
# Relationships
|
||||
users = relationship("User", back_populates="role")
|
||||
|
||||
def has_permission(self, permission: str) -> bool:
|
||||
"""Check if role has specific permission"""
|
||||
if not self.permissions:
|
||||
return False
|
||||
return self.permissions.get(permission, False)
|
||||
|
||||
def __repr__(self):
|
||||
return f"<Role(id={self.id}, name='{self.name}')>"
|
||||
|
||||
|
||||
class User(Base):
|
||||
__tablename__ = "users"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
username = Column(String(50), unique=True, nullable=False, index=True)
|
||||
email = Column(String(255), unique=True, nullable=False, index=True)
|
||||
hashed_password = Column(String(255), nullable=False)
|
||||
full_name = Column(String(100), nullable=True)
|
||||
|
||||
is_active = Column(Boolean, default=True, nullable=False)
|
||||
is_admin = Column(Boolean, default=False, nullable=False) # Legacy, use role instead
|
||||
|
||||
# Role-based access
|
||||
role_id = Column(Integer, ForeignKey("roles.id"), nullable=True, index=True)
|
||||
role = relationship("Role", back_populates="users", lazy="joined")
|
||||
|
||||
# Security fields
|
||||
failed_login_attempts = Column(Integer, default=0, nullable=False)
|
||||
locked_until = Column(DateTime(timezone=True), nullable=True)
|
||||
last_password_change = Column(DateTime(timezone=True), nullable=True)
|
||||
require_password_change = Column(Boolean, default=False, nullable=False)
|
||||
two_factor_enabled = Column(Boolean, default=False, nullable=False)
|
||||
two_factor_secret = Column(String(100), nullable=True)
|
||||
|
||||
created_at = Column(DateTime(timezone=True), server_default=func.now(), nullable=False)
|
||||
updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now(), nullable=False)
|
||||
last_login = Column(DateTime(timezone=True), nullable=True)
|
||||
|
||||
# Relationships
|
||||
sessions = relationship("ActiveSession", back_populates="user", cascade="all, delete-orphan")
|
||||
|
||||
def has_permission(self, permission: str) -> bool:
|
||||
"""
|
||||
Check if user has specific permission.
|
||||
Uses new RBAC engine with legacy format support.
|
||||
"""
|
||||
# Import here to avoid circular imports
|
||||
try:
|
||||
from .rbac import PermissionEngine
|
||||
return PermissionEngine.has_permission(self, permission)
|
||||
except ImportError:
|
||||
# Fallback for tests or if rbac module not available
|
||||
if self.is_admin:
|
||||
return True
|
||||
if self.role:
|
||||
return self.role.has_permission(permission)
|
||||
return False
|
||||
|
||||
def get_permissions(self) -> set:
|
||||
"""Get all effective permissions for this user"""
|
||||
try:
|
||||
from .rbac import PermissionEngine
|
||||
return PermissionEngine.get_user_permissions(self)
|
||||
except ImportError:
|
||||
if self.is_admin:
|
||||
return set() # Admin has all
|
||||
if self.role and self.role.permissions:
|
||||
return {k for k, v in self.role.permissions.items() if v}
|
||||
return set()
|
||||
|
||||
def is_locked(self) -> bool:
|
||||
"""Check if account is locked"""
|
||||
if self.locked_until and self.locked_until > utcnow():
|
||||
return True
|
||||
return False
|
||||
|
||||
@property
|
||||
def role_name(self) -> str:
|
||||
"""Get role name"""
|
||||
if self.role:
|
||||
return self.role.name
|
||||
return "admin" if self.is_admin else "user"
|
||||
|
||||
def __repr__(self):
|
||||
return f"<User(id={self.id}, username='{self.username}', is_admin={self.is_admin})>"
|
||||
|
||||
|
||||
class ActiveSession(Base):
|
||||
"""Active user sessions for single-session enforcement"""
|
||||
__tablename__ = "active_sessions"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
user_id = Column(Integer, ForeignKey("users.id", ondelete="CASCADE"), nullable=False)
|
||||
session_token = Column(String(64), unique=True, nullable=False, index=True)
|
||||
ip_address = Column(String(45), nullable=True)
|
||||
user_agent = Column(String(500), nullable=True)
|
||||
device_info = Column(String(200), nullable=True)
|
||||
created_at = Column(DateTime(timezone=True), server_default=func.now(), nullable=False)
|
||||
expires_at = Column(DateTime(timezone=True), nullable=False)
|
||||
last_activity = Column(DateTime(timezone=True), server_default=func.now(), nullable=False)
|
||||
is_active = Column(Boolean, default=True, nullable=False)
|
||||
|
||||
# Relationships
|
||||
user = relationship("User", back_populates="sessions")
|
||||
|
||||
def is_expired(self) -> bool:
|
||||
"""Check if session is expired"""
|
||||
from datetime import timezone
|
||||
now = datetime.now(timezone.utc)
|
||||
if self.expires_at is None:
|
||||
return True
|
||||
# Compare timezone-aware datetimes
|
||||
return now > self.expires_at
|
||||
|
||||
def __repr__(self):
|
||||
return f"<ActiveSession(id={self.id}, user_id={self.user_id}, active={self.is_active})>"
|
||||
|
||||
|
||||
class LoginAttempt(Base):
|
||||
"""Login attempts for brute-force protection"""
|
||||
__tablename__ = "login_attempts"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
username = Column(String(100), nullable=True, index=True)
|
||||
ip_address = Column(String(45), nullable=False, index=True)
|
||||
user_agent = Column(String(500), nullable=True)
|
||||
success = Column(Boolean, default=False, nullable=False)
|
||||
failure_reason = Column(String(200), nullable=True)
|
||||
attempted_at = Column(DateTime(timezone=True), server_default=func.now(), nullable=False, index=True)
|
||||
|
||||
def __repr__(self):
|
||||
return f"<LoginAttempt(id={self.id}, ip={self.ip_address}, success={self.success})>"
|
||||
|
||||
|
||||
class BlockedIP(Base):
|
||||
"""Blocked IP addresses"""
|
||||
__tablename__ = "blocked_ips"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
ip_address = Column(String(45), unique=True, nullable=False, index=True)
|
||||
reason = Column(String(500), nullable=True)
|
||||
blocked_by = Column(String(100), nullable=True)
|
||||
blocked_at = Column(DateTime(timezone=True), server_default=func.now(), nullable=False)
|
||||
expires_at = Column(DateTime(timezone=True), nullable=True)
|
||||
is_permanent = Column(Boolean, default=False, nullable=False)
|
||||
attempts_count = Column(Integer, default=0, nullable=False)
|
||||
|
||||
def is_blocked(self) -> bool:
|
||||
"""Check if IP is currently blocked"""
|
||||
if self.is_permanent:
|
||||
return True
|
||||
if self.expires_at and self.expires_at > utcnow():
|
||||
return True
|
||||
return False
|
||||
|
||||
def __repr__(self):
|
||||
return f"<BlockedIP(id={self.id}, ip={self.ip_address})>"
|
||||
|
||||
|
||||
class SecuritySetting(Base):
|
||||
"""Security settings"""
|
||||
__tablename__ = "security_settings"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
key = Column(String(100), unique=True, nullable=False, index=True)
|
||||
value = Column(String(500), nullable=False)
|
||||
description = Column(Text, nullable=True)
|
||||
updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now(), nullable=False)
|
||||
|
||||
def __repr__(self):
|
||||
return f"<SecuritySetting(key='{self.key}', value='{self.value}')>"
|
||||
|
||||
|
||||
class Notification(Base):
|
||||
"""User notifications"""
|
||||
__tablename__ = "notifications"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
user_id = Column(Integer, ForeignKey("users.id", ondelete="CASCADE"), nullable=False)
|
||||
type = Column(String(50), nullable=False)
|
||||
level = Column(String(20), nullable=False)
|
||||
title = Column(String(255), nullable=False)
|
||||
message = Column(Text)
|
||||
data = Column(JSON)
|
||||
link = Column(String(500))
|
||||
source = Column(String(50))
|
||||
source_id = Column(String(100))
|
||||
read = Column(Boolean, default=False)
|
||||
read_at = Column(DateTime(timezone=True))
|
||||
created_at = Column(DateTime(timezone=True), server_default=func.now())
|
||||
expires_at = Column(DateTime(timezone=True))
|
||||
|
||||
def to_dict(self):
|
||||
return {
|
||||
"id": self.id,
|
||||
"user_id": self.user_id,
|
||||
"type": self.type,
|
||||
"level": self.level,
|
||||
"title": self.title,
|
||||
"message": self.message,
|
||||
"data": self.data,
|
||||
"link": self.link,
|
||||
"source": self.source,
|
||||
"source_id": self.source_id,
|
||||
"read": self.read,
|
||||
"read_at": self.read_at.isoformat() if self.read_at else None,
|
||||
"created_at": self.created_at.isoformat() if self.created_at else None,
|
||||
"expires_at": self.expires_at.isoformat() if self.expires_at else None,
|
||||
}
|
||||
|
||||
|
||||
class NotificationPreference(Base):
|
||||
"""User notification preferences"""
|
||||
__tablename__ = "notification_preferences"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
user_id = Column(Integer, ForeignKey("users.id", ondelete="CASCADE"), unique=True, nullable=False)
|
||||
enabled = Column(Boolean, default=True)
|
||||
email_enabled = Column(Boolean, default=False)
|
||||
email_critical_only = Column(Boolean, default=True)
|
||||
telegram_enabled = Column(Boolean, default=False)
|
||||
telegram_chat_id = Column(String(100))
|
||||
webhook_url = Column(String(500))
|
||||
notification_levels = Column(JSON, default=["critical", "warning", "info", "success"])
|
||||
notification_types = Column(JSON, default=["vm_status", "resource_alert", "system"])
|
||||
quiet_hours_start = Column(String(5))
|
||||
quiet_hours_end = Column(String(5))
|
||||
created_at = Column(DateTime(timezone=True), server_default=func.now())
|
||||
updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now())
|
||||
|
||||
def to_dict(self):
|
||||
return {
|
||||
"id": self.id,
|
||||
"user_id": self.user_id,
|
||||
"enabled": self.enabled,
|
||||
"email_enabled": self.email_enabled,
|
||||
"email_critical_only": self.email_critical_only,
|
||||
"telegram_enabled": self.telegram_enabled,
|
||||
"telegram_chat_id": self.telegram_chat_id,
|
||||
"webhook_url": self.webhook_url,
|
||||
"notification_levels": self.notification_levels,
|
||||
"notification_types": self.notification_types,
|
||||
"quiet_hours_start": self.quiet_hours_start,
|
||||
"quiet_hours_end": self.quiet_hours_end,
|
||||
"created_at": self.created_at.isoformat() if self.created_at else None,
|
||||
"updated_at": self.updated_at.isoformat() if self.updated_at else None,
|
||||
}
|
||||
|
||||
|
||||
class OSTemplateGroup(Base):
|
||||
"""Group of OS templates (e.g., 'Ubuntu', 'Debian', 'Windows')"""
|
||||
__tablename__ = "os_template_groups"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
name = Column(String(100), nullable=False, index=True) # e.g., "Ubuntu", "CentOS"
|
||||
icon = Column(String(200), nullable=True) # FA icon HTML e.g., '<i class="fa-brands fa-ubuntu os-icon"></i>'
|
||||
description = Column(Text, nullable=True)
|
||||
sort_order = Column(Integer, nullable=False, default=0)
|
||||
is_active = Column(Boolean, default=True, nullable=False)
|
||||
|
||||
created_at = Column(DateTime(timezone=True), server_default=func.now(), nullable=False)
|
||||
updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now(), nullable=False)
|
||||
|
||||
def __repr__(self):
|
||||
return f"<OSTemplateGroup(id={self.id}, name='{self.name}')>"
|
||||
|
||||
|
||||
class OSTemplate(Base):
|
||||
"""OS Template linked to Proxmox VM template"""
|
||||
__tablename__ = "os_templates"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
group_id = Column(Integer, nullable=False, index=True) # FK to OSTemplateGroup
|
||||
server_id = Column(Integer, nullable=False, index=True) # FK to ProxmoxServer
|
||||
|
||||
name = Column(String(100), nullable=False) # Display name, e.g., "Ubuntu 22.04 LTS"
|
||||
vmid = Column(Integer, nullable=False) # Proxmox template VMID on source node
|
||||
node = Column(String(100), nullable=True) # Primary/source node (optional for cross-node templates)
|
||||
|
||||
# Cross-node replication support
|
||||
source_node = Column(String(100), nullable=True) # Primary node where template exists
|
||||
replicated_nodes = Column(JSON, nullable=True, default={}) # {"node_name": vmid, ...}
|
||||
|
||||
# Default VM configuration
|
||||
default_cores = Column(Integer, nullable=False, default=1)
|
||||
default_memory = Column(Integer, nullable=False, default=1024) # in MB
|
||||
default_disk = Column(Integer, nullable=False, default=10) # in GB
|
||||
min_cores = Column(Integer, nullable=False, default=1)
|
||||
min_memory = Column(Integer, nullable=False, default=512) # in MB
|
||||
min_disk = Column(Integer, nullable=False, default=5) # in GB
|
||||
|
||||
description = Column(Text, nullable=True)
|
||||
is_active = Column(Boolean, default=True, nullable=False)
|
||||
sort_order = Column(Integer, nullable=False, default=0)
|
||||
|
||||
created_at = Column(DateTime(timezone=True), server_default=func.now(), nullable=False)
|
||||
updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now(), nullable=False)
|
||||
|
||||
__table_args__ = (
|
||||
Index('idx_os_template_group', 'group_id'),
|
||||
Index('idx_os_template_server', 'server_id'),
|
||||
Index('idx_os_template_vmid', 'server_id', 'vmid'),
|
||||
)
|
||||
|
||||
def get_source_node(self) -> str:
|
||||
"""Get the primary source node for this template"""
|
||||
return self.source_node or self.node
|
||||
|
||||
def get_vmid_for_node(self, node_name: str) -> Optional[int]:
|
||||
"""Get template VMID for specific node, returns None if not replicated"""
|
||||
source = self.get_source_node()
|
||||
if node_name == source:
|
||||
return self.vmid
|
||||
if self.replicated_nodes and node_name in self.replicated_nodes:
|
||||
return self.replicated_nodes[node_name]
|
||||
return None
|
||||
|
||||
def add_replicated_node(self, node_name: str, vmid: int):
|
||||
"""Add a replicated node entry"""
|
||||
if not self.replicated_nodes:
|
||||
self.replicated_nodes = {}
|
||||
self.replicated_nodes[node_name] = vmid
|
||||
|
||||
def __repr__(self):
|
||||
return f"<OSTemplate(id={self.id}, name='{self.name}', vmid={self.vmid})>"
|
||||
|
||||
|
||||
class ProxmoxServer(Base):
|
||||
"""Proxmox VE server with API token authentication"""
|
||||
__tablename__ = "proxmox_servers"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
name = Column(String(100), nullable=False, index=True)
|
||||
hostname = Column(String(255), nullable=False, index=True)
|
||||
ip_address = Column(String(50), nullable=False, index=True)
|
||||
port = Column(Integer, nullable=False, default=8006)
|
||||
|
||||
# API Token Authentication (recommended)
|
||||
api_user = Column(String(100), nullable=False, default="root@pam")
|
||||
api_token_name = Column(String(100), nullable=True) # e.g., "my-token"
|
||||
api_token_value = Column(String(255), nullable=True) # Secret token value
|
||||
|
||||
# Optional: Password authentication (less secure)
|
||||
use_password = Column(Boolean, nullable=False, default=False)
|
||||
password = Column(String(255), nullable=True) # Encrypted in production
|
||||
|
||||
# SSL/TLS verification
|
||||
verify_ssl = Column(Boolean, nullable=False, default=False)
|
||||
|
||||
# Metadata
|
||||
description = Column(Text, nullable=True)
|
||||
created_at = Column(DateTime(timezone=True), server_default=func.now(), nullable=False)
|
||||
updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now(), nullable=False)
|
||||
last_check = Column(DateTime(timezone=True), nullable=True)
|
||||
|
||||
# Status tracking
|
||||
is_online = Column(Boolean, nullable=True, default=None)
|
||||
last_error = Column(Text, nullable=True)
|
||||
|
||||
__table_args__ = (
|
||||
Index('idx_proxmox_status', 'is_online', 'last_check'),
|
||||
)
|
||||
|
||||
def __repr__(self):
|
||||
return f"<ProxmoxServer(id={self.id}, name='{self.name}', ip='{self.ip_address}')>"
|
||||
|
||||
@property
|
||||
def connection_info(self) -> dict:
|
||||
"""Get safe connection info without sensitive data"""
|
||||
return {
|
||||
'id': self.id,
|
||||
'name': self.name,
|
||||
'hostname': self.hostname,
|
||||
'ip_address': self.ip_address,
|
||||
'port': self.port,
|
||||
'api_user': self.api_user,
|
||||
'verify_ssl': self.verify_ssl,
|
||||
'is_online': self.is_online,
|
||||
'last_check': self.last_check
|
||||
}
|
||||
|
||||
def update_status(self, is_online: bool, error: str = None):
|
||||
"""Update server status"""
|
||||
self.is_online = is_online
|
||||
self.last_check = utcnow()
|
||||
if error:
|
||||
self.last_error = error
|
||||
elif is_online:
|
||||
self.last_error = None
|
||||
|
||||
|
||||
class VMInstance(Base):
|
||||
"""VM/Container instance cache and configuration storage"""
|
||||
__tablename__ = "vm_instances"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
server_id = Column(Integer, nullable=False, index=True) # FK to ProxmoxServer
|
||||
vmid = Column(Integer, nullable=False, index=True) # Proxmox VMID
|
||||
node = Column(String(100), nullable=False) # Proxmox node name
|
||||
vm_type = Column(String(20), nullable=False) # 'qemu' or 'lxc'
|
||||
name = Column(String(100), nullable=False)
|
||||
|
||||
# Owner (for VPS-style user isolation)
|
||||
owner_id = Column(Integer, ForeignKey('users.id'), nullable=True, index=True)
|
||||
owner = relationship("User", backref="instances", foreign_keys=[owner_id])
|
||||
|
||||
# Status (cached from Proxmox)
|
||||
status = Column(String(20), default='unknown') # running, stopped, paused, etc.
|
||||
is_template = Column(Boolean, default=False)
|
||||
|
||||
# Hardware configuration (cached)
|
||||
cores = Column(Integer, nullable=True)
|
||||
memory = Column(BigInteger, nullable=True) # in bytes
|
||||
disk_size = Column(BigInteger, nullable=True) # in bytes
|
||||
|
||||
# OS info
|
||||
os_type = Column(String(50), nullable=True) # ostype field from Proxmox
|
||||
|
||||
# Network configuration
|
||||
ip_address = Column(String(50), nullable=True) # Primary IP
|
||||
ip_prefix = Column(Integer, nullable=True, default=24) # CIDR prefix
|
||||
gateway = Column(String(50), nullable=True)
|
||||
nameserver = Column(String(50), nullable=True)
|
||||
|
||||
# Cloud-init configuration
|
||||
cloud_init_user = Column(String(100), nullable=True)
|
||||
cloud_init_password = Column(String(255), nullable=True) # Should be encrypted
|
||||
ssh_keys = Column(Text, nullable=True) # SSH public keys
|
||||
|
||||
# Template info
|
||||
template_id = Column(Integer, nullable=True) # FK to OSTemplate (if deployed from template)
|
||||
template_name = Column(String(100), nullable=True) # Cached template name for display
|
||||
|
||||
# Metadata
|
||||
description = Column(Text, nullable=True)
|
||||
tags = Column(String(255), nullable=True)
|
||||
created_at = Column(DateTime(timezone=True), server_default=func.now(), nullable=False)
|
||||
updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now(), nullable=False)
|
||||
deleted_at = Column(DateTime(timezone=True), nullable=True) # Soft delete
|
||||
last_sync_at = Column(DateTime(timezone=True), nullable=True) # Last sync with Proxmox
|
||||
|
||||
# Additional config as JSON
|
||||
extra_config = Column(JSON, nullable=True)
|
||||
|
||||
__table_args__ = (
|
||||
Index('idx_vm_instance_server_vmid', 'server_id', 'vmid', unique=True),
|
||||
Index('idx_vm_instance_active', 'server_id', 'deleted_at'),
|
||||
Index('idx_vm_instance_owner', 'owner_id'),
|
||||
)
|
||||
|
||||
def __repr__(self):
|
||||
return f"<VMInstance(id={self.id}, server_id={self.server_id}, vmid={self.vmid}, name='{self.name}')>"
|
||||
|
||||
|
||||
# ==================== IPAM Models ====================
|
||||
|
||||
class IPAMNetwork(Base):
|
||||
"""Сети/подсети для IPAM"""
|
||||
__tablename__ = "ipam_networks"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
name = Column(String(100), nullable=False) # "Production", "Management"
|
||||
description = Column(Text, nullable=True)
|
||||
|
||||
# Сетевые параметры
|
||||
network = Column(String(18), nullable=False, index=True) # "10.10.10.0/24"
|
||||
gateway = Column(String(45), nullable=True) # "10.10.10.1" (support IPv6)
|
||||
vlan_id = Column(Integer, nullable=True) # 100
|
||||
|
||||
# DNS настройки
|
||||
dns_primary = Column(String(45), nullable=True)
|
||||
dns_secondary = Column(String(45), nullable=True)
|
||||
dns_domain = Column(String(255), nullable=True) # "example.local"
|
||||
|
||||
# Привязка к Proxmox
|
||||
proxmox_server_id = Column(Integer, nullable=True, index=True) # FK to ProxmoxServer
|
||||
proxmox_bridge = Column(String(20), nullable=True) # "vmbr0"
|
||||
|
||||
# Метаданные
|
||||
is_active = Column(Boolean, default=True, nullable=False)
|
||||
created_at = Column(DateTime(timezone=True), server_default=func.now(), nullable=False)
|
||||
updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now(), nullable=False)
|
||||
|
||||
__table_args__ = (
|
||||
Index('idx_ipam_network_name', 'name'),
|
||||
Index('idx_ipam_network_active', 'is_active'),
|
||||
)
|
||||
|
||||
def __repr__(self):
|
||||
return f"<IPAMNetwork(id={self.id}, name='{self.name}', network='{self.network}')>"
|
||||
|
||||
|
||||
class IPAMPool(Base):
|
||||
"""Пулы IP-адресов внутри сети"""
|
||||
__tablename__ = "ipam_pools"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
network_id = Column(Integer, nullable=False, index=True) # FK to IPAMNetwork
|
||||
|
||||
name = Column(String(100), nullable=False) # "DHCP Pool", "Static IPs", "Reserved"
|
||||
pool_type = Column(String(20), default="static", nullable=False) # "static", "dhcp", "reserved"
|
||||
|
||||
# Диапазон
|
||||
range_start = Column(String(45), nullable=False) # "10.10.10.100"
|
||||
range_end = Column(String(45), nullable=False) # "10.10.10.200"
|
||||
|
||||
# Для автоматического выделения
|
||||
auto_assign = Column(Boolean, default=True, nullable=False)
|
||||
|
||||
description = Column(Text, nullable=True)
|
||||
is_active = Column(Boolean, default=True, nullable=False)
|
||||
created_at = Column(DateTime(timezone=True), server_default=func.now(), nullable=False)
|
||||
updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now(), nullable=False)
|
||||
|
||||
__table_args__ = (
|
||||
Index('idx_ipam_pool_network', 'network_id'),
|
||||
Index('idx_ipam_pool_type', 'pool_type'),
|
||||
)
|
||||
|
||||
def __repr__(self):
|
||||
return f"<IPAMPool(id={self.id}, name='{self.name}', range='{self.range_start}-{self.range_end}')>"
|
||||
|
||||
|
||||
class IPAMAllocation(Base):
|
||||
"""Выделенные IP-адреса"""
|
||||
__tablename__ = "ipam_allocations"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
network_id = Column(Integer, nullable=False, index=True) # FK to IPAMNetwork
|
||||
pool_id = Column(Integer, nullable=True, index=True) # FK to IPAMPool (optional)
|
||||
|
||||
# IP адрес
|
||||
ip_address = Column(String(45), nullable=False, unique=True, index=True)
|
||||
mac_address = Column(String(17), nullable=True) # "AA:BB:CC:DD:EE:FF"
|
||||
|
||||
# Привязка к ресурсу
|
||||
resource_type = Column(String(20), nullable=True) # "vm", "lxc", "physical", "service", "reserved"
|
||||
resource_id = Column(Integer, nullable=True) # VMID или ID сервера
|
||||
resource_name = Column(String(100), nullable=True) # "web-server-01"
|
||||
|
||||
# Привязка к Proxmox
|
||||
proxmox_server_id = Column(Integer, nullable=True, index=True)
|
||||
proxmox_vmid = Column(Integer, nullable=True)
|
||||
proxmox_node = Column(String(100), nullable=True)
|
||||
|
||||
# Статус
|
||||
status = Column(String(20), default="allocated", nullable=False) # "allocated", "reserved", "available", "conflict"
|
||||
allocation_type = Column(String(20), default="static", nullable=False) # "static", "dhcp", "floating"
|
||||
|
||||
# DNS
|
||||
hostname = Column(String(255), nullable=True, index=True)
|
||||
fqdn = Column(String(255), nullable=True) # "web-server-01.example.local"
|
||||
dns_ptr_record = Column(Boolean, default=False, nullable=False) # Create PTR record
|
||||
|
||||
# Аудит
|
||||
allocated_by = Column(String(100), nullable=True) # username
|
||||
allocated_at = Column(DateTime(timezone=True), server_default=func.now(), nullable=False)
|
||||
expires_at = Column(DateTime(timezone=True), nullable=True) # для временных выделений
|
||||
last_seen = Column(DateTime(timezone=True), nullable=True) # последний ping/arp
|
||||
|
||||
notes = Column(Text, nullable=True)
|
||||
|
||||
created_at = Column(DateTime(timezone=True), server_default=func.now(), nullable=False)
|
||||
updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now(), nullable=False)
|
||||
|
||||
__table_args__ = (
|
||||
Index('idx_ipam_alloc_network', 'network_id'),
|
||||
Index('idx_ipam_alloc_resource', 'resource_type', 'resource_id'),
|
||||
Index('idx_ipam_alloc_proxmox', 'proxmox_server_id', 'proxmox_vmid'),
|
||||
Index('idx_ipam_alloc_status', 'status'),
|
||||
)
|
||||
|
||||
def __repr__(self):
|
||||
return f"<IPAMAllocation(id={self.id}, ip='{self.ip_address}', resource='{self.resource_name}')>"
|
||||
|
||||
|
||||
class IPAMHistory(Base):
|
||||
"""История изменений IPAM"""
|
||||
__tablename__ = "ipam_history"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
|
||||
ip_address = Column(String(45), nullable=False, index=True)
|
||||
network_id = Column(Integer, nullable=True, index=True)
|
||||
|
||||
action = Column(String(50), nullable=False) # "allocated", "released", "modified", "conflict_detected", "scanned"
|
||||
|
||||
# Детали изменения
|
||||
old_value = Column(JSON, nullable=True) # {"resource_name": "old-vm", "status": "allocated"}
|
||||
new_value = Column(JSON, nullable=True) # {"resource_name": "new-vm", "status": "allocated"}
|
||||
|
||||
# Связь с ресурсом
|
||||
resource_type = Column(String(20), nullable=True)
|
||||
resource_id = Column(Integer, nullable=True)
|
||||
resource_name = Column(String(100), nullable=True)
|
||||
|
||||
# Аудит
|
||||
performed_by = Column(String(100), nullable=True) # username or "system"
|
||||
performed_at = Column(DateTime(timezone=True), server_default=func.now(), nullable=False)
|
||||
|
||||
notes = Column(Text, nullable=True)
|
||||
|
||||
__table_args__ = (
|
||||
Index('idx_ipam_history_ip', 'ip_address'),
|
||||
Index('idx_ipam_history_action', 'action'),
|
||||
Index('idx_ipam_history_date', 'performed_at'),
|
||||
)
|
||||
|
||||
def __repr__(self):
|
||||
return f"<IPAMHistory(id={self.id}, ip='{self.ip_address}', action='{self.action}')>"
|
||||
|
||||
|
||||
# ==================== Audit Log Model ====================
|
||||
|
||||
class AuditLog(Base):
|
||||
"""Логи аудита системы"""
|
||||
__tablename__ = "audit_logs"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
|
||||
# Уровень и категория
|
||||
level = Column(String(20), nullable=False, index=True) # debug, info, warning, error, critical
|
||||
category = Column(String(50), nullable=False, index=True) # auth, proxmox, ipam, system, api
|
||||
|
||||
# Действие
|
||||
action = Column(String(100), nullable=False, index=True) # login, vm_start, vm_stop, etc.
|
||||
message = Column(Text, nullable=False)
|
||||
|
||||
# Контекст запроса
|
||||
request_id = Column(String(36), nullable=True, index=True) # UUID для связи логов одного запроса
|
||||
session_id = Column(String(64), nullable=True, index=True) # ID сессии пользователя
|
||||
|
||||
# Пользователь
|
||||
user_id = Column(Integer, nullable=True, index=True)
|
||||
username = Column(String(100), nullable=True, index=True)
|
||||
ip_address = Column(String(45), nullable=True, index=True)
|
||||
user_agent = Column(String(500), nullable=True)
|
||||
geo_location = Column(String(100), nullable=True) # Геолокация по IP (опционально)
|
||||
|
||||
# Ресурс
|
||||
resource_type = Column(String(50), nullable=True, index=True) # vm, container, server, network, user
|
||||
resource_id = Column(String(100), nullable=True)
|
||||
resource_name = Column(String(200), nullable=True)
|
||||
server_id = Column(Integer, nullable=True, index=True) # ID Proxmox сервера
|
||||
server_name = Column(String(100), nullable=True) # Имя Proxmox сервера
|
||||
node_name = Column(String(100), nullable=True) # Имя ноды
|
||||
|
||||
# Детали (JSON)
|
||||
details = Column(JSON, nullable=True) # {"vmid": 100, "node": "pve1", "old_state": "stopped", "new_state": "running"}
|
||||
request_body = Column(JSON, nullable=True) # Тело запроса (без паролей)
|
||||
response_body = Column(JSON, nullable=True) # Сокращённое тело ответа
|
||||
|
||||
# HTTP запрос (для API логов)
|
||||
request_method = Column(String(10), nullable=True)
|
||||
request_path = Column(String(500), nullable=True)
|
||||
query_params = Column(String(1000), nullable=True) # Query параметры
|
||||
response_status = Column(Integer, nullable=True)
|
||||
duration_ms = Column(Integer, nullable=True) # Время выполнения в мс
|
||||
|
||||
# Результат
|
||||
success = Column(Boolean, default=True, nullable=False)
|
||||
error_message = Column(Text, nullable=True)
|
||||
error_traceback = Column(Text, nullable=True) # Stack trace при ошибке
|
||||
|
||||
# Время
|
||||
created_at = Column(DateTime(timezone=True), server_default=func.now(), nullable=False, index=True)
|
||||
|
||||
__table_args__ = (
|
||||
Index('idx_audit_level_category', 'level', 'category'),
|
||||
Index('idx_audit_user_time', 'username', 'created_at'),
|
||||
Index('idx_audit_resource', 'resource_type', 'resource_id'),
|
||||
Index('idx_audit_created', 'created_at'),
|
||||
Index('idx_audit_request_id', 'request_id'),
|
||||
Index('idx_audit_ip', 'ip_address'),
|
||||
Index('idx_audit_server', 'server_id'),
|
||||
)
|
||||
|
||||
def __repr__(self):
|
||||
return f"<AuditLog(id={self.id}, level='{self.level}', action='{self.action}')>"
|
||||
|
||||
|
||||
# ==================== Panel Settings Model ====================
|
||||
|
||||
class PanelSettings(Base):
|
||||
"""Настройки панели"""
|
||||
__tablename__ = "panel_settings"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
key = Column(String(100), unique=True, nullable=False, index=True) # Уникальный ключ настройки
|
||||
value = Column(String(500), nullable=False) # Значение настройки
|
||||
description = Column(Text, nullable=True) # Описание настройки
|
||||
|
||||
created_at = Column(DateTime(timezone=True), server_default=func.now(), nullable=False)
|
||||
updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now(), nullable=False)
|
||||
|
||||
def __repr__(self):
|
||||
return f"<PanelSettings(id={self.id}, key='{self.key}', value='{self.value}')>"
|
||||
|
||||
|
||||
# ==================== Task Queue Model ====================
|
||||
|
||||
class TaskQueue(Base):
|
||||
"""Background task queue for bulk operations"""
|
||||
__tablename__ = "task_queue"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
|
||||
# Task identification
|
||||
task_type = Column(String(50), nullable=False, index=True) # bulk_start, bulk_stop, bulk_restart, bulk_delete
|
||||
status = Column(String(20), nullable=False, default='pending', index=True) # pending, running, completed, failed, cancelled
|
||||
|
||||
# Task details
|
||||
user_id = Column(Integer, nullable=False, index=True) # Who initiated
|
||||
|
||||
# Progress tracking
|
||||
total_items = Column(Integer, nullable=False, default=0)
|
||||
completed_items = Column(Integer, nullable=False, default=0)
|
||||
failed_items = Column(Integer, nullable=False, default=0)
|
||||
|
||||
# Task data (JSON with list of VMs/containers to process)
|
||||
task_data = Column(JSON, nullable=False) # [{server_id, vmid, vm_type, name}, ...]
|
||||
|
||||
# Results (JSON with success/error for each item)
|
||||
results = Column(JSON, nullable=True) # [{vmid, success, message}, ...]
|
||||
|
||||
# Error message if task failed
|
||||
error_message = Column(Text, nullable=True)
|
||||
|
||||
# Timestamps
|
||||
created_at = Column(DateTime(timezone=True), server_default=func.now(), nullable=False)
|
||||
started_at = Column(DateTime(timezone=True), nullable=True)
|
||||
completed_at = Column(DateTime(timezone=True), nullable=True)
|
||||
|
||||
__table_args__ = (
|
||||
Index('idx_task_status_created', 'status', 'created_at'),
|
||||
Index('idx_task_user_status', 'user_id', 'status'),
|
||||
)
|
||||
|
||||
def __repr__(self):
|
||||
return f"<TaskQueue(id={self.id}, type='{self.task_type}', status='{self.status}')>"
|
||||
|
||||
@property
|
||||
def progress_percent(self) -> int:
|
||||
if self.total_items == 0:
|
||||
return 0
|
||||
return int((self.completed_items + self.failed_items) / self.total_items * 100)
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {
|
||||
'id': self.id,
|
||||
'task_type': self.task_type,
|
||||
'status': self.status,
|
||||
'total_items': self.total_items,
|
||||
'completed_items': self.completed_items,
|
||||
'failed_items': self.failed_items,
|
||||
'progress_percent': self.progress_percent,
|
||||
'results': self.results,
|
||||
'error_message': self.error_message,
|
||||
'created_at': self.created_at.isoformat() if self.created_at else None,
|
||||
'started_at': self.started_at.isoformat() if self.started_at else None,
|
||||
'completed_at': self.completed_at.isoformat() if self.completed_at else None,
|
||||
}
|
||||
|
||||
|
||||
# ==================== Snapshot Archive ====================
|
||||
|
||||
class VMSnapshotArchive(Base):
|
||||
"""
|
||||
Archive of VM/Container snapshots before deletion.
|
||||
Stores snapshot configuration when instance is deleted for audit and potential recovery.
|
||||
"""
|
||||
__tablename__ = "vm_snapshot_archives"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
|
||||
# Reference to deleted instance
|
||||
server_id = Column(Integer, nullable=False, index=True)
|
||||
server_name = Column(String(100), nullable=True)
|
||||
vmid = Column(Integer, nullable=False, index=True)
|
||||
vm_name = Column(String(100), nullable=True)
|
||||
vm_type = Column(String(20), nullable=False) # 'qemu' or 'lxc'
|
||||
node = Column(String(100), nullable=False)
|
||||
|
||||
# Snapshot details
|
||||
snapname = Column(String(100), nullable=False)
|
||||
description = Column(Text, nullable=True)
|
||||
snaptime = Column(BigInteger, nullable=True) # Unix timestamp from Proxmox
|
||||
parent = Column(String(100), nullable=True) # Parent snapshot name
|
||||
|
||||
# For VM snapshots - whether RAM state was included
|
||||
vmstate = Column(Boolean, default=False, nullable=False)
|
||||
|
||||
# Full snapshot config as JSON
|
||||
snapshot_config = Column(JSON, nullable=True)
|
||||
|
||||
# Deletion metadata
|
||||
deleted_by = Column(String(100), nullable=True) # Username who deleted the instance
|
||||
deletion_reason = Column(Text, nullable=True) # Why it was deleted
|
||||
archived_at = Column(DateTime(timezone=True), server_default=func.now(), nullable=False)
|
||||
|
||||
__table_args__ = (
|
||||
Index('idx_snapshot_archive_server_vmid', 'server_id', 'vmid'),
|
||||
Index('idx_snapshot_archive_archived', 'archived_at'),
|
||||
)
|
||||
|
||||
def __repr__(self):
|
||||
return f"<VMSnapshotArchive(id={self.id}, vmid={self.vmid}, snapname='{self.snapname}')>"
|
||||
|
||||
|
||||
|
||||
85
backend/app/models/notification.py
Normal file
85
backend/app/models/notification.py
Normal file
@@ -0,0 +1,85 @@
|
||||
"""
|
||||
Notification models for SQLAlchemy
|
||||
"""
|
||||
|
||||
from sqlalchemy import Column, Integer, String, Boolean, DateTime, Text, ForeignKey, JSON
|
||||
from sqlalchemy.sql import func
|
||||
from backend.app.db import Base
|
||||
|
||||
|
||||
class Notification(Base):
|
||||
"""Notification model"""
|
||||
__tablename__ = "notifications"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
user_id = Column(Integer, ForeignKey("users.id", ondelete="CASCADE"), nullable=False)
|
||||
type = Column(String(50), nullable=False) # vm_status, resource_alert, system, etc
|
||||
level = Column(String(20), nullable=False) # critical, warning, info, success
|
||||
title = Column(String(255), nullable=False)
|
||||
message = Column(Text)
|
||||
data = Column(JSON) # Additional structured data
|
||||
link = Column(String(500)) # Deep link to related resource
|
||||
source = Column(String(50)) # proxmox, ipam, system, docker
|
||||
source_id = Column(String(100)) # VM ID, Network ID, etc
|
||||
read = Column(Boolean, default=False)
|
||||
read_at = Column(DateTime(timezone=True))
|
||||
created_at = Column(DateTime(timezone=True), server_default=func.now())
|
||||
expires_at = Column(DateTime(timezone=True)) # Auto-delete old notifications
|
||||
|
||||
def to_dict(self):
|
||||
"""Convert to dictionary"""
|
||||
return {
|
||||
"id": self.id,
|
||||
"user_id": self.user_id,
|
||||
"type": self.type,
|
||||
"level": self.level,
|
||||
"title": self.title,
|
||||
"message": self.message,
|
||||
"data": self.data,
|
||||
"link": self.link,
|
||||
"source": self.source,
|
||||
"source_id": self.source_id,
|
||||
"read": self.read,
|
||||
"read_at": self.read_at.isoformat() if self.read_at else None,
|
||||
"created_at": self.created_at.isoformat() if self.created_at else None,
|
||||
"expires_at": self.expires_at.isoformat() if self.expires_at else None,
|
||||
}
|
||||
|
||||
|
||||
class NotificationPreference(Base):
|
||||
"""User notification preferences"""
|
||||
__tablename__ = "notification_preferences"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
user_id = Column(Integer, ForeignKey("users.id", ondelete="CASCADE"), unique=True, nullable=False)
|
||||
enabled = Column(Boolean, default=True)
|
||||
email_enabled = Column(Boolean, default=False)
|
||||
email_critical_only = Column(Boolean, default=True)
|
||||
telegram_enabled = Column(Boolean, default=False)
|
||||
telegram_chat_id = Column(String(100))
|
||||
webhook_url = Column(String(500))
|
||||
notification_levels = Column(JSON, default=["critical", "warning", "info", "success"])
|
||||
notification_types = Column(JSON, default=["vm_status", "resource_alert", "system"])
|
||||
quiet_hours_start = Column(String(5)) # HH:MM format
|
||||
quiet_hours_end = Column(String(5)) # HH:MM format
|
||||
created_at = Column(DateTime(timezone=True), server_default=func.now())
|
||||
updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now())
|
||||
|
||||
def to_dict(self):
|
||||
"""Convert to dictionary"""
|
||||
return {
|
||||
"id": self.id,
|
||||
"user_id": self.user_id,
|
||||
"enabled": self.enabled,
|
||||
"email_enabled": self.email_enabled,
|
||||
"email_critical_only": self.email_critical_only,
|
||||
"telegram_enabled": self.telegram_enabled,
|
||||
"telegram_chat_id": self.telegram_chat_id,
|
||||
"webhook_url": self.webhook_url,
|
||||
"notification_levels": self.notification_levels,
|
||||
"notification_types": self.notification_types,
|
||||
"quiet_hours_start": self.quiet_hours_start,
|
||||
"quiet_hours_end": self.quiet_hours_end,
|
||||
"created_at": self.created_at.isoformat() if self.created_at else None,
|
||||
"updated_at": self.updated_at.isoformat() if self.updated_at else None,
|
||||
}
|
||||
2911
backend/app/proxmox_client.py
Normal file
2911
backend/app/proxmox_client.py
Normal file
File diff suppressed because it is too large
Load Diff
78
backend/app/rbac/__init__.py
Normal file
78
backend/app/rbac/__init__.py
Normal file
@@ -0,0 +1,78 @@
|
||||
"""
|
||||
RBAC Module - Role-Based Access Control
|
||||
Provides atomic permission model with resource:action:scope format
|
||||
"""
|
||||
|
||||
from .permissions import (
|
||||
Permission,
|
||||
PermissionRegistry,
|
||||
PERMISSIONS,
|
||||
ScopeType,
|
||||
ResourceType,
|
||||
ActionType,
|
||||
LEGACY_PERMISSION_MAP,
|
||||
resolve_permission,
|
||||
get_permission_info
|
||||
)
|
||||
from .engine import (
|
||||
PermissionEngine,
|
||||
require_permission,
|
||||
check_permission,
|
||||
get_user_permissions
|
||||
)
|
||||
from .middleware import (
|
||||
PermissionChecker,
|
||||
ScopedPermissionChecker,
|
||||
ResourceAccessChecker
|
||||
)
|
||||
from .decorators import (
|
||||
requires_permission,
|
||||
requires_any_permission,
|
||||
requires_all_permissions
|
||||
)
|
||||
from .audit import RBACAuditService
|
||||
from .migration import (
|
||||
convert_permissions_to_new_format,
|
||||
convert_permissions_to_legacy_format,
|
||||
get_permission_categories,
|
||||
get_permission_categories_legacy,
|
||||
migrate_all_roles_to_new_format,
|
||||
ensure_default_roles_new_format,
|
||||
NEW_DEFAULT_ROLES
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
# Permissions
|
||||
"Permission",
|
||||
"PermissionRegistry",
|
||||
"PERMISSIONS",
|
||||
"ScopeType",
|
||||
"ResourceType",
|
||||
"ActionType",
|
||||
"LEGACY_PERMISSION_MAP",
|
||||
"resolve_permission",
|
||||
"get_permission_info",
|
||||
# Engine
|
||||
"PermissionEngine",
|
||||
"require_permission",
|
||||
"check_permission",
|
||||
"get_user_permissions",
|
||||
# Middleware
|
||||
"PermissionChecker",
|
||||
"ScopedPermissionChecker",
|
||||
"ResourceAccessChecker",
|
||||
# Decorators
|
||||
"requires_permission",
|
||||
"requires_any_permission",
|
||||
"requires_all_permissions",
|
||||
# Audit
|
||||
"RBACAuditService",
|
||||
# Migration
|
||||
"convert_permissions_to_new_format",
|
||||
"convert_permissions_to_legacy_format",
|
||||
"get_permission_categories",
|
||||
"get_permission_categories_legacy",
|
||||
"migrate_all_roles_to_new_format",
|
||||
"ensure_default_roles_new_format",
|
||||
"NEW_DEFAULT_ROLES",
|
||||
]
|
||||
267
backend/app/rbac/audit.py
Normal file
267
backend/app/rbac/audit.py
Normal file
@@ -0,0 +1,267 @@
|
||||
"""
|
||||
RBAC Audit Service - Logs all permission and role changes
|
||||
"""
|
||||
|
||||
from datetime import datetime, timezone
|
||||
from typing import Optional, Dict, Any, List
|
||||
from sqlalchemy.orm import Session
|
||||
from sqlalchemy import desc
|
||||
from loguru import logger
|
||||
|
||||
from .permissions import PERMISSIONS, resolve_permission
|
||||
|
||||
|
||||
def utcnow() -> datetime:
|
||||
"""Get current UTC time"""
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
class RBACAuditService:
|
||||
"""
|
||||
Service for auditing RBAC changes.
|
||||
Logs role creation, permission changes, role assignments, etc.
|
||||
"""
|
||||
|
||||
AUDIT_ACTIONS = {
|
||||
"role_created": "Role Created",
|
||||
"role_updated": "Role Updated",
|
||||
"role_deleted": "Role Deleted",
|
||||
"role_assigned": "Role Assigned to User",
|
||||
"role_removed": "Role Removed from User",
|
||||
"permission_added": "Permission Added",
|
||||
"permission_removed": "Permission Removed",
|
||||
"permission_denied": "Permission Denied",
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def log_role_created(
|
||||
db: Session,
|
||||
role_id: int,
|
||||
role_name: str,
|
||||
permissions: Dict[str, bool],
|
||||
created_by_id: int,
|
||||
created_by_username: str,
|
||||
ip_address: Optional[str] = None
|
||||
) -> None:
|
||||
"""Log role creation"""
|
||||
from ..models import AuditLog
|
||||
|
||||
log_entry = AuditLog(
|
||||
level="info",
|
||||
category="rbac",
|
||||
action="role_created",
|
||||
message=f"Role '{role_name}' created by {created_by_username}",
|
||||
user_id=created_by_id,
|
||||
username=created_by_username,
|
||||
ip_address=ip_address,
|
||||
resource_type="role",
|
||||
resource_id=str(role_id),
|
||||
resource_name=role_name,
|
||||
details={
|
||||
"permissions": permissions,
|
||||
"permissions_count": sum(1 for v in permissions.values() if v)
|
||||
},
|
||||
success=True
|
||||
)
|
||||
db.add(log_entry)
|
||||
db.commit()
|
||||
|
||||
logger.info(f"RBAC Audit: Role '{role_name}' created by {created_by_username}")
|
||||
|
||||
@staticmethod
|
||||
def log_role_updated(
|
||||
db: Session,
|
||||
role_id: int,
|
||||
role_name: str,
|
||||
old_permissions: Dict[str, bool],
|
||||
new_permissions: Dict[str, bool],
|
||||
updated_by_id: int,
|
||||
updated_by_username: str,
|
||||
ip_address: Optional[str] = None
|
||||
) -> None:
|
||||
"""Log role update with permission diff"""
|
||||
from ..models import AuditLog
|
||||
|
||||
# Calculate diff
|
||||
added = []
|
||||
removed = []
|
||||
|
||||
for perm, enabled in new_permissions.items():
|
||||
old_value = old_permissions.get(perm, False)
|
||||
if enabled and not old_value:
|
||||
added.append(perm)
|
||||
elif not enabled and old_value:
|
||||
removed.append(perm)
|
||||
|
||||
log_entry = AuditLog(
|
||||
level="info",
|
||||
category="rbac",
|
||||
action="role_updated",
|
||||
message=f"Role '{role_name}' updated by {updated_by_username}: +{len(added)} -{len(removed)} permissions",
|
||||
user_id=updated_by_id,
|
||||
username=updated_by_username,
|
||||
ip_address=ip_address,
|
||||
resource_type="role",
|
||||
resource_id=str(role_id),
|
||||
resource_name=role_name,
|
||||
details={
|
||||
"permissions_added": added,
|
||||
"permissions_removed": removed,
|
||||
"old_permissions_count": sum(1 for v in old_permissions.values() if v),
|
||||
"new_permissions_count": sum(1 for v in new_permissions.values() if v)
|
||||
},
|
||||
success=True
|
||||
)
|
||||
db.add(log_entry)
|
||||
db.commit()
|
||||
|
||||
logger.info(f"RBAC Audit: Role '{role_name}' updated: +{len(added)} -{len(removed)}")
|
||||
|
||||
@staticmethod
|
||||
def log_role_deleted(
|
||||
db: Session,
|
||||
role_id: int,
|
||||
role_name: str,
|
||||
deleted_by_id: int,
|
||||
deleted_by_username: str,
|
||||
affected_users: int = 0,
|
||||
ip_address: Optional[str] = None
|
||||
) -> None:
|
||||
"""Log role deletion"""
|
||||
from ..models import AuditLog
|
||||
|
||||
log_entry = AuditLog(
|
||||
level="warning",
|
||||
category="rbac",
|
||||
action="role_deleted",
|
||||
message=f"Role '{role_name}' deleted by {deleted_by_username}, {affected_users} users affected",
|
||||
user_id=deleted_by_id,
|
||||
username=deleted_by_username,
|
||||
ip_address=ip_address,
|
||||
resource_type="role",
|
||||
resource_id=str(role_id),
|
||||
resource_name=role_name,
|
||||
details={
|
||||
"affected_users": affected_users
|
||||
},
|
||||
success=True
|
||||
)
|
||||
db.add(log_entry)
|
||||
db.commit()
|
||||
|
||||
logger.warning(f"RBAC Audit: Role '{role_name}' deleted, {affected_users} users affected")
|
||||
|
||||
@staticmethod
|
||||
def log_role_assigned(
|
||||
db: Session,
|
||||
user_id: int,
|
||||
username: str,
|
||||
role_id: int,
|
||||
role_name: str,
|
||||
old_role_name: Optional[str],
|
||||
assigned_by_id: int,
|
||||
assigned_by_username: str,
|
||||
ip_address: Optional[str] = None
|
||||
) -> None:
|
||||
"""Log role assignment to user"""
|
||||
from ..models import AuditLog
|
||||
|
||||
msg = f"Role '{role_name}' assigned to user '{username}'"
|
||||
if old_role_name:
|
||||
msg += f" (was: {old_role_name})"
|
||||
msg += f" by {assigned_by_username}"
|
||||
|
||||
log_entry = AuditLog(
|
||||
level="info",
|
||||
category="rbac",
|
||||
action="role_assigned",
|
||||
message=msg,
|
||||
user_id=assigned_by_id,
|
||||
username=assigned_by_username,
|
||||
ip_address=ip_address,
|
||||
resource_type="user",
|
||||
resource_id=str(user_id),
|
||||
resource_name=username,
|
||||
details={
|
||||
"new_role_id": role_id,
|
||||
"new_role_name": role_name,
|
||||
"old_role_name": old_role_name,
|
||||
"target_user_id": user_id,
|
||||
"target_username": username
|
||||
},
|
||||
success=True
|
||||
)
|
||||
db.add(log_entry)
|
||||
db.commit()
|
||||
|
||||
logger.info(f"RBAC Audit: {msg}")
|
||||
|
||||
@staticmethod
|
||||
def log_permission_denied(
|
||||
db: Session,
|
||||
user_id: int,
|
||||
username: str,
|
||||
permission: str,
|
||||
resource_type: Optional[str] = None,
|
||||
resource_id: Optional[str] = None,
|
||||
ip_address: Optional[str] = None,
|
||||
request_path: Optional[str] = None
|
||||
) -> None:
|
||||
"""Log denied permission attempt"""
|
||||
from ..models import AuditLog
|
||||
|
||||
log_entry = AuditLog(
|
||||
level="warning",
|
||||
category="rbac",
|
||||
action="permission_denied",
|
||||
message=f"Permission '{permission}' denied for user '{username}'",
|
||||
user_id=user_id,
|
||||
username=username,
|
||||
ip_address=ip_address,
|
||||
resource_type=resource_type,
|
||||
resource_id=resource_id,
|
||||
request_path=request_path,
|
||||
details={
|
||||
"permission": permission,
|
||||
"resolved_permission": resolve_permission(permission)
|
||||
},
|
||||
success=False
|
||||
)
|
||||
db.add(log_entry)
|
||||
db.commit()
|
||||
|
||||
logger.warning(f"RBAC Audit: Permission '{permission}' denied for '{username}'")
|
||||
|
||||
@staticmethod
|
||||
def get_rbac_logs(
|
||||
db: Session,
|
||||
limit: int = 100,
|
||||
offset: int = 0,
|
||||
user_id: Optional[int] = None,
|
||||
action: Optional[str] = None
|
||||
) -> List:
|
||||
"""Get RBAC audit logs"""
|
||||
from ..models import AuditLog
|
||||
|
||||
query = db.query(AuditLog).filter(AuditLog.category == "rbac")
|
||||
|
||||
if user_id:
|
||||
query = query.filter(AuditLog.user_id == user_id)
|
||||
if action:
|
||||
query = query.filter(AuditLog.action == action)
|
||||
|
||||
return query.order_by(desc(AuditLog.created_at)).offset(offset).limit(limit).all()
|
||||
|
||||
@staticmethod
|
||||
def get_user_permission_history(
|
||||
db: Session,
|
||||
user_id: int,
|
||||
limit: int = 50
|
||||
) -> List:
|
||||
"""Get permission change history for a user"""
|
||||
from ..models import AuditLog
|
||||
|
||||
return db.query(AuditLog).filter(
|
||||
AuditLog.category == "rbac",
|
||||
AuditLog.details.contains({"target_user_id": user_id})
|
||||
).order_by(desc(AuditLog.created_at)).limit(limit).all()
|
||||
163
backend/app/rbac/decorators.py
Normal file
163
backend/app/rbac/decorators.py
Normal file
@@ -0,0 +1,163 @@
|
||||
"""
|
||||
Permission Decorators - Function decorators for permission checks
|
||||
"""
|
||||
|
||||
from functools import wraps
|
||||
from typing import List, Callable, Union
|
||||
from fastapi import HTTPException, status
|
||||
|
||||
from .engine import PermissionEngine
|
||||
from .permissions import ScopeType
|
||||
|
||||
|
||||
def requires_permission(
|
||||
permission: str,
|
||||
scope: ScopeType = ScopeType.GLOBAL,
|
||||
user_param: str = "current_user"
|
||||
):
|
||||
"""
|
||||
Decorator to require a specific permission.
|
||||
|
||||
Usage:
|
||||
@requires_permission("vm:create")
|
||||
async def create_vm(current_user: User, ...):
|
||||
...
|
||||
"""
|
||||
def decorator(func: Callable):
|
||||
@wraps(func)
|
||||
async def async_wrapper(*args, **kwargs):
|
||||
user = kwargs.get(user_param)
|
||||
if user is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="User not found in request"
|
||||
)
|
||||
|
||||
PermissionEngine.check_permission(user, permission, scope)
|
||||
return await func(*args, **kwargs)
|
||||
|
||||
@wraps(func)
|
||||
def sync_wrapper(*args, **kwargs):
|
||||
user = kwargs.get(user_param)
|
||||
if user is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="User not found in request"
|
||||
)
|
||||
|
||||
PermissionEngine.check_permission(user, permission, scope)
|
||||
return func(*args, **kwargs)
|
||||
|
||||
# Return appropriate wrapper based on function type
|
||||
import asyncio
|
||||
if asyncio.iscoroutinefunction(func):
|
||||
return async_wrapper
|
||||
return sync_wrapper
|
||||
|
||||
return decorator
|
||||
|
||||
|
||||
def requires_any_permission(
|
||||
permissions: List[str],
|
||||
scope: ScopeType = ScopeType.GLOBAL,
|
||||
user_param: str = "current_user"
|
||||
):
|
||||
"""
|
||||
Decorator to require any one of the listed permissions.
|
||||
|
||||
Usage:
|
||||
@requires_any_permission(["vm:create", "lxc:create"])
|
||||
async def create_instance(current_user: User, ...):
|
||||
...
|
||||
"""
|
||||
def decorator(func: Callable):
|
||||
@wraps(func)
|
||||
async def async_wrapper(*args, **kwargs):
|
||||
user = kwargs.get(user_param)
|
||||
if user is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="User not found in request"
|
||||
)
|
||||
|
||||
if not PermissionEngine.has_any_permission(user, permissions):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail=f"Permission denied: requires one of {permissions}"
|
||||
)
|
||||
|
||||
return await func(*args, **kwargs)
|
||||
|
||||
@wraps(func)
|
||||
def sync_wrapper(*args, **kwargs):
|
||||
user = kwargs.get(user_param)
|
||||
if user is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="User not found in request"
|
||||
)
|
||||
|
||||
if not PermissionEngine.has_any_permission(user, permissions):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail=f"Permission denied: requires one of {permissions}"
|
||||
)
|
||||
|
||||
return func(*args, **kwargs)
|
||||
|
||||
import asyncio
|
||||
if asyncio.iscoroutinefunction(func):
|
||||
return async_wrapper
|
||||
return sync_wrapper
|
||||
|
||||
return decorator
|
||||
|
||||
|
||||
def requires_all_permissions(
|
||||
permissions: List[str],
|
||||
scope: ScopeType = ScopeType.GLOBAL,
|
||||
user_param: str = "current_user"
|
||||
):
|
||||
"""
|
||||
Decorator to require all of the listed permissions.
|
||||
|
||||
Usage:
|
||||
@requires_all_permissions(["vm:view", "vm:update"])
|
||||
async def update_vm(current_user: User, ...):
|
||||
...
|
||||
"""
|
||||
def decorator(func: Callable):
|
||||
@wraps(func)
|
||||
async def async_wrapper(*args, **kwargs):
|
||||
user = kwargs.get(user_param)
|
||||
if user is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="User not found in request"
|
||||
)
|
||||
|
||||
for perm in permissions:
|
||||
PermissionEngine.check_permission(user, perm, scope)
|
||||
|
||||
return await func(*args, **kwargs)
|
||||
|
||||
@wraps(func)
|
||||
def sync_wrapper(*args, **kwargs):
|
||||
user = kwargs.get(user_param)
|
||||
if user is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="User not found in request"
|
||||
)
|
||||
|
||||
for perm in permissions:
|
||||
PermissionEngine.check_permission(user, perm, scope)
|
||||
|
||||
return func(*args, **kwargs)
|
||||
|
||||
import asyncio
|
||||
if asyncio.iscoroutinefunction(func):
|
||||
return async_wrapper
|
||||
return sync_wrapper
|
||||
|
||||
return decorator
|
||||
245
backend/app/rbac/engine.py
Normal file
245
backend/app/rbac/engine.py
Normal file
@@ -0,0 +1,245 @@
|
||||
"""
|
||||
Permission Engine - Central authorization logic
|
||||
Handles all permission checks with scope awareness
|
||||
"""
|
||||
|
||||
from typing import Optional, List, Set, Dict, Any
|
||||
from sqlalchemy.orm import Session
|
||||
from fastapi import HTTPException, status
|
||||
from loguru import logger
|
||||
|
||||
from .permissions import (
|
||||
Permission,
|
||||
PermissionRegistry,
|
||||
PERMISSIONS,
|
||||
ScopeType,
|
||||
resolve_permission,
|
||||
LEGACY_PERMISSION_MAP
|
||||
)
|
||||
|
||||
|
||||
class PermissionEngine:
|
||||
"""
|
||||
Central permission checking engine.
|
||||
All authorization decisions go through this class.
|
||||
"""
|
||||
|
||||
@staticmethod
|
||||
def get_user_permissions(user) -> Set[str]:
|
||||
"""
|
||||
Get all effective permissions for a user.
|
||||
Returns set of permission codes.
|
||||
"""
|
||||
permissions = set()
|
||||
|
||||
# Check if user is admin (has all permissions)
|
||||
if getattr(user, 'is_admin', False):
|
||||
return {p.code for p in PERMISSIONS.all()}
|
||||
|
||||
# Get permissions from role
|
||||
if user.role and user.role.permissions:
|
||||
role_perms = user.role.permissions
|
||||
for perm_code, enabled in role_perms.items():
|
||||
if enabled:
|
||||
# Resolve legacy to new format
|
||||
resolved = resolve_permission(perm_code)
|
||||
permissions.add(resolved)
|
||||
|
||||
# Also keep legacy for backwards compatibility
|
||||
if perm_code != resolved:
|
||||
permissions.add(perm_code)
|
||||
|
||||
return permissions
|
||||
|
||||
@staticmethod
|
||||
def has_permission(
|
||||
user,
|
||||
permission: str,
|
||||
scope: ScopeType = ScopeType.GLOBAL,
|
||||
resource_id: Optional[int] = None,
|
||||
organization_id: Optional[int] = None,
|
||||
workspace_id: Optional[int] = None,
|
||||
) -> bool:
|
||||
"""
|
||||
Check if user has specific permission.
|
||||
|
||||
Args:
|
||||
user: User object
|
||||
permission: Permission code (new or legacy format)
|
||||
scope: Permission scope level
|
||||
resource_id: Specific resource ID (for instance scope)
|
||||
organization_id: Organization context
|
||||
workspace_id: Workspace context
|
||||
|
||||
Returns:
|
||||
True if user has permission, False otherwise
|
||||
"""
|
||||
# Admin bypass - full access
|
||||
if getattr(user, 'is_admin', False):
|
||||
return True
|
||||
|
||||
# Get user permissions
|
||||
user_permissions = PermissionEngine.get_user_permissions(user)
|
||||
|
||||
# Resolve permission code
|
||||
resolved_perm = resolve_permission(permission)
|
||||
|
||||
# Check direct permission
|
||||
if resolved_perm in user_permissions or permission in user_permissions:
|
||||
return True
|
||||
|
||||
# Check wildcard permissions (e.g., vm:* grants all vm permissions)
|
||||
resource = resolved_perm.split(':')[0] if ':' in resolved_perm else permission.split('.')[0]
|
||||
wildcard = f"{resource}:*"
|
||||
if wildcard in user_permissions:
|
||||
return True
|
||||
|
||||
# Check manage permission (implies most actions)
|
||||
manage_perm = f"{resource}:manage"
|
||||
if manage_perm in user_permissions:
|
||||
# manage implies view, update, and some actions
|
||||
action = resolved_perm.split(':')[1] if ':' in resolved_perm else None
|
||||
implied_actions = {'view', 'list', 'update', 'start', 'stop', 'restart'}
|
||||
if action in implied_actions:
|
||||
return True
|
||||
|
||||
return False
|
||||
|
||||
@staticmethod
|
||||
def check_permission(
|
||||
user,
|
||||
permission: str,
|
||||
scope: ScopeType = ScopeType.GLOBAL,
|
||||
resource_id: Optional[int] = None,
|
||||
organization_id: Optional[int] = None,
|
||||
workspace_id: Optional[int] = None,
|
||||
) -> None:
|
||||
"""
|
||||
Check permission and raise 403 if denied.
|
||||
"""
|
||||
if not PermissionEngine.has_permission(
|
||||
user, permission, scope, resource_id, organization_id, workspace_id
|
||||
):
|
||||
logger.warning(
|
||||
f"Permission denied: user={user.username}, "
|
||||
f"permission={permission}, scope={scope}"
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail=f"Permission denied: {permission}"
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def has_any_permission(user, permissions: List[str]) -> bool:
|
||||
"""Check if user has any of the listed permissions"""
|
||||
for perm in permissions:
|
||||
if PermissionEngine.has_permission(user, perm):
|
||||
return True
|
||||
return False
|
||||
|
||||
@staticmethod
|
||||
def has_all_permissions(user, permissions: List[str]) -> bool:
|
||||
"""Check if user has all of the listed permissions"""
|
||||
for perm in permissions:
|
||||
if not PermissionEngine.has_permission(user, perm):
|
||||
return False
|
||||
return True
|
||||
|
||||
@staticmethod
|
||||
def filter_permissions(user, permissions: List[str]) -> List[str]:
|
||||
"""Filter list to only permissions user has"""
|
||||
return [p for p in permissions if PermissionEngine.has_permission(user, p)]
|
||||
|
||||
@staticmethod
|
||||
def get_effective_permissions(user) -> Dict[str, Any]:
|
||||
"""
|
||||
Get effective permissions with metadata.
|
||||
Returns dict suitable for UI display.
|
||||
"""
|
||||
user_perms = PermissionEngine.get_user_permissions(user)
|
||||
result = {}
|
||||
|
||||
for perm in PERMISSIONS.all():
|
||||
has_perm = perm.code in user_perms
|
||||
result[perm.code] = {
|
||||
"code": perm.code,
|
||||
"display_name": perm.display_name,
|
||||
"description": perm.description,
|
||||
"category": perm.category,
|
||||
"granted": has_perm,
|
||||
"source": "admin" if user.is_admin else ("role" if has_perm else None)
|
||||
}
|
||||
|
||||
return result
|
||||
|
||||
@staticmethod
|
||||
def get_permissions_by_category(user) -> Dict[str, List[Dict]]:
|
||||
"""Get effective permissions grouped by category"""
|
||||
effective = PermissionEngine.get_effective_permissions(user)
|
||||
by_category = {}
|
||||
|
||||
for perm_info in effective.values():
|
||||
category = perm_info["category"]
|
||||
if category not in by_category:
|
||||
by_category[category] = []
|
||||
by_category[category].append(perm_info)
|
||||
|
||||
return by_category
|
||||
|
||||
@staticmethod
|
||||
def can_assign_permission(assigner, permission: str) -> bool:
|
||||
"""
|
||||
Check if user can assign a specific permission to others.
|
||||
Users cannot grant permissions they don't have themselves.
|
||||
"""
|
||||
# Must have role management permission
|
||||
if not PermissionEngine.has_permission(assigner, "role:manage"):
|
||||
return False
|
||||
|
||||
# Cannot assign permission you don't have (unless admin)
|
||||
if not assigner.is_admin:
|
||||
if not PermissionEngine.has_permission(assigner, permission):
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
@staticmethod
|
||||
def validate_role_permissions(assigner, permissions: Dict[str, bool]) -> tuple[Dict, List[str]]:
|
||||
"""
|
||||
Validate permissions that user is trying to assign.
|
||||
Returns (valid_permissions, denied_permissions)
|
||||
"""
|
||||
valid = {}
|
||||
denied = []
|
||||
|
||||
for perm, enabled in permissions.items():
|
||||
if enabled:
|
||||
if PermissionEngine.can_assign_permission(assigner, perm):
|
||||
valid[perm] = True
|
||||
else:
|
||||
denied.append(perm)
|
||||
else:
|
||||
valid[perm] = False
|
||||
|
||||
return valid, denied
|
||||
|
||||
|
||||
# Convenience functions
|
||||
def require_permission(
|
||||
user,
|
||||
permission: str,
|
||||
scope: ScopeType = ScopeType.GLOBAL,
|
||||
resource_id: Optional[int] = None,
|
||||
) -> None:
|
||||
"""Require permission or raise 403"""
|
||||
PermissionEngine.check_permission(user, permission, scope, resource_id)
|
||||
|
||||
|
||||
def check_permission(user, permission: str) -> bool:
|
||||
"""Check if user has permission"""
|
||||
return PermissionEngine.has_permission(user, permission)
|
||||
|
||||
|
||||
def get_user_permissions(user) -> Set[str]:
|
||||
"""Get all user permissions"""
|
||||
return PermissionEngine.get_user_permissions(user)
|
||||
230
backend/app/rbac/middleware.py
Normal file
230
backend/app/rbac/middleware.py
Normal file
@@ -0,0 +1,230 @@
|
||||
"""
|
||||
Authorization Middleware - FastAPI dependencies for permission checks
|
||||
Replaces old PermissionChecker with enhanced functionality
|
||||
"""
|
||||
|
||||
from typing import Optional, List, Union
|
||||
from fastapi import Depends, HTTPException, status, Request
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from .engine import PermissionEngine
|
||||
from .permissions import ScopeType, resolve_permission
|
||||
|
||||
|
||||
class PermissionChecker:
|
||||
"""
|
||||
FastAPI dependency for checking permissions.
|
||||
|
||||
Usage:
|
||||
@router.get("/vms")
|
||||
async def list_vms(user = Depends(PermissionChecker("vm:view"))):
|
||||
...
|
||||
|
||||
# Multiple permissions (any)
|
||||
@router.post("/vms")
|
||||
async def create_vm(user = Depends(PermissionChecker(["vm:create", "lxc:create"]))):
|
||||
...
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
permission: Union[str, List[str]],
|
||||
require_all: bool = False,
|
||||
scope: ScopeType = ScopeType.GLOBAL
|
||||
):
|
||||
"""
|
||||
Args:
|
||||
permission: Permission code or list of codes
|
||||
require_all: If True, requires all permissions (AND), else any (OR)
|
||||
scope: Permission scope level
|
||||
"""
|
||||
if isinstance(permission, str):
|
||||
self.permissions = [permission]
|
||||
else:
|
||||
self.permissions = permission
|
||||
self.require_all = require_all
|
||||
self.scope = scope
|
||||
|
||||
def __call__(self, request: Request, db: Session = None):
|
||||
"""Check permissions for current user"""
|
||||
# Import here to avoid circular imports
|
||||
from ..auth import get_current_user
|
||||
from ..db import get_db
|
||||
|
||||
# Get user from request state if available
|
||||
user = getattr(request.state, 'user', None)
|
||||
|
||||
if user is None:
|
||||
# Fall back to standard auth
|
||||
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
||||
from ..auth import decode_access_token
|
||||
from ..models import User
|
||||
from sqlalchemy.orm import joinedload
|
||||
|
||||
security = HTTPBearer()
|
||||
|
||||
# Get token from header
|
||||
auth_header = request.headers.get("Authorization")
|
||||
if not auth_header or not auth_header.startswith("Bearer "):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Not authenticated",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
|
||||
token = auth_header.split(" ")[1]
|
||||
payload = decode_access_token(token)
|
||||
username = payload.get("sub")
|
||||
|
||||
if db is None:
|
||||
# Get DB session
|
||||
from ..db import SessionLocal
|
||||
db = SessionLocal()
|
||||
try:
|
||||
user = db.query(User).options(joinedload(User.role)).filter(
|
||||
User.username == username
|
||||
).first()
|
||||
finally:
|
||||
db.close()
|
||||
else:
|
||||
user = db.query(User).options(joinedload(User.role)).filter(
|
||||
User.username == username
|
||||
).first()
|
||||
|
||||
if user is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="User not found",
|
||||
)
|
||||
|
||||
# Check permissions
|
||||
if self.require_all:
|
||||
# Must have all permissions
|
||||
for perm in self.permissions:
|
||||
if not PermissionEngine.has_permission(user, perm, self.scope):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail=f"Permission denied: {perm}"
|
||||
)
|
||||
else:
|
||||
# Must have at least one permission
|
||||
has_any = False
|
||||
for perm in self.permissions:
|
||||
if PermissionEngine.has_permission(user, perm, self.scope):
|
||||
has_any = True
|
||||
break
|
||||
|
||||
if not has_any:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail=f"Permission denied: requires one of {self.permissions}"
|
||||
)
|
||||
|
||||
return user
|
||||
|
||||
|
||||
class ScopedPermissionChecker:
|
||||
"""
|
||||
Permission checker with resource-level scope.
|
||||
|
||||
Usage:
|
||||
@router.get("/vms/{vm_id}")
|
||||
async def get_vm(
|
||||
vm_id: int,
|
||||
user = Depends(ScopedPermissionChecker("vm:view", resource_param="vm_id"))
|
||||
):
|
||||
...
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
permission: str,
|
||||
scope: ScopeType = ScopeType.INSTANCE,
|
||||
resource_param: str = "resource_id",
|
||||
organization_param: Optional[str] = None,
|
||||
workspace_param: Optional[str] = None
|
||||
):
|
||||
self.permission = permission
|
||||
self.scope = scope
|
||||
self.resource_param = resource_param
|
||||
self.organization_param = organization_param
|
||||
self.workspace_param = workspace_param
|
||||
|
||||
def __call__(self, request: Request):
|
||||
"""Check scoped permission"""
|
||||
from ..auth import get_current_user
|
||||
from ..db import SessionLocal
|
||||
from ..models import User
|
||||
from sqlalchemy.orm import joinedload
|
||||
|
||||
# Get resource ID from path params
|
||||
resource_id = request.path_params.get(self.resource_param)
|
||||
organization_id = request.path_params.get(self.organization_param) if self.organization_param else None
|
||||
workspace_id = request.path_params.get(self.workspace_param) if self.workspace_param else None
|
||||
|
||||
# Get user
|
||||
auth_header = request.headers.get("Authorization")
|
||||
if not auth_header or not auth_header.startswith("Bearer "):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Not authenticated",
|
||||
)
|
||||
|
||||
token = auth_header.split(" ")[1]
|
||||
from ..auth import decode_access_token
|
||||
payload = decode_access_token(token)
|
||||
username = payload.get("sub")
|
||||
|
||||
db = SessionLocal()
|
||||
try:
|
||||
user = db.query(User).options(joinedload(User.role)).filter(
|
||||
User.username == username
|
||||
).first()
|
||||
|
||||
if user is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="User not found",
|
||||
)
|
||||
|
||||
# Check permission with scope
|
||||
if not PermissionEngine.has_permission(
|
||||
user,
|
||||
self.permission,
|
||||
self.scope,
|
||||
resource_id=int(resource_id) if resource_id else None,
|
||||
organization_id=int(organization_id) if organization_id else None,
|
||||
workspace_id=int(workspace_id) if workspace_id else None
|
||||
):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail=f"Permission denied: {self.permission}"
|
||||
)
|
||||
|
||||
return user
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
class ResourceAccessChecker:
|
||||
"""
|
||||
Check access to specific resource based on ownership/membership.
|
||||
Future use for organization/workspace scoping.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
resource_type: str,
|
||||
permission: str,
|
||||
id_param: str = "id"
|
||||
):
|
||||
self.resource_type = resource_type
|
||||
self.permission = permission
|
||||
self.id_param = id_param
|
||||
|
||||
def __call__(self, request: Request):
|
||||
"""Check resource access"""
|
||||
# Placeholder for future organization/workspace checks
|
||||
# For now, just check permission
|
||||
checker = PermissionChecker(self.permission)
|
||||
return checker(request)
|
||||
424
backend/app/rbac/migration.py
Normal file
424
backend/app/rbac/migration.py
Normal file
@@ -0,0 +1,424 @@
|
||||
"""
|
||||
RBAC Migration Utilities
|
||||
Converts legacy permission format to new format
|
||||
"""
|
||||
|
||||
from typing import Dict, Optional
|
||||
from loguru import logger
|
||||
from sqlalchemy import text
|
||||
|
||||
from .permissions import LEGACY_PERMISSION_MAP, PERMISSIONS
|
||||
|
||||
|
||||
# New format DEFAULT_ROLES with resource:action format
|
||||
NEW_DEFAULT_ROLES = [
|
||||
{
|
||||
"name": "admin",
|
||||
"display_name": "Administrator",
|
||||
"description": "Full access to all features",
|
||||
"is_system": True,
|
||||
"permissions": {
|
||||
# Dashboard
|
||||
"dashboard:view": True,
|
||||
# Servers
|
||||
"server:view": True,
|
||||
"server:create": True,
|
||||
"server:update": True,
|
||||
"server:delete": True,
|
||||
"server:manage": True,
|
||||
# VMs
|
||||
"vm:view": True,
|
||||
"vm:create": True,
|
||||
"vm:update": True,
|
||||
"vm:delete": True,
|
||||
"vm:start": True,
|
||||
"vm:stop": True,
|
||||
"vm:restart": True,
|
||||
"vm:console": True,
|
||||
"vm:migrate": True,
|
||||
"vm:execute": True,
|
||||
# LXC
|
||||
"lxc:view": True,
|
||||
"lxc:create": True,
|
||||
"lxc:update": True,
|
||||
"lxc:delete": True,
|
||||
"lxc:start": True,
|
||||
"lxc:stop": True,
|
||||
"lxc:restart": True,
|
||||
"lxc:console": True,
|
||||
"lxc:migrate": True,
|
||||
# Templates
|
||||
"template:view": True,
|
||||
"template:create": True,
|
||||
"template:update": True,
|
||||
"template:delete": True,
|
||||
"template:manage": True,
|
||||
# Storage
|
||||
"storage:view": True,
|
||||
"storage:manage": True,
|
||||
# Backups
|
||||
"backup:view": True,
|
||||
"backup:create": True,
|
||||
"backup:delete": True,
|
||||
"backup:manage": True,
|
||||
# IPAM
|
||||
"ipam:view": True,
|
||||
"ipam:manage": True,
|
||||
# Users
|
||||
"user:view": True,
|
||||
"user:create": True,
|
||||
"user:update": True,
|
||||
"user:delete": True,
|
||||
# Roles
|
||||
"role:view": True,
|
||||
"role:create": True,
|
||||
"role:update": True,
|
||||
"role:delete": True,
|
||||
"role:manage": True,
|
||||
# Logs
|
||||
"log:view": True,
|
||||
"log:export": True,
|
||||
"log:delete": True,
|
||||
# Settings
|
||||
"setting:view": True,
|
||||
"setting:update": True,
|
||||
"setting:manage": True,
|
||||
# Notifications
|
||||
"notification:view": True,
|
||||
"notification:manage": True,
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "moderator",
|
||||
"display_name": "Moderator",
|
||||
"description": "Can manage VMs and view logs",
|
||||
"is_system": True,
|
||||
"permissions": {
|
||||
"dashboard:view": True,
|
||||
"server:view": True,
|
||||
"vm:view": True,
|
||||
"vm:create": True,
|
||||
"vm:start": True,
|
||||
"vm:stop": True,
|
||||
"vm:restart": True,
|
||||
"vm:console": True,
|
||||
"lxc:view": True,
|
||||
"lxc:create": True,
|
||||
"lxc:start": True,
|
||||
"lxc:stop": True,
|
||||
"lxc:restart": True,
|
||||
"lxc:console": True,
|
||||
"template:view": True,
|
||||
"storage:view": True,
|
||||
"backup:view": True,
|
||||
"backup:create": True,
|
||||
"ipam:view": True,
|
||||
"user:view": True,
|
||||
"log:view": True,
|
||||
"log:export": True,
|
||||
"setting:view": True,
|
||||
"notification:view": True,
|
||||
"notification:manage": True,
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "user",
|
||||
"display_name": "User",
|
||||
"description": "Standard user with limited access",
|
||||
"is_system": True,
|
||||
"permissions": {
|
||||
"dashboard:view": True,
|
||||
"server:view": True,
|
||||
"vm:view": True,
|
||||
"vm:start": True,
|
||||
"vm:stop": True,
|
||||
"vm:restart": True,
|
||||
"vm:console": True,
|
||||
"lxc:view": True,
|
||||
"lxc:start": True,
|
||||
"lxc:stop": True,
|
||||
"lxc:restart": True,
|
||||
"lxc:console": True,
|
||||
"template:view": True,
|
||||
"storage:view": True,
|
||||
"ipam:view": True,
|
||||
"setting:view": True,
|
||||
"notification:view": True,
|
||||
"notification:manage": True,
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "demo",
|
||||
"display_name": "Demo User",
|
||||
"description": "Read-only access for demonstration",
|
||||
"is_system": True,
|
||||
"permissions": {
|
||||
"dashboard:view": True,
|
||||
"server:view": True,
|
||||
"vm:view": True,
|
||||
"lxc:view": True,
|
||||
"template:view": True,
|
||||
"storage:view": True,
|
||||
"ipam:view": True,
|
||||
}
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
def convert_permissions_to_new_format(old_permissions: Dict[str, bool]) -> Dict[str, bool]:
|
||||
"""
|
||||
Convert legacy permission format to new format.
|
||||
|
||||
Args:
|
||||
old_permissions: Dict with old format like {"vms.view": True, "proxmox.manage": True}
|
||||
|
||||
Returns:
|
||||
Dict with new format like {"vm:view": True, "server:manage": True}
|
||||
"""
|
||||
if not old_permissions:
|
||||
return {}
|
||||
|
||||
new_permissions = {}
|
||||
|
||||
for perm, value in old_permissions.items():
|
||||
# Check if already in new format
|
||||
if ":" in perm:
|
||||
new_permissions[perm] = value
|
||||
continue
|
||||
|
||||
# Convert using legacy map
|
||||
if perm in LEGACY_PERMISSION_MAP:
|
||||
new_perm = LEGACY_PERMISSION_MAP[perm]
|
||||
# Only add True permissions to new format
|
||||
if value:
|
||||
new_permissions[new_perm] = value
|
||||
else:
|
||||
# Keep unknown permissions as-is for backwards compatibility
|
||||
if value:
|
||||
logger.warning(f"Unknown permission format: {perm}")
|
||||
new_permissions[perm] = value
|
||||
|
||||
return new_permissions
|
||||
|
||||
|
||||
def convert_permissions_to_legacy_format(new_permissions: Dict[str, bool]) -> Dict[str, bool]:
|
||||
"""
|
||||
Convert new permission format back to legacy format (for backwards compatibility).
|
||||
|
||||
Args:
|
||||
new_permissions: Dict with new format like {"vm:view": True}
|
||||
|
||||
Returns:
|
||||
Dict with old format like {"vms.view": True}
|
||||
"""
|
||||
if not new_permissions:
|
||||
return {}
|
||||
|
||||
# Create reverse map
|
||||
reverse_map = {v: k for k, v in LEGACY_PERMISSION_MAP.items()}
|
||||
|
||||
legacy_permissions = {}
|
||||
|
||||
for perm, value in new_permissions.items():
|
||||
if not value:
|
||||
continue
|
||||
|
||||
# Check if in new format
|
||||
if ":" in perm and perm in reverse_map:
|
||||
legacy_perm = reverse_map[perm]
|
||||
legacy_permissions[legacy_perm] = value
|
||||
else:
|
||||
# Keep as-is
|
||||
legacy_permissions[perm] = value
|
||||
|
||||
return legacy_permissions
|
||||
|
||||
|
||||
def get_permission_categories() -> Dict[str, Dict[str, str]]:
|
||||
"""
|
||||
Get permissions grouped by category with display names.
|
||||
|
||||
Returns:
|
||||
Dict like {"Virtual Machines": {"vm:view": "View VMs", "vm:create": "Create VMs"}}
|
||||
"""
|
||||
categories = {}
|
||||
|
||||
for perm in PERMISSIONS.all():
|
||||
if perm.category not in categories:
|
||||
categories[perm.category] = {}
|
||||
categories[perm.category][perm.code] = perm.display_name
|
||||
|
||||
return categories
|
||||
|
||||
|
||||
def get_permission_categories_legacy() -> Dict[str, Dict[str, str]]:
|
||||
"""
|
||||
Get permissions in legacy format grouped by category.
|
||||
For backwards compatibility with existing UI.
|
||||
|
||||
Returns:
|
||||
Dict like {"Virtual Machines": {"vms.view": "View VMs"}}
|
||||
"""
|
||||
# Create reverse map
|
||||
reverse_map = {v: k for k, v in LEGACY_PERMISSION_MAP.items()}
|
||||
|
||||
categories = {}
|
||||
|
||||
for perm in PERMISSIONS.all():
|
||||
if perm.category not in categories:
|
||||
categories[perm.category] = {}
|
||||
|
||||
# Use legacy code if available
|
||||
legacy_code = reverse_map.get(perm.code, perm.code)
|
||||
categories[perm.category][legacy_code] = perm.display_name
|
||||
|
||||
return categories
|
||||
|
||||
|
||||
def migrate_role_permissions(conn, role_id: int, old_permissions: dict) -> dict:
|
||||
"""
|
||||
Migrate a single role's permissions to new format.
|
||||
|
||||
Args:
|
||||
conn: Database connection
|
||||
role_id: Role ID
|
||||
old_permissions: Old permissions dict
|
||||
|
||||
Returns:
|
||||
New permissions dict
|
||||
"""
|
||||
import json
|
||||
|
||||
new_permissions = convert_permissions_to_new_format(old_permissions)
|
||||
|
||||
conn.execute(
|
||||
text("UPDATE roles SET permissions = :perms WHERE id = :id"),
|
||||
{"perms": json.dumps(new_permissions), "id": role_id}
|
||||
)
|
||||
|
||||
logger.info(f"Migrated role {role_id} permissions to new format")
|
||||
return new_permissions
|
||||
|
||||
|
||||
def migrate_all_roles_to_new_format(conn) -> int:
|
||||
"""
|
||||
Migrate all roles to new permission format.
|
||||
|
||||
Args:
|
||||
conn: Database connection
|
||||
|
||||
Returns:
|
||||
Number of migrated roles
|
||||
"""
|
||||
import json
|
||||
|
||||
# Get all roles
|
||||
result = conn.execute(text("SELECT id, name, permissions FROM roles"))
|
||||
roles = result.fetchall()
|
||||
|
||||
migrated_count = 0
|
||||
|
||||
for role in roles:
|
||||
role_id, role_name, permissions = role
|
||||
|
||||
if not permissions:
|
||||
continue
|
||||
|
||||
# Parse permissions if string
|
||||
if isinstance(permissions, str):
|
||||
try:
|
||||
permissions = json.loads(permissions)
|
||||
except:
|
||||
continue
|
||||
|
||||
# Check if already migrated (has : in keys)
|
||||
has_new_format = any(":" in k for k in permissions.keys())
|
||||
has_old_format = any("." in k and ":" not in k for k in permissions.keys())
|
||||
|
||||
if has_old_format and not has_new_format:
|
||||
new_permissions = convert_permissions_to_new_format(permissions)
|
||||
|
||||
conn.execute(
|
||||
text("UPDATE roles SET permissions = :perms WHERE id = :id"),
|
||||
{"perms": json.dumps(new_permissions), "id": role_id}
|
||||
)
|
||||
|
||||
logger.info(f"Migrated role '{role_name}' (id={role_id}) to new permission format")
|
||||
migrated_count += 1
|
||||
elif has_old_format and has_new_format:
|
||||
# Mixed format - merge and convert
|
||||
new_permissions = convert_permissions_to_new_format(permissions)
|
||||
|
||||
conn.execute(
|
||||
text("UPDATE roles SET permissions = :perms WHERE id = :id"),
|
||||
{"perms": json.dumps(new_permissions), "id": role_id}
|
||||
)
|
||||
|
||||
logger.info(f"Merged and migrated role '{role_name}' (id={role_id})")
|
||||
migrated_count += 1
|
||||
|
||||
return migrated_count
|
||||
|
||||
|
||||
def ensure_default_roles_new_format(conn) -> None:
|
||||
"""
|
||||
Ensure default roles exist with new permission format.
|
||||
Updates existing roles or creates new ones.
|
||||
"""
|
||||
import json
|
||||
|
||||
for role_data in NEW_DEFAULT_ROLES:
|
||||
# Check if role exists
|
||||
result = conn.execute(
|
||||
text("SELECT id, permissions FROM roles WHERE name = :name"),
|
||||
{"name": role_data["name"]}
|
||||
)
|
||||
existing = result.fetchone()
|
||||
|
||||
if existing:
|
||||
role_id, current_perms = existing
|
||||
|
||||
# Parse current permissions
|
||||
if isinstance(current_perms, str):
|
||||
try:
|
||||
current_perms = json.loads(current_perms)
|
||||
except:
|
||||
current_perms = {}
|
||||
|
||||
# Check if needs update
|
||||
has_old_format = any("." in k and ":" not in k for k in (current_perms or {}).keys())
|
||||
|
||||
if has_old_format or not current_perms:
|
||||
# Update to new format
|
||||
conn.execute(
|
||||
text("""
|
||||
UPDATE roles
|
||||
SET permissions = :perms,
|
||||
display_name = :display_name,
|
||||
description = :description
|
||||
WHERE id = :id
|
||||
"""),
|
||||
{
|
||||
"perms": json.dumps(role_data["permissions"]),
|
||||
"display_name": role_data["display_name"],
|
||||
"description": role_data["description"],
|
||||
"id": role_id
|
||||
}
|
||||
)
|
||||
logger.info(f"Updated role '{role_data['name']}' with new permission format")
|
||||
else:
|
||||
# Create new role
|
||||
conn.execute(
|
||||
text("""
|
||||
INSERT INTO roles (name, display_name, description, permissions, is_system)
|
||||
VALUES (:name, :display_name, :description, :permissions, :is_system)
|
||||
"""),
|
||||
{
|
||||
"name": role_data["name"],
|
||||
"display_name": role_data["display_name"],
|
||||
"description": role_data["description"],
|
||||
"permissions": json.dumps(role_data["permissions"]),
|
||||
"is_system": role_data["is_system"]
|
||||
}
|
||||
)
|
||||
logger.info(f"Created role '{role_data['name']}' with new permission format")
|
||||
652
backend/app/rbac/permissions.py
Normal file
652
backend/app/rbac/permissions.py
Normal file
@@ -0,0 +1,652 @@
|
||||
"""
|
||||
Permission Registry - Central definition of all permissions
|
||||
Format: resource:action[:scope]
|
||||
|
||||
Resources: cluster, node, vm, lxc, storage, network, backup, template, user, role, log, setting, ipam
|
||||
Actions: view, list, create, update, delete, start, stop, restart, console, migrate, manage
|
||||
Scopes: global, organization, workspace, instance (optional, defaults to global)
|
||||
"""
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Dict, List, Optional, Set
|
||||
from enum import Enum
|
||||
|
||||
|
||||
class ResourceType(str, Enum):
|
||||
"""Resource types in the system"""
|
||||
CLUSTER = "cluster"
|
||||
NODE = "node"
|
||||
SERVER = "server" # Proxmox server
|
||||
VM = "vm"
|
||||
LXC = "lxc"
|
||||
STORAGE = "storage"
|
||||
NETWORK = "network"
|
||||
BACKUP = "backup"
|
||||
TEMPLATE = "template"
|
||||
USER = "user"
|
||||
ROLE = "role"
|
||||
LOG = "log"
|
||||
SETTING = "setting"
|
||||
IPAM = "ipam"
|
||||
NOTIFICATION = "notification"
|
||||
DASHBOARD = "dashboard"
|
||||
|
||||
|
||||
class ActionType(str, Enum):
|
||||
"""Action types"""
|
||||
VIEW = "view"
|
||||
LIST = "list"
|
||||
CREATE = "create"
|
||||
UPDATE = "update"
|
||||
DELETE = "delete"
|
||||
START = "start"
|
||||
STOP = "stop"
|
||||
RESTART = "restart"
|
||||
CONSOLE = "console"
|
||||
MIGRATE = "migrate"
|
||||
MANAGE = "manage"
|
||||
EXPORT = "export"
|
||||
EXECUTE = "execute" # For running commands
|
||||
|
||||
|
||||
class ScopeType(str, Enum):
|
||||
"""Permission scope levels"""
|
||||
GLOBAL = "global" # Platform-wide access
|
||||
ORGANIZATION = "org" # Within organization
|
||||
WORKSPACE = "workspace" # Within workspace
|
||||
INSTANCE = "instance" # Specific resource only
|
||||
|
||||
|
||||
@dataclass
|
||||
class Permission:
|
||||
"""
|
||||
Atomic permission definition.
|
||||
|
||||
Format: resource:action or resource:action:scope
|
||||
Examples:
|
||||
- vm:view (global scope)
|
||||
- vm:create:workspace (workspace scope)
|
||||
- vm:delete:instance (instance scope)
|
||||
"""
|
||||
resource: str
|
||||
action: str
|
||||
scope: ScopeType = ScopeType.GLOBAL
|
||||
display_name: str = ""
|
||||
description: str = ""
|
||||
category: str = ""
|
||||
requires: List[str] = field(default_factory=list) # Dependencies
|
||||
|
||||
@property
|
||||
def code(self) -> str:
|
||||
"""Get permission code"""
|
||||
if self.scope == ScopeType.GLOBAL:
|
||||
return f"{self.resource}:{self.action}"
|
||||
return f"{self.resource}:{self.action}:{self.scope.value}"
|
||||
|
||||
@property
|
||||
def legacy_code(self) -> str:
|
||||
"""Get legacy permission code for backwards compatibility"""
|
||||
# Map to old format: resource.action
|
||||
return f"{self.resource}.{self.action}"
|
||||
|
||||
def __hash__(self):
|
||||
return hash(self.code)
|
||||
|
||||
def __eq__(self, other):
|
||||
if isinstance(other, Permission):
|
||||
return self.code == other.code
|
||||
return False
|
||||
|
||||
|
||||
class PermissionRegistry:
|
||||
"""
|
||||
Central registry of all permissions.
|
||||
Provides validation, lookup, and category grouping.
|
||||
"""
|
||||
|
||||
_instance = None
|
||||
_permissions: Dict[str, Permission] = {}
|
||||
_by_category: Dict[str, List[Permission]] = {}
|
||||
_by_resource: Dict[str, List[Permission]] = {}
|
||||
_legacy_map: Dict[str, str] = {} # legacy code -> new code
|
||||
|
||||
def __new__(cls):
|
||||
if cls._instance is None:
|
||||
cls._instance = super().__new__(cls)
|
||||
cls._instance._initialized = False
|
||||
return cls._instance
|
||||
|
||||
def __init__(self):
|
||||
if self._initialized:
|
||||
return
|
||||
self._initialized = True
|
||||
self._permissions = {}
|
||||
self._by_category = {}
|
||||
self._by_resource = {}
|
||||
self._legacy_map = {}
|
||||
|
||||
def register(self, permission: Permission) -> None:
|
||||
"""Register a permission"""
|
||||
self._permissions[permission.code] = permission
|
||||
|
||||
# Index by category
|
||||
if permission.category not in self._by_category:
|
||||
self._by_category[permission.category] = []
|
||||
self._by_category[permission.category].append(permission)
|
||||
|
||||
# Index by resource
|
||||
if permission.resource not in self._by_resource:
|
||||
self._by_resource[permission.resource] = []
|
||||
self._by_resource[permission.resource].append(permission)
|
||||
|
||||
# Legacy mapping
|
||||
self._legacy_map[permission.legacy_code] = permission.code
|
||||
|
||||
def get(self, code: str) -> Optional[Permission]:
|
||||
"""Get permission by code"""
|
||||
# Try direct lookup
|
||||
if code in self._permissions:
|
||||
return self._permissions[code]
|
||||
# Try legacy format
|
||||
if code in self._legacy_map:
|
||||
return self._permissions[self._legacy_map[code]]
|
||||
return None
|
||||
|
||||
def exists(self, code: str) -> bool:
|
||||
"""Check if permission exists"""
|
||||
return code in self._permissions or code in self._legacy_map
|
||||
|
||||
def resolve(self, code: str) -> Optional[str]:
|
||||
"""Resolve legacy code to new code"""
|
||||
if code in self._permissions:
|
||||
return code
|
||||
return self._legacy_map.get(code)
|
||||
|
||||
def all(self) -> List[Permission]:
|
||||
"""Get all permissions"""
|
||||
return list(self._permissions.values())
|
||||
|
||||
def by_category(self, category: str) -> List[Permission]:
|
||||
"""Get permissions by category"""
|
||||
return self._by_category.get(category, [])
|
||||
|
||||
def by_resource(self, resource: str) -> List[Permission]:
|
||||
"""Get permissions by resource"""
|
||||
return self._by_resource.get(resource, [])
|
||||
|
||||
def categories(self) -> List[str]:
|
||||
"""Get all categories"""
|
||||
return list(self._by_category.keys())
|
||||
|
||||
def resources(self) -> List[str]:
|
||||
"""Get all resources"""
|
||||
return list(self._by_resource.keys())
|
||||
|
||||
def validate(self, codes: List[str]) -> tuple[List[str], List[str]]:
|
||||
"""Validate permission codes, returns (valid, invalid)"""
|
||||
valid = []
|
||||
invalid = []
|
||||
for code in codes:
|
||||
if self.exists(code):
|
||||
valid.append(self.resolve(code) or code)
|
||||
else:
|
||||
invalid.append(code)
|
||||
return valid, invalid
|
||||
|
||||
|
||||
# ==================== Permission Definitions ====================
|
||||
|
||||
def _create_permissions() -> PermissionRegistry:
|
||||
"""Create and populate the permission registry"""
|
||||
registry = PermissionRegistry()
|
||||
|
||||
# Dashboard permissions
|
||||
registry.register(Permission(
|
||||
resource="dashboard", action="view",
|
||||
display_name="View Dashboard",
|
||||
description="Access to dashboard and overview",
|
||||
category="Dashboard"
|
||||
))
|
||||
|
||||
# Server (Proxmox) permissions
|
||||
registry.register(Permission(
|
||||
resource="server", action="view",
|
||||
display_name="View Servers",
|
||||
description="View Proxmox server list and status",
|
||||
category="Proxmox Servers"
|
||||
))
|
||||
registry.register(Permission(
|
||||
resource="server", action="create",
|
||||
display_name="Add Server",
|
||||
description="Add new Proxmox servers",
|
||||
category="Proxmox Servers"
|
||||
))
|
||||
registry.register(Permission(
|
||||
resource="server", action="update",
|
||||
display_name="Edit Server",
|
||||
description="Edit Proxmox server settings",
|
||||
category="Proxmox Servers"
|
||||
))
|
||||
registry.register(Permission(
|
||||
resource="server", action="delete",
|
||||
display_name="Delete Server",
|
||||
description="Remove Proxmox servers",
|
||||
category="Proxmox Servers"
|
||||
))
|
||||
registry.register(Permission(
|
||||
resource="server", action="manage",
|
||||
display_name="Manage Servers",
|
||||
description="Full server management including cluster operations",
|
||||
category="Proxmox Servers",
|
||||
requires=["server:view"]
|
||||
))
|
||||
|
||||
# VM permissions
|
||||
registry.register(Permission(
|
||||
resource="vm", action="view",
|
||||
display_name="View VMs",
|
||||
description="View virtual machines list and details",
|
||||
category="Virtual Machines"
|
||||
))
|
||||
registry.register(Permission(
|
||||
resource="vm", action="create",
|
||||
display_name="Create VMs",
|
||||
description="Create new virtual machines",
|
||||
category="Virtual Machines",
|
||||
requires=["vm:view", "template:view"]
|
||||
))
|
||||
registry.register(Permission(
|
||||
resource="vm", action="update",
|
||||
display_name="Update VMs",
|
||||
description="Modify VM configuration",
|
||||
category="Virtual Machines",
|
||||
requires=["vm:view"]
|
||||
))
|
||||
registry.register(Permission(
|
||||
resource="vm", action="delete",
|
||||
display_name="Delete VMs",
|
||||
description="Delete virtual machines",
|
||||
category="Virtual Machines",
|
||||
requires=["vm:view"]
|
||||
))
|
||||
registry.register(Permission(
|
||||
resource="vm", action="start",
|
||||
display_name="Start VMs",
|
||||
description="Start virtual machines",
|
||||
category="Virtual Machines",
|
||||
requires=["vm:view"]
|
||||
))
|
||||
registry.register(Permission(
|
||||
resource="vm", action="stop",
|
||||
display_name="Stop VMs",
|
||||
description="Stop virtual machines",
|
||||
category="Virtual Machines",
|
||||
requires=["vm:view"]
|
||||
))
|
||||
registry.register(Permission(
|
||||
resource="vm", action="restart",
|
||||
display_name="Restart VMs",
|
||||
description="Restart virtual machines",
|
||||
category="Virtual Machines",
|
||||
requires=["vm:view"]
|
||||
))
|
||||
registry.register(Permission(
|
||||
resource="vm", action="console",
|
||||
display_name="VM Console",
|
||||
description="Access VM console (noVNC/xterm.js)",
|
||||
category="Virtual Machines",
|
||||
requires=["vm:view"]
|
||||
))
|
||||
registry.register(Permission(
|
||||
resource="vm", action="migrate",
|
||||
display_name="Migrate VMs",
|
||||
description="Migrate VMs between nodes",
|
||||
category="Virtual Machines",
|
||||
requires=["vm:view"]
|
||||
))
|
||||
registry.register(Permission(
|
||||
resource="vm", action="execute",
|
||||
display_name="Execute Commands",
|
||||
description="Execute commands on VMs via QEMU agent",
|
||||
category="Virtual Machines",
|
||||
requires=["vm:console"]
|
||||
))
|
||||
|
||||
# LXC (Container) permissions - same structure as VM
|
||||
registry.register(Permission(
|
||||
resource="lxc", action="view",
|
||||
display_name="View Containers",
|
||||
description="View LXC containers list and details",
|
||||
category="Containers"
|
||||
))
|
||||
registry.register(Permission(
|
||||
resource="lxc", action="create",
|
||||
display_name="Create Containers",
|
||||
description="Create new LXC containers",
|
||||
category="Containers",
|
||||
requires=["lxc:view", "template:view"]
|
||||
))
|
||||
registry.register(Permission(
|
||||
resource="lxc", action="update",
|
||||
display_name="Update Containers",
|
||||
description="Modify container configuration",
|
||||
category="Containers",
|
||||
requires=["lxc:view"]
|
||||
))
|
||||
registry.register(Permission(
|
||||
resource="lxc", action="delete",
|
||||
display_name="Delete Containers",
|
||||
description="Delete LXC containers",
|
||||
category="Containers",
|
||||
requires=["lxc:view"]
|
||||
))
|
||||
registry.register(Permission(
|
||||
resource="lxc", action="start",
|
||||
display_name="Start Containers",
|
||||
description="Start LXC containers",
|
||||
category="Containers",
|
||||
requires=["lxc:view"]
|
||||
))
|
||||
registry.register(Permission(
|
||||
resource="lxc", action="stop",
|
||||
display_name="Stop Containers",
|
||||
description="Stop LXC containers",
|
||||
category="Containers",
|
||||
requires=["lxc:view"]
|
||||
))
|
||||
registry.register(Permission(
|
||||
resource="lxc", action="restart",
|
||||
display_name="Restart Containers",
|
||||
description="Restart LXC containers",
|
||||
category="Containers",
|
||||
requires=["lxc:view"]
|
||||
))
|
||||
registry.register(Permission(
|
||||
resource="lxc", action="console",
|
||||
display_name="Container Console",
|
||||
description="Access container console",
|
||||
category="Containers",
|
||||
requires=["lxc:view"]
|
||||
))
|
||||
registry.register(Permission(
|
||||
resource="lxc", action="migrate",
|
||||
display_name="Migrate Containers",
|
||||
description="Migrate containers between nodes",
|
||||
category="Containers",
|
||||
requires=["lxc:view"]
|
||||
))
|
||||
|
||||
# Template permissions
|
||||
registry.register(Permission(
|
||||
resource="template", action="view",
|
||||
display_name="View Templates",
|
||||
description="View OS templates",
|
||||
category="Templates"
|
||||
))
|
||||
registry.register(Permission(
|
||||
resource="template", action="create",
|
||||
display_name="Create Templates",
|
||||
description="Create new templates",
|
||||
category="Templates",
|
||||
requires=["template:view"]
|
||||
))
|
||||
registry.register(Permission(
|
||||
resource="template", action="update",
|
||||
display_name="Update Templates",
|
||||
description="Edit template settings",
|
||||
category="Templates",
|
||||
requires=["template:view"]
|
||||
))
|
||||
registry.register(Permission(
|
||||
resource="template", action="delete",
|
||||
display_name="Delete Templates",
|
||||
description="Delete templates",
|
||||
category="Templates",
|
||||
requires=["template:view"]
|
||||
))
|
||||
registry.register(Permission(
|
||||
resource="template", action="manage",
|
||||
display_name="Manage Templates",
|
||||
description="Full template management including download",
|
||||
category="Templates",
|
||||
requires=["template:view"]
|
||||
))
|
||||
|
||||
# Storage permissions
|
||||
registry.register(Permission(
|
||||
resource="storage", action="view",
|
||||
display_name="View Storage",
|
||||
description="View storage pools and usage",
|
||||
category="Storage"
|
||||
))
|
||||
registry.register(Permission(
|
||||
resource="storage", action="manage",
|
||||
display_name="Manage Storage",
|
||||
description="Manage storage pools and volumes",
|
||||
category="Storage",
|
||||
requires=["storage:view"]
|
||||
))
|
||||
|
||||
# Backup permissions
|
||||
registry.register(Permission(
|
||||
resource="backup", action="view",
|
||||
display_name="View Backups",
|
||||
description="View backup list",
|
||||
category="Backups"
|
||||
))
|
||||
registry.register(Permission(
|
||||
resource="backup", action="create",
|
||||
display_name="Create Backups",
|
||||
description="Create new backups",
|
||||
category="Backups",
|
||||
requires=["backup:view"]
|
||||
))
|
||||
registry.register(Permission(
|
||||
resource="backup", action="delete",
|
||||
display_name="Delete Backups",
|
||||
description="Delete backups",
|
||||
category="Backups",
|
||||
requires=["backup:view"]
|
||||
))
|
||||
registry.register(Permission(
|
||||
resource="backup", action="manage",
|
||||
display_name="Restore Backups",
|
||||
description="Restore from backups",
|
||||
category="Backups",
|
||||
requires=["backup:view", "vm:create"]
|
||||
))
|
||||
|
||||
# IPAM permissions
|
||||
registry.register(Permission(
|
||||
resource="ipam", action="view",
|
||||
display_name="View IPAM",
|
||||
description="View IP address management",
|
||||
category="IPAM"
|
||||
))
|
||||
registry.register(Permission(
|
||||
resource="ipam", action="manage",
|
||||
display_name="Manage IPAM",
|
||||
description="Manage networks and IP allocations",
|
||||
category="IPAM",
|
||||
requires=["ipam:view"]
|
||||
))
|
||||
|
||||
# User management permissions
|
||||
registry.register(Permission(
|
||||
resource="user", action="view",
|
||||
display_name="View Users",
|
||||
description="View user list",
|
||||
category="User Management"
|
||||
))
|
||||
registry.register(Permission(
|
||||
resource="user", action="create",
|
||||
display_name="Create Users",
|
||||
description="Create new users",
|
||||
category="User Management",
|
||||
requires=["user:view"]
|
||||
))
|
||||
registry.register(Permission(
|
||||
resource="user", action="update",
|
||||
display_name="Update Users",
|
||||
description="Edit user profiles",
|
||||
category="User Management",
|
||||
requires=["user:view"]
|
||||
))
|
||||
registry.register(Permission(
|
||||
resource="user", action="delete",
|
||||
display_name="Delete Users",
|
||||
description="Delete users",
|
||||
category="User Management",
|
||||
requires=["user:view"]
|
||||
))
|
||||
|
||||
# Role management permissions
|
||||
registry.register(Permission(
|
||||
resource="role", action="view",
|
||||
display_name="View Roles",
|
||||
description="View roles and permissions",
|
||||
category="Role Management"
|
||||
))
|
||||
registry.register(Permission(
|
||||
resource="role", action="create",
|
||||
display_name="Create Roles",
|
||||
description="Create new roles",
|
||||
category="Role Management",
|
||||
requires=["role:view"]
|
||||
))
|
||||
registry.register(Permission(
|
||||
resource="role", action="update",
|
||||
display_name="Update Roles",
|
||||
description="Edit role permissions",
|
||||
category="Role Management",
|
||||
requires=["role:view"]
|
||||
))
|
||||
registry.register(Permission(
|
||||
resource="role", action="delete",
|
||||
display_name="Delete Roles",
|
||||
description="Delete roles",
|
||||
category="Role Management",
|
||||
requires=["role:view"]
|
||||
))
|
||||
registry.register(Permission(
|
||||
resource="role", action="manage",
|
||||
display_name="Manage Roles",
|
||||
description="Full role management including assignment",
|
||||
category="Role Management",
|
||||
requires=["role:view", "user:view"]
|
||||
))
|
||||
|
||||
# Log permissions
|
||||
registry.register(Permission(
|
||||
resource="log", action="view",
|
||||
display_name="View Logs",
|
||||
description="View audit logs",
|
||||
category="Logs"
|
||||
))
|
||||
registry.register(Permission(
|
||||
resource="log", action="export",
|
||||
display_name="Export Logs",
|
||||
description="Export log data",
|
||||
category="Logs",
|
||||
requires=["log:view"]
|
||||
))
|
||||
registry.register(Permission(
|
||||
resource="log", action="delete",
|
||||
display_name="Delete Logs",
|
||||
description="Delete log entries",
|
||||
category="Logs",
|
||||
requires=["log:view"]
|
||||
))
|
||||
|
||||
# Settings permissions
|
||||
registry.register(Permission(
|
||||
resource="setting", action="view",
|
||||
display_name="View Settings",
|
||||
description="View panel settings",
|
||||
category="Settings"
|
||||
))
|
||||
registry.register(Permission(
|
||||
resource="setting", action="update",
|
||||
display_name="Update Settings",
|
||||
description="Modify panel settings",
|
||||
category="Settings",
|
||||
requires=["setting:view"]
|
||||
))
|
||||
registry.register(Permission(
|
||||
resource="setting", action="manage",
|
||||
display_name="Manage Security Settings",
|
||||
description="Manage security and advanced settings",
|
||||
category="Settings",
|
||||
requires=["setting:view"]
|
||||
))
|
||||
|
||||
# Notification permissions
|
||||
registry.register(Permission(
|
||||
resource="notification", action="view",
|
||||
display_name="View Notifications",
|
||||
description="View notifications",
|
||||
category="Notifications"
|
||||
))
|
||||
registry.register(Permission(
|
||||
resource="notification", action="manage",
|
||||
display_name="Manage Notifications",
|
||||
description="Manage notification settings",
|
||||
category="Notifications",
|
||||
requires=["notification:view"]
|
||||
))
|
||||
|
||||
return registry
|
||||
|
||||
|
||||
# Global registry instance
|
||||
PERMISSIONS = _create_permissions()
|
||||
|
||||
|
||||
# ==================== Legacy Permission Mapping ====================
|
||||
|
||||
LEGACY_PERMISSION_MAP = {
|
||||
# Old format -> New format
|
||||
"dashboard.view": "dashboard:view",
|
||||
"proxmox.view": "server:view",
|
||||
"proxmox.manage": "server:manage",
|
||||
"proxmox.servers.add": "server:create",
|
||||
"proxmox.servers.edit": "server:update",
|
||||
"proxmox.servers.delete": "server:delete",
|
||||
"proxmox.vm.manage": "vm:manage",
|
||||
"vms.view": "vm:view",
|
||||
"vms.create": "vm:create",
|
||||
"vms.start": "vm:start",
|
||||
"vms.stop": "vm:stop",
|
||||
"vms.restart": "vm:restart",
|
||||
"vms.delete": "vm:delete",
|
||||
"vms.console": "vm:console",
|
||||
"vms.migrate": "vm:migrate",
|
||||
"templates.view": "template:view",
|
||||
"templates.manage": "template:manage",
|
||||
"ipam.view": "ipam:view",
|
||||
"ipam.manage": "ipam:manage",
|
||||
"logs.view": "log:view",
|
||||
"logs.export": "log:export",
|
||||
"logs.delete": "log:delete",
|
||||
"settings.view": "setting:view",
|
||||
"settings.panel": "setting:update",
|
||||
"settings.security": "setting:manage",
|
||||
"users.view": "user:view",
|
||||
"users.create": "user:create",
|
||||
"users.edit": "user:update",
|
||||
"users.delete": "user:delete",
|
||||
"roles.view": "role:view",
|
||||
"roles.manage": "role:manage",
|
||||
"notifications.manage": "notification:manage",
|
||||
}
|
||||
|
||||
|
||||
def resolve_permission(code: str) -> str:
|
||||
"""Resolve legacy permission code to new format"""
|
||||
return LEGACY_PERMISSION_MAP.get(code, code)
|
||||
|
||||
|
||||
def get_permission_info(code: str) -> Optional[Permission]:
|
||||
"""Get permission object by code (supports legacy)"""
|
||||
resolved = resolve_permission(code)
|
||||
return PERMISSIONS.get(resolved)
|
||||
731
backend/app/schemas.py
Normal file
731
backend/app/schemas.py
Normal file
@@ -0,0 +1,731 @@
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
import ipaddress
|
||||
|
||||
from pydantic import BaseModel, Field, field_validator, model_validator, EmailStr
|
||||
|
||||
|
||||
# ==================== User Schemas ====================
|
||||
|
||||
class UserBase(BaseModel):
|
||||
username: str = Field(..., min_length=3, max_length=50, description="Username")
|
||||
email: EmailStr = Field(..., description="Email address")
|
||||
full_name: Optional[str] = Field(None, max_length=100, description="Full name")
|
||||
|
||||
|
||||
class UserCreate(UserBase):
|
||||
password: str = Field(..., min_length=6, max_length=100, description="Password")
|
||||
|
||||
|
||||
class UserUpdate(BaseModel):
|
||||
email: Optional[EmailStr] = None
|
||||
full_name: Optional[str] = Field(None, max_length=100)
|
||||
password: Optional[str] = Field(None, min_length=6, max_length=100)
|
||||
is_active: Optional[bool] = None
|
||||
|
||||
|
||||
class UserResponse(UserBase):
|
||||
id: int
|
||||
is_active: bool
|
||||
is_admin: bool
|
||||
created_at: datetime
|
||||
last_login: Optional[datetime] = None
|
||||
|
||||
model_config = {
|
||||
"from_attributes": True
|
||||
}
|
||||
|
||||
|
||||
class Token(BaseModel):
|
||||
access_token: str
|
||||
token_type: str = "bearer"
|
||||
|
||||
|
||||
class TokenData(BaseModel):
|
||||
username: Optional[str] = None
|
||||
|
||||
|
||||
class LoginRequest(BaseModel):
|
||||
username: str = Field(..., description="Username")
|
||||
password: str = Field(..., description="Password")
|
||||
|
||||
|
||||
# ==================== Proxmox Server Schemas ====================
|
||||
|
||||
class ProxmoxServerBase(BaseModel):
|
||||
name: str = Field(..., min_length=1, max_length=100, description="Server name")
|
||||
hostname: str = Field(..., min_length=1, max_length=255, description="Server hostname/FQDN")
|
||||
ip_address: str = Field(..., min_length=7, max_length=50, description="IP address")
|
||||
port: int = Field(default=8006, ge=1, le=65535, description="Proxmox API port")
|
||||
api_user: str = Field(default="root@pam", max_length=100, description="API username (e.g., root@pam)")
|
||||
api_token_name: Optional[str] = Field(None, max_length=100, description="API token name")
|
||||
api_token_value: Optional[str] = Field(None, max_length=255, description="API token value")
|
||||
use_password: bool = Field(default=False, description="Use password instead of token")
|
||||
password: Optional[str] = Field(None, max_length=255, description="Password (if use_password=True)")
|
||||
verify_ssl: bool = Field(default=False, description="Verify SSL certificate")
|
||||
description: Optional[str] = Field(None, description="Server description")
|
||||
|
||||
@field_validator('ip_address')
|
||||
@classmethod
|
||||
def validate_ip_address(cls, v):
|
||||
"""Validate IP address format"""
|
||||
try:
|
||||
ipaddress.ip_address(v)
|
||||
return v
|
||||
except ValueError:
|
||||
raise ValueError('Invalid IP address format')
|
||||
|
||||
@field_validator('name')
|
||||
@classmethod
|
||||
def validate_name(cls, v):
|
||||
"""Validate server name"""
|
||||
if not v or not v.strip():
|
||||
raise ValueError('Server name cannot be empty')
|
||||
return v.strip()
|
||||
|
||||
@field_validator('hostname')
|
||||
@classmethod
|
||||
def validate_hostname(cls, v):
|
||||
"""Validate hostname"""
|
||||
if not v or not v.strip():
|
||||
raise ValueError('Hostname cannot be empty')
|
||||
return v.strip()
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_auth_config(self):
|
||||
"""Validate authentication configuration"""
|
||||
if self.use_password:
|
||||
if not self.password:
|
||||
raise ValueError('Password is required when use_password=True')
|
||||
else:
|
||||
if not self.api_token_name or not self.api_token_value:
|
||||
raise ValueError('API token name and value are required when using token auth')
|
||||
return self
|
||||
|
||||
|
||||
class ProxmoxServerCreate(BaseModel):
|
||||
"""Schema for creating a new Proxmox server"""
|
||||
name: str = Field(..., min_length=1, max_length=100, description="Server name")
|
||||
hostname: str = Field(..., min_length=1, max_length=255, description="Server hostname/FQDN")
|
||||
ip_address: str = Field(..., min_length=7, max_length=50, description="IP address")
|
||||
port: int = Field(default=8006, ge=1, le=65535, description="Proxmox API port")
|
||||
api_user: str = Field(default="root@pam", max_length=100, description="API username (e.g., root@pam)")
|
||||
api_token_name: Optional[str] = Field(None, max_length=100, description="API token name")
|
||||
api_token_value: Optional[str] = Field(None, max_length=255, description="API token value")
|
||||
use_password: bool = Field(default=False, description="Use password instead of token")
|
||||
password: Optional[str] = Field(None, max_length=255, description="Password (if use_password=True)")
|
||||
verify_ssl: bool = Field(default=False, description="Verify SSL certificate")
|
||||
description: Optional[str] = Field(None, description="Server description")
|
||||
|
||||
@field_validator('ip_address')
|
||||
@classmethod
|
||||
def validate_ip_address(cls, v):
|
||||
"""Validate IP address format"""
|
||||
try:
|
||||
ipaddress.ip_address(v)
|
||||
return v
|
||||
except ValueError:
|
||||
raise ValueError('Invalid IP address format')
|
||||
|
||||
@field_validator('name')
|
||||
@classmethod
|
||||
def validate_name(cls, v):
|
||||
"""Validate server name"""
|
||||
if not v or not v.strip():
|
||||
raise ValueError('Server name cannot be empty')
|
||||
return v.strip()
|
||||
|
||||
@field_validator('hostname')
|
||||
@classmethod
|
||||
def validate_hostname(cls, v):
|
||||
"""Validate hostname"""
|
||||
if not v or not v.strip():
|
||||
raise ValueError('Hostname cannot be empty')
|
||||
return v.strip()
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_auth_config(self):
|
||||
"""Validate authentication configuration"""
|
||||
if self.use_password:
|
||||
if not self.password:
|
||||
raise ValueError('Password is required when use_password=True')
|
||||
else:
|
||||
if not self.api_token_name or not self.api_token_value:
|
||||
raise ValueError('API token name and value are required when using token auth')
|
||||
return self
|
||||
|
||||
|
||||
class ProxmoxServerUpdate(BaseModel):
|
||||
"""Schema for updating a Proxmox server"""
|
||||
name: Optional[str] = Field(None, min_length=1, max_length=100)
|
||||
hostname: Optional[str] = Field(None, min_length=1, max_length=255)
|
||||
ip_address: Optional[str] = Field(None, min_length=7, max_length=50)
|
||||
port: Optional[int] = Field(None, ge=1, le=65535)
|
||||
api_user: Optional[str] = Field(None, max_length=100)
|
||||
api_token_name: Optional[str] = Field(None, max_length=100)
|
||||
api_token_value: Optional[str] = Field(None, max_length=255)
|
||||
use_password: Optional[bool] = None
|
||||
password: Optional[str] = Field(None, max_length=255)
|
||||
verify_ssl: Optional[bool] = None
|
||||
description: Optional[str] = None
|
||||
|
||||
|
||||
class ProxmoxServerResponse(BaseModel):
|
||||
"""Schema for Proxmox server response"""
|
||||
id: int
|
||||
name: str
|
||||
hostname: str
|
||||
ip_address: str
|
||||
port: int
|
||||
api_user: str
|
||||
verify_ssl: bool
|
||||
description: Optional[str] = None
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
last_check: Optional[datetime] = None
|
||||
is_online: Optional[bool] = None
|
||||
last_error: Optional[str] = None
|
||||
|
||||
# Exclude sensitive fields
|
||||
api_token_value: Optional[str] = Field(None, exclude=True)
|
||||
password: Optional[str] = Field(None, exclude=True)
|
||||
|
||||
model_config = {
|
||||
"from_attributes": True
|
||||
}
|
||||
|
||||
|
||||
class ProxmoxVMResponse(BaseModel):
|
||||
"""Schema for Proxmox VM/Container response"""
|
||||
vmid: int
|
||||
name: Optional[str] = None
|
||||
status: str
|
||||
type: str # 'qemu' or 'lxc'
|
||||
node: str
|
||||
cpu: Optional[float] = None
|
||||
mem: Optional[int] = None
|
||||
maxmem: Optional[int] = None
|
||||
disk: Optional[int] = None
|
||||
maxdisk: Optional[int] = None
|
||||
uptime: Optional[int] = None
|
||||
|
||||
|
||||
# ==================== OS Template Schemas ====================
|
||||
|
||||
class OSTemplateGroupBase(BaseModel):
|
||||
"""Base schema for OS Template Group"""
|
||||
name: str = Field(..., min_length=1, max_length=100, description="Group name (e.g., Ubuntu, Debian)")
|
||||
icon: Optional[str] = Field(None, max_length=200, description="Icon (emoji, class or HTML)")
|
||||
description: Optional[str] = Field(None, description="Group description")
|
||||
sort_order: int = Field(default=0, description="Sort order")
|
||||
is_active: bool = Field(default=True, description="Is group active")
|
||||
|
||||
|
||||
class OSTemplateGroupCreate(OSTemplateGroupBase):
|
||||
"""Schema for creating OS Template Group"""
|
||||
pass
|
||||
|
||||
|
||||
class OSTemplateGroupUpdate(BaseModel):
|
||||
"""Schema for updating OS Template Group"""
|
||||
name: Optional[str] = Field(None, min_length=1, max_length=100)
|
||||
icon: Optional[str] = Field(None, max_length=200)
|
||||
description: Optional[str] = None
|
||||
sort_order: Optional[int] = None
|
||||
is_active: Optional[bool] = None
|
||||
|
||||
|
||||
class OSTemplateGroupResponse(OSTemplateGroupBase):
|
||||
"""Schema for OS Template Group response"""
|
||||
id: int
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
|
||||
model_config = {
|
||||
"from_attributes": True
|
||||
}
|
||||
|
||||
|
||||
class OSTemplateBase(BaseModel):
|
||||
"""Base schema for OS Template"""
|
||||
group_id: int = Field(..., description="Template group ID")
|
||||
server_id: int = Field(..., description="Proxmox server ID")
|
||||
name: str = Field(..., min_length=1, max_length=100, description="Display name")
|
||||
vmid: int = Field(..., ge=100, description="Proxmox template VMID")
|
||||
node: str = Field(..., min_length=1, max_length=100, description="Proxmox node name")
|
||||
default_cores: int = Field(default=1, ge=1, le=128, description="Default CPU cores")
|
||||
default_memory: int = Field(default=1024, ge=128, description="Default memory in MB")
|
||||
default_disk: int = Field(default=10, ge=1, description="Default disk size in GB")
|
||||
min_cores: int = Field(default=1, ge=1, description="Minimum CPU cores")
|
||||
min_memory: int = Field(default=512, ge=128, description="Minimum memory in MB")
|
||||
min_disk: int = Field(default=5, ge=1, description="Minimum disk size in GB")
|
||||
description: Optional[str] = Field(None, description="Template description")
|
||||
is_active: bool = Field(default=True, description="Is template active")
|
||||
sort_order: int = Field(default=0, description="Sort order")
|
||||
|
||||
|
||||
class OSTemplateCreate(OSTemplateBase):
|
||||
"""Schema for creating OS Template"""
|
||||
pass
|
||||
|
||||
|
||||
class OSTemplateUpdate(BaseModel):
|
||||
"""Schema for updating OS Template"""
|
||||
group_id: Optional[int] = None
|
||||
server_id: Optional[int] = None
|
||||
name: Optional[str] = Field(None, min_length=1, max_length=100)
|
||||
vmid: Optional[int] = Field(None, ge=100)
|
||||
node: Optional[str] = Field(None, min_length=1, max_length=100)
|
||||
default_cores: Optional[int] = Field(None, ge=1, le=128)
|
||||
default_memory: Optional[int] = Field(None, ge=128)
|
||||
default_disk: Optional[int] = Field(None, ge=1)
|
||||
min_cores: Optional[int] = Field(None, ge=1)
|
||||
min_memory: Optional[int] = Field(None, ge=128)
|
||||
min_disk: Optional[int] = Field(None, ge=1)
|
||||
description: Optional[str] = None
|
||||
is_active: Optional[bool] = None
|
||||
sort_order: Optional[int] = None
|
||||
|
||||
|
||||
class OSTemplateResponse(OSTemplateBase):
|
||||
"""Schema for OS Template response"""
|
||||
id: int
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
|
||||
model_config = {
|
||||
"from_attributes": True
|
||||
}
|
||||
|
||||
|
||||
class OSTemplateWithGroup(OSTemplateResponse):
|
||||
"""Schema for OS Template with group info"""
|
||||
group_name: Optional[str] = None
|
||||
group_icon: Optional[str] = None
|
||||
server_name: Optional[str] = None
|
||||
|
||||
|
||||
class VMDeployRequest(BaseModel):
|
||||
"""Schema for deploying a new VM from template"""
|
||||
template_id: int = Field(..., description="OS Template ID")
|
||||
name: str = Field(..., min_length=1, max_length=100, description="New VM name")
|
||||
vmid: Optional[int] = Field(None, ge=100, le=999999999, description="Specific VMID to use (optional, for reinstall)")
|
||||
target_node: Optional[str] = Field(None, description="Target node for VM deployment (optional, allows cross-node deployment)")
|
||||
cores: Optional[int] = Field(None, ge=1, le=128, description="CPU cores")
|
||||
memory: Optional[int] = Field(None, ge=128, description="Memory in MB")
|
||||
disk: Optional[int] = Field(None, ge=1, description="Disk size in GB")
|
||||
target_storage: Optional[str] = Field(None, description="Target storage for VM disk (e.g., local-lvm)")
|
||||
start_after_create: bool = Field(default=True, description="Start VM after creation")
|
||||
onboot: bool = Field(default=False, description="Start VM on host boot")
|
||||
# High Availability
|
||||
enable_ha: bool = Field(default=False, description="Enable High Availability for VM (cluster only)")
|
||||
# Network configuration
|
||||
network_bridge: Optional[str] = Field(default="vmbr0", description="Network bridge")
|
||||
ip_address: Optional[str] = Field(None, description="Static IP address")
|
||||
gateway: Optional[str] = Field(None, description="Gateway IP")
|
||||
# IPAM integration
|
||||
ipam_network_id: Optional[int] = Field(None, description="IPAM network ID for auto IP allocation")
|
||||
ipam_pool_id: Optional[int] = Field(None, description="IPAM pool ID (optional)")
|
||||
# Cloud-init (if template supports)
|
||||
cloud_init_user: Optional[str] = Field(None, max_length=50, description="Cloud-init username")
|
||||
cloud_init_password: Optional[str] = Field(None, max_length=100, description="Cloud-init password")
|
||||
ssh_keys: Optional[str] = Field(None, description="SSH public keys")
|
||||
|
||||
|
||||
class VMDeployResponse(BaseModel):
|
||||
"""Schema for VM deploy response"""
|
||||
success: bool
|
||||
vmid: int
|
||||
name: str
|
||||
node: str
|
||||
server_id: int
|
||||
task_upid: Optional[str] = None
|
||||
message: str
|
||||
|
||||
|
||||
# ==================== IPAM Schemas ====================
|
||||
|
||||
class IPAMNetworkBase(BaseModel):
|
||||
"""Base schema for IPAM Network"""
|
||||
name: str = Field(..., min_length=1, max_length=100, description="Network name")
|
||||
description: Optional[str] = Field(None, description="Network description")
|
||||
network: str = Field(..., description="Network CIDR (e.g., 10.10.10.0/24)")
|
||||
gateway: Optional[str] = Field(None, description="Gateway IP")
|
||||
vlan_id: Optional[int] = Field(None, ge=1, le=4094, description="VLAN ID")
|
||||
dns_primary: Optional[str] = Field(None, description="Primary DNS server")
|
||||
dns_secondary: Optional[str] = Field(None, description="Secondary DNS server")
|
||||
dns_domain: Optional[str] = Field(None, max_length=255, description="DNS domain")
|
||||
proxmox_server_id: Optional[int] = Field(None, description="Associated Proxmox server ID")
|
||||
proxmox_bridge: Optional[str] = Field(None, max_length=20, description="Proxmox bridge (e.g., vmbr0)")
|
||||
is_active: bool = Field(default=True, description="Is network active")
|
||||
|
||||
@field_validator('network')
|
||||
@classmethod
|
||||
def validate_network_cidr(cls, v):
|
||||
"""Validate network CIDR format"""
|
||||
try:
|
||||
ipaddress.ip_network(v, strict=False)
|
||||
return v
|
||||
except ValueError:
|
||||
raise ValueError('Invalid network CIDR format (e.g., 10.10.10.0/24)')
|
||||
|
||||
@field_validator('gateway', 'dns_primary', 'dns_secondary')
|
||||
@classmethod
|
||||
def validate_ip(cls, v):
|
||||
"""Validate IP address format"""
|
||||
if v is None:
|
||||
return v
|
||||
try:
|
||||
ipaddress.ip_address(v)
|
||||
return v
|
||||
except ValueError:
|
||||
raise ValueError('Invalid IP address format')
|
||||
|
||||
|
||||
class IPAMNetworkCreate(IPAMNetworkBase):
|
||||
"""Schema for creating IPAM Network"""
|
||||
pass
|
||||
|
||||
|
||||
class IPAMNetworkUpdate(BaseModel):
|
||||
"""Schema for updating IPAM Network"""
|
||||
name: Optional[str] = Field(None, min_length=1, max_length=100)
|
||||
description: Optional[str] = None
|
||||
gateway: Optional[str] = None
|
||||
vlan_id: Optional[int] = Field(None, ge=1, le=4094)
|
||||
dns_primary: Optional[str] = None
|
||||
dns_secondary: Optional[str] = None
|
||||
dns_domain: Optional[str] = Field(None, max_length=255)
|
||||
proxmox_server_id: Optional[int] = None
|
||||
proxmox_bridge: Optional[str] = Field(None, max_length=20)
|
||||
is_active: Optional[bool] = None
|
||||
|
||||
|
||||
class IPAMNetworkResponse(IPAMNetworkBase):
|
||||
"""Schema for IPAM Network response"""
|
||||
id: int
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
# Computed fields (will be added in API)
|
||||
total_ips: Optional[int] = None
|
||||
used_ips: Optional[int] = None
|
||||
available_ips: Optional[int] = None
|
||||
utilization_percent: Optional[float] = None
|
||||
server_name: Optional[str] = None
|
||||
|
||||
model_config = {
|
||||
"from_attributes": True
|
||||
}
|
||||
|
||||
|
||||
class IPAMPoolBase(BaseModel):
|
||||
"""Base schema for IPAM Pool"""
|
||||
network_id: int = Field(..., description="Parent network ID")
|
||||
name: str = Field(..., min_length=1, max_length=100, description="Pool name")
|
||||
pool_type: str = Field(default="static", description="Pool type: static, dhcp, reserved")
|
||||
range_start: str = Field(..., description="Range start IP")
|
||||
range_end: str = Field(..., description="Range end IP")
|
||||
auto_assign: bool = Field(default=True, description="Allow auto-assignment from this pool")
|
||||
description: Optional[str] = Field(None, description="Pool description")
|
||||
is_active: bool = Field(default=True, description="Is pool active")
|
||||
|
||||
@field_validator('pool_type')
|
||||
@classmethod
|
||||
def validate_pool_type(cls, v):
|
||||
"""Validate pool type"""
|
||||
allowed = ['static', 'dhcp', 'reserved']
|
||||
if v not in allowed:
|
||||
raise ValueError(f'Pool type must be one of: {", ".join(allowed)}')
|
||||
return v
|
||||
|
||||
@field_validator('range_start', 'range_end')
|
||||
@classmethod
|
||||
def validate_range_ip(cls, v):
|
||||
"""Validate IP address format"""
|
||||
try:
|
||||
ipaddress.ip_address(v)
|
||||
return v
|
||||
except ValueError:
|
||||
raise ValueError('Invalid IP address format')
|
||||
|
||||
|
||||
class IPAMPoolCreate(IPAMPoolBase):
|
||||
"""Schema for creating IPAM Pool"""
|
||||
pass
|
||||
|
||||
|
||||
class IPAMPoolUpdate(BaseModel):
|
||||
"""Schema for updating IPAM Pool"""
|
||||
name: Optional[str] = Field(None, min_length=1, max_length=100)
|
||||
pool_type: Optional[str] = None
|
||||
range_start: Optional[str] = None
|
||||
range_end: Optional[str] = None
|
||||
auto_assign: Optional[bool] = None
|
||||
description: Optional[str] = None
|
||||
is_active: Optional[bool] = None
|
||||
|
||||
|
||||
class IPAMPoolResponse(IPAMPoolBase):
|
||||
"""Schema for IPAM Pool response"""
|
||||
id: int
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
# Computed fields
|
||||
total_ips: Optional[int] = None
|
||||
used_ips: Optional[int] = None
|
||||
available_ips: Optional[int] = None
|
||||
|
||||
model_config = {
|
||||
"from_attributes": True
|
||||
}
|
||||
|
||||
|
||||
class IPAMAllocationBase(BaseModel):
|
||||
"""Base schema for IPAM Allocation"""
|
||||
network_id: int = Field(..., description="Network ID")
|
||||
pool_id: Optional[int] = Field(None, description="Pool ID (optional)")
|
||||
ip_address: str = Field(..., description="IP address")
|
||||
mac_address: Optional[str] = Field(None, max_length=17, description="MAC address")
|
||||
resource_type: Optional[str] = Field(None, description="Resource type: vm, lxc, physical, service, reserved")
|
||||
resource_id: Optional[int] = Field(None, description="Resource ID (e.g., VMID)")
|
||||
resource_name: Optional[str] = Field(None, max_length=100, description="Resource name")
|
||||
proxmox_server_id: Optional[int] = Field(None, description="Proxmox server ID")
|
||||
proxmox_vmid: Optional[int] = Field(None, description="Proxmox VMID")
|
||||
proxmox_node: Optional[str] = Field(None, max_length=100, description="Proxmox node")
|
||||
status: str = Field(default="allocated", description="Status: allocated, reserved, available, conflict")
|
||||
allocation_type: str = Field(default="static", description="Type: static, dhcp, floating")
|
||||
hostname: Optional[str] = Field(None, max_length=255, description="Hostname")
|
||||
fqdn: Optional[str] = Field(None, max_length=255, description="Fully qualified domain name")
|
||||
dns_ptr_record: bool = Field(default=False, description="Create PTR record")
|
||||
expires_at: Optional[datetime] = Field(None, description="Expiration date (for temp allocations)")
|
||||
notes: Optional[str] = Field(None, description="Notes")
|
||||
|
||||
@field_validator('ip_address')
|
||||
@classmethod
|
||||
def validate_ip_address(cls, v):
|
||||
"""Validate IP address format"""
|
||||
try:
|
||||
ipaddress.ip_address(v)
|
||||
return v
|
||||
except ValueError:
|
||||
raise ValueError('Invalid IP address format')
|
||||
|
||||
@field_validator('mac_address')
|
||||
@classmethod
|
||||
def validate_mac_address(cls, v):
|
||||
"""Validate MAC address format"""
|
||||
if v is None:
|
||||
return v
|
||||
import re
|
||||
mac_pattern = re.compile(r'^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$')
|
||||
if not mac_pattern.match(v):
|
||||
raise ValueError('Invalid MAC address format (e.g., AA:BB:CC:DD:EE:FF)')
|
||||
return v.upper()
|
||||
|
||||
@field_validator('status')
|
||||
@classmethod
|
||||
def validate_status(cls, v):
|
||||
"""Validate status"""
|
||||
allowed = ['allocated', 'reserved', 'available', 'conflict']
|
||||
if v not in allowed:
|
||||
raise ValueError(f'Status must be one of: {", ".join(allowed)}')
|
||||
return v
|
||||
|
||||
|
||||
class IPAMAllocationCreate(IPAMAllocationBase):
|
||||
"""Schema for creating IPAM Allocation"""
|
||||
allocated_by: Optional[str] = Field(None, max_length=100, description="Allocated by username")
|
||||
|
||||
|
||||
class IPAMAllocationUpdate(BaseModel):
|
||||
"""Schema for updating IPAM Allocation"""
|
||||
pool_id: Optional[int] = None
|
||||
mac_address: Optional[str] = Field(None, max_length=17)
|
||||
resource_type: Optional[str] = None
|
||||
resource_id: Optional[int] = None
|
||||
resource_name: Optional[str] = Field(None, max_length=100)
|
||||
proxmox_server_id: Optional[int] = None
|
||||
proxmox_vmid: Optional[int] = None
|
||||
proxmox_node: Optional[str] = Field(None, max_length=100)
|
||||
status: Optional[str] = None
|
||||
allocation_type: Optional[str] = None
|
||||
hostname: Optional[str] = Field(None, max_length=255)
|
||||
fqdn: Optional[str] = Field(None, max_length=255)
|
||||
dns_ptr_record: Optional[bool] = None
|
||||
expires_at: Optional[datetime] = None
|
||||
notes: Optional[str] = None
|
||||
|
||||
|
||||
class IPAMAllocationResponse(IPAMAllocationBase):
|
||||
"""Schema for IPAM Allocation response"""
|
||||
id: int
|
||||
allocated_by: Optional[str] = None
|
||||
allocated_at: datetime
|
||||
last_seen: Optional[datetime] = None
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
# Extended info
|
||||
network_name: Optional[str] = None
|
||||
pool_name: Optional[str] = None
|
||||
|
||||
model_config = {
|
||||
"from_attributes": True
|
||||
}
|
||||
|
||||
|
||||
class IPAMHistoryResponse(BaseModel):
|
||||
"""Schema for IPAM History response"""
|
||||
id: int
|
||||
ip_address: str
|
||||
network_id: Optional[int] = None
|
||||
action: str
|
||||
old_value: Optional[dict] = None
|
||||
new_value: Optional[dict] = None
|
||||
resource_type: Optional[str] = None
|
||||
resource_id: Optional[int] = None
|
||||
resource_name: Optional[str] = None
|
||||
performed_by: Optional[str] = None
|
||||
performed_at: datetime
|
||||
notes: Optional[str] = None
|
||||
|
||||
model_config = {
|
||||
"from_attributes": True
|
||||
}
|
||||
|
||||
|
||||
class IPAMAutoAllocateRequest(BaseModel):
|
||||
"""Schema for auto-allocating an IP from a network/pool"""
|
||||
network_id: int = Field(..., description="Network ID to allocate from")
|
||||
pool_id: Optional[int] = Field(None, description="Specific pool ID (optional)")
|
||||
resource_type: Optional[str] = Field(None, description="Resource type")
|
||||
resource_id: Optional[int] = Field(None, description="Resource ID")
|
||||
resource_name: Optional[str] = Field(None, max_length=100, description="Resource name")
|
||||
hostname: Optional[str] = Field(None, max_length=255, description="Hostname")
|
||||
notes: Optional[str] = Field(None, description="Notes")
|
||||
|
||||
|
||||
class IPAMScanRequest(BaseModel):
|
||||
"""Schema for network scan request"""
|
||||
network_id: int = Field(..., description="Network ID to scan")
|
||||
scan_type: str = Field(default="ping", description="Scan type: ping, arp, full")
|
||||
update_last_seen: bool = Field(default=True, description="Update last_seen for found IPs")
|
||||
detect_new: bool = Field(default=True, description="Detect and add new allocations")
|
||||
|
||||
|
||||
class IPAMSyncRequest(BaseModel):
|
||||
"""Schema for Proxmox sync request"""
|
||||
proxmox_server_id: int = Field(..., description="Proxmox server ID to sync from")
|
||||
network_id: Optional[int] = Field(None, description="Target network ID (optional)")
|
||||
create_allocations: bool = Field(default=True, description="Create allocations for found VMs")
|
||||
update_existing: bool = Field(default=True, description="Update existing allocations")
|
||||
|
||||
|
||||
class IPAMNetworkStats(BaseModel):
|
||||
"""Schema for network statistics"""
|
||||
network_id: int
|
||||
network_name: str
|
||||
network_cidr: str
|
||||
total_ips: int
|
||||
allocated_ips: int
|
||||
reserved_ips: int
|
||||
available_ips: int
|
||||
utilization_percent: float
|
||||
pools_count: int
|
||||
vms_count: int
|
||||
lxc_count: int
|
||||
physical_count: int
|
||||
other_count: int
|
||||
|
||||
|
||||
"""
|
||||
Pydantic schemas for notifications
|
||||
"""
|
||||
|
||||
from typing import Optional, List, Any
|
||||
from datetime import datetime
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
class NotificationCreate(BaseModel):
|
||||
"""Schema for creating a notification"""
|
||||
user_id: int
|
||||
type: str = Field(..., description="Type: vm_status, resource_alert, system, ipam, template")
|
||||
level: str = Field(..., description="Level: critical, warning, info, success")
|
||||
title: str = Field(..., max_length=255)
|
||||
message: Optional[str] = None
|
||||
data: Optional[dict] = None
|
||||
link: Optional[str] = None
|
||||
source: Optional[str] = Field(None, description="Source: proxmox, ipam, system, docker")
|
||||
source_id: Optional[str] = None
|
||||
expires_at: Optional[datetime] = None
|
||||
|
||||
|
||||
class NotificationUpdate(BaseModel):
|
||||
"""Schema for updating a notification"""
|
||||
read: Optional[bool] = None
|
||||
|
||||
|
||||
class NotificationResponse(BaseModel):
|
||||
"""Schema for notification response"""
|
||||
id: int
|
||||
user_id: int
|
||||
type: str
|
||||
level: str
|
||||
title: str
|
||||
message: Optional[str]
|
||||
data: Optional[dict]
|
||||
link: Optional[str]
|
||||
source: Optional[str]
|
||||
source_id: Optional[str]
|
||||
read: bool
|
||||
read_at: Optional[datetime]
|
||||
created_at: datetime
|
||||
expires_at: Optional[datetime]
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
|
||||
class NotificationListResponse(BaseModel):
|
||||
"""Schema for notification list response"""
|
||||
total: int
|
||||
unread_count: int
|
||||
notifications: List[NotificationResponse]
|
||||
|
||||
|
||||
class NotificationPreferenceUpdate(BaseModel):
|
||||
"""Schema for updating notification preferences"""
|
||||
enabled: Optional[bool] = None
|
||||
email_enabled: Optional[bool] = None
|
||||
email_critical_only: Optional[bool] = None
|
||||
telegram_enabled: Optional[bool] = None
|
||||
telegram_chat_id: Optional[str] = None
|
||||
webhook_url: Optional[str] = None
|
||||
notification_levels: Optional[List[str]] = None
|
||||
notification_types: Optional[List[str]] = None
|
||||
quiet_hours_start: Optional[str] = Field(None, pattern=r"^\d{2}:\d{2}$")
|
||||
quiet_hours_end: Optional[str] = Field(None, pattern=r"^\d{2}:\d{2}$")
|
||||
|
||||
|
||||
class NotificationPreferenceResponse(BaseModel):
|
||||
"""Schema for notification preference response"""
|
||||
id: int
|
||||
user_id: int
|
||||
enabled: bool
|
||||
email_enabled: bool
|
||||
email_critical_only: bool
|
||||
telegram_enabled: bool
|
||||
telegram_chat_id: Optional[str]
|
||||
webhook_url: Optional[str]
|
||||
notification_levels: List[str]
|
||||
notification_types: List[str]
|
||||
quiet_hours_start: Optional[str]
|
||||
quiet_hours_end: Optional[str]
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
|
||||
# Notification schemas added above
|
||||
225
backend/app/services/logo_service.py
Normal file
225
backend/app/services/logo_service.py
Normal file
@@ -0,0 +1,225 @@
|
||||
"""
|
||||
Logo Protection Service with RSA Digital Signature
|
||||
===================================================
|
||||
|
||||
Protects the panel logo from unauthorized modifications using RSA digital signatures.
|
||||
|
||||
How it works:
|
||||
1. Logo creator signs the logo with their PRIVATE key (kept secret, never shared)
|
||||
2. PUBLIC key is embedded in this code
|
||||
3. On each request, signature is verified with public key
|
||||
4. Without the private key, it's cryptographically impossible to create a valid signature
|
||||
|
||||
For logo updates: Contact the project maintainer with the new logo.
|
||||
"""
|
||||
|
||||
import base64
|
||||
import os
|
||||
from pathlib import Path
|
||||
from loguru import logger
|
||||
|
||||
try:
|
||||
from cryptography.hazmat.primitives import hashes
|
||||
from cryptography.hazmat.primitives.asymmetric import padding
|
||||
from cryptography.hazmat.primitives import serialization
|
||||
CRYPTO_AVAILABLE = True
|
||||
except ImportError:
|
||||
CRYPTO_AVAILABLE = False
|
||||
logger.warning("cryptography library not available, logo protection disabled")
|
||||
|
||||
# Get the static directory path
|
||||
STATIC_DIR = Path(__file__).parent.parent / "static"
|
||||
LOGO_PATH = STATIC_DIR / "img" / "logo.png"
|
||||
LOGO_SIG_PATH = STATIC_DIR / "img" / "logo.sig"
|
||||
|
||||
# ============================================================
|
||||
# PUBLIC KEY - Safe to be in open source code
|
||||
# This key can only VERIFY signatures, not create them
|
||||
# ============================================================
|
||||
PUBLIC_KEY_PEM = """-----BEGIN PUBLIC KEY-----
|
||||
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvM0VCWkP0fg2PMAPYJdn
|
||||
JF0YO9EkJtJmnhV2v+VIIqqXdiBnNDVFHxAxxDmeMHkXff9VbZ5PRRDc/AMRSjwY
|
||||
f1tN/xCCfQG8GVNlIKDcr11GJCAm7vOjy64bSEs/VpOK/A0l4js0FX6o/nEvqDqF
|
||||
hSdrxhrnX4iWbm6UaXL5ZcWrHYXXyD0zsc2g5xEXAtf7sy8U8bHtD6NjaLNNIVWz
|
||||
LzZqNTaAzOKXKOgKdwsYT4JXvWNLgrjMHo5TUcYDAnrPDSE2E6Ms2TZDS0BicB7Q
|
||||
g6FZ5M8H9NrttpDxvS0Gwen0AfRbI/0Cocn9nG88eiX/hbsodPxmJIlloAUOhtRa
|
||||
dwIDAQAB
|
||||
-----END PUBLIC KEY-----"""
|
||||
|
||||
# Fallback logo (simple base64 encoded placeholder - 64x64 transparent PNG)
|
||||
FALLBACK_LOGO_B64 = """
|
||||
iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAACXBIWXMAAAsTAAALEwEAmpwYAAAD
|
||||
GUlEQVR4nO2bS27bMBCGP7RZdNNFb9BFT+Au0hv0Br1BeoMe4QSNF+4q3fQGXfQG3fQEi+xatQ8g
|
||||
kCIlPkTJUuL5gICRPMP5OZwhKQOGYRiGYRiGYRiGYRhGIpI0dQ/nOy64QC4F/gI/gO/A17LkoyAJ
|
||||
cAX4AFwCF8AvYAf8Bn4C38o/+xaQBLgGPgNXZbkA/gDb8s+2wC/gS1nykZAEvAXeA2/Ksg1sgB/l
|
||||
n+2ALfBpmXIXBUnAO+AD8Los62AB/C7/bAN8L0s+CpKAG+A98LosK+Av8Kf8sw3wo/yzb4IkwDXw
|
||||
CXhdljXwB/hb/tkW+FWWfBQkAa6BT8DrsmyAX8Dv8s82wM+y5CMhCXANfAJelWUN/AZ+lX+2Bn6U
|
||||
JR8JSYBr4CPwqixr4Bfwu/yzNfCjLPlISAJcAx+BV2VZAb+A3+WfrYEfZclHQhLgGvgAvCrLEvgJ
|
||||
/Cr/bAn8KEs+EpIA18B74GVZFsAP4Ff5ZwvgR1nykZAEuAbeAy/LMgd+AD/LP5sDX8uSj4QkwDXw
|
||||
DnhZljnwA/hZ/tkc+FKWfCQkAa6Bd8DLskyBb8DP8s+mwJey5CMhCXANvAVelmUCfAN+ln82Ab6U
|
||||
JR8JSYBr4A3wsiw3wFfgR/lnN8CXsuQjIQlwDbwBXpTlGvgK/Cj/7Br4UpZ8JCQBroHXwIuyXAFf
|
||||
gB/ln10Bn8uSj4QkwBXwGnhRlkvgM/Cj/LNL4HNZ8pGQBLgCXgMvyjIGPgM/yj8bA5/Lko+EJMAV
|
||||
8Bp4UZYx8An4Uf7ZGPhclnwkJAEugdfAi7JcAJ+AH+WfXQCfy5KPhCTAJfAaeFGWMfAR+FH+2Rj4
|
||||
VJZ8JCQBLoHXwIuyjIEPwI/yz8bAx7LkIyEJcAm8Bp6XZQS8B76Xfz4C3pclHwlJgAvgNfC8LEPg
|
||||
HfC9/PMh8K4s+UhIAlwAr4HnZRkCb4Hv5Z8PgbdlyUdCEuACeA08L8sQeAN8L/98CLwpSz4SkgAX
|
||||
wCvgeVkGwGvge/nnA+B1WfKRkAS4AF4Bz8syAF4B38s/HwCvypKPhGEYhmEYhmEYhmEYhmH8D/wD
|
||||
F0bN8E0rJrsAAAAASUVORK5CYII=
|
||||
""".strip().replace('\n', '')
|
||||
|
||||
|
||||
class LogoService:
|
||||
"""Service for logo protection using RSA digital signatures"""
|
||||
|
||||
_public_key = None
|
||||
|
||||
@classmethod
|
||||
def _get_public_key(cls):
|
||||
"""Load and cache public key"""
|
||||
if cls._public_key is None and CRYPTO_AVAILABLE:
|
||||
try:
|
||||
cls._public_key = serialization.load_pem_public_key(
|
||||
PUBLIC_KEY_PEM.encode()
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to load public key: {e}")
|
||||
return cls._public_key
|
||||
|
||||
@staticmethod
|
||||
def verify_signature(data: bytes, signature: bytes) -> bool:
|
||||
"""Verify RSA signature of data"""
|
||||
if not CRYPTO_AVAILABLE:
|
||||
return True # Skip verification if crypto not available
|
||||
|
||||
public_key = LogoService._get_public_key()
|
||||
if not public_key:
|
||||
return False
|
||||
|
||||
try:
|
||||
public_key.verify(
|
||||
signature,
|
||||
data,
|
||||
padding.PKCS1v15(),
|
||||
hashes.SHA256()
|
||||
)
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.warning(f"Signature verification failed: {e}")
|
||||
return False
|
||||
|
||||
@staticmethod
|
||||
def get_stored_signature() -> bytes | None:
|
||||
"""Get stored signature from file"""
|
||||
try:
|
||||
if LOGO_SIG_PATH.exists():
|
||||
# Signature is stored as base64
|
||||
sig_b64 = LOGO_SIG_PATH.read_text().strip()
|
||||
return base64.b64decode(sig_b64)
|
||||
except Exception as e:
|
||||
logger.error(f"Error reading logo signature: {e}")
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def verify_logo() -> bool:
|
||||
"""Verify logo integrity using RSA signature"""
|
||||
try:
|
||||
if not LOGO_PATH.exists():
|
||||
logger.warning("Logo file not found")
|
||||
return False
|
||||
|
||||
signature = LogoService.get_stored_signature()
|
||||
if not signature:
|
||||
logger.warning("No signature found for logo")
|
||||
return False
|
||||
|
||||
logo_data = LOGO_PATH.read_bytes()
|
||||
|
||||
if not LogoService.verify_signature(logo_data, signature):
|
||||
logger.warning("Logo signature verification FAILED - unauthorized modification detected!")
|
||||
return False
|
||||
|
||||
logger.debug("Logo signature verified successfully")
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error verifying logo: {e}")
|
||||
return False
|
||||
|
||||
@staticmethod
|
||||
def get_logo_bytes() -> bytes:
|
||||
"""Get logo bytes - verified original or fallback"""
|
||||
if LogoService.verify_logo():
|
||||
return LOGO_PATH.read_bytes()
|
||||
else:
|
||||
logger.info("Using fallback logo (signature verification failed)")
|
||||
return base64.b64decode(FALLBACK_LOGO_B64)
|
||||
|
||||
@staticmethod
|
||||
def get_logo_base64() -> str:
|
||||
"""Get logo as base64 string"""
|
||||
return base64.b64encode(LogoService.get_logo_bytes()).decode()
|
||||
|
||||
@staticmethod
|
||||
def is_logo_valid() -> bool:
|
||||
"""Check if current logo is valid (has valid signature)"""
|
||||
return LogoService.verify_logo()
|
||||
|
||||
|
||||
# ============================================================
|
||||
# SIGNING FUNCTIONS - Only work with private key
|
||||
# These are used by the sign_logo.py script
|
||||
# ============================================================
|
||||
|
||||
def sign_logo_with_private_key(logo_path: str, private_key_path: str, output_sig_path: str = None) -> tuple[bool, str]:
|
||||
"""
|
||||
Sign a logo file with private key.
|
||||
This function is for the logo creator only.
|
||||
|
||||
Args:
|
||||
logo_path: Path to the logo PNG file
|
||||
private_key_path: Path to the private key PEM file
|
||||
output_sig_path: Path for output signature file (default: logo_path + '.sig')
|
||||
|
||||
Returns:
|
||||
tuple (success, message)
|
||||
"""
|
||||
if not CRYPTO_AVAILABLE:
|
||||
return False, "cryptography library not installed"
|
||||
|
||||
try:
|
||||
# Load logo
|
||||
logo_path = Path(logo_path)
|
||||
if not logo_path.exists():
|
||||
return False, f"Logo file not found: {logo_path}"
|
||||
|
||||
logo_data = logo_path.read_bytes()
|
||||
|
||||
# Verify it's a PNG
|
||||
if not logo_data[:8] == b'\x89PNG\r\n\x1a\n':
|
||||
return False, "File is not a valid PNG"
|
||||
|
||||
# Load private key
|
||||
private_key_path = Path(private_key_path)
|
||||
if not private_key_path.exists():
|
||||
return False, f"Private key not found: {private_key_path}"
|
||||
|
||||
private_key = serialization.load_pem_private_key(
|
||||
private_key_path.read_bytes(),
|
||||
password=None
|
||||
)
|
||||
|
||||
# Create signature
|
||||
signature = private_key.sign(
|
||||
logo_data,
|
||||
padding.PKCS1v15(),
|
||||
hashes.SHA256()
|
||||
)
|
||||
|
||||
# Save signature as base64
|
||||
sig_path = Path(output_sig_path) if output_sig_path else logo_path.with_suffix('.sig')
|
||||
sig_b64 = base64.b64encode(signature).decode()
|
||||
sig_path.write_text(sig_b64)
|
||||
|
||||
return True, f"Signature saved to: {sig_path}"
|
||||
|
||||
except Exception as e:
|
||||
return False, str(e)
|
||||
470
backend/app/services/notification_channels.py
Normal file
470
backend/app/services/notification_channels.py
Normal file
@@ -0,0 +1,470 @@
|
||||
"""
|
||||
Notification Channels - Email (SMTP) and Telegram Bot
|
||||
Settings are loaded from database (panel_settings table)
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import smtplib
|
||||
import ssl
|
||||
from email.mime.text import MIMEText
|
||||
from email.mime.multipart import MIMEMultipart
|
||||
from email.mime.image import MIMEImage
|
||||
from typing import Optional, Dict, Any, Tuple
|
||||
from datetime import datetime
|
||||
from loguru import logger
|
||||
|
||||
try:
|
||||
import httpx
|
||||
except ImportError:
|
||||
httpx = None
|
||||
|
||||
|
||||
def get_local_time() -> str:
|
||||
"""Get current local time formatted string"""
|
||||
return datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
||||
|
||||
|
||||
def get_notification_setting(key: str, default: str = None) -> Optional[str]:
|
||||
"""Get notification setting from database"""
|
||||
from ..db import SessionLocal
|
||||
from ..models import PanelSettings
|
||||
|
||||
db = SessionLocal()
|
||||
try:
|
||||
setting = db.query(PanelSettings).filter(PanelSettings.key == key).first()
|
||||
return setting.value if setting else default
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
def get_panel_name() -> str:
|
||||
"""Get panel name from database"""
|
||||
return get_notification_setting('panel_name', 'PVEmanager') or 'PVEmanager'
|
||||
|
||||
|
||||
def get_logo_base64() -> Optional[str]:
|
||||
"""Get logo as base64 for email embedding"""
|
||||
import base64
|
||||
import os
|
||||
|
||||
logo_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'static', 'img', 'logo.png')
|
||||
|
||||
if os.path.exists(logo_path):
|
||||
try:
|
||||
with open(logo_path, 'rb') as f:
|
||||
logo_data = f.read()
|
||||
return base64.b64encode(logo_data).decode('utf-8')
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to read logo: {e}")
|
||||
return None
|
||||
|
||||
|
||||
def get_logo_bytes() -> Optional[bytes]:
|
||||
"""Get logo as bytes for email attachment"""
|
||||
import os
|
||||
|
||||
logo_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'static', 'img', 'logo.png')
|
||||
|
||||
if os.path.exists(logo_path):
|
||||
try:
|
||||
with open(logo_path, 'rb') as f:
|
||||
return f.read()
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to read logo: {e}")
|
||||
return None
|
||||
|
||||
|
||||
class EmailChannel:
|
||||
"""SMTP Email notification channel - settings from database"""
|
||||
|
||||
def __init__(self):
|
||||
self._load_settings()
|
||||
|
||||
def _load_settings(self):
|
||||
"""Load SMTP settings from database"""
|
||||
self.smtp_host = get_notification_setting('smtp_host')
|
||||
self.smtp_port = int(get_notification_setting('smtp_port', '587') or '587')
|
||||
self.smtp_user = get_notification_setting('smtp_user')
|
||||
self.smtp_password = get_notification_setting('smtp_password')
|
||||
self.smtp_from = get_notification_setting('smtp_from') or self.smtp_user
|
||||
self.smtp_tls = get_notification_setting('smtp_tls', 'true').lower() == 'true'
|
||||
self.enabled = bool(self.smtp_host and self.smtp_user and self.smtp_password)
|
||||
|
||||
def reload_settings(self):
|
||||
"""Reload settings from database"""
|
||||
self._load_settings()
|
||||
|
||||
def is_configured(self) -> bool:
|
||||
"""Check if SMTP is configured"""
|
||||
self._load_settings() # Always reload to get latest settings
|
||||
return self.enabled
|
||||
|
||||
async def send(
|
||||
self,
|
||||
to_email: str,
|
||||
subject: str,
|
||||
body: str,
|
||||
html_body: Optional[str] = None,
|
||||
embedded_images: Optional[Dict[str, bytes]] = None
|
||||
) -> bool:
|
||||
"""Send email notification
|
||||
|
||||
Args:
|
||||
to_email: Recipient email
|
||||
subject: Email subject
|
||||
body: Plain text body
|
||||
html_body: HTML body (optional)
|
||||
embedded_images: Dict of {cid: image_bytes} for embedding (optional)
|
||||
"""
|
||||
if not self.is_configured():
|
||||
logger.warning("SMTP not configured, skipping email notification")
|
||||
return False
|
||||
|
||||
try:
|
||||
# Create message - use 'related' for embedded images
|
||||
if embedded_images:
|
||||
msg = MIMEMultipart("related")
|
||||
msg_alt = MIMEMultipart("alternative")
|
||||
msg.attach(msg_alt)
|
||||
else:
|
||||
msg = MIMEMultipart("alternative")
|
||||
msg_alt = msg
|
||||
|
||||
msg["Subject"] = subject
|
||||
msg["From"] = self.smtp_from
|
||||
msg["To"] = to_email
|
||||
|
||||
# Add plain text
|
||||
msg_alt.attach(MIMEText(body, "plain", "utf-8"))
|
||||
|
||||
# Add HTML if provided
|
||||
if html_body:
|
||||
msg_alt.attach(MIMEText(html_body, "html", "utf-8"))
|
||||
|
||||
# Attach embedded images
|
||||
if embedded_images:
|
||||
for cid, image_data in embedded_images.items():
|
||||
img = MIMEImage(image_data)
|
||||
img.add_header('Content-ID', f'<{cid}>')
|
||||
img.add_header('Content-Disposition', 'inline', filename=f'{cid}.png')
|
||||
msg.attach(img)
|
||||
|
||||
# Send in thread pool to not block async
|
||||
# Use asyncio.to_thread for better compatibility with FastAPI
|
||||
try:
|
||||
await asyncio.wait_for(
|
||||
asyncio.to_thread(self._send_sync, to_email, msg),
|
||||
timeout=15.0 # 15 second timeout for entire operation
|
||||
)
|
||||
except asyncio.TimeoutError:
|
||||
logger.error(f"Email sending to {to_email} timed out after 15 seconds")
|
||||
return False
|
||||
|
||||
logger.info(f"Email notification sent to {to_email}")
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to send email to {to_email}: {e}")
|
||||
return False
|
||||
|
||||
def _send_sync(self, to_email: str, msg: MIMEMultipart):
|
||||
"""Synchronous email sending with timeout"""
|
||||
context = ssl.create_default_context()
|
||||
timeout = 10 # 10 seconds timeout
|
||||
|
||||
# Port 465 always uses SSL (SMTPS)
|
||||
# Port 587 uses STARTTLS (SMTP with upgrade)
|
||||
# Port 25 uses plain SMTP (or STARTTLS if smtp_tls=True)
|
||||
use_ssl = self.smtp_port == 465
|
||||
|
||||
logger.info(f"Sending email via {self.smtp_host}:{self.smtp_port} (SSL={use_ssl}, TLS={self.smtp_tls})")
|
||||
|
||||
if use_ssl:
|
||||
# SSL connection (port 465 - SMTPS)
|
||||
with smtplib.SMTP_SSL(self.smtp_host, self.smtp_port, context=context, timeout=timeout) as server:
|
||||
server.login(self.smtp_user, self.smtp_password)
|
||||
server.sendmail(self.smtp_from, to_email, msg.as_string())
|
||||
else:
|
||||
# STARTTLS connection (port 587, 25, or custom)
|
||||
with smtplib.SMTP(self.smtp_host, self.smtp_port, timeout=timeout) as server:
|
||||
if self.smtp_tls:
|
||||
server.starttls(context=context)
|
||||
server.login(self.smtp_user, self.smtp_password)
|
||||
server.sendmail(self.smtp_from, to_email, msg.as_string())
|
||||
|
||||
def format_notification(self, notification: Dict[str, Any]) -> tuple:
|
||||
"""Format notification for email - returns (subject, body, html_body, embedded_images)"""
|
||||
level_emoji = {
|
||||
"critical": "🔴",
|
||||
"warning": "🟠",
|
||||
"info": "🔵",
|
||||
"success": "🟢"
|
||||
}
|
||||
|
||||
level = notification.get("level", "info")
|
||||
emoji = level_emoji.get(level, "🔵")
|
||||
title = notification.get("title", "Notification")
|
||||
message = notification.get("message", "")
|
||||
source = notification.get("source", "system")
|
||||
created_at = notification.get("created_at", "now")
|
||||
|
||||
# Получаем имя панели
|
||||
panel_name = get_panel_name()
|
||||
|
||||
subject = f"{emoji} [{panel_name}] {title}"
|
||||
|
||||
body = f"""
|
||||
{title}
|
||||
|
||||
{message}
|
||||
|
||||
Level: {level.upper()}
|
||||
Source: {source}
|
||||
Time: {created_at}
|
||||
|
||||
---
|
||||
{panel_name}
|
||||
""".strip()
|
||||
|
||||
# Получаем логотип для встраивания
|
||||
logo_bytes = get_logo_bytes()
|
||||
embedded_images = {}
|
||||
|
||||
if logo_bytes:
|
||||
embedded_images['logo'] = logo_bytes
|
||||
logo_html = f'<img src="cid:logo" alt="{panel_name}" style="max-height: 128px;">'
|
||||
else:
|
||||
logo_html = f'<span style="font-size: 64px;">🖥️</span>'
|
||||
|
||||
html_body = f"""
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<style>
|
||||
body {{ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: #1a1a2e; color: #eee; padding: 20px; margin: 0; }}
|
||||
.container {{ max-width: 600px; margin: 0 auto; background: #16213e; border-radius: 12px; overflow: hidden; }}
|
||||
.header {{ background: linear-gradient(135deg, #667eea 0%, #4f46e5 100%); padding: 24px; text-align: center; }}
|
||||
.logo {{ display: flex; align-items: center; justify-content: center; }}
|
||||
.content {{ padding: 24px; }}
|
||||
.level {{ display: inline-block; padding: 4px 12px; border-radius: 20px; font-size: 12px; font-weight: bold; margin-bottom: 16px; }}
|
||||
.level.critical {{ background: #f44336; color: white; }}
|
||||
.level.warning {{ background: #ff9800; color: white; }}
|
||||
.level.info {{ background: #2196f3; color: white; }}
|
||||
.level.success {{ background: #4caf50; color: white; }}
|
||||
.title {{ font-size: 20px; font-weight: bold; margin-bottom: 12px; color: #fff; }}
|
||||
.message {{ color: #b0b0b0; line-height: 1.6; margin-bottom: 20px; }}
|
||||
.meta {{ color: #666; font-size: 12px; }}
|
||||
.footer {{ padding: 16px 24px; background: #0f0f23; color: #666; font-size: 12px; text-align: center; }}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<div class="header">
|
||||
<div class="logo">{logo_html}</div>
|
||||
</div>
|
||||
<div class="content">
|
||||
<span class="level {level}">{level.upper()}</span>
|
||||
<div class="title">{emoji} {title}</div>
|
||||
<div class="message">{message}</div>
|
||||
<div class="meta">
|
||||
Source: {source} | Time: {created_at}
|
||||
</div>
|
||||
</div>
|
||||
<div class="footer">
|
||||
{panel_name} Notifications
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
"""
|
||||
|
||||
return subject, body, html_body, embedded_images
|
||||
|
||||
|
||||
class TelegramChannel:
|
||||
"""Telegram Bot notification channel - settings from database"""
|
||||
|
||||
def __init__(self):
|
||||
self._load_settings()
|
||||
|
||||
def _load_settings(self):
|
||||
"""Load Telegram settings from database"""
|
||||
self.bot_token = get_notification_setting('telegram_bot_token')
|
||||
self.enabled = bool(self.bot_token)
|
||||
self.api_url = f"https://api.telegram.org/bot{self.bot_token}" if self.bot_token else ""
|
||||
|
||||
def reload_settings(self):
|
||||
"""Reload settings from database"""
|
||||
self._load_settings()
|
||||
|
||||
def is_configured(self) -> bool:
|
||||
"""Check if Telegram bot is configured"""
|
||||
self._load_settings() # Always reload to get latest settings
|
||||
return self.enabled
|
||||
|
||||
async def send(self, chat_id: str, message: str, parse_mode: str = "HTML") -> bool:
|
||||
"""Send Telegram message"""
|
||||
if not self.is_configured():
|
||||
logger.warning("Telegram bot not configured, skipping notification")
|
||||
return False
|
||||
|
||||
if httpx is None:
|
||||
logger.error("httpx library not installed")
|
||||
return False
|
||||
|
||||
try:
|
||||
async with httpx.AsyncClient() as client:
|
||||
response = await client.post(
|
||||
f"{self.api_url}/sendMessage",
|
||||
json={
|
||||
"chat_id": chat_id,
|
||||
"text": message,
|
||||
"parse_mode": parse_mode,
|
||||
"disable_web_page_preview": True
|
||||
},
|
||||
timeout=10.0
|
||||
)
|
||||
|
||||
if response.status_code == 200:
|
||||
logger.info(f"Telegram notification sent to {chat_id}")
|
||||
return True
|
||||
else:
|
||||
logger.error(f"Telegram API error: {response.text}")
|
||||
return False
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to send Telegram message to {chat_id}: {e}")
|
||||
return False
|
||||
|
||||
async def send_photo(self, chat_id: str, photo_bytes: bytes, caption: str, parse_mode: str = "HTML") -> bool:
|
||||
"""Send Telegram message with photo"""
|
||||
if not self.is_configured():
|
||||
logger.warning("Telegram bot not configured, skipping notification")
|
||||
return False
|
||||
|
||||
if httpx is None:
|
||||
logger.error("httpx library not installed")
|
||||
return False
|
||||
|
||||
try:
|
||||
async with httpx.AsyncClient() as client:
|
||||
files = {'photo': ('logo.png', photo_bytes, 'image/png')}
|
||||
data = {
|
||||
'chat_id': chat_id,
|
||||
'caption': caption,
|
||||
'parse_mode': parse_mode
|
||||
}
|
||||
response = await client.post(
|
||||
f"{self.api_url}/sendPhoto",
|
||||
data=data,
|
||||
files=files,
|
||||
timeout=15.0
|
||||
)
|
||||
|
||||
if response.status_code == 200:
|
||||
logger.info(f"Telegram photo notification sent to {chat_id}")
|
||||
return True
|
||||
else:
|
||||
logger.error(f"Telegram API error: {response.text}")
|
||||
# Fallback to text message
|
||||
return await self.send(chat_id, caption, parse_mode)
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to send Telegram photo to {chat_id}: {e}")
|
||||
# Fallback to text message
|
||||
return await self.send(chat_id, caption, parse_mode)
|
||||
|
||||
async def get_bot_info(self) -> Optional[Dict[str, Any]]:
|
||||
"""Get bot information"""
|
||||
if not self.is_configured() or httpx is None:
|
||||
return None
|
||||
|
||||
try:
|
||||
async with httpx.AsyncClient() as client:
|
||||
response = await client.get(f"{self.api_url}/getMe", timeout=10.0)
|
||||
if response.status_code == 200:
|
||||
return response.json().get("result")
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to get bot info: {e}")
|
||||
return None
|
||||
|
||||
async def verify_chat_id(self, chat_id: str) -> bool:
|
||||
"""Verify chat_id by sending a test message"""
|
||||
local_time = get_local_time()
|
||||
panel_name = get_panel_name()
|
||||
return await self.send(
|
||||
chat_id,
|
||||
f"✅ <b>{panel_name}</b>\n\n"
|
||||
f"Telegram notifications configured successfully!\n\n"
|
||||
f"🕐 Server time: {local_time}",
|
||||
"HTML"
|
||||
)
|
||||
|
||||
def format_notification(self, notification: Dict[str, Any]) -> Tuple[str, Optional[bytes]]:
|
||||
"""Format notification for Telegram - returns (message, logo_bytes)"""
|
||||
level_emoji = {
|
||||
"critical": "🔴",
|
||||
"warning": "🟠",
|
||||
"info": "🔵",
|
||||
"success": "🟢"
|
||||
}
|
||||
|
||||
level = notification.get("level", "info")
|
||||
emoji = level_emoji.get(level, "🔵")
|
||||
title = notification.get("title", "Notification")
|
||||
message = notification.get("message", "")
|
||||
source = notification.get("source", "system")
|
||||
created_at = notification.get("created_at", "now")
|
||||
|
||||
# Получаем имя панели
|
||||
panel_name = get_panel_name()
|
||||
|
||||
# Получаем логотип
|
||||
logo_bytes = get_logo_bytes()
|
||||
|
||||
text = f"""
|
||||
{emoji} <b>[{panel_name}] {title}</b>
|
||||
|
||||
{message}
|
||||
|
||||
<i>Level:</i> {level.upper()}
|
||||
<i>Source:</i> {source}
|
||||
<i>Time:</i> {created_at}
|
||||
""".strip()
|
||||
|
||||
return text, logo_bytes
|
||||
|
||||
|
||||
# Singleton instances - initialized lazily
|
||||
_email_channel: Optional[EmailChannel] = None
|
||||
_telegram_channel: Optional[TelegramChannel] = None
|
||||
|
||||
|
||||
def get_email_channel() -> EmailChannel:
|
||||
"""Get or create EmailChannel singleton"""
|
||||
global _email_channel
|
||||
if _email_channel is None:
|
||||
_email_channel = EmailChannel()
|
||||
else:
|
||||
_email_channel.reload_settings()
|
||||
return _email_channel
|
||||
|
||||
|
||||
def get_telegram_channel() -> TelegramChannel:
|
||||
"""Get or create TelegramChannel singleton"""
|
||||
global _telegram_channel
|
||||
if _telegram_channel is None:
|
||||
_telegram_channel = TelegramChannel()
|
||||
else:
|
||||
_telegram_channel.reload_settings()
|
||||
return _telegram_channel
|
||||
|
||||
|
||||
def reload_notification_channels():
|
||||
"""Force reload all notification channel settings"""
|
||||
global _email_channel, _telegram_channel
|
||||
if _email_channel:
|
||||
_email_channel.reload_settings()
|
||||
if _telegram_channel:
|
||||
_telegram_channel.reload_settings()
|
||||
687
backend/app/services/notification_service.py
Normal file
687
backend/app/services/notification_service.py
Normal file
@@ -0,0 +1,687 @@
|
||||
"""
|
||||
Notification Service - Business logic for notifications
|
||||
"""
|
||||
|
||||
from typing import List, Optional, Dict, Any
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from sqlalchemy.orm import Session
|
||||
from sqlalchemy import and_, or_, desc
|
||||
from loguru import logger
|
||||
|
||||
|
||||
def utcnow() -> datetime:
|
||||
"""Get current UTC time as timezone-aware datetime"""
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
from ..models import Notification, NotificationPreference, User, PanelSettings
|
||||
from ..schemas import (
|
||||
NotificationCreate,
|
||||
NotificationUpdate,
|
||||
NotificationPreferenceUpdate
|
||||
)
|
||||
from ..i18n import t
|
||||
|
||||
|
||||
def get_panel_language(db: Session) -> str:
|
||||
"""Get panel language from settings"""
|
||||
setting = db.query(PanelSettings).filter(PanelSettings.key == "language").first()
|
||||
return setting.value if setting else "ru"
|
||||
|
||||
|
||||
class NotificationService:
|
||||
"""Service for managing notifications"""
|
||||
|
||||
@staticmethod
|
||||
def create_notification(
|
||||
db: Session,
|
||||
notification_data: NotificationCreate
|
||||
) -> Notification:
|
||||
"""
|
||||
Create a new notification
|
||||
|
||||
Args:
|
||||
db: Database session
|
||||
notification_data: Notification data
|
||||
|
||||
Returns:
|
||||
Created notification
|
||||
"""
|
||||
user_id = notification_data.user_id
|
||||
level = notification_data.level
|
||||
title = notification_data.title
|
||||
|
||||
# Check user preferences
|
||||
prefs = NotificationService.get_user_preferences(db, user_id)
|
||||
|
||||
if not prefs or not prefs.enabled:
|
||||
# User has disabled notifications
|
||||
logger.info(f"[NOTIFICATION SKIPPED] User {user_id}: notifications disabled | Level: {level} | Title: {title}")
|
||||
return None
|
||||
|
||||
# Check if notification level is allowed
|
||||
if notification_data.level not in prefs.notification_levels:
|
||||
logger.info(f"[NOTIFICATION SKIPPED] User {user_id}: level '{level}' not in allowed levels {prefs.notification_levels} | Title: {title}")
|
||||
return None
|
||||
|
||||
# Check if notification type is allowed
|
||||
if notification_data.type not in prefs.notification_types:
|
||||
logger.info(f"[NOTIFICATION SKIPPED] User {user_id}: type '{notification_data.type}' not in allowed types | Title: {title}")
|
||||
return None
|
||||
|
||||
# Check quiet hours
|
||||
if NotificationService._is_quiet_hours(prefs):
|
||||
# Only critical notifications during quiet hours
|
||||
if notification_data.level != "critical":
|
||||
logger.info(f"[NOTIFICATION SKIPPED] User {user_id}: quiet hours active, only critical allowed | Level: {level} | Title: {title}")
|
||||
return None
|
||||
|
||||
# Create notification
|
||||
notification = Notification(
|
||||
user_id=notification_data.user_id,
|
||||
type=notification_data.type,
|
||||
level=notification_data.level,
|
||||
title=notification_data.title,
|
||||
message=notification_data.message,
|
||||
data=notification_data.data,
|
||||
link=notification_data.link,
|
||||
source=notification_data.source,
|
||||
source_id=notification_data.source_id,
|
||||
expires_at=notification_data.expires_at or (utcnow() + timedelta(days=7))
|
||||
)
|
||||
|
||||
db.add(notification)
|
||||
db.commit()
|
||||
db.refresh(notification)
|
||||
|
||||
logger.info(f"[NOTIFICATION CREATED] ID: {notification.id} | User: {user_id} | Level: {level} | Type: {notification_data.type} | Title: {title}")
|
||||
|
||||
return notification
|
||||
|
||||
@staticmethod
|
||||
def get_user_notifications(
|
||||
db: Session,
|
||||
user_id: int,
|
||||
unread_only: bool = False,
|
||||
level: Optional[str] = None,
|
||||
limit: int = 50,
|
||||
offset: int = 0
|
||||
) -> tuple[List[Notification], int]:
|
||||
"""
|
||||
Get user notifications with filters
|
||||
|
||||
Args:
|
||||
db: Database session
|
||||
user_id: User ID
|
||||
unread_only: Only unread notifications
|
||||
level: Filter by level (critical, warning, info, success)
|
||||
limit: Maximum number of notifications
|
||||
offset: Offset for pagination
|
||||
|
||||
Returns:
|
||||
Tuple of (notifications, total_count)
|
||||
"""
|
||||
query = db.query(Notification).filter(Notification.user_id == user_id)
|
||||
|
||||
if unread_only:
|
||||
query = query.filter(Notification.read == False)
|
||||
|
||||
if level:
|
||||
query = query.filter(Notification.level == level)
|
||||
|
||||
# Filter out expired notifications
|
||||
query = query.filter(
|
||||
or_(
|
||||
Notification.expires_at.is_(None),
|
||||
Notification.expires_at > utcnow()
|
||||
)
|
||||
)
|
||||
|
||||
total = query.count()
|
||||
notifications = query.order_by(desc(Notification.created_at)).limit(limit).offset(offset).all()
|
||||
|
||||
return notifications, total
|
||||
|
||||
@staticmethod
|
||||
def get_unread_count(db: Session, user_id: int) -> int:
|
||||
"""Get count of unread notifications"""
|
||||
return db.query(Notification).filter(
|
||||
and_(
|
||||
Notification.user_id == user_id,
|
||||
Notification.read == False,
|
||||
or_(
|
||||
Notification.expires_at.is_(None),
|
||||
Notification.expires_at > utcnow()
|
||||
)
|
||||
)
|
||||
).count()
|
||||
|
||||
@staticmethod
|
||||
def mark_as_read(
|
||||
db: Session,
|
||||
notification_id: int,
|
||||
user_id: int
|
||||
) -> Optional[Notification]:
|
||||
"""Mark notification as read"""
|
||||
notification = db.query(Notification).filter(
|
||||
and_(
|
||||
Notification.id == notification_id,
|
||||
Notification.user_id == user_id
|
||||
)
|
||||
).first()
|
||||
|
||||
if notification and not notification.read:
|
||||
notification.read = True
|
||||
notification.read_at = utcnow()
|
||||
db.commit()
|
||||
db.refresh(notification)
|
||||
|
||||
return notification
|
||||
|
||||
@staticmethod
|
||||
def mark_all_as_read(db: Session, user_id: int) -> int:
|
||||
"""Mark all notifications as read for user"""
|
||||
count = db.query(Notification).filter(
|
||||
and_(
|
||||
Notification.user_id == user_id,
|
||||
Notification.read == False
|
||||
)
|
||||
).update({
|
||||
"read": True,
|
||||
"read_at": utcnow()
|
||||
})
|
||||
db.commit()
|
||||
return count
|
||||
|
||||
@staticmethod
|
||||
def delete_notification(
|
||||
db: Session,
|
||||
notification_id: int,
|
||||
user_id: int
|
||||
) -> bool:
|
||||
"""Delete a notification"""
|
||||
notification = db.query(Notification).filter(
|
||||
and_(
|
||||
Notification.id == notification_id,
|
||||
Notification.user_id == user_id
|
||||
)
|
||||
).first()
|
||||
|
||||
if notification:
|
||||
db.delete(notification)
|
||||
db.commit()
|
||||
return True
|
||||
return False
|
||||
|
||||
@staticmethod
|
||||
def delete_all_read(db: Session, user_id: int) -> int:
|
||||
"""Delete all read notifications for user"""
|
||||
count = db.query(Notification).filter(
|
||||
and_(
|
||||
Notification.user_id == user_id,
|
||||
Notification.read == True
|
||||
)
|
||||
).delete()
|
||||
db.commit()
|
||||
return count
|
||||
|
||||
@staticmethod
|
||||
def cleanup_expired(db: Session) -> int:
|
||||
"""Delete all expired notifications"""
|
||||
count = db.query(Notification).filter(
|
||||
and_(
|
||||
Notification.expires_at.isnot(None),
|
||||
Notification.expires_at < utcnow()
|
||||
)
|
||||
).delete()
|
||||
db.commit()
|
||||
return count
|
||||
|
||||
# Preferences management
|
||||
|
||||
@staticmethod
|
||||
def get_user_preferences(
|
||||
db: Session,
|
||||
user_id: int
|
||||
) -> Optional[NotificationPreference]:
|
||||
"""Get user notification preferences"""
|
||||
prefs = db.query(NotificationPreference).filter(
|
||||
NotificationPreference.user_id == user_id
|
||||
).first()
|
||||
|
||||
# Create default preferences if not exist
|
||||
if not prefs:
|
||||
prefs = NotificationPreference(
|
||||
user_id=user_id,
|
||||
enabled=True,
|
||||
email_enabled=False,
|
||||
email_critical_only=True,
|
||||
telegram_enabled=False,
|
||||
notification_levels=["critical", "warning", "info", "success"],
|
||||
notification_types=["vm_status", "resource_alert", "system", "ipam", "template"]
|
||||
)
|
||||
db.add(prefs)
|
||||
db.commit()
|
||||
db.refresh(prefs)
|
||||
|
||||
return prefs
|
||||
|
||||
@staticmethod
|
||||
def update_user_preferences(
|
||||
db: Session,
|
||||
user_id: int,
|
||||
prefs_data: NotificationPreferenceUpdate
|
||||
) -> NotificationPreference:
|
||||
"""Update user notification preferences"""
|
||||
prefs = NotificationService.get_user_preferences(db, user_id)
|
||||
|
||||
# Update fields
|
||||
update_data = prefs_data.model_dump(exclude_unset=True)
|
||||
for field, value in update_data.items():
|
||||
setattr(prefs, field, value)
|
||||
|
||||
prefs.updated_at = utcnow()
|
||||
db.commit()
|
||||
db.refresh(prefs)
|
||||
|
||||
return prefs
|
||||
|
||||
# Helper methods
|
||||
|
||||
@staticmethod
|
||||
def _is_quiet_hours(prefs: NotificationPreference) -> bool:
|
||||
"""Check if current time is in quiet hours"""
|
||||
if not prefs.quiet_hours_start or not prefs.quiet_hours_end:
|
||||
return False
|
||||
|
||||
now = utcnow().time()
|
||||
start = datetime.strptime(prefs.quiet_hours_start, "%H:%M").time()
|
||||
end = datetime.strptime(prefs.quiet_hours_end, "%H:%M").time()
|
||||
|
||||
if start <= end:
|
||||
return start <= now <= end
|
||||
else:
|
||||
# Crosses midnight
|
||||
return now >= start or now <= end
|
||||
|
||||
# Convenience methods for creating specific notification types
|
||||
|
||||
@staticmethod
|
||||
def notify_vm_status(
|
||||
db: Session,
|
||||
user_id: int,
|
||||
vm_id: int,
|
||||
vm_name: str,
|
||||
status: str,
|
||||
level: str = "info",
|
||||
server_name: str = "",
|
||||
old_status: str = ""
|
||||
) -> Optional[Notification]:
|
||||
"""Create VM status notification"""
|
||||
lang = get_panel_language(db)
|
||||
|
||||
# Determine title and message based on status
|
||||
if status == "running" and old_status == "stopped":
|
||||
title = t("notify_vm_started_title", lang, vm_name=vm_name)
|
||||
message = t("notify_vm_started_message", lang, vm_name=vm_name, server_name=server_name)
|
||||
elif status == "stopped" and old_status == "running":
|
||||
title = t("notify_vm_stopped_title", lang, vm_name=vm_name)
|
||||
message = t("notify_vm_stopped_message", lang, vm_name=vm_name, server_name=server_name)
|
||||
else:
|
||||
title = t("notify_vm_status_change_title", lang, vm_name=vm_name)
|
||||
message = t("notify_vm_status_change_message", lang, vm_name=vm_name, old_status=old_status, new_status=status)
|
||||
|
||||
return NotificationService.create_notification(
|
||||
db,
|
||||
NotificationCreate(
|
||||
user_id=user_id,
|
||||
type="vm_status",
|
||||
level=level,
|
||||
title=title,
|
||||
message=message,
|
||||
data={"vm_id": vm_id, "vm_name": vm_name, "status": status, "old_status": old_status},
|
||||
link=f"/vms/instance/{vm_id}",
|
||||
source="proxmox",
|
||||
source_id=str(vm_id)
|
||||
)
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def notify_resource_alert(
|
||||
db: Session,
|
||||
user_id: int,
|
||||
resource_type: str,
|
||||
resource_name: str,
|
||||
usage_percent: float,
|
||||
threshold: float
|
||||
) -> Optional[Notification]:
|
||||
"""Create resource usage alert"""
|
||||
lang = get_panel_language(db)
|
||||
level = "critical" if usage_percent >= 90 else "warning"
|
||||
|
||||
title = t("notify_resource_alert_title", lang, resource_type=resource_type)
|
||||
message = t("notify_resource_alert_message", lang,
|
||||
resource_name=resource_name,
|
||||
usage=f"{usage_percent:.1f}",
|
||||
threshold=f"{threshold:.0f}")
|
||||
|
||||
return NotificationService.create_notification(
|
||||
db,
|
||||
NotificationCreate(
|
||||
user_id=user_id,
|
||||
type="resource_alert",
|
||||
level=level,
|
||||
title=title,
|
||||
message=message,
|
||||
data={
|
||||
"resource_type": resource_type,
|
||||
"resource_name": resource_name,
|
||||
"usage": usage_percent,
|
||||
"threshold": threshold
|
||||
},
|
||||
source="system"
|
||||
)
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def notify_system_event(
|
||||
db: Session,
|
||||
user_id: int,
|
||||
title: str,
|
||||
message: str,
|
||||
level: str = "info",
|
||||
data: Optional[dict] = None
|
||||
) -> Optional[Notification]:
|
||||
"""Create generic system notification"""
|
||||
return NotificationService.create_notification(
|
||||
db,
|
||||
NotificationCreate(
|
||||
user_id=user_id,
|
||||
type="system",
|
||||
level=level,
|
||||
title=title,
|
||||
message=message,
|
||||
data=data,
|
||||
source="system"
|
||||
)
|
||||
)
|
||||
|
||||
# ============================================
|
||||
# Async methods for multi-channel notifications
|
||||
# ============================================
|
||||
|
||||
@staticmethod
|
||||
async def create_and_send(
|
||||
db: Session,
|
||||
user_id: int,
|
||||
notification_type: str,
|
||||
level: str,
|
||||
title: str,
|
||||
message: str,
|
||||
data: Optional[Dict[str, Any]] = None,
|
||||
link: Optional[str] = None,
|
||||
source: Optional[str] = None,
|
||||
source_id: Optional[str] = None,
|
||||
force_send: bool = False
|
||||
) -> Optional[Notification]:
|
||||
"""
|
||||
Create notification and send through enabled channels (Email, Telegram)
|
||||
|
||||
Args:
|
||||
db: Database session
|
||||
user_id: User ID
|
||||
notification_type: Type of notification
|
||||
level: Level (critical, warning, info, success)
|
||||
title: Notification title
|
||||
message: Notification message
|
||||
data: Additional data
|
||||
link: Optional link
|
||||
source: Source system
|
||||
source_id: Source entity ID
|
||||
force_send: If True, send to external channels even if "Critical Only" is enabled
|
||||
|
||||
Returns:
|
||||
Created notification
|
||||
"""
|
||||
# Create in-app notification
|
||||
notification = NotificationService.create_notification(
|
||||
db,
|
||||
NotificationCreate(
|
||||
user_id=user_id,
|
||||
type=notification_type,
|
||||
level=level,
|
||||
title=title,
|
||||
message=message,
|
||||
data=data,
|
||||
link=link,
|
||||
source=source,
|
||||
source_id=source_id
|
||||
)
|
||||
)
|
||||
|
||||
if not notification:
|
||||
logger.warning(f"[NOTIFICATION] In-app notification was not created for user {user_id} | Level: {level} | Title: {title}")
|
||||
return None
|
||||
|
||||
# Get user preferences for external channels
|
||||
prefs = NotificationService.get_user_preferences(db, user_id)
|
||||
if not prefs or not prefs.enabled:
|
||||
logger.info(f"[EXTERNAL CHANNELS SKIPPED] User {user_id}: preferences disabled | Notification ID: {notification.id}")
|
||||
return notification
|
||||
|
||||
# Get user for email
|
||||
user = db.query(User).filter(User.id == user_id).first()
|
||||
|
||||
# Prepare notification dict for formatting
|
||||
notification_dict = {
|
||||
"title": title,
|
||||
"message": message,
|
||||
"level": level,
|
||||
"source": source or "system",
|
||||
"created_at": notification.created_at.strftime("%Y-%m-%d %H:%M:%S") if notification.created_at else "now"
|
||||
}
|
||||
|
||||
# Log channel delivery attempt details
|
||||
logger.info(f"[EXTERNAL CHANNELS] Processing notification {notification.id} | Level: {level} | Email enabled: {prefs.email_enabled} | Telegram enabled: {prefs.telegram_enabled} | Critical only: {prefs.email_critical_only} | Force send: {force_send}")
|
||||
|
||||
# Send Email
|
||||
if prefs.email_enabled and user and user.email:
|
||||
# Check critical only setting (bypass if force_send is True)
|
||||
if prefs.email_critical_only and level != "critical" and not force_send:
|
||||
logger.info(f"[EMAIL SKIPPED] User {user_id}: critical_only=True but level='{level}' | Notification ID: {notification.id}")
|
||||
else:
|
||||
try:
|
||||
from .notification_channels import get_email_channel
|
||||
email_ch = get_email_channel()
|
||||
logger.info(f"[EMAIL] Attempting to send | To: {user.email} | SMTP configured: {email_ch.is_configured()} | Host: {email_ch.smtp_host}")
|
||||
if email_ch.is_configured():
|
||||
subject, body, html_body, embedded_images = email_ch.format_notification(notification_dict)
|
||||
result = await email_ch.send(user.email, subject, body, html_body, embedded_images)
|
||||
if result:
|
||||
logger.info(f"[EMAIL SUCCESS] Sent to {user.email} | Notification ID: {notification.id}")
|
||||
else:
|
||||
logger.error(f"[EMAIL FAILED] Could not send to {user.email} | Notification ID: {notification.id}")
|
||||
else:
|
||||
logger.warning(f"[EMAIL SKIPPED] SMTP not configured | Host: {email_ch.smtp_host} | User: {email_ch.smtp_user}")
|
||||
except Exception as e:
|
||||
logger.error(f"[EMAIL ERROR] Failed to send to {user.email}: {e} | Notification ID: {notification.id}")
|
||||
else:
|
||||
if not prefs.email_enabled:
|
||||
logger.debug(f"[EMAIL SKIPPED] User {user_id}: email_enabled=False")
|
||||
elif not user or not user.email:
|
||||
logger.warning(f"[EMAIL SKIPPED] User {user_id}: no email address configured")
|
||||
|
||||
# Send Telegram
|
||||
if prefs.telegram_enabled and prefs.telegram_chat_id:
|
||||
# Check critical only for Telegram too if set (bypass if force_send is True)
|
||||
if prefs.email_critical_only and level != "critical" and not force_send:
|
||||
logger.info(f"[TELEGRAM SKIPPED] User {user_id}: critical_only=True but level='{level}' | Notification ID: {notification.id}")
|
||||
else:
|
||||
try:
|
||||
from .notification_channels import get_telegram_channel
|
||||
tg_ch = get_telegram_channel()
|
||||
logger.info(f"[TELEGRAM] Attempting to send | Chat ID: {prefs.telegram_chat_id} | Bot configured: {tg_ch.is_configured()}")
|
||||
if tg_ch.is_configured():
|
||||
tg_message, logo_bytes = tg_ch.format_notification(notification_dict)
|
||||
if logo_bytes:
|
||||
result = await tg_ch.send_photo(prefs.telegram_chat_id, logo_bytes, tg_message)
|
||||
else:
|
||||
result = await tg_ch.send(prefs.telegram_chat_id, tg_message)
|
||||
if result:
|
||||
logger.info(f"[TELEGRAM SUCCESS] Sent to {prefs.telegram_chat_id} | Notification ID: {notification.id}")
|
||||
else:
|
||||
logger.error(f"[TELEGRAM FAILED] Could not send to {prefs.telegram_chat_id} | Notification ID: {notification.id}")
|
||||
else:
|
||||
logger.warning(f"[TELEGRAM SKIPPED] Bot not configured")
|
||||
except Exception as e:
|
||||
logger.error(f"[TELEGRAM ERROR] Failed to send to {prefs.telegram_chat_id}: {e} | Notification ID: {notification.id}")
|
||||
else:
|
||||
if not prefs.telegram_enabled:
|
||||
logger.debug(f"[TELEGRAM SKIPPED] User {user_id}: telegram_enabled=False")
|
||||
elif not prefs.telegram_chat_id:
|
||||
logger.warning(f"[TELEGRAM SKIPPED] User {user_id}: no telegram_chat_id configured")
|
||||
|
||||
return notification
|
||||
|
||||
@staticmethod
|
||||
async def send_test_notification(
|
||||
db: Session,
|
||||
user_id: int,
|
||||
channel: str = "all"
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Send test notification through specified channels
|
||||
|
||||
Args:
|
||||
db: Database session
|
||||
user_id: User ID
|
||||
channel: Channel to test (all, email, telegram, inapp)
|
||||
|
||||
Returns:
|
||||
Dict with results for each channel
|
||||
"""
|
||||
results = {"inapp": False, "email": False, "telegram": False, "errors": []}
|
||||
|
||||
user = db.query(User).filter(User.id == user_id).first()
|
||||
prefs = NotificationService.get_user_preferences(db, user_id)
|
||||
|
||||
# Get panel language
|
||||
lang = get_panel_language(db)
|
||||
|
||||
# Use local time instead of UTC
|
||||
local_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
||||
|
||||
test_notification = {
|
||||
"title": t("notify_test_title", lang),
|
||||
"message": t("notify_test_message", lang),
|
||||
"level": "info",
|
||||
"source": "system",
|
||||
"created_at": local_time
|
||||
}
|
||||
|
||||
# In-app notification
|
||||
if channel in ["all", "inapp"]:
|
||||
try:
|
||||
notification = NotificationService.create_notification(
|
||||
db,
|
||||
NotificationCreate(
|
||||
user_id=user_id,
|
||||
type="system",
|
||||
level="info",
|
||||
title=test_notification["title"],
|
||||
message=test_notification["message"],
|
||||
source="system"
|
||||
)
|
||||
)
|
||||
results["inapp"] = notification is not None
|
||||
except Exception as e:
|
||||
results["errors"].append(f"In-app: {str(e)}")
|
||||
|
||||
# Email
|
||||
if channel in ["all", "email"]:
|
||||
try:
|
||||
from .notification_channels import get_email_channel
|
||||
email_ch = get_email_channel()
|
||||
if email_ch.is_configured():
|
||||
if user and user.email:
|
||||
subject, body, html_body, embedded_images = email_ch.format_notification(test_notification)
|
||||
results["email"] = await email_ch.send(user.email, subject, body, html_body, embedded_images)
|
||||
else:
|
||||
results["errors"].append("Email: User has no email address")
|
||||
else:
|
||||
results["errors"].append("Email: SMTP not configured")
|
||||
except Exception as e:
|
||||
results["errors"].append(f"Email: {str(e)}")
|
||||
|
||||
# Telegram
|
||||
if channel in ["all", "telegram"]:
|
||||
try:
|
||||
from .notification_channels import get_telegram_channel
|
||||
tg_ch = get_telegram_channel()
|
||||
if tg_ch.is_configured():
|
||||
if prefs and prefs.telegram_chat_id:
|
||||
tg_message, logo_bytes = tg_ch.format_notification(test_notification)
|
||||
if logo_bytes:
|
||||
results["telegram"] = await tg_ch.send_photo(prefs.telegram_chat_id, logo_bytes, tg_message)
|
||||
else:
|
||||
results["telegram"] = await tg_ch.send(prefs.telegram_chat_id, tg_message)
|
||||
else:
|
||||
results["errors"].append("Telegram: Chat ID not configured")
|
||||
else:
|
||||
results["errors"].append("Telegram: Bot token not configured")
|
||||
except Exception as e:
|
||||
results["errors"].append(f"Telegram: {str(e)}")
|
||||
|
||||
return results
|
||||
|
||||
@staticmethod
|
||||
async def get_channels_status(db: Session, user_id: int) -> Dict[str, Any]:
|
||||
"""
|
||||
Get status of notification channels
|
||||
|
||||
Args:
|
||||
db: Database session
|
||||
user_id: User ID
|
||||
|
||||
Returns:
|
||||
Dict with channel status information
|
||||
"""
|
||||
from .notification_channels import get_email_channel, get_telegram_channel
|
||||
|
||||
user = db.query(User).filter(User.id == user_id).first()
|
||||
prefs = NotificationService.get_user_preferences(db, user_id)
|
||||
|
||||
email_ch = get_email_channel()
|
||||
tg_ch = get_telegram_channel()
|
||||
|
||||
# Get Telegram bot info if configured
|
||||
telegram_bot_info = None
|
||||
if tg_ch.is_configured():
|
||||
try:
|
||||
telegram_bot_info = await tg_ch.get_bot_info()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return {
|
||||
"email": {
|
||||
"configured": email_ch.is_configured(),
|
||||
"enabled": prefs.email_enabled if prefs else False,
|
||||
"user_email": user.email if user else None,
|
||||
"smtp_host": email_ch.smtp_host if email_ch.is_configured() else None,
|
||||
"critical_only": prefs.email_critical_only if prefs else True
|
||||
},
|
||||
"telegram": {
|
||||
"configured": tg_ch.is_configured(),
|
||||
"enabled": prefs.telegram_enabled if prefs else False,
|
||||
"chat_id": prefs.telegram_chat_id if prefs else None,
|
||||
"bot_info": telegram_bot_info
|
||||
},
|
||||
"inapp": {
|
||||
"configured": True,
|
||||
"enabled": prefs.enabled if prefs else True
|
||||
},
|
||||
"quiet_hours": {
|
||||
"start": prefs.quiet_hours_start if prefs else None,
|
||||
"end": prefs.quiet_hours_end if prefs else None
|
||||
}
|
||||
}
|
||||
599
backend/app/services/security_service.py
Normal file
599
backend/app/services/security_service.py
Normal file
@@ -0,0 +1,599 @@
|
||||
"""
|
||||
Security Service - Authentication, sessions, and protection
|
||||
"""
|
||||
|
||||
import secrets
|
||||
import hashlib
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Optional, Dict, Any, Tuple
|
||||
from sqlalchemy.orm import Session
|
||||
from sqlalchemy import and_, or_, func
|
||||
from loguru import logger
|
||||
|
||||
from ..models import (
|
||||
User, Role, ActiveSession, LoginAttempt, BlockedIP, SecuritySetting
|
||||
)
|
||||
|
||||
|
||||
def utcnow() -> datetime:
|
||||
"""Get current UTC time as timezone-aware datetime"""
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
class SecurityService:
|
||||
"""Service for security operations"""
|
||||
|
||||
# Cache for security settings
|
||||
_settings_cache: Dict[str, str] = {}
|
||||
_cache_time: datetime = None
|
||||
_cache_ttl = 60 # seconds
|
||||
|
||||
@classmethod
|
||||
def get_setting(cls, db: Session, key: str, default: str = None) -> str:
|
||||
"""Get security setting with caching"""
|
||||
# Check cache
|
||||
now = utcnow()
|
||||
if cls._cache_time and (now - cls._cache_time).seconds < cls._cache_ttl:
|
||||
if key in cls._settings_cache:
|
||||
return cls._settings_cache[key]
|
||||
|
||||
# Query from DB
|
||||
setting = db.query(SecuritySetting).filter(SecuritySetting.key == key).first()
|
||||
value = setting.value if setting else default
|
||||
|
||||
# Update cache
|
||||
cls._settings_cache[key] = value
|
||||
cls._cache_time = now
|
||||
|
||||
return value
|
||||
|
||||
@classmethod
|
||||
def get_setting_int(cls, db: Session, key: str, default: int = 0) -> int:
|
||||
"""Get security setting as integer"""
|
||||
value = cls.get_setting(db, key, str(default))
|
||||
try:
|
||||
return int(value)
|
||||
except (ValueError, TypeError):
|
||||
return default
|
||||
|
||||
@classmethod
|
||||
def get_setting_bool(cls, db: Session, key: str, default: bool = False) -> bool:
|
||||
"""Get security setting as boolean"""
|
||||
value = cls.get_setting(db, key, str(default).lower())
|
||||
|
||||
# Handle None/empty values gracefully
|
||||
if value is None:
|
||||
return default
|
||||
|
||||
# Accept real booleans from DB/cache
|
||||
if isinstance(value, bool):
|
||||
return value
|
||||
|
||||
return str(value).lower() in ('true', '1', 'yes', 'on')
|
||||
|
||||
@classmethod
|
||||
def update_setting(cls, db: Session, key: str, value: str) -> bool:
|
||||
"""Update security setting"""
|
||||
setting = db.query(SecuritySetting).filter(SecuritySetting.key == key).first()
|
||||
if setting:
|
||||
setting.value = value
|
||||
setting.updated_at = utcnow()
|
||||
else:
|
||||
setting = SecuritySetting(key=key, value=value)
|
||||
db.add(setting)
|
||||
|
||||
db.commit()
|
||||
|
||||
# Clear cache
|
||||
cls._settings_cache.pop(key, None)
|
||||
return True
|
||||
|
||||
# ==================== IP Blocking ====================
|
||||
|
||||
@staticmethod
|
||||
def is_ip_blocked(db: Session, ip_address: str) -> Tuple[bool, Optional[str]]:
|
||||
"""Check if IP is blocked, returns (is_blocked, reason)"""
|
||||
blocked = db.query(BlockedIP).filter(BlockedIP.ip_address == ip_address).first()
|
||||
|
||||
if not blocked:
|
||||
return False, None
|
||||
|
||||
if blocked.is_permanent:
|
||||
return True, blocked.reason
|
||||
|
||||
# Compare timezone-aware datetimes
|
||||
now = utcnow()
|
||||
if blocked.expires_at and blocked.expires_at > now:
|
||||
return True, blocked.reason
|
||||
|
||||
# Block expired, remove it
|
||||
db.delete(blocked)
|
||||
db.commit()
|
||||
return False, None
|
||||
|
||||
@staticmethod
|
||||
def block_ip(
|
||||
db: Session,
|
||||
ip_address: str,
|
||||
reason: str,
|
||||
blocked_by: str = "system",
|
||||
duration_minutes: int = 60,
|
||||
permanent: bool = False
|
||||
) -> BlockedIP:
|
||||
"""Block an IP address"""
|
||||
blocked = db.query(BlockedIP).filter(BlockedIP.ip_address == ip_address).first()
|
||||
|
||||
if blocked:
|
||||
blocked.reason = reason
|
||||
blocked.blocked_by = blocked_by
|
||||
blocked.blocked_at = utcnow()
|
||||
blocked.attempts_count += 1
|
||||
blocked.is_permanent = permanent
|
||||
if not permanent:
|
||||
blocked.expires_at = utcnow() + timedelta(minutes=duration_minutes)
|
||||
else:
|
||||
blocked = BlockedIP(
|
||||
ip_address=ip_address,
|
||||
reason=reason,
|
||||
blocked_by=blocked_by,
|
||||
expires_at=None if permanent else utcnow() + timedelta(minutes=duration_minutes),
|
||||
is_permanent=permanent,
|
||||
attempts_count=1
|
||||
)
|
||||
db.add(blocked)
|
||||
|
||||
db.commit()
|
||||
logger.warning(f"IP {ip_address} blocked: {reason}")
|
||||
return blocked
|
||||
|
||||
@staticmethod
|
||||
def unblock_ip(db: Session, ip_address: str) -> bool:
|
||||
"""Unblock an IP address"""
|
||||
blocked = db.query(BlockedIP).filter(BlockedIP.ip_address == ip_address).first()
|
||||
if blocked:
|
||||
db.delete(blocked)
|
||||
db.commit()
|
||||
logger.info(f"IP {ip_address} unblocked")
|
||||
return True
|
||||
return False
|
||||
|
||||
# ==================== Login Attempts ====================
|
||||
|
||||
@staticmethod
|
||||
def record_login_attempt(
|
||||
db: Session,
|
||||
ip_address: str,
|
||||
username: str = None,
|
||||
success: bool = False,
|
||||
failure_reason: str = None,
|
||||
user_agent: str = None
|
||||
) -> LoginAttempt:
|
||||
"""Record a login attempt"""
|
||||
attempt = LoginAttempt(
|
||||
username=username,
|
||||
ip_address=ip_address,
|
||||
user_agent=user_agent[:500] if user_agent else None,
|
||||
success=success,
|
||||
failure_reason=failure_reason
|
||||
)
|
||||
db.add(attempt)
|
||||
db.commit()
|
||||
return attempt
|
||||
|
||||
@classmethod
|
||||
def check_brute_force(cls, db: Session, ip_address: str, username: str = None) -> Tuple[bool, str]:
|
||||
"""
|
||||
Check for brute force attacks
|
||||
Returns (should_block, reason)
|
||||
"""
|
||||
threshold = cls.get_setting_int(db, "ip_block_threshold", 10)
|
||||
window_minutes = 30
|
||||
|
||||
# Count recent failed attempts from this IP
|
||||
since = utcnow() - timedelta(minutes=window_minutes)
|
||||
|
||||
failed_count = db.query(LoginAttempt).filter(
|
||||
and_(
|
||||
LoginAttempt.ip_address == ip_address,
|
||||
LoginAttempt.success == False,
|
||||
LoginAttempt.attempted_at > since
|
||||
)
|
||||
).count()
|
||||
|
||||
if failed_count >= threshold:
|
||||
return True, f"Too many failed login attempts ({failed_count})"
|
||||
|
||||
return False, None
|
||||
|
||||
# ==================== Session Management ====================
|
||||
|
||||
@staticmethod
|
||||
def generate_session_token() -> str:
|
||||
"""Generate a secure session token"""
|
||||
return secrets.token_hex(32)
|
||||
|
||||
@classmethod
|
||||
def create_session(
|
||||
cls,
|
||||
db: Session,
|
||||
user: User,
|
||||
ip_address: str = None,
|
||||
user_agent: str = None
|
||||
) -> Tuple[ActiveSession, bool]:
|
||||
"""
|
||||
Create a new session for user.
|
||||
Returns (session, was_other_session_terminated)
|
||||
"""
|
||||
session_timeout = cls.get_setting_int(db, "session_timeout_minutes", 60)
|
||||
|
||||
terminated_other = False
|
||||
|
||||
# Create new session
|
||||
token = cls.generate_session_token()
|
||||
expires_at = utcnow() + timedelta(minutes=session_timeout)
|
||||
|
||||
# Parse device info from user agent
|
||||
device_info = cls._parse_device_info(user_agent) if user_agent else None
|
||||
|
||||
session = ActiveSession(
|
||||
user_id=user.id,
|
||||
session_token=token,
|
||||
ip_address=ip_address,
|
||||
user_agent=user_agent[:500] if user_agent else None,
|
||||
device_info=device_info,
|
||||
expires_at=expires_at,
|
||||
is_active=True
|
||||
)
|
||||
|
||||
db.add(session)
|
||||
db.commit()
|
||||
db.refresh(session)
|
||||
|
||||
logger.info(f"Session created for user {user.username} from {ip_address}")
|
||||
|
||||
return session, terminated_other
|
||||
|
||||
@staticmethod
|
||||
def _parse_device_info(user_agent: str) -> str:
|
||||
"""Parse device info from user agent"""
|
||||
if not user_agent:
|
||||
return "Unknown"
|
||||
|
||||
ua = user_agent.lower()
|
||||
|
||||
# Browser detection
|
||||
browser = "Unknown"
|
||||
if "firefox" in ua:
|
||||
browser = "Firefox"
|
||||
elif "edg" in ua:
|
||||
browser = "Edge"
|
||||
elif "chrome" in ua:
|
||||
browser = "Chrome"
|
||||
elif "safari" in ua:
|
||||
browser = "Safari"
|
||||
elif "opera" in ua:
|
||||
browser = "Opera"
|
||||
|
||||
# OS detection
|
||||
os = "Unknown"
|
||||
if "windows" in ua:
|
||||
os = "Windows"
|
||||
elif "mac os" in ua or "macos" in ua:
|
||||
os = "macOS"
|
||||
elif "linux" in ua:
|
||||
os = "Linux"
|
||||
elif "android" in ua:
|
||||
os = "Android"
|
||||
elif "iphone" in ua or "ipad" in ua:
|
||||
os = "iOS"
|
||||
|
||||
return f"{browser} on {os}"
|
||||
|
||||
@staticmethod
|
||||
def validate_session(db: Session, token: str) -> Optional[ActiveSession]:
|
||||
"""Validate session token and return session if valid"""
|
||||
session = db.query(ActiveSession).filter(
|
||||
and_(
|
||||
ActiveSession.session_token == token,
|
||||
ActiveSession.is_active == True
|
||||
)
|
||||
).first()
|
||||
|
||||
if not session:
|
||||
return None
|
||||
|
||||
# Check expiration
|
||||
# Compare timezone-aware datetimes
|
||||
now = utcnow()
|
||||
if session.expires_at < now:
|
||||
session.is_active = False
|
||||
db.commit()
|
||||
return None
|
||||
|
||||
# Update last activity and extend session expiration (sliding expiration)
|
||||
session.last_activity = utcnow()
|
||||
# Get session timeout setting
|
||||
session_timeout = SecurityService.get_setting_int(db, "session_timeout_minutes", 60)
|
||||
session.expires_at = utcnow() + timedelta(minutes=session_timeout)
|
||||
db.commit()
|
||||
|
||||
return session
|
||||
|
||||
@staticmethod
|
||||
def terminate_session(db: Session, token: str) -> bool:
|
||||
"""Terminate a session"""
|
||||
session = db.query(ActiveSession).filter(
|
||||
ActiveSession.session_token == token
|
||||
).first()
|
||||
|
||||
if session:
|
||||
session.is_active = False
|
||||
db.commit()
|
||||
return True
|
||||
return False
|
||||
|
||||
@staticmethod
|
||||
def terminate_all_user_sessions(db: Session, user_id: int) -> int:
|
||||
"""Terminate all sessions for a user"""
|
||||
count = db.query(ActiveSession).filter(
|
||||
and_(
|
||||
ActiveSession.user_id == user_id,
|
||||
ActiveSession.is_active == True
|
||||
)
|
||||
).update({"is_active": False})
|
||||
db.commit()
|
||||
return count
|
||||
|
||||
@staticmethod
|
||||
def get_user_sessions(db: Session, user_id: int) -> list:
|
||||
"""Get all active sessions for a user"""
|
||||
return db.query(ActiveSession).filter(
|
||||
and_(
|
||||
ActiveSession.user_id == user_id,
|
||||
ActiveSession.is_active == True
|
||||
)
|
||||
).all()
|
||||
|
||||
@staticmethod
|
||||
def cleanup_expired_sessions(db: Session) -> int:
|
||||
"""Clean up expired sessions"""
|
||||
count = db.query(ActiveSession).filter(
|
||||
or_(
|
||||
ActiveSession.expires_at < utcnow(),
|
||||
ActiveSession.is_active == False
|
||||
)
|
||||
).delete()
|
||||
db.commit()
|
||||
logger.info(f"Cleaned up {count} expired sessions")
|
||||
return count
|
||||
|
||||
# ==================== Account Locking ====================
|
||||
|
||||
@classmethod
|
||||
def increment_failed_attempts(cls, db: Session, user: User) -> bool:
|
||||
"""
|
||||
Increment failed login attempts for user.
|
||||
Returns True if account was locked.
|
||||
"""
|
||||
max_attempts = cls.get_setting_int(db, "max_login_attempts", 5)
|
||||
lockout_minutes = cls.get_setting_int(db, "lockout_duration_minutes", 30)
|
||||
|
||||
user.failed_login_attempts += 1
|
||||
|
||||
if user.failed_login_attempts >= max_attempts:
|
||||
user.locked_until = utcnow() + timedelta(minutes=lockout_minutes)
|
||||
db.commit()
|
||||
logger.warning(f"User {user.username} locked out after {user.failed_login_attempts} failed attempts")
|
||||
return True
|
||||
|
||||
db.commit()
|
||||
return False
|
||||
|
||||
@staticmethod
|
||||
def reset_failed_attempts(db: Session, user: User):
|
||||
"""Reset failed login attempts after successful login"""
|
||||
user.failed_login_attempts = 0
|
||||
user.locked_until = None
|
||||
db.commit()
|
||||
|
||||
@staticmethod
|
||||
def is_account_locked(user: User) -> Tuple[bool, Optional[datetime]]:
|
||||
"""Check if account is locked, returns (is_locked, locked_until)"""
|
||||
if not user.locked_until:
|
||||
return False, None
|
||||
|
||||
# Compare timezone-aware datetimes
|
||||
if user.locked_until > utcnow():
|
||||
return True, user.locked_until
|
||||
|
||||
return False, None
|
||||
|
||||
# ==================== Role & Permission Management ====================
|
||||
|
||||
@staticmethod
|
||||
def get_role(db: Session, role_name: str) -> Optional[Role]:
|
||||
"""Get role by name"""
|
||||
return db.query(Role).filter(Role.name == role_name).first()
|
||||
|
||||
@staticmethod
|
||||
def get_all_roles(db: Session, include_inactive: bool = False) -> list:
|
||||
"""Get all roles"""
|
||||
query = db.query(Role)
|
||||
if not include_inactive:
|
||||
query = query.filter(Role.is_active == True)
|
||||
return query.order_by(Role.name).all()
|
||||
|
||||
@staticmethod
|
||||
def create_role(
|
||||
db: Session,
|
||||
name: str,
|
||||
display_name: str,
|
||||
description: str = None,
|
||||
permissions: dict = None
|
||||
) -> Role:
|
||||
"""Create a new role"""
|
||||
role = Role(
|
||||
name=name.lower(),
|
||||
display_name=display_name,
|
||||
description=description,
|
||||
permissions=permissions or {},
|
||||
is_system=False
|
||||
)
|
||||
db.add(role)
|
||||
db.commit()
|
||||
db.refresh(role)
|
||||
return role
|
||||
|
||||
@staticmethod
|
||||
def update_role(
|
||||
db: Session,
|
||||
role_id: int,
|
||||
display_name: str = None,
|
||||
description: str = None,
|
||||
permissions: dict = None
|
||||
) -> Optional[Role]:
|
||||
"""Update a role"""
|
||||
role = db.query(Role).filter(Role.id == role_id).first()
|
||||
if not role:
|
||||
return None
|
||||
|
||||
if display_name:
|
||||
role.display_name = display_name
|
||||
if description is not None:
|
||||
role.description = description
|
||||
if permissions is not None:
|
||||
role.permissions = permissions
|
||||
|
||||
role.updated_at = utcnow()
|
||||
db.commit()
|
||||
db.refresh(role)
|
||||
return role
|
||||
|
||||
@staticmethod
|
||||
def delete_role(db: Session, role_id: int) -> Tuple[bool, str]:
|
||||
"""Delete a role if it's not a system role"""
|
||||
role = db.query(Role).filter(Role.id == role_id).first()
|
||||
if not role:
|
||||
return False, "Role not found"
|
||||
|
||||
if role.is_system:
|
||||
return False, "Cannot delete system role"
|
||||
|
||||
# Check if any users have this role
|
||||
user_count = db.query(User).filter(User.role_id == role_id).count()
|
||||
if user_count > 0:
|
||||
return False, f"Cannot delete role with {user_count} assigned users"
|
||||
|
||||
db.delete(role)
|
||||
db.commit()
|
||||
return True, "Role deleted"
|
||||
|
||||
@staticmethod
|
||||
def get_all_permissions() -> Dict[str, Dict[str, str]]:
|
||||
"""
|
||||
Get all available permissions grouped by category.
|
||||
Returns permissions in legacy format for backwards compatibility with UI.
|
||||
"""
|
||||
try:
|
||||
from ..rbac import get_permission_categories_legacy
|
||||
return get_permission_categories_legacy()
|
||||
except ImportError:
|
||||
# Fallback to static list if RBAC module not available
|
||||
return {
|
||||
"Dashboard": {
|
||||
"dashboard.view": "View dashboard"
|
||||
},
|
||||
"Proxmox Servers": {
|
||||
"proxmox.view": "View servers",
|
||||
"proxmox.manage": "Manage server settings",
|
||||
"proxmox.servers.add": "Add new servers",
|
||||
"proxmox.servers.edit": "Edit servers",
|
||||
"proxmox.servers.delete": "Delete servers"
|
||||
},
|
||||
"Virtual Machines": {
|
||||
"vms.view": "View VMs",
|
||||
"vms.create": "Create VMs",
|
||||
"vms.start": "Start VMs",
|
||||
"vms.stop": "Stop VMs",
|
||||
"vms.restart": "Restart VMs",
|
||||
"vms.delete": "Delete VMs",
|
||||
"vms.console": "Access VM console",
|
||||
"vms.migrate": "Migrate VMs"
|
||||
},
|
||||
"Templates": {
|
||||
"templates.view": "View templates",
|
||||
"templates.manage": "Manage templates"
|
||||
},
|
||||
"IPAM": {
|
||||
"ipam.view": "View IPAM",
|
||||
"ipam.manage": "Manage IPAM"
|
||||
},
|
||||
"Logs": {
|
||||
"logs.view": "View logs",
|
||||
"logs.export": "Export logs",
|
||||
"logs.delete": "Delete logs"
|
||||
},
|
||||
"Settings": {
|
||||
"settings.view": "View settings",
|
||||
"settings.panel": "Panel settings",
|
||||
"settings.security": "Security settings"
|
||||
},
|
||||
"Users": {
|
||||
"users.view": "View users",
|
||||
"users.create": "Create users",
|
||||
"users.edit": "Edit users",
|
||||
"users.delete": "Delete users"
|
||||
},
|
||||
"Roles": {
|
||||
"roles.view": "View roles",
|
||||
"roles.manage": "Manage roles"
|
||||
},
|
||||
"Notifications": {
|
||||
"notifications.manage": "Manage notifications"
|
||||
}
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def get_all_permissions_v2() -> Dict[str, Dict[str, str]]:
|
||||
"""
|
||||
Get all available permissions in new format grouped by category.
|
||||
Uses new resource:action format.
|
||||
"""
|
||||
try:
|
||||
from ..rbac import get_permission_categories
|
||||
return get_permission_categories()
|
||||
except ImportError:
|
||||
return SecurityService.get_all_permissions()
|
||||
|
||||
# ==================== Password Validation ====================
|
||||
|
||||
@classmethod
|
||||
def validate_password(cls, db: Session, password: str) -> Tuple[bool, list]:
|
||||
"""
|
||||
Validate password against security requirements.
|
||||
Returns (is_valid, list_of_errors)
|
||||
"""
|
||||
errors = []
|
||||
|
||||
min_length = cls.get_setting_int(db, "password_min_length", 8)
|
||||
require_upper = cls.get_setting_bool(db, "password_require_uppercase", True)
|
||||
require_lower = cls.get_setting_bool(db, "password_require_lowercase", True)
|
||||
require_numbers = cls.get_setting_bool(db, "password_require_numbers", True)
|
||||
require_special = cls.get_setting_bool(db, "password_require_special", False)
|
||||
|
||||
if len(password) < min_length:
|
||||
errors.append(f"Password must be at least {min_length} characters")
|
||||
|
||||
if require_upper and not any(c.isupper() for c in password):
|
||||
errors.append("Password must contain at least one uppercase letter")
|
||||
|
||||
if require_lower and not any(c.islower() for c in password):
|
||||
errors.append("Password must contain at least one lowercase letter")
|
||||
|
||||
if require_numbers and not any(c.isdigit() for c in password):
|
||||
errors.append("Password must contain at least one number")
|
||||
|
||||
if require_special and not any(c in "!@#$%^&*()_+-=[]{}|;:,.<>?" for c in password):
|
||||
errors.append("Password must contain at least one special character")
|
||||
|
||||
return len(errors) == 0, errors
|
||||
338
backend/app/services/task_queue_service.py
Normal file
338
backend/app/services/task_queue_service.py
Normal file
@@ -0,0 +1,338 @@
|
||||
"""
|
||||
Task Queue Service for bulk VM/Container operations
|
||||
Processes tasks from the queue in background
|
||||
"""
|
||||
|
||||
from datetime import datetime, timezone
|
||||
from typing import List, Dict, Any, Optional
|
||||
from loguru import logger
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
|
||||
def utcnow() -> datetime:
|
||||
"""Get current UTC time as timezone-aware datetime"""
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
try:
|
||||
from backend.app.db import SessionLocal
|
||||
from backend.app.models import TaskQueue, ProxmoxServer, User
|
||||
from backend.app.proxmox_client import ProxmoxClient
|
||||
except ImportError:
|
||||
from app.db import SessionLocal
|
||||
from app.models import TaskQueue, ProxmoxServer, User
|
||||
from app.proxmox_client import ProxmoxClient
|
||||
|
||||
|
||||
class TaskQueueService:
|
||||
"""Service for managing and processing bulk operation tasks"""
|
||||
|
||||
# Valid task types
|
||||
TASK_TYPES = ['bulk_start', 'bulk_stop', 'bulk_restart', 'bulk_delete', 'bulk_shutdown']
|
||||
|
||||
@staticmethod
|
||||
def create_task(
|
||||
db: Session,
|
||||
task_type: str,
|
||||
user_id: int,
|
||||
items: List[Dict[str, Any]]
|
||||
) -> TaskQueue:
|
||||
"""
|
||||
Create a new bulk operation task
|
||||
|
||||
Args:
|
||||
db: Database session
|
||||
task_type: Type of operation (bulk_start, bulk_stop, etc.)
|
||||
user_id: ID of user who initiated
|
||||
items: List of VMs/containers to process
|
||||
Each item: {server_id, vmid, vm_type, name, node}
|
||||
"""
|
||||
if task_type not in TaskQueueService.TASK_TYPES:
|
||||
raise ValueError(f"Invalid task type: {task_type}")
|
||||
|
||||
if not items:
|
||||
raise ValueError("No items provided for bulk operation")
|
||||
|
||||
task = TaskQueue(
|
||||
task_type=task_type,
|
||||
status='pending',
|
||||
user_id=user_id,
|
||||
total_items=len(items),
|
||||
completed_items=0,
|
||||
failed_items=0,
|
||||
task_data=items,
|
||||
results=[]
|
||||
)
|
||||
db.add(task)
|
||||
db.commit()
|
||||
db.refresh(task)
|
||||
|
||||
logger.info(f"[TASK QUEUE] Created task #{task.id}: {task_type} with {len(items)} items")
|
||||
return task
|
||||
|
||||
@staticmethod
|
||||
def get_pending_tasks(db: Session) -> List[TaskQueue]:
|
||||
"""Get all pending tasks ordered by creation time"""
|
||||
return db.query(TaskQueue).filter(
|
||||
TaskQueue.status == 'pending'
|
||||
).order_by(TaskQueue.created_at.asc()).all()
|
||||
|
||||
@staticmethod
|
||||
def get_running_tasks(db: Session) -> List[TaskQueue]:
|
||||
"""Get all currently running tasks"""
|
||||
return db.query(TaskQueue).filter(
|
||||
TaskQueue.status == 'running'
|
||||
).all()
|
||||
|
||||
@staticmethod
|
||||
def get_user_tasks(db: Session, user_id: int, limit: int = 20) -> List[TaskQueue]:
|
||||
"""Get recent tasks for a user"""
|
||||
return db.query(TaskQueue).filter(
|
||||
TaskQueue.user_id == user_id
|
||||
).order_by(TaskQueue.created_at.desc()).limit(limit).all()
|
||||
|
||||
@staticmethod
|
||||
def get_active_tasks(db: Session) -> List[TaskQueue]:
|
||||
"""Get all active (pending or running) tasks"""
|
||||
return db.query(TaskQueue).filter(
|
||||
TaskQueue.status.in_(['pending', 'running'])
|
||||
).order_by(TaskQueue.created_at.asc()).all()
|
||||
|
||||
@staticmethod
|
||||
def cancel_task(db: Session, task_id: int, user_id: int) -> bool:
|
||||
"""Cancel a pending task"""
|
||||
task = db.query(TaskQueue).filter(
|
||||
TaskQueue.id == task_id,
|
||||
TaskQueue.user_id == user_id,
|
||||
TaskQueue.status == 'pending'
|
||||
).first()
|
||||
|
||||
if not task:
|
||||
return False
|
||||
|
||||
task.status = 'cancelled'
|
||||
task.completed_at = utcnow()
|
||||
db.commit()
|
||||
|
||||
logger.info(f"[TASK QUEUE] Task #{task_id} cancelled by user {user_id}")
|
||||
return True
|
||||
|
||||
|
||||
class TaskQueueProcessor:
|
||||
"""Processor that executes tasks from the queue"""
|
||||
|
||||
def __init__(self):
|
||||
self._proxmox_clients: Dict[int, ProxmoxClient] = {}
|
||||
|
||||
def _get_proxmox_client(self, db: Session, server_id: int) -> Optional[ProxmoxClient]:
|
||||
"""Get or create Proxmox client for server"""
|
||||
if server_id in self._proxmox_clients:
|
||||
client = self._proxmox_clients[server_id]
|
||||
if client.is_connected():
|
||||
return client
|
||||
|
||||
server = db.query(ProxmoxServer).filter(ProxmoxServer.id == server_id).first()
|
||||
if not server:
|
||||
return None
|
||||
|
||||
try:
|
||||
host = server.ip_address or server.hostname
|
||||
if server.port and server.port != 8006:
|
||||
host = f"{host}:{server.port}"
|
||||
|
||||
if server.use_password and server.password:
|
||||
client = ProxmoxClient(
|
||||
host=host,
|
||||
user=server.api_user,
|
||||
password=server.password,
|
||||
verify_ssl=server.verify_ssl
|
||||
)
|
||||
elif server.api_token_name and server.api_token_value:
|
||||
client = ProxmoxClient(
|
||||
host=host,
|
||||
user=server.api_user,
|
||||
token_name=server.api_token_name,
|
||||
token_value=server.api_token_value,
|
||||
verify_ssl=server.verify_ssl
|
||||
)
|
||||
else:
|
||||
return None
|
||||
|
||||
self._proxmox_clients[server_id] = client
|
||||
return client
|
||||
except Exception as e:
|
||||
logger.error(f"[TASK QUEUE] Failed to connect to server {server_id}: {e}")
|
||||
return None
|
||||
|
||||
def _execute_vm_action(
|
||||
self,
|
||||
client: ProxmoxClient,
|
||||
action: str,
|
||||
vmid: int,
|
||||
vm_type: str,
|
||||
node: str
|
||||
) -> tuple[bool, str]:
|
||||
"""Execute action on VM/container"""
|
||||
try:
|
||||
if vm_type == 'lxc':
|
||||
if action == 'start':
|
||||
client.start_container(node, vmid)
|
||||
elif action == 'stop':
|
||||
client.stop_container(node, vmid)
|
||||
elif action == 'restart':
|
||||
client.restart_container(node, vmid)
|
||||
elif action == 'shutdown':
|
||||
# Shutdown = graceful stop
|
||||
client.stop_container(node, vmid)
|
||||
elif action == 'delete':
|
||||
client.delete_container(node, vmid)
|
||||
else:
|
||||
return False, f"Unknown action: {action}"
|
||||
else: # qemu
|
||||
if action == 'start':
|
||||
client.start_vm(node, vmid)
|
||||
elif action == 'stop':
|
||||
client.stop_vm(node, vmid)
|
||||
elif action == 'restart':
|
||||
client.restart_vm(node, vmid)
|
||||
elif action == 'shutdown':
|
||||
# Shutdown = graceful stop
|
||||
client.stop_vm(node, vmid)
|
||||
elif action == 'delete':
|
||||
client.delete_vm(node, vmid)
|
||||
else:
|
||||
return False, f"Unknown action: {action}"
|
||||
|
||||
return True, "OK"
|
||||
except Exception as e:
|
||||
return False, str(e)
|
||||
|
||||
def process_task(self, task: TaskQueue) -> None:
|
||||
"""Process a single task"""
|
||||
db = SessionLocal()
|
||||
try:
|
||||
# Mark as running
|
||||
task = db.query(TaskQueue).filter(TaskQueue.id == task.id).first()
|
||||
if not task or task.status != 'pending':
|
||||
return
|
||||
|
||||
task.status = 'running'
|
||||
task.started_at = utcnow()
|
||||
db.commit()
|
||||
|
||||
logger.info(f"[TASK QUEUE] Starting task #{task.id}: {task.task_type}")
|
||||
|
||||
# Determine action from task type
|
||||
action_map = {
|
||||
'bulk_start': 'start',
|
||||
'bulk_stop': 'stop',
|
||||
'bulk_restart': 'restart',
|
||||
'bulk_shutdown': 'shutdown',
|
||||
'bulk_delete': 'delete',
|
||||
}
|
||||
action = action_map.get(task.task_type)
|
||||
|
||||
if not action:
|
||||
task.status = 'failed'
|
||||
task.error_message = f"Unknown task type: {task.task_type}"
|
||||
task.completed_at = utcnow()
|
||||
db.commit()
|
||||
return
|
||||
|
||||
results = []
|
||||
items = task.task_data or []
|
||||
|
||||
for item in items:
|
||||
server_id = item.get('server_id')
|
||||
vmid = item.get('vmid')
|
||||
vm_type = item.get('vm_type', 'qemu')
|
||||
node = item.get('node', '')
|
||||
name = item.get('name', f'{vm_type.upper()}-{vmid}')
|
||||
|
||||
client = self._get_proxmox_client(db, server_id)
|
||||
if not client:
|
||||
results.append({
|
||||
'server_id': server_id,
|
||||
'vmid': vmid,
|
||||
'name': name,
|
||||
'success': False,
|
||||
'message': 'Failed to connect to Proxmox server'
|
||||
})
|
||||
task.failed_items += 1
|
||||
else:
|
||||
success, message = self._execute_vm_action(client, action, vmid, vm_type, node)
|
||||
results.append({
|
||||
'server_id': server_id,
|
||||
'vmid': vmid,
|
||||
'name': name,
|
||||
'success': success,
|
||||
'message': message
|
||||
})
|
||||
if success:
|
||||
task.completed_items += 1
|
||||
else:
|
||||
task.failed_items += 1
|
||||
|
||||
# Update progress
|
||||
task.results = results
|
||||
db.commit()
|
||||
|
||||
# Mark as completed
|
||||
task.status = 'completed'
|
||||
task.completed_at = utcnow()
|
||||
db.commit()
|
||||
|
||||
logger.info(f"[TASK QUEUE] Completed task #{task.id}: {task.completed_items} success, {task.failed_items} failed")
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"[TASK QUEUE] Task #{task.id} failed with error: {e}")
|
||||
try:
|
||||
task.status = 'failed'
|
||||
task.error_message = str(e)
|
||||
task.completed_at = utcnow()
|
||||
db.commit()
|
||||
except:
|
||||
pass
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
def process_pending_tasks(self) -> int:
|
||||
"""Process all pending tasks. Returns number of tasks processed."""
|
||||
db = SessionLocal()
|
||||
try:
|
||||
# Get pending tasks
|
||||
pending_tasks = TaskQueueService.get_pending_tasks(db)
|
||||
|
||||
if not pending_tasks:
|
||||
return 0
|
||||
|
||||
# Check if there's already a running task
|
||||
running_tasks = TaskQueueService.get_running_tasks(db)
|
||||
if running_tasks:
|
||||
logger.debug(f"[TASK QUEUE] {len(running_tasks)} task(s) already running, skipping")
|
||||
return 0
|
||||
|
||||
# Process first pending task
|
||||
task = pending_tasks[0]
|
||||
db.close() # Close before processing (will create new session)
|
||||
|
||||
self.process_task(task)
|
||||
return 1
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"[TASK QUEUE] Error processing pending tasks: {e}")
|
||||
return 0
|
||||
finally:
|
||||
try:
|
||||
db.close()
|
||||
except:
|
||||
pass
|
||||
|
||||
|
||||
# Global processor instance
|
||||
task_processor = TaskQueueProcessor()
|
||||
|
||||
|
||||
def process_task_queue():
|
||||
"""Function to be called by scheduler to process queue"""
|
||||
return task_processor.process_pending_tasks()
|
||||
307
backend/app/services/update_service.py
Normal file
307
backend/app/services/update_service.py
Normal file
@@ -0,0 +1,307 @@
|
||||
"""
|
||||
Update Service - Check for updates and perform system updates
|
||||
"""
|
||||
import os
|
||||
import subprocess
|
||||
import asyncio
|
||||
import logging
|
||||
from typing import Optional, Dict, Any
|
||||
from datetime import datetime
|
||||
import httpx
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Путь к корню проекта (монтируется через volume или хост)
|
||||
# В Docker это /project, на хосте - определяется через переменную окружения
|
||||
PROJECT_ROOT = os.environ.get('PROJECT_ROOT', '/project')
|
||||
VERSION_FILE = os.path.join(PROJECT_ROOT, "VERSION")
|
||||
|
||||
# Для fallback - путь внутри контейнера где может быть VERSION
|
||||
CONTAINER_VERSION_FILE = "/app/VERSION"
|
||||
|
||||
# Статус обновления (in-memory)
|
||||
update_status = {
|
||||
"is_updating": False,
|
||||
"started_at": None,
|
||||
"stage": None,
|
||||
"progress": 0,
|
||||
"error": None,
|
||||
"completed": False
|
||||
}
|
||||
|
||||
|
||||
def get_current_version() -> str:
|
||||
"""Получить текущую версию из файла VERSION"""
|
||||
# Сначала пробуем файл из проекта (если монтирован)
|
||||
if os.path.exists(VERSION_FILE):
|
||||
try:
|
||||
with open(VERSION_FILE, "r") as f:
|
||||
return f.read().strip()
|
||||
except Exception as e:
|
||||
logger.error(f"Error reading VERSION file from project: {e}")
|
||||
|
||||
# Fallback - читаем из контейнера
|
||||
if os.path.exists(CONTAINER_VERSION_FILE):
|
||||
try:
|
||||
with open(CONTAINER_VERSION_FILE, "r") as f:
|
||||
return f.read().strip()
|
||||
except Exception as e:
|
||||
logger.error(f"Error reading VERSION file from container: {e}")
|
||||
|
||||
return "unknown"
|
||||
|
||||
|
||||
def is_git_available() -> bool:
|
||||
"""Проверить, доступен ли git"""
|
||||
try:
|
||||
result = subprocess.run(
|
||||
["git", "--version"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=5
|
||||
)
|
||||
return result.returncode == 0
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def is_project_mounted() -> bool:
|
||||
"""Проверить, смонтирован ли проект с .git"""
|
||||
git_dir = os.path.join(PROJECT_ROOT, ".git")
|
||||
return os.path.exists(git_dir)
|
||||
|
||||
|
||||
def ensure_safe_directory():
|
||||
"""Добавить PROJECT_ROOT в git safe.directory"""
|
||||
try:
|
||||
subprocess.run(
|
||||
["git", "config", "--global", "--add", "safe.directory", PROJECT_ROOT],
|
||||
capture_output=True,
|
||||
timeout=5
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
async def check_for_updates() -> Dict[str, Any]:
|
||||
"""
|
||||
Проверить наличие обновлений
|
||||
Сравнивает локальную версию с удалённой
|
||||
"""
|
||||
current_version = get_current_version()
|
||||
|
||||
result = {
|
||||
"current_version": current_version,
|
||||
"latest_version": None,
|
||||
"update_available": False,
|
||||
"changelog": None,
|
||||
"error": None,
|
||||
"git_available": is_git_available(),
|
||||
"project_mounted": is_project_mounted()
|
||||
}
|
||||
|
||||
# Проверяем доступность git и проекта
|
||||
if not result["git_available"]:
|
||||
result["error"] = "Git is not installed in container. Mount project directory with docker-compose volume."
|
||||
return result
|
||||
|
||||
if not result["project_mounted"]:
|
||||
result["error"] = "Project directory not mounted. Add volume mount in docker-compose.yml: ./:/project"
|
||||
return result
|
||||
|
||||
# Добавляем safe.directory для git
|
||||
ensure_safe_directory()
|
||||
|
||||
try:
|
||||
# Fetch последних изменений без merge
|
||||
fetch_result = subprocess.run(
|
||||
["git", "fetch", "origin", "main"],
|
||||
cwd=PROJECT_ROOT,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=30
|
||||
)
|
||||
|
||||
if fetch_result.returncode != 0:
|
||||
result["error"] = f"Failed to fetch updates: {fetch_result.stderr}"
|
||||
return result
|
||||
|
||||
# Получить версию из удалённого репозитория
|
||||
remote_version_result = subprocess.run(
|
||||
["git", "show", "origin/main:VERSION"],
|
||||
cwd=PROJECT_ROOT,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=10
|
||||
)
|
||||
|
||||
if remote_version_result.returncode == 0:
|
||||
result["latest_version"] = remote_version_result.stdout.strip()
|
||||
else:
|
||||
result["error"] = "Failed to get remote version"
|
||||
return result
|
||||
|
||||
# Сравнить версии
|
||||
if result["latest_version"] != current_version:
|
||||
result["update_available"] = True
|
||||
|
||||
# Получить changelog из удалённого репозитория
|
||||
changelog_result = subprocess.run(
|
||||
["git", "show", "origin/main:CHANGELOG.md"],
|
||||
cwd=PROJECT_ROOT,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=10
|
||||
)
|
||||
|
||||
if changelog_result.returncode == 0:
|
||||
# Извлекаем только последнюю версию из changelog
|
||||
changelog_lines = changelog_result.stdout.split('\n')
|
||||
latest_changelog = []
|
||||
in_latest_version = False
|
||||
version_count = 0
|
||||
|
||||
for line in changelog_lines:
|
||||
if line.startswith('## [v'):
|
||||
version_count += 1
|
||||
if version_count == 1:
|
||||
in_latest_version = True
|
||||
elif version_count == 2:
|
||||
break
|
||||
|
||||
if in_latest_version:
|
||||
latest_changelog.append(line)
|
||||
|
||||
result["changelog"] = '\n'.join(latest_changelog)
|
||||
|
||||
# Проверить количество коммитов позади
|
||||
behind_result = subprocess.run(
|
||||
["git", "rev-list", "--count", "HEAD..origin/main"],
|
||||
cwd=PROJECT_ROOT,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=10
|
||||
)
|
||||
|
||||
if behind_result.returncode == 0:
|
||||
result["commits_behind"] = int(behind_result.stdout.strip())
|
||||
|
||||
except subprocess.TimeoutExpired:
|
||||
result["error"] = "Timeout while checking for updates"
|
||||
except Exception as e:
|
||||
result["error"] = str(e)
|
||||
logger.error(f"Error checking for updates: {e}")
|
||||
|
||||
return result
|
||||
|
||||
|
||||
def get_update_status() -> Dict[str, Any]:
|
||||
"""Получить текущий статус обновления"""
|
||||
return update_status.copy()
|
||||
|
||||
|
||||
async def perform_update() -> Dict[str, Any]:
|
||||
"""
|
||||
Выполнить обновление системы
|
||||
1. Git pull
|
||||
2. Docker compose build
|
||||
3. Docker compose up
|
||||
"""
|
||||
global update_status
|
||||
|
||||
if update_status["is_updating"]:
|
||||
return {"success": False, "error": "Update already in progress"}
|
||||
|
||||
# Проверяем доступность
|
||||
if not is_git_available():
|
||||
return {"success": False, "error": "Git not available"}
|
||||
|
||||
if not is_project_mounted():
|
||||
return {"success": False, "error": "Project not mounted"}
|
||||
|
||||
# Добавляем safe.directory для git
|
||||
ensure_safe_directory()
|
||||
|
||||
# Сбросить статус
|
||||
update_status = {
|
||||
"is_updating": True,
|
||||
"started_at": datetime.now().isoformat(),
|
||||
"stage": "initializing",
|
||||
"progress": 0,
|
||||
"error": None,
|
||||
"completed": False
|
||||
}
|
||||
|
||||
try:
|
||||
# Stage 1: Git pull (10%)
|
||||
update_status["stage"] = "pulling"
|
||||
update_status["progress"] = 10
|
||||
|
||||
pull_result = subprocess.run(
|
||||
["git", "pull", "origin", "main"],
|
||||
cwd=PROJECT_ROOT,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=120
|
||||
)
|
||||
|
||||
if pull_result.returncode != 0:
|
||||
raise Exception(f"Git pull failed: {pull_result.stderr}")
|
||||
|
||||
# Stage 2: Docker build (50%)
|
||||
update_status["stage"] = "building"
|
||||
update_status["progress"] = 30
|
||||
|
||||
# Запускаем rebuild в фоне - это перезапустит сам контейнер
|
||||
# Используем nohup чтобы процесс продолжился после рестарта
|
||||
build_script = f"""
|
||||
cd {PROJECT_ROOT}
|
||||
docker compose up -d --build app 2>&1 | tee /tmp/update.log
|
||||
"""
|
||||
|
||||
# Записываем скрипт обновления
|
||||
script_path = "/tmp/update_panel.sh"
|
||||
with open(script_path, "w") as f:
|
||||
f.write(build_script)
|
||||
os.chmod(script_path, 0o755)
|
||||
|
||||
# Запускаем скрипт через nohup
|
||||
subprocess.Popen(
|
||||
["nohup", "sh", script_path],
|
||||
cwd=PROJECT_ROOT,
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
start_new_session=True
|
||||
)
|
||||
|
||||
update_status["stage"] = "restarting"
|
||||
update_status["progress"] = 80
|
||||
|
||||
return {
|
||||
"success": True,
|
||||
"message": "Update started. The panel will restart shortly."
|
||||
}
|
||||
|
||||
except subprocess.TimeoutExpired:
|
||||
update_status["error"] = "Update timeout"
|
||||
update_status["is_updating"] = False
|
||||
return {"success": False, "error": "Update timeout"}
|
||||
except Exception as e:
|
||||
update_status["error"] = str(e)
|
||||
update_status["is_updating"] = False
|
||||
logger.error(f"Update failed: {e}")
|
||||
return {"success": False, "error": str(e)}
|
||||
|
||||
|
||||
def reset_update_status():
|
||||
"""Сбросить статус обновления"""
|
||||
global update_status
|
||||
update_status = {
|
||||
"is_updating": False,
|
||||
"started_at": None,
|
||||
"stage": None,
|
||||
"progress": 0,
|
||||
"error": None,
|
||||
"completed": False
|
||||
}
|
||||
|
||||
419
backend/app/ssh_client.py
Normal file
419
backend/app/ssh_client.py
Normal file
@@ -0,0 +1,419 @@
|
||||
import logging
|
||||
import asyncio
|
||||
from typing import Dict, Optional, Union
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import paramiko
|
||||
from paramiko.ssh_exception import SSHException, NoValidConnectionsError
|
||||
import socket
|
||||
from functools import lru_cache
|
||||
import time
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Thread pool for blocking SSH operations
|
||||
ssh_executor = ThreadPoolExecutor(max_workers=10, thread_name_prefix="ssh_")
|
||||
|
||||
|
||||
class SSHClient:
|
||||
"""Улучшенный SSH клиент для подключения к серверам с кешированием"""
|
||||
|
||||
# Connection cache
|
||||
_connections = {}
|
||||
_connection_times = {}
|
||||
|
||||
def __init__(self, hostname: str, port: int = 22, username: str = "root",
|
||||
key_path: Optional[str] = None, timeout: int = 10, max_retries: int = 3):
|
||||
self.hostname = hostname
|
||||
self.port = port
|
||||
self.username = username
|
||||
self.key_path = key_path
|
||||
self.timeout = timeout
|
||||
self.max_retries = max_retries
|
||||
self.client = None
|
||||
self.connection_key = f"{hostname}:{port}:{username}"
|
||||
self._connected = False
|
||||
|
||||
def _get_cached_connection(self) -> Optional[paramiko.SSHClient]:
|
||||
"""Get cached connection if available and valid"""
|
||||
if self.connection_key in self._connections:
|
||||
client = self._connections[self.connection_key]
|
||||
connection_time = self._connection_times.get(self.connection_key, 0)
|
||||
|
||||
# Check if connection is still valid (max 5 minutes)
|
||||
if time.time() - connection_time < 300:
|
||||
try:
|
||||
# Test connection with a simple command
|
||||
transport = client.get_transport()
|
||||
if transport and transport.is_active():
|
||||
return client
|
||||
except:
|
||||
pass
|
||||
|
||||
# Remove invalid connection
|
||||
self._cleanup_connection()
|
||||
|
||||
return None
|
||||
|
||||
def _cache_connection(self, client: paramiko.SSHClient):
|
||||
"""Cache successful connection"""
|
||||
self._connections[self.connection_key] = client
|
||||
self._connection_times[self.connection_key] = time.time()
|
||||
|
||||
def _cleanup_connection(self):
|
||||
"""Clean up cached connection"""
|
||||
if self.connection_key in self._connections:
|
||||
try:
|
||||
self._connections[self.connection_key].close()
|
||||
except:
|
||||
pass
|
||||
del self._connections[self.connection_key]
|
||||
del self._connection_times[self.connection_key]
|
||||
|
||||
def connect(self) -> bool:
|
||||
"""Установить SSH соединение с повторными попытками"""
|
||||
# Try to get cached connection first
|
||||
cached_client = self._get_cached_connection()
|
||||
if cached_client:
|
||||
self.client = cached_client
|
||||
self._connected = True
|
||||
logger.debug(f"Using cached SSH connection to {self.hostname}")
|
||||
return True
|
||||
|
||||
for attempt in range(self.max_retries):
|
||||
try:
|
||||
client = paramiko.SSHClient()
|
||||
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
|
||||
connect_kwargs = {
|
||||
'hostname': self.hostname,
|
||||
'port': self.port,
|
||||
'username': self.username,
|
||||
'timeout': self.timeout,
|
||||
'banner_timeout': self.timeout,
|
||||
'auth_timeout': self.timeout,
|
||||
}
|
||||
|
||||
# Try key authentication first
|
||||
if self.key_path:
|
||||
try:
|
||||
connect_kwargs['key_filename'] = self.key_path
|
||||
client.connect(**connect_kwargs, look_for_keys=False, allow_agent=False)
|
||||
except paramiko.AuthenticationException:
|
||||
logger.debug(f"Key auth failed for {self.hostname}, trying other methods")
|
||||
# Remove key and try other methods
|
||||
del connect_kwargs['key_filename']
|
||||
client.connect(**connect_kwargs, look_for_keys=True, allow_agent=True)
|
||||
else:
|
||||
client.connect(**connect_kwargs, look_for_keys=True, allow_agent=True)
|
||||
|
||||
self.client = client
|
||||
self._connected = True
|
||||
self._cache_connection(client)
|
||||
logger.info(f"Successfully connected to {self.hostname} (attempt {attempt + 1})")
|
||||
return True
|
||||
|
||||
except paramiko.AuthenticationException as e:
|
||||
logger.error(f"Authentication failed for {self.hostname}: {e}")
|
||||
return False
|
||||
except (SSHException, NoValidConnectionsError, socket.timeout,
|
||||
socket.error, ConnectionRefusedError) as e:
|
||||
logger.warning(f"Connection attempt {attempt + 1} failed for {self.hostname}: {e}")
|
||||
if attempt == self.max_retries - 1:
|
||||
logger.error(f"All connection attempts failed for {self.hostname}")
|
||||
return False
|
||||
# Wait before retry
|
||||
time.sleep(2 ** attempt) # Exponential backoff
|
||||
except Exception as e:
|
||||
logger.error(f"Unexpected error connecting to {self.hostname}: {e}")
|
||||
return False
|
||||
|
||||
return False
|
||||
|
||||
def execute(self, command: str, return_exit_code: bool = False) -> Union[Optional[str], tuple]:
|
||||
"""Выполнить команду на сервере"""
|
||||
if not self._connected or not self.client:
|
||||
if not self.connect():
|
||||
return (None, -1) if return_exit_code else None
|
||||
|
||||
try:
|
||||
stdin, stdout, stderr = self.client.exec_command(
|
||||
command, timeout=self.timeout, get_pty=False
|
||||
)
|
||||
|
||||
# Wait for command to complete
|
||||
exit_code = stdout.channel.recv_exit_status()
|
||||
|
||||
output = stdout.read().decode('utf-8', errors='ignore').strip()
|
||||
error_output = stderr.read().decode('utf-8', errors='ignore').strip()
|
||||
|
||||
if error_output and exit_code != 0:
|
||||
logger.warning(f"Command failed on {self.hostname} (exit {exit_code}): {error_output}")
|
||||
return (error_output, exit_code) if return_exit_code else None
|
||||
|
||||
return (output, exit_code) if return_exit_code else output
|
||||
|
||||
except socket.timeout:
|
||||
logger.error(f"Command timeout on {self.hostname}: {command}")
|
||||
return (None, -1) if return_exit_code else None
|
||||
except Exception as e:
|
||||
logger.error(f"Error executing command on {self.hostname}: {e}")
|
||||
# Connection might be broken, clean up
|
||||
self._connected = False
|
||||
self._cleanup_connection()
|
||||
return (None, -1) if return_exit_code else None
|
||||
|
||||
def is_connected(self) -> bool:
|
||||
"""Check if connection is active"""
|
||||
if not self.client or not self._connected:
|
||||
return False
|
||||
try:
|
||||
transport = self.client.get_transport()
|
||||
return transport and transport.is_active()
|
||||
except:
|
||||
return False
|
||||
|
||||
def close(self):
|
||||
"""Закрыть SSH соединение"""
|
||||
self._connected = False
|
||||
# Don't close cached connections immediately
|
||||
self.client = None
|
||||
|
||||
def force_close(self):
|
||||
"""Принудительно закрыть соединение"""
|
||||
self._connected = False
|
||||
self._cleanup_connection()
|
||||
self.client = None
|
||||
|
||||
def __enter__(self):
|
||||
self.connect()
|
||||
return self
|
||||
|
||||
def __exit__(self, exc_type, exc_val, exc_tb):
|
||||
self.close()
|
||||
|
||||
def get_interactive_shell(self, term: str = "xterm", width: int = 80, height: int = 24):
|
||||
"""
|
||||
Создать интерактивную shell сессию для WebSocket terminal
|
||||
|
||||
Args:
|
||||
term: Тип терминала (xterm, vt100, etc)
|
||||
width: Ширина терминала в символах
|
||||
height: Высота терминала в строках
|
||||
|
||||
Returns:
|
||||
paramiko.Channel объект для интерактивной сессии
|
||||
"""
|
||||
if not self.is_connected():
|
||||
if not self.connect():
|
||||
raise Exception("Cannot connect to SSH server")
|
||||
|
||||
try:
|
||||
channel = self.client.invoke_shell(term=term, width=width, height=height)
|
||||
channel.settimeout(0.0) # Non-blocking mode
|
||||
return channel
|
||||
except Exception as e:
|
||||
logger.error(f"Error creating interactive shell on {self.hostname}: {e}")
|
||||
raise
|
||||
|
||||
def resize_shell(self, channel, width: int, height: int):
|
||||
"""
|
||||
Изменить размер терминала
|
||||
|
||||
Args:
|
||||
channel: paramiko.Channel объект
|
||||
width: Новая ширина в символах
|
||||
height: Новая высота в строках
|
||||
"""
|
||||
try:
|
||||
channel.resize_pty(width=width, height=height)
|
||||
except Exception as e:
|
||||
logger.error(f"Error resizing terminal: {e}")
|
||||
|
||||
@classmethod
|
||||
def cleanup_all_connections(cls):
|
||||
"""Clean up all cached connections"""
|
||||
for key in list(cls._connections.keys()):
|
||||
try:
|
||||
cls._connections[key].close()
|
||||
except:
|
||||
pass
|
||||
cls._connections.clear()
|
||||
cls._connection_times.clear()
|
||||
|
||||
|
||||
def check_server_status(hostname: str, port: int = 22, username: str = "root",
|
||||
key_path: Optional[str] = None) -> Dict:
|
||||
"""
|
||||
Проверить статус сервера и получить системную информацию
|
||||
|
||||
Returns:
|
||||
Dict с информацией о сервере: online, uptime, cpu, memory, disk
|
||||
"""
|
||||
result = {
|
||||
"online": False,
|
||||
"uptime": None,
|
||||
"cpu_percent": None,
|
||||
"memory_percent": None,
|
||||
"memory_used": None,
|
||||
"memory_total": None,
|
||||
"disk_percent": None,
|
||||
"disk_used": None,
|
||||
"disk_total": None,
|
||||
"load_average": None,
|
||||
"error": None,
|
||||
}
|
||||
|
||||
try:
|
||||
with SSHClient(hostname, port, username, key_path, timeout=5) as ssh:
|
||||
if not ssh.is_connected():
|
||||
result["error"] = "SSH connection failed"
|
||||
return result
|
||||
|
||||
result["online"] = True
|
||||
|
||||
# Uptime
|
||||
uptime_output = ssh.execute("uptime -p 2>/dev/null || uptime")
|
||||
if uptime_output:
|
||||
result["uptime"] = uptime_output
|
||||
|
||||
# Load average
|
||||
load_output = ssh.execute("cat /proc/loadavg 2>/dev/null | awk '{print $1, $2, $3}'")
|
||||
if load_output:
|
||||
result["load_average"] = load_output
|
||||
|
||||
# CPU usage (более точный метод)
|
||||
cpu_script = """
|
||||
# Get CPU usage over 1 second interval
|
||||
cpu_idle=$(top -bn2 -d1 | grep "Cpu(s)" | tail -1 | awk '{print $8}' | cut -d'%' -f1)
|
||||
if [ -n "$cpu_idle" ]; then
|
||||
echo "scale=1; 100 - $cpu_idle" | bc 2>/dev/null || echo "0"
|
||||
else
|
||||
echo "0"
|
||||
fi
|
||||
"""
|
||||
cpu_output = ssh.execute(cpu_script)
|
||||
if cpu_output and cpu_output.replace('.', '').isdigit():
|
||||
try:
|
||||
result["cpu_percent"] = float(cpu_output)
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
# Memory usage
|
||||
mem_output = ssh.execute(
|
||||
"free -m | awk 'NR==2{printf \"%.1f %.0f %.0f\", $3*100/$2, $3, $2}'"
|
||||
)
|
||||
if mem_output:
|
||||
try:
|
||||
parts = mem_output.split()
|
||||
result["memory_percent"] = float(parts[0])
|
||||
result["memory_used"] = int(parts[1])
|
||||
result["memory_total"] = int(parts[2])
|
||||
except (IndexError, ValueError):
|
||||
pass
|
||||
|
||||
# Disk usage (root partition)
|
||||
disk_output = ssh.execute(
|
||||
"df -h / | awk 'NR==2{printf \"%.1f %s %s\", $5+0, $3, $2}'"
|
||||
)
|
||||
if disk_output:
|
||||
try:
|
||||
parts = disk_output.split()
|
||||
result["disk_percent"] = float(parts[0])
|
||||
result["disk_used"] = parts[1]
|
||||
result["disk_total"] = parts[2]
|
||||
except (IndexError, ValueError):
|
||||
pass
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error checking status of {hostname}: {e}")
|
||||
result["error"] = str(e)
|
||||
|
||||
return result
|
||||
|
||||
|
||||
async def async_check_server_status(hostname: str, port: int = 22, username: str = "root",
|
||||
key_path: Optional[str] = None) -> Dict:
|
||||
"""Асинхронная версия проверки статуса сервера"""
|
||||
loop = asyncio.get_event_loop()
|
||||
return await loop.run_in_executor(
|
||||
ssh_executor,
|
||||
check_server_status,
|
||||
hostname, port, username, key_path
|
||||
)
|
||||
|
||||
|
||||
def test_ssh_connection(hostname: str, port: int = 22, username: str = "root",
|
||||
key_path: Optional[str] = None) -> bool:
|
||||
"""Быстрая проверка SSH подключения"""
|
||||
try:
|
||||
with SSHClient(hostname, port, username, key_path, timeout=3) as ssh:
|
||||
return ssh.is_connected()
|
||||
except Exception as e:
|
||||
logger.debug(f"SSH connection test failed for {hostname}: {e}")
|
||||
return False
|
||||
|
||||
|
||||
async def async_test_ssh_connection(hostname: str, port: int = 22, username: str = "root",
|
||||
key_path: Optional[str] = None) -> bool:
|
||||
"""Асинхронная версия тестирования SSH подключения"""
|
||||
loop = asyncio.get_event_loop()
|
||||
return await loop.run_in_executor(
|
||||
ssh_executor,
|
||||
test_ssh_connection,
|
||||
hostname, port, username, key_path
|
||||
)
|
||||
|
||||
|
||||
async def batch_check_servers_status(servers: list) -> Dict[int, Dict]:
|
||||
"""Асинхронная проверка статуса множества серверов"""
|
||||
tasks = []
|
||||
for server in servers:
|
||||
task = async_check_server_status(
|
||||
hostname=server.ip_address,
|
||||
port=server.ssh_port or 22,
|
||||
username=server.ssh_user or "root",
|
||||
key_path=server.ssh_key_path
|
||||
)
|
||||
tasks.append((server.id, task))
|
||||
|
||||
results = {}
|
||||
completed_tasks = await asyncio.gather(*[task for _, task in tasks], return_exceptions=True)
|
||||
|
||||
for i, (server_id, _) in enumerate(tasks):
|
||||
result = completed_tasks[i]
|
||||
if isinstance(result, Exception):
|
||||
results[server_id] = {
|
||||
"online": False,
|
||||
"error": str(result)
|
||||
}
|
||||
else:
|
||||
results[server_id] = result
|
||||
|
||||
return results
|
||||
|
||||
|
||||
# Connection cleanup scheduler
|
||||
async def cleanup_ssh_connections():
|
||||
"""Периодическая очистка неиспользуемых SSH подключений"""
|
||||
while True:
|
||||
try:
|
||||
await asyncio.sleep(300) # Check every 5 minutes
|
||||
current_time = time.time()
|
||||
expired_keys = []
|
||||
|
||||
for key, connection_time in SSHClient._connection_times.items():
|
||||
if current_time - connection_time > 600: # 10 minutes
|
||||
expired_keys.append(key)
|
||||
|
||||
for key in expired_keys:
|
||||
if key in SSHClient._connections:
|
||||
try:
|
||||
SSHClient._connections[key].close()
|
||||
except:
|
||||
pass
|
||||
del SSHClient._connections[key]
|
||||
del SSHClient._connection_times[key]
|
||||
logger.debug(f"Cleaned up expired SSH connection: {key}")
|
||||
except Exception as e:
|
||||
logger.error(f"Error in SSH cleanup task: {e}")
|
||||
await asyncio.sleep(60) # Wait a minute on error
|
||||
2241
backend/app/static/css/theme.css
Normal file
2241
backend/app/static/css/theme.css
Normal file
File diff suppressed because it is too large
Load Diff
BIN
backend/app/static/img/logo.png
Normal file
BIN
backend/app/static/img/logo.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 8.1 KiB |
1
backend/app/static/img/logo.sig
Normal file
1
backend/app/static/img/logo.sig
Normal file
@@ -0,0 +1 @@
|
||||
AjThUqFMBAmdy3p+Cm57QzxXQJmuS3fCdh1AJ7yi+ZuuSjhL/uJfJlsMKitXNjRWMBIQC3yKV1TM/NRi4zf8sB2ygursMmQo6QnhGgVMGIAyjD2XKxurRgNJTKFfn7YXSIG/IpRGs8Nxo0w34GDr4c+3hLrfdbrcJyqeg0hdlcaP4rxsWQFRsJ2V8YQ8MqwxeMWcgGYjXdyc1H4HzAMHPZ8dKR1xZmrfkFpJ3/AujFpoPw1JJtczEDwGVFoFveZPflSSry40sxqlcmDK4jiXfDzUFfv3+juOflBYBSoAluH6IYcszSq/w7O1UhzXbAcuKQbO4uq64sDJLuwW8rWPQw==
|
||||
99
backend/app/static/js/i18n.js
Normal file
99
backend/app/static/js/i18n.js
Normal file
@@ -0,0 +1,99 @@
|
||||
/**
|
||||
* Client-side translations
|
||||
* Synchronized with backend i18n.py
|
||||
*/
|
||||
|
||||
const translations = {
|
||||
ru: {
|
||||
// Common
|
||||
loading: "Загрузка...",
|
||||
save: "Сохранить",
|
||||
cancel: "Отмена",
|
||||
delete: "Удалить",
|
||||
edit: "Редактировать",
|
||||
add: "Добавить",
|
||||
search: "Поиск",
|
||||
filter: "Фильтр",
|
||||
actions: "Действия",
|
||||
status: "Статус",
|
||||
name: "Название",
|
||||
description: "Описание",
|
||||
success: "Успешно",
|
||||
error: "Ошибка",
|
||||
warning: "Предупреждение",
|
||||
confirm: "Подтвердить",
|
||||
yes: "Да",
|
||||
no: "Нет",
|
||||
|
||||
// Messages
|
||||
profile_updated: "Профиль обновлён",
|
||||
password_changed: "Пароль успешно изменён",
|
||||
settings_saved: "Настройки сохранены",
|
||||
language_changed: "Язык изменён. Страница будет перезагружена...",
|
||||
error_occurred: "Произошла ошибка",
|
||||
confirm_delete: "Вы уверены, что хотите удалить?",
|
||||
},
|
||||
|
||||
en: {
|
||||
// Common
|
||||
loading: "Loading...",
|
||||
save: "Save",
|
||||
cancel: "Cancel",
|
||||
delete: "Delete",
|
||||
edit: "Edit",
|
||||
add: "Add",
|
||||
search: "Search",
|
||||
filter: "Filter",
|
||||
actions: "Actions",
|
||||
status: "Status",
|
||||
name: "Name",
|
||||
description: "Description",
|
||||
success: "Success",
|
||||
error: "Error",
|
||||
warning: "Warning",
|
||||
confirm: "Confirm",
|
||||
yes: "Yes",
|
||||
no: "No",
|
||||
|
||||
// Messages
|
||||
profile_updated: "Profile updated",
|
||||
password_changed: "Password changed successfully",
|
||||
settings_saved: "Settings saved",
|
||||
language_changed: "Language changed. Page will reload...",
|
||||
error_occurred: "An error occurred",
|
||||
confirm_delete: "Are you sure you want to delete?",
|
||||
}
|
||||
};
|
||||
|
||||
// Get current language from localStorage or default
|
||||
function getCurrentLanguage() {
|
||||
return localStorage.getItem('panel_language') || 'ru';
|
||||
}
|
||||
|
||||
// Set language
|
||||
function setLanguage(lang) {
|
||||
localStorage.setItem('panel_language', lang);
|
||||
}
|
||||
|
||||
// Get translation
|
||||
function t(key, lang = null) {
|
||||
if (!lang) {
|
||||
lang = getCurrentLanguage();
|
||||
}
|
||||
|
||||
if (translations[lang] && translations[lang][key]) {
|
||||
return translations[lang][key];
|
||||
}
|
||||
|
||||
// Fallback to Russian
|
||||
if (translations.ru[key]) {
|
||||
return translations.ru[key];
|
||||
}
|
||||
|
||||
return key;
|
||||
}
|
||||
|
||||
// Export for use in other scripts
|
||||
if (typeof module !== 'undefined' && module.exports) {
|
||||
module.exports = { translations, t, getCurrentLanguage, setLanguage };
|
||||
}
|
||||
148
backend/app/static/js/theme.js
Normal file
148
backend/app/static/js/theme.js
Normal file
@@ -0,0 +1,148 @@
|
||||
/**
|
||||
* Theme Manager - Handles light/dark mode switching and sidebar toggle
|
||||
*/
|
||||
|
||||
(function() {
|
||||
'use strict';
|
||||
|
||||
const THEME_KEY = 'panel-theme';
|
||||
const SIDEBAR_KEY = 'panel-sidebar';
|
||||
const DARK_THEME = 'dark';
|
||||
const LIGHT_THEME = 'light';
|
||||
|
||||
// Get saved theme or system preference
|
||||
function getPreferredTheme() {
|
||||
const savedTheme = localStorage.getItem(THEME_KEY);
|
||||
if (savedTheme) {
|
||||
return savedTheme;
|
||||
}
|
||||
|
||||
// Check system preference
|
||||
if (window.matchMedia && window.matchMedia('(prefers-color-scheme: light)').matches) {
|
||||
return LIGHT_THEME;
|
||||
}
|
||||
|
||||
return DARK_THEME;
|
||||
}
|
||||
|
||||
// Apply theme to document
|
||||
function applyTheme(theme) {
|
||||
document.documentElement.setAttribute('data-theme', theme);
|
||||
localStorage.setItem(THEME_KEY, theme);
|
||||
|
||||
// Update toggle button icon
|
||||
updateToggleIcon(theme);
|
||||
}
|
||||
|
||||
// Update toggle button icon
|
||||
function updateToggleIcon(theme) {
|
||||
const toggle = document.getElementById('themeToggle');
|
||||
if (!toggle) return;
|
||||
|
||||
const sunIcon = toggle.querySelector('.icon-sun');
|
||||
const moonIcon = toggle.querySelector('.icon-moon');
|
||||
|
||||
if (sunIcon && moonIcon) {
|
||||
if (theme === DARK_THEME) {
|
||||
sunIcon.style.display = 'block';
|
||||
moonIcon.style.display = 'none';
|
||||
} else {
|
||||
sunIcon.style.display = 'none';
|
||||
moonIcon.style.display = 'block';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Toggle theme
|
||||
function toggleTheme() {
|
||||
const currentTheme = document.documentElement.getAttribute('data-theme') || DARK_THEME;
|
||||
const newTheme = currentTheme === DARK_THEME ? LIGHT_THEME : DARK_THEME;
|
||||
applyTheme(newTheme);
|
||||
}
|
||||
|
||||
// Toggle sidebar
|
||||
function toggleSidebar() {
|
||||
const sidebar = document.getElementById('sidebar');
|
||||
const overlay = document.getElementById('sidebarOverlay');
|
||||
|
||||
if (sidebar) {
|
||||
sidebar.classList.toggle('open');
|
||||
|
||||
if (overlay) {
|
||||
overlay.classList.toggle('active', sidebar.classList.contains('open'));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Close sidebar on escape key
|
||||
function handleKeydown(e) {
|
||||
if (e.key === 'Escape') {
|
||||
const sidebar = document.getElementById('sidebar');
|
||||
const overlay = document.getElementById('sidebarOverlay');
|
||||
|
||||
if (sidebar && sidebar.classList.contains('open')) {
|
||||
sidebar.classList.remove('open');
|
||||
if (overlay) {
|
||||
overlay.classList.remove('active');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Initialize on DOM load
|
||||
function init() {
|
||||
// Apply saved or preferred theme immediately
|
||||
const theme = getPreferredTheme();
|
||||
applyTheme(theme);
|
||||
|
||||
// Set up toggle button
|
||||
const toggle = document.getElementById('themeToggle');
|
||||
if (toggle) {
|
||||
toggle.addEventListener('click', toggleTheme);
|
||||
}
|
||||
|
||||
// Listen for escape key
|
||||
document.addEventListener('keydown', handleKeydown);
|
||||
|
||||
// Listen for system theme changes
|
||||
if (window.matchMedia) {
|
||||
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {
|
||||
// Only auto-switch if user hasn't manually selected a theme
|
||||
if (!localStorage.getItem(THEME_KEY)) {
|
||||
applyTheme(e.matches ? DARK_THEME : LIGHT_THEME);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Close sidebar when clicking on a link (mobile)
|
||||
const sidebarLinks = document.querySelectorAll('.sidebar-nav a');
|
||||
sidebarLinks.forEach(link => {
|
||||
link.addEventListener('click', () => {
|
||||
const sidebar = document.getElementById('sidebar');
|
||||
const overlay = document.getElementById('sidebarOverlay');
|
||||
|
||||
if (window.innerWidth <= 768 && sidebar) {
|
||||
sidebar.classList.remove('open');
|
||||
if (overlay) {
|
||||
overlay.classList.remove('active');
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// Apply theme before DOM is ready to prevent flash
|
||||
const savedTheme = getPreferredTheme();
|
||||
document.documentElement.setAttribute('data-theme', savedTheme);
|
||||
|
||||
// Initialize when DOM is ready
|
||||
if (document.readyState === 'loading') {
|
||||
document.addEventListener('DOMContentLoaded', init);
|
||||
} else {
|
||||
init();
|
||||
}
|
||||
|
||||
// Expose functions globally
|
||||
window.toggleTheme = toggleTheme;
|
||||
window.toggleSidebar = toggleSidebar;
|
||||
})();
|
||||
13
backend/app/static/novnc/AUTHORS
Normal file
13
backend/app/static/novnc/AUTHORS
Normal file
@@ -0,0 +1,13 @@
|
||||
maintainers:
|
||||
- Samuel Mannehed for Cendio AB (@samhed)
|
||||
- Pierre Ossman for Cendio AB (@CendioOssman)
|
||||
maintainersEmeritus:
|
||||
- Joel Martin (@kanaka)
|
||||
- Solly Ross (@directxman12)
|
||||
- @astrand
|
||||
contributors:
|
||||
# There are a bunch of people that should be here.
|
||||
# If you want to be on this list, feel free send a PR
|
||||
# to add yourself.
|
||||
- jalf <git@jalf.dk>
|
||||
- NTT corp.
|
||||
62
backend/app/static/novnc/LICENSE.txt
Normal file
62
backend/app/static/novnc/LICENSE.txt
Normal file
@@ -0,0 +1,62 @@
|
||||
noVNC is Copyright (C) 2022 The noVNC Authors
|
||||
(./AUTHORS)
|
||||
|
||||
The noVNC core library files are licensed under the MPL 2.0 (Mozilla
|
||||
Public License 2.0). The noVNC core library is composed of the
|
||||
Javascript code necessary for full noVNC operation. This includes (but
|
||||
is not limited to):
|
||||
|
||||
core/**/*.js
|
||||
app/*.js
|
||||
test/playback.js
|
||||
|
||||
The HTML, CSS, font and images files that included with the noVNC
|
||||
source distibution (or repository) are not considered part of the
|
||||
noVNC core library and are licensed under more permissive licenses.
|
||||
The intent is to allow easy integration of noVNC into existing web
|
||||
sites and web applications.
|
||||
|
||||
The HTML, CSS, font and image files are licensed as follows:
|
||||
|
||||
*.html : 2-Clause BSD license
|
||||
|
||||
app/styles/*.css : 2-Clause BSD license
|
||||
|
||||
app/styles/Orbitron* : SIL Open Font License 1.1
|
||||
(Copyright 2009 Matt McInerney)
|
||||
|
||||
app/images/ : Creative Commons Attribution-ShareAlike
|
||||
http://creativecommons.org/licenses/by-sa/3.0/
|
||||
|
||||
Some portions of noVNC are copyright to their individual authors.
|
||||
Please refer to the individual source files and/or to the noVNC commit
|
||||
history: https://github.com/novnc/noVNC/commits/master
|
||||
|
||||
The are several files and projects that have been incorporated into
|
||||
the noVNC core library. Here is a list of those files and the original
|
||||
licenses (all MPL 2.0 compatible):
|
||||
|
||||
core/base64.js : MPL 2.0
|
||||
|
||||
core/des.js : Various BSD style licenses
|
||||
|
||||
vendor/pako/ : MIT
|
||||
|
||||
Any other files not mentioned above are typically marked with
|
||||
a copyright/license header at the top of the file. The default noVNC
|
||||
license is MPL-2.0.
|
||||
|
||||
The following license texts are included:
|
||||
|
||||
docs/LICENSE.MPL-2.0
|
||||
docs/LICENSE.OFL-1.1
|
||||
docs/LICENSE.BSD-3-Clause (New BSD)
|
||||
docs/LICENSE.BSD-2-Clause (Simplified BSD / FreeBSD)
|
||||
vendor/pako/LICENSE (MIT)
|
||||
|
||||
Or alternatively the license texts may be found here:
|
||||
|
||||
http://www.mozilla.org/MPL/2.0/
|
||||
http://scripts.sil.org/OFL
|
||||
http://en.wikipedia.org/wiki/BSD_licenses
|
||||
https://opensource.org/licenses/MIT
|
||||
230
backend/app/static/novnc/README.md
Normal file
230
backend/app/static/novnc/README.md
Normal file
@@ -0,0 +1,230 @@
|
||||
## noVNC: HTML VNC Client Library and Application
|
||||
|
||||
[](https://github.com/novnc/noVNC/actions?query=workflow%3ATest)
|
||||
[](https://github.com/novnc/noVNC/actions?query=workflow%3ALint)
|
||||
|
||||
### Description
|
||||
|
||||
noVNC is both a HTML VNC client JavaScript library and an application built on
|
||||
top of that library. noVNC runs well in any modern browser including mobile
|
||||
browsers (iOS and Android).
|
||||
|
||||
Many companies, projects and products have integrated noVNC including
|
||||
[OpenStack](http://www.openstack.org),
|
||||
[OpenNebula](http://opennebula.org/),
|
||||
[LibVNCServer](http://libvncserver.sourceforge.net), and
|
||||
[ThinLinc](https://cendio.com/thinlinc). See
|
||||
[the Projects and Companies wiki page](https://github.com/novnc/noVNC/wiki/Projects-and-companies-using-noVNC)
|
||||
for a more complete list with additional info and links.
|
||||
|
||||
### Table of Contents
|
||||
|
||||
- [News/help/contact](#newshelpcontact)
|
||||
- [Features](#features)
|
||||
- [Screenshots](#screenshots)
|
||||
- [Browser Requirements](#browser-requirements)
|
||||
- [Server Requirements](#server-requirements)
|
||||
- [Quick Start](#quick-start)
|
||||
- [Installation from Snap Package](#installation-from-snap-package)
|
||||
- [Integration and Deployment](#integration-and-deployment)
|
||||
- [Authors/Contributors](#authorscontributors)
|
||||
|
||||
### News/help/contact
|
||||
|
||||
The project website is found at [novnc.com](http://novnc.com).
|
||||
Notable commits, announcements and news are posted to
|
||||
[@noVNC](http://www.twitter.com/noVNC).
|
||||
|
||||
If you are a noVNC developer/integrator/user (or want to be) please join the
|
||||
[noVNC discussion group](https://groups.google.com/forum/?fromgroups#!forum/novnc).
|
||||
|
||||
Bugs and feature requests can be submitted via
|
||||
[github issues](https://github.com/novnc/noVNC/issues). If you have questions
|
||||
about using noVNC then please first use the
|
||||
[discussion group](https://groups.google.com/forum/?fromgroups#!forum/novnc).
|
||||
We also have a [wiki](https://github.com/novnc/noVNC/wiki/) with lots of
|
||||
helpful information.
|
||||
|
||||
If you are looking for a place to start contributing to noVNC, a good place to
|
||||
start would be the issues that are marked as
|
||||
["patchwelcome"](https://github.com/novnc/noVNC/issues?labels=patchwelcome).
|
||||
Please check our
|
||||
[contribution guide](https://github.com/novnc/noVNC/wiki/Contributing) though.
|
||||
|
||||
If you want to show appreciation for noVNC you could donate to a great non-
|
||||
profits such as:
|
||||
[Compassion International](http://www.compassion.com/),
|
||||
[SIL](http://www.sil.org),
|
||||
[Habitat for Humanity](http://www.habitat.org),
|
||||
[Electronic Frontier Foundation](https://www.eff.org/),
|
||||
[Against Malaria Foundation](http://www.againstmalaria.com/),
|
||||
[Nothing But Nets](http://www.nothingbutnets.net/), etc.
|
||||
Please tweet [@noVNC](http://www.twitter.com/noVNC) if you do.
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* Supports all modern browsers including mobile (iOS, Android)
|
||||
* Supported authentication methods: none, classical VNC, RealVNC's
|
||||
RSA-AES, Tight, VeNCrypt Plain, XVP, Apple's Diffie-Hellman,
|
||||
UltraVNC's MSLogonII
|
||||
* Supported VNC encodings: raw, copyrect, rre, hextile, tight, tightPNG,
|
||||
ZRLE, JPEG
|
||||
* Supports scaling, clipping and resizing the desktop
|
||||
* Local cursor rendering
|
||||
* Clipboard copy/paste with full Unicode support
|
||||
* Translations
|
||||
* Touch gestures for emulating common mouse actions
|
||||
* Licensed mainly under the [MPL 2.0](http://www.mozilla.org/MPL/2.0/), see
|
||||
[the license document](LICENSE.txt) for details
|
||||
|
||||
### Screenshots
|
||||
|
||||
Running in Firefox before and after connecting:
|
||||
|
||||
<img src="http://novnc.com/img/noVNC-1-login.png" width=400>
|
||||
<img src="http://novnc.com/img/noVNC-3-connected.png" width=400>
|
||||
|
||||
See more screenshots
|
||||
[here](http://novnc.com/screenshots.html).
|
||||
|
||||
|
||||
### Browser Requirements
|
||||
|
||||
noVNC uses many modern web technologies so a formal requirement list is
|
||||
not available. However these are the minimum versions we are currently
|
||||
aware of:
|
||||
|
||||
* Chrome 64, Firefox 79, Safari 13.4, Opera 51, Edge 79
|
||||
|
||||
|
||||
### Server Requirements
|
||||
|
||||
noVNC follows the standard VNC protocol, but unlike other VNC clients it does
|
||||
require WebSockets support. Many servers include support (e.g.
|
||||
[x11vnc/libvncserver](http://libvncserver.sourceforge.net/),
|
||||
[QEMU](http://www.qemu.org/), and
|
||||
[MobileVNC](http://www.smartlab.at/mobilevnc/)), but for the others you need to
|
||||
use a WebSockets to TCP socket proxy. noVNC has a sister project
|
||||
[websockify](https://github.com/novnc/websockify) that provides a simple such
|
||||
proxy.
|
||||
|
||||
|
||||
### Quick Start
|
||||
|
||||
* Use the `novnc_proxy` script to automatically download and start websockify, which
|
||||
includes a mini-webserver and the WebSockets proxy. The `--vnc` option is
|
||||
used to specify the location of a running VNC server:
|
||||
|
||||
`./utils/novnc_proxy --vnc localhost:5901`
|
||||
|
||||
* If you don't need to expose the web server to public internet, you can
|
||||
bind to localhost:
|
||||
|
||||
`./utils/novnc_proxy --vnc localhost:5901 --listen localhost:6081`
|
||||
|
||||
* Point your browser to the cut-and-paste URL that is output by the `novnc_proxy`
|
||||
script. Hit the Connect button, enter a password if the VNC server has one
|
||||
configured, and enjoy!
|
||||
|
||||
### Installation from Snap Package
|
||||
Running the command below will install the latest release of noVNC from Snap:
|
||||
|
||||
`sudo snap install novnc`
|
||||
|
||||
#### Running noVNC from Snap Directly
|
||||
|
||||
You can run the Snap-package installed novnc directly with, for example:
|
||||
|
||||
`novnc --listen 6081 --vnc localhost:5901 # /snap/bin/novnc if /snap/bin is not in your PATH`
|
||||
|
||||
If you want to use certificate files, due to standard Snap confinement restrictions you need to have them in the /home/\<user\>/snap/novnc/current/ directory. If your username is jsmith an example command would be:
|
||||
|
||||
`novnc --listen 8443 --cert ~jsmith/snap/novnc/current/self.crt --key ~jsmith/snap/novnc/current/self.key --vnc ubuntu.example.com:5901`
|
||||
|
||||
#### Running noVNC from Snap as a Service (Daemon)
|
||||
The Snap package also has the capability to run a 'novnc' service which can be
|
||||
configured to listen on multiple ports connecting to multiple VNC servers
|
||||
(effectively a service runing multiple instances of novnc).
|
||||
Instructions (with example values):
|
||||
|
||||
List current services (out-of-box this will be blank):
|
||||
|
||||
```
|
||||
sudo snap get novnc services
|
||||
Key Value
|
||||
services.n6080 {...}
|
||||
services.n6081 {...}
|
||||
```
|
||||
|
||||
Create a new service that listens on port 6082 and connects to the VNC server
|
||||
running on port 5902 on localhost:
|
||||
|
||||
`sudo snap set novnc services.n6082.listen=6082 services.n6082.vnc=localhost:5902`
|
||||
|
||||
(Any services you define with 'snap set' will be automatically started)
|
||||
Note that the name of the service, 'n6082' in this example, can be anything
|
||||
as long as it doesn't start with a number or contain spaces/special characters.
|
||||
|
||||
View the configuration of the service just created:
|
||||
|
||||
```
|
||||
sudo snap get novnc services.n6082
|
||||
Key Value
|
||||
services.n6082.listen 6082
|
||||
services.n6082.vnc localhost:5902
|
||||
```
|
||||
|
||||
Disable a service (note that because of a limitation in Snap it's currently not
|
||||
possible to unset config variables, setting them to blank values is the way
|
||||
to disable a service):
|
||||
|
||||
`sudo snap set novnc services.n6082.listen='' services.n6082.vnc=''`
|
||||
|
||||
(Any services you set to blank with 'snap set' like this will be automatically stopped)
|
||||
|
||||
Verify that the service is disabled (blank values):
|
||||
|
||||
```
|
||||
sudo snap get novnc services.n6082
|
||||
Key Value
|
||||
services.n6082.listen
|
||||
services.n6082.vnc
|
||||
```
|
||||
|
||||
### Integration and Deployment
|
||||
|
||||
Please see our other documents for how to integrate noVNC in your own software,
|
||||
or deploying the noVNC application in production environments:
|
||||
|
||||
* [Embedding](docs/EMBEDDING.md) - For the noVNC application
|
||||
* [Library](docs/LIBRARY.md) - For the noVNC JavaScript library
|
||||
|
||||
|
||||
### Authors/Contributors
|
||||
|
||||
See [AUTHORS](AUTHORS) for a (full-ish) list of authors. If you're not on
|
||||
that list and you think you should be, feel free to send a PR to fix that.
|
||||
|
||||
* Core team:
|
||||
* [Samuel Mannehed](https://github.com/samhed) (Cendio)
|
||||
* [Pierre Ossman](https://github.com/CendioOssman) (Cendio)
|
||||
|
||||
* Previous core contributors:
|
||||
* [Joel Martin](https://github.com/kanaka) (Project founder)
|
||||
* [Solly Ross](https://github.com/DirectXMan12) (Red Hat / OpenStack)
|
||||
|
||||
* Notable contributions:
|
||||
* UI and Icons : Pierre Ossman, Chris Gordon
|
||||
* Original Logo : Michael Sersen
|
||||
* tight encoding : Michael Tinglof (Mercuri.ca)
|
||||
* RealVNC RSA AES authentication : USTC Vlab Team
|
||||
|
||||
* Included libraries:
|
||||
* base64 : Martijn Pieters (Digital Creations 2), Samuel Sieb (sieb.net)
|
||||
* DES : Dave Zimmerman (Widget Workshop), Jef Poskanzer (ACME Labs)
|
||||
* Pako : Vitaly Puzrin (https://github.com/nodeca/pako)
|
||||
|
||||
Do you want to be on this list? Check out our
|
||||
[contribution guide](https://github.com/novnc/noVNC/wiki/Contributing) and
|
||||
start hacking!
|
||||
104
backend/app/static/novnc/core/base64.js
Normal file
104
backend/app/static/novnc/core/base64.js
Normal file
@@ -0,0 +1,104 @@
|
||||
/* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
|
||||
|
||||
// From: http://hg.mozilla.org/mozilla-central/raw-file/ec10630b1a54/js/src/devtools/jint/sunspider/string-base64.js
|
||||
|
||||
import * as Log from './util/logging.js';
|
||||
|
||||
export default {
|
||||
/* Convert data (an array of integers) to a Base64 string. */
|
||||
toBase64Table: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='.split(''),
|
||||
base64Pad: '=',
|
||||
|
||||
encode(data) {
|
||||
"use strict";
|
||||
let result = '';
|
||||
const length = data.length;
|
||||
const lengthpad = (length % 3);
|
||||
// Convert every three bytes to 4 ascii characters.
|
||||
|
||||
for (let i = 0; i < (length - 2); i += 3) {
|
||||
result += this.toBase64Table[data[i] >> 2];
|
||||
result += this.toBase64Table[((data[i] & 0x03) << 4) + (data[i + 1] >> 4)];
|
||||
result += this.toBase64Table[((data[i + 1] & 0x0f) << 2) + (data[i + 2] >> 6)];
|
||||
result += this.toBase64Table[data[i + 2] & 0x3f];
|
||||
}
|
||||
|
||||
// Convert the remaining 1 or 2 bytes, pad out to 4 characters.
|
||||
const j = length - lengthpad;
|
||||
if (lengthpad === 2) {
|
||||
result += this.toBase64Table[data[j] >> 2];
|
||||
result += this.toBase64Table[((data[j] & 0x03) << 4) + (data[j + 1] >> 4)];
|
||||
result += this.toBase64Table[(data[j + 1] & 0x0f) << 2];
|
||||
result += this.toBase64Table[64];
|
||||
} else if (lengthpad === 1) {
|
||||
result += this.toBase64Table[data[j] >> 2];
|
||||
result += this.toBase64Table[(data[j] & 0x03) << 4];
|
||||
result += this.toBase64Table[64];
|
||||
result += this.toBase64Table[64];
|
||||
}
|
||||
|
||||
return result;
|
||||
},
|
||||
|
||||
/* Convert Base64 data to a string */
|
||||
/* eslint-disable comma-spacing */
|
||||
toBinaryTable: [
|
||||
-1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
|
||||
-1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
|
||||
-1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,62, -1,-1,-1,63,
|
||||
52,53,54,55, 56,57,58,59, 60,61,-1,-1, -1, 0,-1,-1,
|
||||
-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11,12,13,14,
|
||||
15,16,17,18, 19,20,21,22, 23,24,25,-1, -1,-1,-1,-1,
|
||||
-1,26,27,28, 29,30,31,32, 33,34,35,36, 37,38,39,40,
|
||||
41,42,43,44, 45,46,47,48, 49,50,51,-1, -1,-1,-1,-1
|
||||
],
|
||||
/* eslint-enable comma-spacing */
|
||||
|
||||
decode(data, offset = 0) {
|
||||
let dataLength = data.indexOf('=') - offset;
|
||||
if (dataLength < 0) { dataLength = data.length - offset; }
|
||||
|
||||
/* Every four characters is 3 resulting numbers */
|
||||
const resultLength = (dataLength >> 2) * 3 + Math.floor((dataLength % 4) / 1.5);
|
||||
const result = new Array(resultLength);
|
||||
|
||||
// Convert one by one.
|
||||
|
||||
let leftbits = 0; // number of bits decoded, but yet to be appended
|
||||
let leftdata = 0; // bits decoded, but yet to be appended
|
||||
for (let idx = 0, i = offset; i < data.length; i++) {
|
||||
const c = this.toBinaryTable[data.charCodeAt(i) & 0x7f];
|
||||
const padding = (data.charAt(i) === this.base64Pad);
|
||||
// Skip illegal characters and whitespace
|
||||
if (c === -1) {
|
||||
Log.Error("Illegal character code " + data.charCodeAt(i) + " at position " + i);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Collect data into leftdata, update bitcount
|
||||
leftdata = (leftdata << 6) | c;
|
||||
leftbits += 6;
|
||||
|
||||
// If we have 8 or more bits, append 8 bits to the result
|
||||
if (leftbits >= 8) {
|
||||
leftbits -= 8;
|
||||
// Append if not padding.
|
||||
if (!padding) {
|
||||
result[idx++] = (leftdata >> leftbits) & 0xff;
|
||||
}
|
||||
leftdata &= (1 << leftbits) - 1;
|
||||
}
|
||||
}
|
||||
|
||||
// If there are any bits left, the base64 string was corrupted
|
||||
if (leftbits) {
|
||||
const err = new Error('Corrupted base64 string');
|
||||
err.name = 'Base64-Error';
|
||||
throw err;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}; /* End of Base64 namespace */
|
||||
27
backend/app/static/novnc/core/decoders/copyrect.js
Normal file
27
backend/app/static/novnc/core/decoders/copyrect.js
Normal file
@@ -0,0 +1,27 @@
|
||||
/*
|
||||
* noVNC: HTML5 VNC client
|
||||
* Copyright (C) 2019 The noVNC Authors
|
||||
* Licensed under MPL 2.0 (see LICENSE.txt)
|
||||
*
|
||||
* See README.md for usage and integration instructions.
|
||||
*
|
||||
*/
|
||||
|
||||
export default class CopyRectDecoder {
|
||||
decodeRect(x, y, width, height, sock, display, depth) {
|
||||
if (sock.rQwait("COPYRECT", 4)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
let deltaX = sock.rQshift16();
|
||||
let deltaY = sock.rQshift16();
|
||||
|
||||
if ((width === 0) || (height === 0)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
display.copyImage(deltaX, deltaY, x, y, width, height);
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
191
backend/app/static/novnc/core/decoders/hextile.js
Normal file
191
backend/app/static/novnc/core/decoders/hextile.js
Normal file
@@ -0,0 +1,191 @@
|
||||
/*
|
||||
* noVNC: HTML5 VNC client
|
||||
* Copyright (C) 2019 The noVNC Authors
|
||||
* Licensed under MPL 2.0 (see LICENSE.txt)
|
||||
*
|
||||
* See README.md for usage and integration instructions.
|
||||
*
|
||||
*/
|
||||
|
||||
import * as Log from '../util/logging.js';
|
||||
|
||||
export default class HextileDecoder {
|
||||
constructor() {
|
||||
this._tiles = 0;
|
||||
this._lastsubencoding = 0;
|
||||
this._tileBuffer = new Uint8Array(16 * 16 * 4);
|
||||
}
|
||||
|
||||
decodeRect(x, y, width, height, sock, display, depth) {
|
||||
if (this._tiles === 0) {
|
||||
this._tilesX = Math.ceil(width / 16);
|
||||
this._tilesY = Math.ceil(height / 16);
|
||||
this._totalTiles = this._tilesX * this._tilesY;
|
||||
this._tiles = this._totalTiles;
|
||||
}
|
||||
|
||||
while (this._tiles > 0) {
|
||||
let bytes = 1;
|
||||
|
||||
if (sock.rQwait("HEXTILE", bytes)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
let rQ = sock.rQ;
|
||||
let rQi = sock.rQi;
|
||||
|
||||
let subencoding = rQ[rQi]; // Peek
|
||||
if (subencoding > 30) { // Raw
|
||||
throw new Error("Illegal hextile subencoding (subencoding: " +
|
||||
subencoding + ")");
|
||||
}
|
||||
|
||||
const currTile = this._totalTiles - this._tiles;
|
||||
const tileX = currTile % this._tilesX;
|
||||
const tileY = Math.floor(currTile / this._tilesX);
|
||||
const tx = x + tileX * 16;
|
||||
const ty = y + tileY * 16;
|
||||
const tw = Math.min(16, (x + width) - tx);
|
||||
const th = Math.min(16, (y + height) - ty);
|
||||
|
||||
// Figure out how much we are expecting
|
||||
if (subencoding & 0x01) { // Raw
|
||||
bytes += tw * th * 4;
|
||||
} else {
|
||||
if (subencoding & 0x02) { // Background
|
||||
bytes += 4;
|
||||
}
|
||||
if (subencoding & 0x04) { // Foreground
|
||||
bytes += 4;
|
||||
}
|
||||
if (subencoding & 0x08) { // AnySubrects
|
||||
bytes++; // Since we aren't shifting it off
|
||||
|
||||
if (sock.rQwait("HEXTILE", bytes)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
let subrects = rQ[rQi + bytes - 1]; // Peek
|
||||
if (subencoding & 0x10) { // SubrectsColoured
|
||||
bytes += subrects * (4 + 2);
|
||||
} else {
|
||||
bytes += subrects * 2;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (sock.rQwait("HEXTILE", bytes)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// We know the encoding and have a whole tile
|
||||
rQi++;
|
||||
if (subencoding === 0) {
|
||||
if (this._lastsubencoding & 0x01) {
|
||||
// Weird: ignore blanks are RAW
|
||||
Log.Debug(" Ignoring blank after RAW");
|
||||
} else {
|
||||
display.fillRect(tx, ty, tw, th, this._background);
|
||||
}
|
||||
} else if (subencoding & 0x01) { // Raw
|
||||
let pixels = tw * th;
|
||||
// Max sure the image is fully opaque
|
||||
for (let i = 0;i < pixels;i++) {
|
||||
rQ[rQi + i * 4 + 3] = 255;
|
||||
}
|
||||
display.blitImage(tx, ty, tw, th, rQ, rQi);
|
||||
rQi += bytes - 1;
|
||||
} else {
|
||||
if (subencoding & 0x02) { // Background
|
||||
this._background = [rQ[rQi], rQ[rQi + 1], rQ[rQi + 2], rQ[rQi + 3]];
|
||||
rQi += 4;
|
||||
}
|
||||
if (subencoding & 0x04) { // Foreground
|
||||
this._foreground = [rQ[rQi], rQ[rQi + 1], rQ[rQi + 2], rQ[rQi + 3]];
|
||||
rQi += 4;
|
||||
}
|
||||
|
||||
this._startTile(tx, ty, tw, th, this._background);
|
||||
if (subencoding & 0x08) { // AnySubrects
|
||||
let subrects = rQ[rQi];
|
||||
rQi++;
|
||||
|
||||
for (let s = 0; s < subrects; s++) {
|
||||
let color;
|
||||
if (subencoding & 0x10) { // SubrectsColoured
|
||||
color = [rQ[rQi], rQ[rQi + 1], rQ[rQi + 2], rQ[rQi + 3]];
|
||||
rQi += 4;
|
||||
} else {
|
||||
color = this._foreground;
|
||||
}
|
||||
const xy = rQ[rQi];
|
||||
rQi++;
|
||||
const sx = (xy >> 4);
|
||||
const sy = (xy & 0x0f);
|
||||
|
||||
const wh = rQ[rQi];
|
||||
rQi++;
|
||||
const sw = (wh >> 4) + 1;
|
||||
const sh = (wh & 0x0f) + 1;
|
||||
|
||||
this._subTile(sx, sy, sw, sh, color);
|
||||
}
|
||||
}
|
||||
this._finishTile(display);
|
||||
}
|
||||
sock.rQi = rQi;
|
||||
this._lastsubencoding = subencoding;
|
||||
this._tiles--;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
// start updating a tile
|
||||
_startTile(x, y, width, height, color) {
|
||||
this._tileX = x;
|
||||
this._tileY = y;
|
||||
this._tileW = width;
|
||||
this._tileH = height;
|
||||
|
||||
const red = color[0];
|
||||
const green = color[1];
|
||||
const blue = color[2];
|
||||
|
||||
const data = this._tileBuffer;
|
||||
for (let i = 0; i < width * height * 4; i += 4) {
|
||||
data[i] = red;
|
||||
data[i + 1] = green;
|
||||
data[i + 2] = blue;
|
||||
data[i + 3] = 255;
|
||||
}
|
||||
}
|
||||
|
||||
// update sub-rectangle of the current tile
|
||||
_subTile(x, y, w, h, color) {
|
||||
const red = color[0];
|
||||
const green = color[1];
|
||||
const blue = color[2];
|
||||
const xend = x + w;
|
||||
const yend = y + h;
|
||||
|
||||
const data = this._tileBuffer;
|
||||
const width = this._tileW;
|
||||
for (let j = y; j < yend; j++) {
|
||||
for (let i = x; i < xend; i++) {
|
||||
const p = (i + (j * width)) * 4;
|
||||
data[p] = red;
|
||||
data[p + 1] = green;
|
||||
data[p + 2] = blue;
|
||||
data[p + 3] = 255;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// draw the current tile to the screen
|
||||
_finishTile(display) {
|
||||
display.blitImage(this._tileX, this._tileY,
|
||||
this._tileW, this._tileH,
|
||||
this._tileBuffer, 0);
|
||||
}
|
||||
}
|
||||
141
backend/app/static/novnc/core/decoders/jpeg.js
Normal file
141
backend/app/static/novnc/core/decoders/jpeg.js
Normal file
@@ -0,0 +1,141 @@
|
||||
/*
|
||||
* noVNC: HTML5 VNC client
|
||||
* Copyright (C) 2019 The noVNC Authors
|
||||
* Licensed under MPL 2.0 (see LICENSE.txt)
|
||||
*
|
||||
* See README.md for usage and integration instructions.
|
||||
*
|
||||
*/
|
||||
|
||||
export default class JPEGDecoder {
|
||||
constructor() {
|
||||
// RealVNC will reuse the quantization tables
|
||||
// and Huffman tables, so we need to cache them.
|
||||
this._quantTables = [];
|
||||
this._huffmanTables = [];
|
||||
this._cachedQuantTables = [];
|
||||
this._cachedHuffmanTables = [];
|
||||
|
||||
this._jpegLength = 0;
|
||||
this._segments = [];
|
||||
}
|
||||
|
||||
decodeRect(x, y, width, height, sock, display, depth) {
|
||||
// A rect of JPEG encodings is simply a JPEG file
|
||||
if (!this._parseJPEG(sock.rQslice(0))) {
|
||||
return false;
|
||||
}
|
||||
const data = sock.rQshiftBytes(this._jpegLength);
|
||||
if (this._quantTables.length != 0 && this._huffmanTables.length != 0) {
|
||||
// If there are quantization tables and Huffman tables in the JPEG
|
||||
// image, we can directly render it.
|
||||
display.imageRect(x, y, width, height, "image/jpeg", data);
|
||||
return true;
|
||||
} else {
|
||||
// Otherwise we need to insert cached tables.
|
||||
const sofIndex = this._segments.findIndex(
|
||||
x => x[1] == 0xC0 || x[1] == 0xC2
|
||||
);
|
||||
if (sofIndex == -1) {
|
||||
throw new Error("Illegal JPEG image without SOF");
|
||||
}
|
||||
let segments = this._segments.slice(0, sofIndex);
|
||||
segments = segments.concat(this._quantTables.length ?
|
||||
this._quantTables :
|
||||
this._cachedQuantTables);
|
||||
segments.push(this._segments[sofIndex]);
|
||||
segments = segments.concat(this._huffmanTables.length ?
|
||||
this._huffmanTables :
|
||||
this._cachedHuffmanTables,
|
||||
this._segments.slice(sofIndex + 1));
|
||||
let length = 0;
|
||||
for (let i = 0; i < segments.length; i++) {
|
||||
length += segments[i].length;
|
||||
}
|
||||
const data = new Uint8Array(length);
|
||||
length = 0;
|
||||
for (let i = 0; i < segments.length; i++) {
|
||||
data.set(segments[i], length);
|
||||
length += segments[i].length;
|
||||
}
|
||||
display.imageRect(x, y, width, height, "image/jpeg", data);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
_parseJPEG(buffer) {
|
||||
if (this._quantTables.length != 0) {
|
||||
this._cachedQuantTables = this._quantTables;
|
||||
}
|
||||
if (this._huffmanTables.length != 0) {
|
||||
this._cachedHuffmanTables = this._huffmanTables;
|
||||
}
|
||||
this._quantTables = [];
|
||||
this._huffmanTables = [];
|
||||
this._segments = [];
|
||||
let i = 0;
|
||||
let bufferLength = buffer.length;
|
||||
while (true) {
|
||||
let j = i;
|
||||
if (j + 2 > bufferLength) {
|
||||
return false;
|
||||
}
|
||||
if (buffer[j] != 0xFF) {
|
||||
throw new Error("Illegal JPEG marker received (byte: " +
|
||||
buffer[j] + ")");
|
||||
}
|
||||
const type = buffer[j+1];
|
||||
j += 2;
|
||||
if (type == 0xD9) {
|
||||
this._jpegLength = j;
|
||||
this._segments.push(buffer.slice(i, j));
|
||||
return true;
|
||||
} else if (type == 0xDA) {
|
||||
// start of scan
|
||||
let hasFoundEndOfScan = false;
|
||||
for (let k = j + 3; k + 1 < bufferLength; k++) {
|
||||
if (buffer[k] == 0xFF && buffer[k+1] != 0x00 &&
|
||||
!(buffer[k+1] >= 0xD0 && buffer[k+1] <= 0xD7)) {
|
||||
j = k;
|
||||
hasFoundEndOfScan = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!hasFoundEndOfScan) {
|
||||
return false;
|
||||
}
|
||||
this._segments.push(buffer.slice(i, j));
|
||||
i = j;
|
||||
continue;
|
||||
} else if (type >= 0xD0 && type < 0xD9 || type == 0x01) {
|
||||
// No length after marker
|
||||
this._segments.push(buffer.slice(i, j));
|
||||
i = j;
|
||||
continue;
|
||||
}
|
||||
if (j + 2 > bufferLength) {
|
||||
return false;
|
||||
}
|
||||
const length = (buffer[j] << 8) + buffer[j+1] - 2;
|
||||
if (length < 0) {
|
||||
throw new Error("Illegal JPEG length received (length: " +
|
||||
length + ")");
|
||||
}
|
||||
j += 2;
|
||||
if (j + length > bufferLength) {
|
||||
return false;
|
||||
}
|
||||
j += length;
|
||||
const segment = buffer.slice(i, j);
|
||||
if (type == 0xC4) {
|
||||
// Huffman tables
|
||||
this._huffmanTables.push(segment);
|
||||
} else if (type == 0xDB) {
|
||||
// Quantization tables
|
||||
this._quantTables.push(segment);
|
||||
}
|
||||
this._segments.push(segment);
|
||||
i = j;
|
||||
}
|
||||
}
|
||||
}
|
||||
66
backend/app/static/novnc/core/decoders/raw.js
Normal file
66
backend/app/static/novnc/core/decoders/raw.js
Normal file
@@ -0,0 +1,66 @@
|
||||
/*
|
||||
* noVNC: HTML5 VNC client
|
||||
* Copyright (C) 2019 The noVNC Authors
|
||||
* Licensed under MPL 2.0 (see LICENSE.txt)
|
||||
*
|
||||
* See README.md for usage and integration instructions.
|
||||
*
|
||||
*/
|
||||
|
||||
export default class RawDecoder {
|
||||
constructor() {
|
||||
this._lines = 0;
|
||||
}
|
||||
|
||||
decodeRect(x, y, width, height, sock, display, depth) {
|
||||
if ((width === 0) || (height === 0)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (this._lines === 0) {
|
||||
this._lines = height;
|
||||
}
|
||||
|
||||
const pixelSize = depth == 8 ? 1 : 4;
|
||||
const bytesPerLine = width * pixelSize;
|
||||
|
||||
if (sock.rQwait("RAW", bytesPerLine)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const curY = y + (height - this._lines);
|
||||
const currHeight = Math.min(this._lines,
|
||||
Math.floor(sock.rQlen / bytesPerLine));
|
||||
const pixels = width * currHeight;
|
||||
|
||||
let data = sock.rQ;
|
||||
let index = sock.rQi;
|
||||
|
||||
// Convert data if needed
|
||||
if (depth == 8) {
|
||||
const newdata = new Uint8Array(pixels * 4);
|
||||
for (let i = 0; i < pixels; i++) {
|
||||
newdata[i * 4 + 0] = ((data[index + i] >> 0) & 0x3) * 255 / 3;
|
||||
newdata[i * 4 + 1] = ((data[index + i] >> 2) & 0x3) * 255 / 3;
|
||||
newdata[i * 4 + 2] = ((data[index + i] >> 4) & 0x3) * 255 / 3;
|
||||
newdata[i * 4 + 3] = 255;
|
||||
}
|
||||
data = newdata;
|
||||
index = 0;
|
||||
}
|
||||
|
||||
// Max sure the image is fully opaque
|
||||
for (let i = 0; i < pixels; i++) {
|
||||
data[index + i * 4 + 3] = 255;
|
||||
}
|
||||
|
||||
display.blitImage(x, curY, width, currHeight, data, index);
|
||||
sock.rQskipBytes(currHeight * bytesPerLine);
|
||||
this._lines -= currHeight;
|
||||
if (this._lines > 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
44
backend/app/static/novnc/core/decoders/rre.js
Normal file
44
backend/app/static/novnc/core/decoders/rre.js
Normal file
@@ -0,0 +1,44 @@
|
||||
/*
|
||||
* noVNC: HTML5 VNC client
|
||||
* Copyright (C) 2019 The noVNC Authors
|
||||
* Licensed under MPL 2.0 (see LICENSE.txt)
|
||||
*
|
||||
* See README.md for usage and integration instructions.
|
||||
*
|
||||
*/
|
||||
|
||||
export default class RREDecoder {
|
||||
constructor() {
|
||||
this._subrects = 0;
|
||||
}
|
||||
|
||||
decodeRect(x, y, width, height, sock, display, depth) {
|
||||
if (this._subrects === 0) {
|
||||
if (sock.rQwait("RRE", 4 + 4)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
this._subrects = sock.rQshift32();
|
||||
|
||||
let color = sock.rQshiftBytes(4); // Background
|
||||
display.fillRect(x, y, width, height, color);
|
||||
}
|
||||
|
||||
while (this._subrects > 0) {
|
||||
if (sock.rQwait("RRE", 4 + 8)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
let color = sock.rQshiftBytes(4);
|
||||
let sx = sock.rQshift16();
|
||||
let sy = sock.rQshift16();
|
||||
let swidth = sock.rQshift16();
|
||||
let sheight = sock.rQshift16();
|
||||
display.fillRect(x + sx, y + sy, swidth, sheight, color);
|
||||
|
||||
this._subrects--;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
331
backend/app/static/novnc/core/decoders/tight.js
Normal file
331
backend/app/static/novnc/core/decoders/tight.js
Normal file
@@ -0,0 +1,331 @@
|
||||
/*
|
||||
* noVNC: HTML5 VNC client
|
||||
* Copyright (C) 2019 The noVNC Authors
|
||||
* (c) 2012 Michael Tinglof, Joe Balaz, Les Piech (Mercuri.ca)
|
||||
* Licensed under MPL 2.0 (see LICENSE.txt)
|
||||
*
|
||||
* See README.md for usage and integration instructions.
|
||||
*
|
||||
*/
|
||||
|
||||
import * as Log from '../util/logging.js';
|
||||
import Inflator from "../inflator.js";
|
||||
|
||||
export default class TightDecoder {
|
||||
constructor() {
|
||||
this._ctl = null;
|
||||
this._filter = null;
|
||||
this._numColors = 0;
|
||||
this._palette = new Uint8Array(1024); // 256 * 4 (max palette size * max bytes-per-pixel)
|
||||
this._len = 0;
|
||||
|
||||
this._zlibs = [];
|
||||
for (let i = 0; i < 4; i++) {
|
||||
this._zlibs[i] = new Inflator();
|
||||
}
|
||||
}
|
||||
|
||||
decodeRect(x, y, width, height, sock, display, depth) {
|
||||
if (this._ctl === null) {
|
||||
if (sock.rQwait("TIGHT compression-control", 1)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
this._ctl = sock.rQshift8();
|
||||
|
||||
// Reset streams if the server requests it
|
||||
for (let i = 0; i < 4; i++) {
|
||||
if ((this._ctl >> i) & 1) {
|
||||
this._zlibs[i].reset();
|
||||
Log.Info("Reset zlib stream " + i);
|
||||
}
|
||||
}
|
||||
|
||||
// Figure out filter
|
||||
this._ctl = this._ctl >> 4;
|
||||
}
|
||||
|
||||
let ret;
|
||||
|
||||
if (this._ctl === 0x08) {
|
||||
ret = this._fillRect(x, y, width, height,
|
||||
sock, display, depth);
|
||||
} else if (this._ctl === 0x09) {
|
||||
ret = this._jpegRect(x, y, width, height,
|
||||
sock, display, depth);
|
||||
} else if (this._ctl === 0x0A) {
|
||||
ret = this._pngRect(x, y, width, height,
|
||||
sock, display, depth);
|
||||
} else if ((this._ctl & 0x08) == 0) {
|
||||
ret = this._basicRect(this._ctl, x, y, width, height,
|
||||
sock, display, depth);
|
||||
} else {
|
||||
throw new Error("Illegal tight compression received (ctl: " +
|
||||
this._ctl + ")");
|
||||
}
|
||||
|
||||
if (ret) {
|
||||
this._ctl = null;
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
_fillRect(x, y, width, height, sock, display, depth) {
|
||||
if (sock.rQwait("TIGHT", 3)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const rQi = sock.rQi;
|
||||
const rQ = sock.rQ;
|
||||
|
||||
display.fillRect(x, y, width, height,
|
||||
[rQ[rQi], rQ[rQi + 1], rQ[rQi + 2]], false);
|
||||
sock.rQskipBytes(3);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
_jpegRect(x, y, width, height, sock, display, depth) {
|
||||
let data = this._readData(sock);
|
||||
if (data === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
display.imageRect(x, y, width, height, "image/jpeg", data);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
_pngRect(x, y, width, height, sock, display, depth) {
|
||||
throw new Error("PNG received in standard Tight rect");
|
||||
}
|
||||
|
||||
_basicRect(ctl, x, y, width, height, sock, display, depth) {
|
||||
if (this._filter === null) {
|
||||
if (ctl & 0x4) {
|
||||
if (sock.rQwait("TIGHT", 1)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
this._filter = sock.rQshift8();
|
||||
} else {
|
||||
// Implicit CopyFilter
|
||||
this._filter = 0;
|
||||
}
|
||||
}
|
||||
|
||||
let streamId = ctl & 0x3;
|
||||
|
||||
let ret;
|
||||
|
||||
switch (this._filter) {
|
||||
case 0: // CopyFilter
|
||||
ret = this._copyFilter(streamId, x, y, width, height,
|
||||
sock, display, depth);
|
||||
break;
|
||||
case 1: // PaletteFilter
|
||||
ret = this._paletteFilter(streamId, x, y, width, height,
|
||||
sock, display, depth);
|
||||
break;
|
||||
case 2: // GradientFilter
|
||||
ret = this._gradientFilter(streamId, x, y, width, height,
|
||||
sock, display, depth);
|
||||
break;
|
||||
default:
|
||||
throw new Error("Illegal tight filter received (ctl: " +
|
||||
this._filter + ")");
|
||||
}
|
||||
|
||||
if (ret) {
|
||||
this._filter = null;
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
_copyFilter(streamId, x, y, width, height, sock, display, depth) {
|
||||
const uncompressedSize = width * height * 3;
|
||||
let data;
|
||||
|
||||
if (uncompressedSize === 0) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (uncompressedSize < 12) {
|
||||
if (sock.rQwait("TIGHT", uncompressedSize)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
data = sock.rQshiftBytes(uncompressedSize);
|
||||
} else {
|
||||
data = this._readData(sock);
|
||||
if (data === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
this._zlibs[streamId].setInput(data);
|
||||
data = this._zlibs[streamId].inflate(uncompressedSize);
|
||||
this._zlibs[streamId].setInput(null);
|
||||
}
|
||||
|
||||
let rgbx = new Uint8Array(width * height * 4);
|
||||
for (let i = 0, j = 0; i < width * height * 4; i += 4, j += 3) {
|
||||
rgbx[i] = data[j];
|
||||
rgbx[i + 1] = data[j + 1];
|
||||
rgbx[i + 2] = data[j + 2];
|
||||
rgbx[i + 3] = 255; // Alpha
|
||||
}
|
||||
|
||||
display.blitImage(x, y, width, height, rgbx, 0, false);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
_paletteFilter(streamId, x, y, width, height, sock, display, depth) {
|
||||
if (this._numColors === 0) {
|
||||
if (sock.rQwait("TIGHT palette", 1)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const numColors = sock.rQpeek8() + 1;
|
||||
const paletteSize = numColors * 3;
|
||||
|
||||
if (sock.rQwait("TIGHT palette", 1 + paletteSize)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
this._numColors = numColors;
|
||||
sock.rQskipBytes(1);
|
||||
|
||||
sock.rQshiftTo(this._palette, paletteSize);
|
||||
}
|
||||
|
||||
const bpp = (this._numColors <= 2) ? 1 : 8;
|
||||
const rowSize = Math.floor((width * bpp + 7) / 8);
|
||||
const uncompressedSize = rowSize * height;
|
||||
|
||||
let data;
|
||||
|
||||
if (uncompressedSize === 0) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (uncompressedSize < 12) {
|
||||
if (sock.rQwait("TIGHT", uncompressedSize)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
data = sock.rQshiftBytes(uncompressedSize);
|
||||
} else {
|
||||
data = this._readData(sock);
|
||||
if (data === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
this._zlibs[streamId].setInput(data);
|
||||
data = this._zlibs[streamId].inflate(uncompressedSize);
|
||||
this._zlibs[streamId].setInput(null);
|
||||
}
|
||||
|
||||
// Convert indexed (palette based) image data to RGB
|
||||
if (this._numColors == 2) {
|
||||
this._monoRect(x, y, width, height, data, this._palette, display);
|
||||
} else {
|
||||
this._paletteRect(x, y, width, height, data, this._palette, display);
|
||||
}
|
||||
|
||||
this._numColors = 0;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
_monoRect(x, y, width, height, data, palette, display) {
|
||||
// Convert indexed (palette based) image data to RGB
|
||||
// TODO: reduce number of calculations inside loop
|
||||
const dest = this._getScratchBuffer(width * height * 4);
|
||||
const w = Math.floor((width + 7) / 8);
|
||||
const w1 = Math.floor(width / 8);
|
||||
|
||||
for (let y = 0; y < height; y++) {
|
||||
let dp, sp, x;
|
||||
for (x = 0; x < w1; x++) {
|
||||
for (let b = 7; b >= 0; b--) {
|
||||
dp = (y * width + x * 8 + 7 - b) * 4;
|
||||
sp = (data[y * w + x] >> b & 1) * 3;
|
||||
dest[dp] = palette[sp];
|
||||
dest[dp + 1] = palette[sp + 1];
|
||||
dest[dp + 2] = palette[sp + 2];
|
||||
dest[dp + 3] = 255;
|
||||
}
|
||||
}
|
||||
|
||||
for (let b = 7; b >= 8 - width % 8; b--) {
|
||||
dp = (y * width + x * 8 + 7 - b) * 4;
|
||||
sp = (data[y * w + x] >> b & 1) * 3;
|
||||
dest[dp] = palette[sp];
|
||||
dest[dp + 1] = palette[sp + 1];
|
||||
dest[dp + 2] = palette[sp + 2];
|
||||
dest[dp + 3] = 255;
|
||||
}
|
||||
}
|
||||
|
||||
display.blitImage(x, y, width, height, dest, 0, false);
|
||||
}
|
||||
|
||||
_paletteRect(x, y, width, height, data, palette, display) {
|
||||
// Convert indexed (palette based) image data to RGB
|
||||
const dest = this._getScratchBuffer(width * height * 4);
|
||||
const total = width * height * 4;
|
||||
for (let i = 0, j = 0; i < total; i += 4, j++) {
|
||||
const sp = data[j] * 3;
|
||||
dest[i] = palette[sp];
|
||||
dest[i + 1] = palette[sp + 1];
|
||||
dest[i + 2] = palette[sp + 2];
|
||||
dest[i + 3] = 255;
|
||||
}
|
||||
|
||||
display.blitImage(x, y, width, height, dest, 0, false);
|
||||
}
|
||||
|
||||
_gradientFilter(streamId, x, y, width, height, sock, display, depth) {
|
||||
throw new Error("Gradient filter not implemented");
|
||||
}
|
||||
|
||||
_readData(sock) {
|
||||
if (this._len === 0) {
|
||||
if (sock.rQwait("TIGHT", 3)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
let byte;
|
||||
|
||||
byte = sock.rQshift8();
|
||||
this._len = byte & 0x7f;
|
||||
if (byte & 0x80) {
|
||||
byte = sock.rQshift8();
|
||||
this._len |= (byte & 0x7f) << 7;
|
||||
if (byte & 0x80) {
|
||||
byte = sock.rQshift8();
|
||||
this._len |= byte << 14;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (sock.rQwait("TIGHT", this._len)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
let data = sock.rQshiftBytes(this._len);
|
||||
this._len = 0;
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
_getScratchBuffer(size) {
|
||||
if (!this._scratchBuffer || (this._scratchBuffer.length < size)) {
|
||||
this._scratchBuffer = new Uint8Array(size);
|
||||
}
|
||||
return this._scratchBuffer;
|
||||
}
|
||||
}
|
||||
27
backend/app/static/novnc/core/decoders/tightpng.js
Normal file
27
backend/app/static/novnc/core/decoders/tightpng.js
Normal file
@@ -0,0 +1,27 @@
|
||||
/*
|
||||
* noVNC: HTML5 VNC client
|
||||
* Copyright (C) 2019 The noVNC Authors
|
||||
* Licensed under MPL 2.0 (see LICENSE.txt)
|
||||
*
|
||||
* See README.md for usage and integration instructions.
|
||||
*
|
||||
*/
|
||||
|
||||
import TightDecoder from './tight.js';
|
||||
|
||||
export default class TightPNGDecoder extends TightDecoder {
|
||||
_pngRect(x, y, width, height, sock, display, depth) {
|
||||
let data = this._readData(sock);
|
||||
if (data === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
display.imageRect(x, y, width, height, "image/png", data);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
_basicRect(ctl, x, y, width, height, sock, display, depth) {
|
||||
throw new Error("BasicCompression received in TightPNG rect");
|
||||
}
|
||||
}
|
||||
185
backend/app/static/novnc/core/decoders/zrle.js
Normal file
185
backend/app/static/novnc/core/decoders/zrle.js
Normal file
@@ -0,0 +1,185 @@
|
||||
/*
|
||||
* noVNC: HTML5 VNC client
|
||||
* Copyright (C) 2021 The noVNC Authors
|
||||
* Licensed under MPL 2.0 (see LICENSE.txt)
|
||||
*
|
||||
* See README.md for usage and integration instructions.
|
||||
*
|
||||
*/
|
||||
|
||||
import Inflate from "../inflator.js";
|
||||
|
||||
const ZRLE_TILE_WIDTH = 64;
|
||||
const ZRLE_TILE_HEIGHT = 64;
|
||||
|
||||
export default class ZRLEDecoder {
|
||||
constructor() {
|
||||
this._length = 0;
|
||||
this._inflator = new Inflate();
|
||||
|
||||
this._pixelBuffer = new Uint8Array(ZRLE_TILE_WIDTH * ZRLE_TILE_HEIGHT * 4);
|
||||
this._tileBuffer = new Uint8Array(ZRLE_TILE_WIDTH * ZRLE_TILE_HEIGHT * 4);
|
||||
}
|
||||
|
||||
decodeRect(x, y, width, height, sock, display, depth) {
|
||||
if (this._length === 0) {
|
||||
if (sock.rQwait("ZLib data length", 4)) {
|
||||
return false;
|
||||
}
|
||||
this._length = sock.rQshift32();
|
||||
}
|
||||
if (sock.rQwait("Zlib data", this._length)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const data = sock.rQshiftBytes(this._length);
|
||||
|
||||
this._inflator.setInput(data);
|
||||
|
||||
for (let ty = y; ty < y + height; ty += ZRLE_TILE_HEIGHT) {
|
||||
let th = Math.min(ZRLE_TILE_HEIGHT, y + height - ty);
|
||||
|
||||
for (let tx = x; tx < x + width; tx += ZRLE_TILE_WIDTH) {
|
||||
let tw = Math.min(ZRLE_TILE_WIDTH, x + width - tx);
|
||||
|
||||
const tileSize = tw * th;
|
||||
const subencoding = this._inflator.inflate(1)[0];
|
||||
if (subencoding === 0) {
|
||||
// raw data
|
||||
const data = this._readPixels(tileSize);
|
||||
display.blitImage(tx, ty, tw, th, data, 0, false);
|
||||
} else if (subencoding === 1) {
|
||||
// solid
|
||||
const background = this._readPixels(1);
|
||||
display.fillRect(tx, ty, tw, th, [background[0], background[1], background[2]]);
|
||||
} else if (subencoding >= 2 && subencoding <= 16) {
|
||||
const data = this._decodePaletteTile(subencoding, tileSize, tw, th);
|
||||
display.blitImage(tx, ty, tw, th, data, 0, false);
|
||||
} else if (subencoding === 128) {
|
||||
const data = this._decodeRLETile(tileSize);
|
||||
display.blitImage(tx, ty, tw, th, data, 0, false);
|
||||
} else if (subencoding >= 130 && subencoding <= 255) {
|
||||
const data = this._decodeRLEPaletteTile(subencoding - 128, tileSize);
|
||||
display.blitImage(tx, ty, tw, th, data, 0, false);
|
||||
} else {
|
||||
throw new Error('Unknown subencoding: ' + subencoding);
|
||||
}
|
||||
}
|
||||
}
|
||||
this._length = 0;
|
||||
return true;
|
||||
}
|
||||
|
||||
_getBitsPerPixelInPalette(paletteSize) {
|
||||
if (paletteSize <= 2) {
|
||||
return 1;
|
||||
} else if (paletteSize <= 4) {
|
||||
return 2;
|
||||
} else if (paletteSize <= 16) {
|
||||
return 4;
|
||||
}
|
||||
}
|
||||
|
||||
_readPixels(pixels) {
|
||||
let data = this._pixelBuffer;
|
||||
const buffer = this._inflator.inflate(3*pixels);
|
||||
for (let i = 0, j = 0; i < pixels*4; i += 4, j += 3) {
|
||||
data[i] = buffer[j];
|
||||
data[i + 1] = buffer[j + 1];
|
||||
data[i + 2] = buffer[j + 2];
|
||||
data[i + 3] = 255; // Add the Alpha
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
_decodePaletteTile(paletteSize, tileSize, tilew, tileh) {
|
||||
const data = this._tileBuffer;
|
||||
const palette = this._readPixels(paletteSize);
|
||||
const bitsPerPixel = this._getBitsPerPixelInPalette(paletteSize);
|
||||
const mask = (1 << bitsPerPixel) - 1;
|
||||
|
||||
let offset = 0;
|
||||
let encoded = this._inflator.inflate(1)[0];
|
||||
|
||||
for (let y=0; y<tileh; y++) {
|
||||
let shift = 8-bitsPerPixel;
|
||||
for (let x=0; x<tilew; x++) {
|
||||
if (shift<0) {
|
||||
shift=8-bitsPerPixel;
|
||||
encoded = this._inflator.inflate(1)[0];
|
||||
}
|
||||
let indexInPalette = (encoded>>shift) & mask;
|
||||
|
||||
data[offset] = palette[indexInPalette * 4];
|
||||
data[offset + 1] = palette[indexInPalette * 4 + 1];
|
||||
data[offset + 2] = palette[indexInPalette * 4 + 2];
|
||||
data[offset + 3] = palette[indexInPalette * 4 + 3];
|
||||
offset += 4;
|
||||
shift-=bitsPerPixel;
|
||||
}
|
||||
if (shift<8-bitsPerPixel && y<tileh-1) {
|
||||
encoded = this._inflator.inflate(1)[0];
|
||||
}
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
_decodeRLETile(tileSize) {
|
||||
const data = this._tileBuffer;
|
||||
let i = 0;
|
||||
while (i < tileSize) {
|
||||
const pixel = this._readPixels(1);
|
||||
const length = this._readRLELength();
|
||||
for (let j = 0; j < length; j++) {
|
||||
data[i * 4] = pixel[0];
|
||||
data[i * 4 + 1] = pixel[1];
|
||||
data[i * 4 + 2] = pixel[2];
|
||||
data[i * 4 + 3] = pixel[3];
|
||||
i++;
|
||||
}
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
_decodeRLEPaletteTile(paletteSize, tileSize) {
|
||||
const data = this._tileBuffer;
|
||||
|
||||
// palette
|
||||
const palette = this._readPixels(paletteSize);
|
||||
|
||||
let offset = 0;
|
||||
while (offset < tileSize) {
|
||||
let indexInPalette = this._inflator.inflate(1)[0];
|
||||
let length = 1;
|
||||
if (indexInPalette >= 128) {
|
||||
indexInPalette -= 128;
|
||||
length = this._readRLELength();
|
||||
}
|
||||
if (indexInPalette > paletteSize) {
|
||||
throw new Error('Too big index in palette: ' + indexInPalette + ', palette size: ' + paletteSize);
|
||||
}
|
||||
if (offset + length > tileSize) {
|
||||
throw new Error('Too big rle length in palette mode: ' + length + ', allowed length is: ' + (tileSize - offset));
|
||||
}
|
||||
|
||||
for (let j = 0; j < length; j++) {
|
||||
data[offset * 4] = palette[indexInPalette * 4];
|
||||
data[offset * 4 + 1] = palette[indexInPalette * 4 + 1];
|
||||
data[offset * 4 + 2] = palette[indexInPalette * 4 + 2];
|
||||
data[offset * 4 + 3] = palette[indexInPalette * 4 + 3];
|
||||
offset++;
|
||||
}
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
_readRLELength() {
|
||||
let length = 0;
|
||||
let current = 0;
|
||||
do {
|
||||
current = this._inflator.inflate(1)[0];
|
||||
length += current;
|
||||
} while (current === 255);
|
||||
return length + 1;
|
||||
}
|
||||
}
|
||||
85
backend/app/static/novnc/core/deflator.js
Normal file
85
backend/app/static/novnc/core/deflator.js
Normal file
@@ -0,0 +1,85 @@
|
||||
/*
|
||||
* noVNC: HTML5 VNC client
|
||||
* Copyright (C) 2020 The noVNC Authors
|
||||
* Licensed under MPL 2.0 (see LICENSE.txt)
|
||||
*
|
||||
* See README.md for usage and integration instructions.
|
||||
*/
|
||||
|
||||
import { deflateInit, deflate } from "../vendor/pako/lib/zlib/deflate.js";
|
||||
import { Z_FULL_FLUSH } from "../vendor/pako/lib/zlib/deflate.js";
|
||||
import ZStream from "../vendor/pako/lib/zlib/zstream.js";
|
||||
|
||||
export default class Deflator {
|
||||
constructor() {
|
||||
this.strm = new ZStream();
|
||||
this.chunkSize = 1024 * 10 * 10;
|
||||
this.outputBuffer = new Uint8Array(this.chunkSize);
|
||||
this.windowBits = 5;
|
||||
|
||||
deflateInit(this.strm, this.windowBits);
|
||||
}
|
||||
|
||||
deflate(inData) {
|
||||
/* eslint-disable camelcase */
|
||||
this.strm.input = inData;
|
||||
this.strm.avail_in = this.strm.input.length;
|
||||
this.strm.next_in = 0;
|
||||
this.strm.output = this.outputBuffer;
|
||||
this.strm.avail_out = this.chunkSize;
|
||||
this.strm.next_out = 0;
|
||||
/* eslint-enable camelcase */
|
||||
|
||||
let lastRet = deflate(this.strm, Z_FULL_FLUSH);
|
||||
let outData = new Uint8Array(this.strm.output.buffer, 0, this.strm.next_out);
|
||||
|
||||
if (lastRet < 0) {
|
||||
throw new Error("zlib deflate failed");
|
||||
}
|
||||
|
||||
if (this.strm.avail_in > 0) {
|
||||
// Read chunks until done
|
||||
|
||||
let chunks = [outData];
|
||||
let totalLen = outData.length;
|
||||
do {
|
||||
/* eslint-disable camelcase */
|
||||
this.strm.output = new Uint8Array(this.chunkSize);
|
||||
this.strm.next_out = 0;
|
||||
this.strm.avail_out = this.chunkSize;
|
||||
/* eslint-enable camelcase */
|
||||
|
||||
lastRet = deflate(this.strm, Z_FULL_FLUSH);
|
||||
|
||||
if (lastRet < 0) {
|
||||
throw new Error("zlib deflate failed");
|
||||
}
|
||||
|
||||
let chunk = new Uint8Array(this.strm.output.buffer, 0, this.strm.next_out);
|
||||
totalLen += chunk.length;
|
||||
chunks.push(chunk);
|
||||
} while (this.strm.avail_in > 0);
|
||||
|
||||
// Combine chunks into a single data
|
||||
|
||||
let newData = new Uint8Array(totalLen);
|
||||
let offset = 0;
|
||||
|
||||
for (let i = 0; i < chunks.length; i++) {
|
||||
newData.set(chunks[i], offset);
|
||||
offset += chunks[i].length;
|
||||
}
|
||||
|
||||
outData = newData;
|
||||
}
|
||||
|
||||
/* eslint-disable camelcase */
|
||||
this.strm.input = null;
|
||||
this.strm.avail_in = 0;
|
||||
this.strm.next_in = 0;
|
||||
/* eslint-enable camelcase */
|
||||
|
||||
return outData;
|
||||
}
|
||||
|
||||
}
|
||||
266
backend/app/static/novnc/core/des.js
Normal file
266
backend/app/static/novnc/core/des.js
Normal file
@@ -0,0 +1,266 @@
|
||||
/*
|
||||
* Ported from Flashlight VNC ActionScript implementation:
|
||||
* http://www.wizhelp.com/flashlight-vnc/
|
||||
*
|
||||
* Full attribution follows:
|
||||
*
|
||||
* -------------------------------------------------------------------------
|
||||
*
|
||||
* This DES class has been extracted from package Acme.Crypto for use in VNC.
|
||||
* The unnecessary odd parity code has been removed.
|
||||
*
|
||||
* These changes are:
|
||||
* Copyright (C) 1999 AT&T Laboratories Cambridge. All Rights Reserved.
|
||||
*
|
||||
* This software is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
|
||||
*
|
||||
|
||||
* DesCipher - the DES encryption method
|
||||
*
|
||||
* The meat of this code is by Dave Zimmerman <dzimm@widget.com>, and is:
|
||||
*
|
||||
* Copyright (c) 1996 Widget Workshop, Inc. All Rights Reserved.
|
||||
*
|
||||
* Permission to use, copy, modify, and distribute this software
|
||||
* and its documentation for NON-COMMERCIAL or COMMERCIAL purposes and
|
||||
* without fee is hereby granted, provided that this copyright notice is kept
|
||||
* intact.
|
||||
*
|
||||
* WIDGET WORKSHOP MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY
|
||||
* OF THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
|
||||
* TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
|
||||
* PARTICULAR PURPOSE, OR NON-INFRINGEMENT. WIDGET WORKSHOP SHALL NOT BE LIABLE
|
||||
* FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
|
||||
* DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
|
||||
*
|
||||
* THIS SOFTWARE IS NOT DESIGNED OR INTENDED FOR USE OR RESALE AS ON-LINE
|
||||
* CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING FAIL-SAFE
|
||||
* PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, AIRCRAFT
|
||||
* NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT LIFE
|
||||
* SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE
|
||||
* SOFTWARE COULD LEAD DIRECTLY TO DEATH, PERSONAL INJURY, OR SEVERE
|
||||
* PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH RISK ACTIVITIES"). WIDGET WORKSHOP
|
||||
* SPECIFICALLY DISCLAIMS ANY EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR
|
||||
* HIGH RISK ACTIVITIES.
|
||||
*
|
||||
*
|
||||
* The rest is:
|
||||
*
|
||||
* Copyright (C) 1996 by Jef Poskanzer <jef@acme.com>. All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
* 1. Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* 2. Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
|
||||
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
|
||||
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
|
||||
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
|
||||
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
||||
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
|
||||
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
|
||||
* SUCH DAMAGE.
|
||||
*
|
||||
* Visit the ACME Labs Java page for up-to-date versions of this and other
|
||||
* fine Java utilities: http://www.acme.com/java/
|
||||
*/
|
||||
|
||||
/* eslint-disable comma-spacing */
|
||||
|
||||
// Tables, permutations, S-boxes, etc.
|
||||
const PC2 = [13,16,10,23, 0, 4, 2,27,14, 5,20, 9,22,18,11, 3,
|
||||
25, 7,15, 6,26,19,12, 1,40,51,30,36,46,54,29,39,
|
||||
50,44,32,47,43,48,38,55,33,52,45,41,49,35,28,31 ],
|
||||
totrot = [ 1, 2, 4, 6, 8,10,12,14,15,17,19,21,23,25,27,28];
|
||||
|
||||
const z = 0x0;
|
||||
let a,b,c,d,e,f;
|
||||
a=1<<16; b=1<<24; c=a|b; d=1<<2; e=1<<10; f=d|e;
|
||||
const SP1 = [c|e,z|z,a|z,c|f,c|d,a|f,z|d,a|z,z|e,c|e,c|f,z|e,b|f,c|d,b|z,z|d,
|
||||
z|f,b|e,b|e,a|e,a|e,c|z,c|z,b|f,a|d,b|d,b|d,a|d,z|z,z|f,a|f,b|z,
|
||||
a|z,c|f,z|d,c|z,c|e,b|z,b|z,z|e,c|d,a|z,a|e,b|d,z|e,z|d,b|f,a|f,
|
||||
c|f,a|d,c|z,b|f,b|d,z|f,a|f,c|e,z|f,b|e,b|e,z|z,a|d,a|e,z|z,c|d];
|
||||
a=1<<20; b=1<<31; c=a|b; d=1<<5; e=1<<15; f=d|e;
|
||||
const SP2 = [c|f,b|e,z|e,a|f,a|z,z|d,c|d,b|f,b|d,c|f,c|e,b|z,b|e,a|z,z|d,c|d,
|
||||
a|e,a|d,b|f,z|z,b|z,z|e,a|f,c|z,a|d,b|d,z|z,a|e,z|f,c|e,c|z,z|f,
|
||||
z|z,a|f,c|d,a|z,b|f,c|z,c|e,z|e,c|z,b|e,z|d,c|f,a|f,z|d,z|e,b|z,
|
||||
z|f,c|e,a|z,b|d,a|d,b|f,b|d,a|d,a|e,z|z,b|e,z|f,b|z,c|d,c|f,a|e];
|
||||
a=1<<17; b=1<<27; c=a|b; d=1<<3; e=1<<9; f=d|e;
|
||||
const SP3 = [z|f,c|e,z|z,c|d,b|e,z|z,a|f,b|e,a|d,b|d,b|d,a|z,c|f,a|d,c|z,z|f,
|
||||
b|z,z|d,c|e,z|e,a|e,c|z,c|d,a|f,b|f,a|e,a|z,b|f,z|d,c|f,z|e,b|z,
|
||||
c|e,b|z,a|d,z|f,a|z,c|e,b|e,z|z,z|e,a|d,c|f,b|e,b|d,z|e,z|z,c|d,
|
||||
b|f,a|z,b|z,c|f,z|d,a|f,a|e,b|d,c|z,b|f,z|f,c|z,a|f,z|d,c|d,a|e];
|
||||
a=1<<13; b=1<<23; c=a|b; d=1<<0; e=1<<7; f=d|e;
|
||||
const SP4 = [c|d,a|f,a|f,z|e,c|e,b|f,b|d,a|d,z|z,c|z,c|z,c|f,z|f,z|z,b|e,b|d,
|
||||
z|d,a|z,b|z,c|d,z|e,b|z,a|d,a|e,b|f,z|d,a|e,b|e,a|z,c|e,c|f,z|f,
|
||||
b|e,b|d,c|z,c|f,z|f,z|z,z|z,c|z,a|e,b|e,b|f,z|d,c|d,a|f,a|f,z|e,
|
||||
c|f,z|f,z|d,a|z,b|d,a|d,c|e,b|f,a|d,a|e,b|z,c|d,z|e,b|z,a|z,c|e];
|
||||
a=1<<25; b=1<<30; c=a|b; d=1<<8; e=1<<19; f=d|e;
|
||||
const SP5 = [z|d,a|f,a|e,c|d,z|e,z|d,b|z,a|e,b|f,z|e,a|d,b|f,c|d,c|e,z|f,b|z,
|
||||
a|z,b|e,b|e,z|z,b|d,c|f,c|f,a|d,c|e,b|d,z|z,c|z,a|f,a|z,c|z,z|f,
|
||||
z|e,c|d,z|d,a|z,b|z,a|e,c|d,b|f,a|d,b|z,c|e,a|f,b|f,z|d,a|z,c|e,
|
||||
c|f,z|f,c|z,c|f,a|e,z|z,b|e,c|z,z|f,a|d,b|d,z|e,z|z,b|e,a|f,b|d];
|
||||
a=1<<22; b=1<<29; c=a|b; d=1<<4; e=1<<14; f=d|e;
|
||||
const SP6 = [b|d,c|z,z|e,c|f,c|z,z|d,c|f,a|z,b|e,a|f,a|z,b|d,a|d,b|e,b|z,z|f,
|
||||
z|z,a|d,b|f,z|e,a|e,b|f,z|d,c|d,c|d,z|z,a|f,c|e,z|f,a|e,c|e,b|z,
|
||||
b|e,z|d,c|d,a|e,c|f,a|z,z|f,b|d,a|z,b|e,b|z,z|f,b|d,c|f,a|e,c|z,
|
||||
a|f,c|e,z|z,c|d,z|d,z|e,c|z,a|f,z|e,a|d,b|f,z|z,c|e,b|z,a|d,b|f];
|
||||
a=1<<21; b=1<<26; c=a|b; d=1<<1; e=1<<11; f=d|e;
|
||||
const SP7 = [a|z,c|d,b|f,z|z,z|e,b|f,a|f,c|e,c|f,a|z,z|z,b|d,z|d,b|z,c|d,z|f,
|
||||
b|e,a|f,a|d,b|e,b|d,c|z,c|e,a|d,c|z,z|e,z|f,c|f,a|e,z|d,b|z,a|e,
|
||||
b|z,a|e,a|z,b|f,b|f,c|d,c|d,z|d,a|d,b|z,b|e,a|z,c|e,z|f,a|f,c|e,
|
||||
z|f,b|d,c|f,c|z,a|e,z|z,z|d,c|f,z|z,a|f,c|z,z|e,b|d,b|e,z|e,a|d];
|
||||
a=1<<18; b=1<<28; c=a|b; d=1<<6; e=1<<12; f=d|e;
|
||||
const SP8 = [b|f,z|e,a|z,c|f,b|z,b|f,z|d,b|z,a|d,c|z,c|f,a|e,c|e,a|f,z|e,z|d,
|
||||
c|z,b|d,b|e,z|f,a|e,a|d,c|d,c|e,z|f,z|z,z|z,c|d,b|d,b|e,a|f,a|z,
|
||||
a|f,a|z,c|e,z|e,z|d,c|d,z|e,a|f,b|e,z|d,b|d,c|z,c|d,b|z,a|z,b|f,
|
||||
z|z,c|f,a|d,b|d,c|z,b|e,b|f,z|z,c|f,a|e,a|e,z|f,z|f,a|d,b|z,c|e];
|
||||
|
||||
/* eslint-enable comma-spacing */
|
||||
|
||||
export default class DES {
|
||||
constructor(password) {
|
||||
this.keys = [];
|
||||
|
||||
// Set the key.
|
||||
const pc1m = [], pcr = [], kn = [];
|
||||
|
||||
for (let j = 0, l = 56; j < 56; ++j, l -= 8) {
|
||||
l += l < -5 ? 65 : l < -3 ? 31 : l < -1 ? 63 : l === 27 ? 35 : 0; // PC1
|
||||
const m = l & 0x7;
|
||||
pc1m[j] = ((password[l >>> 3] & (1<<m)) !== 0) ? 1: 0;
|
||||
}
|
||||
|
||||
for (let i = 0; i < 16; ++i) {
|
||||
const m = i << 1;
|
||||
const n = m + 1;
|
||||
kn[m] = kn[n] = 0;
|
||||
for (let o = 28; o < 59; o += 28) {
|
||||
for (let j = o - 28; j < o; ++j) {
|
||||
const l = j + totrot[i];
|
||||
pcr[j] = l < o ? pc1m[l] : pc1m[l - 28];
|
||||
}
|
||||
}
|
||||
for (let j = 0; j < 24; ++j) {
|
||||
if (pcr[PC2[j]] !== 0) {
|
||||
kn[m] |= 1 << (23 - j);
|
||||
}
|
||||
if (pcr[PC2[j + 24]] !== 0) {
|
||||
kn[n] |= 1 << (23 - j);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// cookey
|
||||
for (let i = 0, rawi = 0, KnLi = 0; i < 16; ++i) {
|
||||
const raw0 = kn[rawi++];
|
||||
const raw1 = kn[rawi++];
|
||||
this.keys[KnLi] = (raw0 & 0x00fc0000) << 6;
|
||||
this.keys[KnLi] |= (raw0 & 0x00000fc0) << 10;
|
||||
this.keys[KnLi] |= (raw1 & 0x00fc0000) >>> 10;
|
||||
this.keys[KnLi] |= (raw1 & 0x00000fc0) >>> 6;
|
||||
++KnLi;
|
||||
this.keys[KnLi] = (raw0 & 0x0003f000) << 12;
|
||||
this.keys[KnLi] |= (raw0 & 0x0000003f) << 16;
|
||||
this.keys[KnLi] |= (raw1 & 0x0003f000) >>> 4;
|
||||
this.keys[KnLi] |= (raw1 & 0x0000003f);
|
||||
++KnLi;
|
||||
}
|
||||
}
|
||||
|
||||
// Encrypt 8 bytes of text
|
||||
enc8(text) {
|
||||
const b = text.slice();
|
||||
let i = 0, l, r, x; // left, right, accumulator
|
||||
|
||||
// Squash 8 bytes to 2 ints
|
||||
l = b[i++]<<24 | b[i++]<<16 | b[i++]<<8 | b[i++];
|
||||
r = b[i++]<<24 | b[i++]<<16 | b[i++]<<8 | b[i++];
|
||||
|
||||
x = ((l >>> 4) ^ r) & 0x0f0f0f0f;
|
||||
r ^= x;
|
||||
l ^= (x << 4);
|
||||
x = ((l >>> 16) ^ r) & 0x0000ffff;
|
||||
r ^= x;
|
||||
l ^= (x << 16);
|
||||
x = ((r >>> 2) ^ l) & 0x33333333;
|
||||
l ^= x;
|
||||
r ^= (x << 2);
|
||||
x = ((r >>> 8) ^ l) & 0x00ff00ff;
|
||||
l ^= x;
|
||||
r ^= (x << 8);
|
||||
r = (r << 1) | ((r >>> 31) & 1);
|
||||
x = (l ^ r) & 0xaaaaaaaa;
|
||||
l ^= x;
|
||||
r ^= x;
|
||||
l = (l << 1) | ((l >>> 31) & 1);
|
||||
|
||||
for (let i = 0, keysi = 0; i < 8; ++i) {
|
||||
x = (r << 28) | (r >>> 4);
|
||||
x ^= this.keys[keysi++];
|
||||
let fval = SP7[x & 0x3f];
|
||||
fval |= SP5[(x >>> 8) & 0x3f];
|
||||
fval |= SP3[(x >>> 16) & 0x3f];
|
||||
fval |= SP1[(x >>> 24) & 0x3f];
|
||||
x = r ^ this.keys[keysi++];
|
||||
fval |= SP8[x & 0x3f];
|
||||
fval |= SP6[(x >>> 8) & 0x3f];
|
||||
fval |= SP4[(x >>> 16) & 0x3f];
|
||||
fval |= SP2[(x >>> 24) & 0x3f];
|
||||
l ^= fval;
|
||||
x = (l << 28) | (l >>> 4);
|
||||
x ^= this.keys[keysi++];
|
||||
fval = SP7[x & 0x3f];
|
||||
fval |= SP5[(x >>> 8) & 0x3f];
|
||||
fval |= SP3[(x >>> 16) & 0x3f];
|
||||
fval |= SP1[(x >>> 24) & 0x3f];
|
||||
x = l ^ this.keys[keysi++];
|
||||
fval |= SP8[x & 0x0000003f];
|
||||
fval |= SP6[(x >>> 8) & 0x3f];
|
||||
fval |= SP4[(x >>> 16) & 0x3f];
|
||||
fval |= SP2[(x >>> 24) & 0x3f];
|
||||
r ^= fval;
|
||||
}
|
||||
|
||||
r = (r << 31) | (r >>> 1);
|
||||
x = (l ^ r) & 0xaaaaaaaa;
|
||||
l ^= x;
|
||||
r ^= x;
|
||||
l = (l << 31) | (l >>> 1);
|
||||
x = ((l >>> 8) ^ r) & 0x00ff00ff;
|
||||
r ^= x;
|
||||
l ^= (x << 8);
|
||||
x = ((l >>> 2) ^ r) & 0x33333333;
|
||||
r ^= x;
|
||||
l ^= (x << 2);
|
||||
x = ((r >>> 16) ^ l) & 0x0000ffff;
|
||||
l ^= x;
|
||||
r ^= (x << 16);
|
||||
x = ((r >>> 4) ^ l) & 0x0f0f0f0f;
|
||||
l ^= x;
|
||||
r ^= (x << 4);
|
||||
|
||||
// Spread ints to bytes
|
||||
x = [r, l];
|
||||
for (i = 0; i < 8; i++) {
|
||||
b[i] = (x[i>>>2] >>> (8 * (3 - (i % 4)))) % 256;
|
||||
if (b[i] < 0) { b[i] += 256; } // unsigned
|
||||
}
|
||||
return b;
|
||||
}
|
||||
|
||||
// Encrypt 16 bytes of text using passwd as key
|
||||
encrypt(t) {
|
||||
return this.enc8(t.slice(0, 8)).concat(this.enc8(t.slice(8, 16)));
|
||||
}
|
||||
}
|
||||
525
backend/app/static/novnc/core/display.js
Normal file
525
backend/app/static/novnc/core/display.js
Normal file
@@ -0,0 +1,525 @@
|
||||
/*
|
||||
* noVNC: HTML5 VNC client
|
||||
* Copyright (C) 2019 The noVNC Authors
|
||||
* Licensed under MPL 2.0 (see LICENSE.txt)
|
||||
*
|
||||
* See README.md for usage and integration instructions.
|
||||
*/
|
||||
|
||||
import * as Log from './util/logging.js';
|
||||
import Base64 from "./base64.js";
|
||||
import { toSigned32bit } from './util/int.js';
|
||||
|
||||
export default class Display {
|
||||
constructor(target) {
|
||||
this._drawCtx = null;
|
||||
|
||||
this._renderQ = []; // queue drawing actions for in-oder rendering
|
||||
this._flushing = false;
|
||||
|
||||
// the full frame buffer (logical canvas) size
|
||||
this._fbWidth = 0;
|
||||
this._fbHeight = 0;
|
||||
|
||||
this._prevDrawStyle = "";
|
||||
|
||||
Log.Debug(">> Display.constructor");
|
||||
|
||||
// The visible canvas
|
||||
this._target = target;
|
||||
|
||||
if (!this._target) {
|
||||
throw new Error("Target must be set");
|
||||
}
|
||||
|
||||
if (typeof this._target === 'string') {
|
||||
throw new Error('target must be a DOM element');
|
||||
}
|
||||
|
||||
if (!this._target.getContext) {
|
||||
throw new Error("no getContext method");
|
||||
}
|
||||
|
||||
this._targetCtx = this._target.getContext('2d');
|
||||
|
||||
// the visible canvas viewport (i.e. what actually gets seen)
|
||||
this._viewportLoc = { 'x': 0, 'y': 0, 'w': this._target.width, 'h': this._target.height };
|
||||
|
||||
// The hidden canvas, where we do the actual rendering
|
||||
this._backbuffer = document.createElement('canvas');
|
||||
this._drawCtx = this._backbuffer.getContext('2d');
|
||||
|
||||
this._damageBounds = { left: 0, top: 0,
|
||||
right: this._backbuffer.width,
|
||||
bottom: this._backbuffer.height };
|
||||
|
||||
Log.Debug("User Agent: " + navigator.userAgent);
|
||||
|
||||
Log.Debug("<< Display.constructor");
|
||||
|
||||
// ===== PROPERTIES =====
|
||||
|
||||
this._scale = 1.0;
|
||||
this._clipViewport = false;
|
||||
|
||||
// ===== EVENT HANDLERS =====
|
||||
|
||||
this.onflush = () => {}; // A flush request has finished
|
||||
}
|
||||
|
||||
// ===== PROPERTIES =====
|
||||
|
||||
get scale() { return this._scale; }
|
||||
set scale(scale) {
|
||||
this._rescale(scale);
|
||||
}
|
||||
|
||||
get clipViewport() { return this._clipViewport; }
|
||||
set clipViewport(viewport) {
|
||||
this._clipViewport = viewport;
|
||||
// May need to readjust the viewport dimensions
|
||||
const vp = this._viewportLoc;
|
||||
this.viewportChangeSize(vp.w, vp.h);
|
||||
this.viewportChangePos(0, 0);
|
||||
}
|
||||
|
||||
get width() {
|
||||
return this._fbWidth;
|
||||
}
|
||||
|
||||
get height() {
|
||||
return this._fbHeight;
|
||||
}
|
||||
|
||||
// ===== PUBLIC METHODS =====
|
||||
|
||||
viewportChangePos(deltaX, deltaY) {
|
||||
const vp = this._viewportLoc;
|
||||
deltaX = Math.floor(deltaX);
|
||||
deltaY = Math.floor(deltaY);
|
||||
|
||||
if (!this._clipViewport) {
|
||||
deltaX = -vp.w; // clamped later of out of bounds
|
||||
deltaY = -vp.h;
|
||||
}
|
||||
|
||||
const vx2 = vp.x + vp.w - 1;
|
||||
const vy2 = vp.y + vp.h - 1;
|
||||
|
||||
// Position change
|
||||
|
||||
if (deltaX < 0 && vp.x + deltaX < 0) {
|
||||
deltaX = -vp.x;
|
||||
}
|
||||
if (vx2 + deltaX >= this._fbWidth) {
|
||||
deltaX -= vx2 + deltaX - this._fbWidth + 1;
|
||||
}
|
||||
|
||||
if (vp.y + deltaY < 0) {
|
||||
deltaY = -vp.y;
|
||||
}
|
||||
if (vy2 + deltaY >= this._fbHeight) {
|
||||
deltaY -= (vy2 + deltaY - this._fbHeight + 1);
|
||||
}
|
||||
|
||||
if (deltaX === 0 && deltaY === 0) {
|
||||
return;
|
||||
}
|
||||
Log.Debug("viewportChange deltaX: " + deltaX + ", deltaY: " + deltaY);
|
||||
|
||||
vp.x += deltaX;
|
||||
vp.y += deltaY;
|
||||
|
||||
this._damage(vp.x, vp.y, vp.w, vp.h);
|
||||
|
||||
this.flip();
|
||||
}
|
||||
|
||||
viewportChangeSize(width, height) {
|
||||
|
||||
if (!this._clipViewport ||
|
||||
typeof(width) === "undefined" ||
|
||||
typeof(height) === "undefined") {
|
||||
|
||||
Log.Debug("Setting viewport to full display region");
|
||||
width = this._fbWidth;
|
||||
height = this._fbHeight;
|
||||
}
|
||||
|
||||
width = Math.floor(width);
|
||||
height = Math.floor(height);
|
||||
|
||||
if (width > this._fbWidth) {
|
||||
width = this._fbWidth;
|
||||
}
|
||||
if (height > this._fbHeight) {
|
||||
height = this._fbHeight;
|
||||
}
|
||||
|
||||
const vp = this._viewportLoc;
|
||||
if (vp.w !== width || vp.h !== height) {
|
||||
vp.w = width;
|
||||
vp.h = height;
|
||||
|
||||
const canvas = this._target;
|
||||
canvas.width = width;
|
||||
canvas.height = height;
|
||||
|
||||
// The position might need to be updated if we've grown
|
||||
this.viewportChangePos(0, 0);
|
||||
|
||||
this._damage(vp.x, vp.y, vp.w, vp.h);
|
||||
this.flip();
|
||||
|
||||
// Update the visible size of the target canvas
|
||||
this._rescale(this._scale);
|
||||
}
|
||||
}
|
||||
|
||||
absX(x) {
|
||||
if (this._scale === 0) {
|
||||
return 0;
|
||||
}
|
||||
return toSigned32bit(x / this._scale + this._viewportLoc.x);
|
||||
}
|
||||
|
||||
absY(y) {
|
||||
if (this._scale === 0) {
|
||||
return 0;
|
||||
}
|
||||
return toSigned32bit(y / this._scale + this._viewportLoc.y);
|
||||
}
|
||||
|
||||
resize(width, height) {
|
||||
this._prevDrawStyle = "";
|
||||
|
||||
this._fbWidth = width;
|
||||
this._fbHeight = height;
|
||||
|
||||
const canvas = this._backbuffer;
|
||||
if (canvas.width !== width || canvas.height !== height) {
|
||||
|
||||
// We have to save the canvas data since changing the size will clear it
|
||||
let saveImg = null;
|
||||
if (canvas.width > 0 && canvas.height > 0) {
|
||||
saveImg = this._drawCtx.getImageData(0, 0, canvas.width, canvas.height);
|
||||
}
|
||||
|
||||
if (canvas.width !== width) {
|
||||
canvas.width = width;
|
||||
}
|
||||
if (canvas.height !== height) {
|
||||
canvas.height = height;
|
||||
}
|
||||
|
||||
if (saveImg) {
|
||||
this._drawCtx.putImageData(saveImg, 0, 0);
|
||||
}
|
||||
}
|
||||
|
||||
// Readjust the viewport as it may be incorrectly sized
|
||||
// and positioned
|
||||
const vp = this._viewportLoc;
|
||||
this.viewportChangeSize(vp.w, vp.h);
|
||||
this.viewportChangePos(0, 0);
|
||||
}
|
||||
|
||||
getImageData() {
|
||||
return this._drawCtx.getImageData(0, 0, this.width, this.height);
|
||||
}
|
||||
|
||||
toDataURL(type, encoderOptions) {
|
||||
return this._backbuffer.toDataURL(type, encoderOptions);
|
||||
}
|
||||
|
||||
toBlob(callback, type, quality) {
|
||||
return this._backbuffer.toBlob(callback, type, quality);
|
||||
}
|
||||
|
||||
// Track what parts of the visible canvas that need updating
|
||||
_damage(x, y, w, h) {
|
||||
if (x < this._damageBounds.left) {
|
||||
this._damageBounds.left = x;
|
||||
}
|
||||
if (y < this._damageBounds.top) {
|
||||
this._damageBounds.top = y;
|
||||
}
|
||||
if ((x + w) > this._damageBounds.right) {
|
||||
this._damageBounds.right = x + w;
|
||||
}
|
||||
if ((y + h) > this._damageBounds.bottom) {
|
||||
this._damageBounds.bottom = y + h;
|
||||
}
|
||||
}
|
||||
|
||||
// Update the visible canvas with the contents of the
|
||||
// rendering canvas
|
||||
flip(fromQueue) {
|
||||
if (this._renderQ.length !== 0 && !fromQueue) {
|
||||
this._renderQPush({
|
||||
'type': 'flip'
|
||||
});
|
||||
} else {
|
||||
let x = this._damageBounds.left;
|
||||
let y = this._damageBounds.top;
|
||||
let w = this._damageBounds.right - x;
|
||||
let h = this._damageBounds.bottom - y;
|
||||
|
||||
let vx = x - this._viewportLoc.x;
|
||||
let vy = y - this._viewportLoc.y;
|
||||
|
||||
if (vx < 0) {
|
||||
w += vx;
|
||||
x -= vx;
|
||||
vx = 0;
|
||||
}
|
||||
if (vy < 0) {
|
||||
h += vy;
|
||||
y -= vy;
|
||||
vy = 0;
|
||||
}
|
||||
|
||||
if ((vx + w) > this._viewportLoc.w) {
|
||||
w = this._viewportLoc.w - vx;
|
||||
}
|
||||
if ((vy + h) > this._viewportLoc.h) {
|
||||
h = this._viewportLoc.h - vy;
|
||||
}
|
||||
|
||||
if ((w > 0) && (h > 0)) {
|
||||
// FIXME: We may need to disable image smoothing here
|
||||
// as well (see copyImage()), but we haven't
|
||||
// noticed any problem yet.
|
||||
this._targetCtx.drawImage(this._backbuffer,
|
||||
x, y, w, h,
|
||||
vx, vy, w, h);
|
||||
}
|
||||
|
||||
this._damageBounds.left = this._damageBounds.top = 65535;
|
||||
this._damageBounds.right = this._damageBounds.bottom = 0;
|
||||
}
|
||||
}
|
||||
|
||||
pending() {
|
||||
return this._renderQ.length > 0;
|
||||
}
|
||||
|
||||
flush() {
|
||||
if (this._renderQ.length === 0) {
|
||||
this.onflush();
|
||||
} else {
|
||||
this._flushing = true;
|
||||
}
|
||||
}
|
||||
|
||||
fillRect(x, y, width, height, color, fromQueue) {
|
||||
if (this._renderQ.length !== 0 && !fromQueue) {
|
||||
this._renderQPush({
|
||||
'type': 'fill',
|
||||
'x': x,
|
||||
'y': y,
|
||||
'width': width,
|
||||
'height': height,
|
||||
'color': color
|
||||
});
|
||||
} else {
|
||||
this._setFillColor(color);
|
||||
this._drawCtx.fillRect(x, y, width, height);
|
||||
this._damage(x, y, width, height);
|
||||
}
|
||||
}
|
||||
|
||||
copyImage(oldX, oldY, newX, newY, w, h, fromQueue) {
|
||||
if (this._renderQ.length !== 0 && !fromQueue) {
|
||||
this._renderQPush({
|
||||
'type': 'copy',
|
||||
'oldX': oldX,
|
||||
'oldY': oldY,
|
||||
'x': newX,
|
||||
'y': newY,
|
||||
'width': w,
|
||||
'height': h,
|
||||
});
|
||||
} else {
|
||||
// Due to this bug among others [1] we need to disable the image-smoothing to
|
||||
// avoid getting a blur effect when copying data.
|
||||
//
|
||||
// 1. https://bugzilla.mozilla.org/show_bug.cgi?id=1194719
|
||||
//
|
||||
// We need to set these every time since all properties are reset
|
||||
// when the the size is changed
|
||||
this._drawCtx.mozImageSmoothingEnabled = false;
|
||||
this._drawCtx.webkitImageSmoothingEnabled = false;
|
||||
this._drawCtx.msImageSmoothingEnabled = false;
|
||||
this._drawCtx.imageSmoothingEnabled = false;
|
||||
|
||||
this._drawCtx.drawImage(this._backbuffer,
|
||||
oldX, oldY, w, h,
|
||||
newX, newY, w, h);
|
||||
this._damage(newX, newY, w, h);
|
||||
}
|
||||
}
|
||||
|
||||
imageRect(x, y, width, height, mime, arr) {
|
||||
/* The internal logic cannot handle empty images, so bail early */
|
||||
if ((width === 0) || (height === 0)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const img = new Image();
|
||||
img.src = "data: " + mime + ";base64," + Base64.encode(arr);
|
||||
|
||||
this._renderQPush({
|
||||
'type': 'img',
|
||||
'img': img,
|
||||
'x': x,
|
||||
'y': y,
|
||||
'width': width,
|
||||
'height': height
|
||||
});
|
||||
}
|
||||
|
||||
blitImage(x, y, width, height, arr, offset, fromQueue) {
|
||||
if (this._renderQ.length !== 0 && !fromQueue) {
|
||||
// NB(directxman12): it's technically more performant here to use preallocated arrays,
|
||||
// but it's a lot of extra work for not a lot of payoff -- if we're using the render queue,
|
||||
// this probably isn't getting called *nearly* as much
|
||||
const newArr = new Uint8Array(width * height * 4);
|
||||
newArr.set(new Uint8Array(arr.buffer, 0, newArr.length));
|
||||
this._renderQPush({
|
||||
'type': 'blit',
|
||||
'data': newArr,
|
||||
'x': x,
|
||||
'y': y,
|
||||
'width': width,
|
||||
'height': height,
|
||||
});
|
||||
} else {
|
||||
// NB(directxman12): arr must be an Type Array view
|
||||
let data = new Uint8ClampedArray(arr.buffer,
|
||||
arr.byteOffset + offset,
|
||||
width * height * 4);
|
||||
let img = new ImageData(data, width, height);
|
||||
this._drawCtx.putImageData(img, x, y);
|
||||
this._damage(x, y, width, height);
|
||||
}
|
||||
}
|
||||
|
||||
drawImage(img, x, y) {
|
||||
this._drawCtx.drawImage(img, x, y);
|
||||
this._damage(x, y, img.width, img.height);
|
||||
}
|
||||
|
||||
autoscale(containerWidth, containerHeight) {
|
||||
let scaleRatio;
|
||||
|
||||
if (containerWidth === 0 || containerHeight === 0) {
|
||||
scaleRatio = 0;
|
||||
|
||||
} else {
|
||||
|
||||
const vp = this._viewportLoc;
|
||||
const targetAspectRatio = containerWidth / containerHeight;
|
||||
const fbAspectRatio = vp.w / vp.h;
|
||||
|
||||
if (fbAspectRatio >= targetAspectRatio) {
|
||||
scaleRatio = containerWidth / vp.w;
|
||||
} else {
|
||||
scaleRatio = containerHeight / vp.h;
|
||||
}
|
||||
}
|
||||
|
||||
this._rescale(scaleRatio);
|
||||
}
|
||||
|
||||
// ===== PRIVATE METHODS =====
|
||||
|
||||
_rescale(factor) {
|
||||
this._scale = factor;
|
||||
const vp = this._viewportLoc;
|
||||
|
||||
// NB(directxman12): If you set the width directly, or set the
|
||||
// style width to a number, the canvas is cleared.
|
||||
// However, if you set the style width to a string
|
||||
// ('NNNpx'), the canvas is scaled without clearing.
|
||||
const width = factor * vp.w + 'px';
|
||||
const height = factor * vp.h + 'px';
|
||||
|
||||
if ((this._target.style.width !== width) ||
|
||||
(this._target.style.height !== height)) {
|
||||
this._target.style.width = width;
|
||||
this._target.style.height = height;
|
||||
}
|
||||
}
|
||||
|
||||
_setFillColor(color) {
|
||||
const newStyle = 'rgb(' + color[0] + ',' + color[1] + ',' + color[2] + ')';
|
||||
if (newStyle !== this._prevDrawStyle) {
|
||||
this._drawCtx.fillStyle = newStyle;
|
||||
this._prevDrawStyle = newStyle;
|
||||
}
|
||||
}
|
||||
|
||||
_renderQPush(action) {
|
||||
this._renderQ.push(action);
|
||||
if (this._renderQ.length === 1) {
|
||||
// If this can be rendered immediately it will be, otherwise
|
||||
// the scanner will wait for the relevant event
|
||||
this._scanRenderQ();
|
||||
}
|
||||
}
|
||||
|
||||
_resumeRenderQ() {
|
||||
// "this" is the object that is ready, not the
|
||||
// display object
|
||||
this.removeEventListener('load', this._noVNCDisplay._resumeRenderQ);
|
||||
this._noVNCDisplay._scanRenderQ();
|
||||
}
|
||||
|
||||
_scanRenderQ() {
|
||||
let ready = true;
|
||||
while (ready && this._renderQ.length > 0) {
|
||||
const a = this._renderQ[0];
|
||||
switch (a.type) {
|
||||
case 'flip':
|
||||
this.flip(true);
|
||||
break;
|
||||
case 'copy':
|
||||
this.copyImage(a.oldX, a.oldY, a.x, a.y, a.width, a.height, true);
|
||||
break;
|
||||
case 'fill':
|
||||
this.fillRect(a.x, a.y, a.width, a.height, a.color, true);
|
||||
break;
|
||||
case 'blit':
|
||||
this.blitImage(a.x, a.y, a.width, a.height, a.data, 0, true);
|
||||
break;
|
||||
case 'img':
|
||||
if (a.img.complete) {
|
||||
if (a.img.width !== a.width || a.img.height !== a.height) {
|
||||
Log.Error("Decoded image has incorrect dimensions. Got " +
|
||||
a.img.width + "x" + a.img.height + ". Expected " +
|
||||
a.width + "x" + a.height + ".");
|
||||
return;
|
||||
}
|
||||
this.drawImage(a.img, a.x, a.y);
|
||||
} else {
|
||||
a.img._noVNCDisplay = this;
|
||||
a.img.addEventListener('load', this._resumeRenderQ);
|
||||
// We need to wait for this image to 'load'
|
||||
// to keep things in-order
|
||||
ready = false;
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
if (ready) {
|
||||
this._renderQ.shift();
|
||||
}
|
||||
}
|
||||
|
||||
if (this._renderQ.length === 0 && this._flushing) {
|
||||
this._flushing = false;
|
||||
this.onflush();
|
||||
}
|
||||
}
|
||||
}
|
||||
48
backend/app/static/novnc/core/encodings.js
Normal file
48
backend/app/static/novnc/core/encodings.js
Normal file
@@ -0,0 +1,48 @@
|
||||
/*
|
||||
* noVNC: HTML5 VNC client
|
||||
* Copyright (C) 2019 The noVNC Authors
|
||||
* Licensed under MPL 2.0 (see LICENSE.txt)
|
||||
*
|
||||
* See README.md for usage and integration instructions.
|
||||
*/
|
||||
|
||||
export const encodings = {
|
||||
encodingRaw: 0,
|
||||
encodingCopyRect: 1,
|
||||
encodingRRE: 2,
|
||||
encodingHextile: 5,
|
||||
encodingTight: 7,
|
||||
encodingZRLE: 16,
|
||||
encodingTightPNG: -260,
|
||||
encodingJPEG: 21,
|
||||
|
||||
pseudoEncodingQualityLevel9: -23,
|
||||
pseudoEncodingQualityLevel0: -32,
|
||||
pseudoEncodingDesktopSize: -223,
|
||||
pseudoEncodingLastRect: -224,
|
||||
pseudoEncodingCursor: -239,
|
||||
pseudoEncodingQEMUExtendedKeyEvent: -258,
|
||||
pseudoEncodingDesktopName: -307,
|
||||
pseudoEncodingExtendedDesktopSize: -308,
|
||||
pseudoEncodingXvp: -309,
|
||||
pseudoEncodingFence: -312,
|
||||
pseudoEncodingContinuousUpdates: -313,
|
||||
pseudoEncodingCompressLevel9: -247,
|
||||
pseudoEncodingCompressLevel0: -256,
|
||||
pseudoEncodingVMwareCursor: 0x574d5664,
|
||||
pseudoEncodingExtendedClipboard: 0xc0a1e5ce
|
||||
};
|
||||
|
||||
export function encodingName(num) {
|
||||
switch (num) {
|
||||
case encodings.encodingRaw: return "Raw";
|
||||
case encodings.encodingCopyRect: return "CopyRect";
|
||||
case encodings.encodingRRE: return "RRE";
|
||||
case encodings.encodingHextile: return "Hextile";
|
||||
case encodings.encodingTight: return "Tight";
|
||||
case encodings.encodingZRLE: return "ZRLE";
|
||||
case encodings.encodingTightPNG: return "TightPNG";
|
||||
case encodings.encodingJPEG: return "JPEG";
|
||||
default: return "[unknown encoding " + num + "]";
|
||||
}
|
||||
}
|
||||
66
backend/app/static/novnc/core/inflator.js
Normal file
66
backend/app/static/novnc/core/inflator.js
Normal file
@@ -0,0 +1,66 @@
|
||||
/*
|
||||
* noVNC: HTML5 VNC client
|
||||
* Copyright (C) 2020 The noVNC Authors
|
||||
* Licensed under MPL 2.0 (see LICENSE.txt)
|
||||
*
|
||||
* See README.md for usage and integration instructions.
|
||||
*/
|
||||
|
||||
import { inflateInit, inflate, inflateReset } from "../vendor/pako/lib/zlib/inflate.js";
|
||||
import ZStream from "../vendor/pako/lib/zlib/zstream.js";
|
||||
|
||||
export default class Inflate {
|
||||
constructor() {
|
||||
this.strm = new ZStream();
|
||||
this.chunkSize = 1024 * 10 * 10;
|
||||
this.strm.output = new Uint8Array(this.chunkSize);
|
||||
this.windowBits = 5;
|
||||
|
||||
inflateInit(this.strm, this.windowBits);
|
||||
}
|
||||
|
||||
setInput(data) {
|
||||
if (!data) {
|
||||
//FIXME: flush remaining data.
|
||||
/* eslint-disable camelcase */
|
||||
this.strm.input = null;
|
||||
this.strm.avail_in = 0;
|
||||
this.strm.next_in = 0;
|
||||
} else {
|
||||
this.strm.input = data;
|
||||
this.strm.avail_in = this.strm.input.length;
|
||||
this.strm.next_in = 0;
|
||||
/* eslint-enable camelcase */
|
||||
}
|
||||
}
|
||||
|
||||
inflate(expected) {
|
||||
// resize our output buffer if it's too small
|
||||
// (we could just use multiple chunks, but that would cause an extra
|
||||
// allocation each time to flatten the chunks)
|
||||
if (expected > this.chunkSize) {
|
||||
this.chunkSize = expected;
|
||||
this.strm.output = new Uint8Array(this.chunkSize);
|
||||
}
|
||||
|
||||
/* eslint-disable camelcase */
|
||||
this.strm.next_out = 0;
|
||||
this.strm.avail_out = expected;
|
||||
/* eslint-enable camelcase */
|
||||
|
||||
let ret = inflate(this.strm, 0); // Flush argument not used.
|
||||
if (ret < 0) {
|
||||
throw new Error("zlib inflate failed");
|
||||
}
|
||||
|
||||
if (this.strm.next_out != expected) {
|
||||
throw new Error("Incomplete zlib block");
|
||||
}
|
||||
|
||||
return new Uint8Array(this.strm.output.buffer, 0, this.strm.next_out);
|
||||
}
|
||||
|
||||
reset() {
|
||||
inflateReset(this.strm);
|
||||
}
|
||||
}
|
||||
311
backend/app/static/novnc/core/input/domkeytable.js
Normal file
311
backend/app/static/novnc/core/input/domkeytable.js
Normal file
@@ -0,0 +1,311 @@
|
||||
/*
|
||||
* noVNC: HTML5 VNC client
|
||||
* Copyright (C) 2018 The noVNC Authors
|
||||
* Licensed under MPL 2.0 or any later version (see LICENSE.txt)
|
||||
*/
|
||||
|
||||
import KeyTable from "./keysym.js";
|
||||
|
||||
/*
|
||||
* Mapping between HTML key values and VNC/X11 keysyms for "special"
|
||||
* keys that cannot be handled via their Unicode codepoint.
|
||||
*
|
||||
* See https://www.w3.org/TR/uievents-key/ for possible values.
|
||||
*/
|
||||
|
||||
const DOMKeyTable = {};
|
||||
|
||||
function addStandard(key, standard) {
|
||||
if (standard === undefined) throw new Error("Undefined keysym for key \"" + key + "\"");
|
||||
if (key in DOMKeyTable) throw new Error("Duplicate entry for key \"" + key + "\"");
|
||||
DOMKeyTable[key] = [standard, standard, standard, standard];
|
||||
}
|
||||
|
||||
function addLeftRight(key, left, right) {
|
||||
if (left === undefined) throw new Error("Undefined keysym for key \"" + key + "\"");
|
||||
if (right === undefined) throw new Error("Undefined keysym for key \"" + key + "\"");
|
||||
if (key in DOMKeyTable) throw new Error("Duplicate entry for key \"" + key + "\"");
|
||||
DOMKeyTable[key] = [left, left, right, left];
|
||||
}
|
||||
|
||||
function addNumpad(key, standard, numpad) {
|
||||
if (standard === undefined) throw new Error("Undefined keysym for key \"" + key + "\"");
|
||||
if (numpad === undefined) throw new Error("Undefined keysym for key \"" + key + "\"");
|
||||
if (key in DOMKeyTable) throw new Error("Duplicate entry for key \"" + key + "\"");
|
||||
DOMKeyTable[key] = [standard, standard, standard, numpad];
|
||||
}
|
||||
|
||||
// 3.2. Modifier Keys
|
||||
|
||||
addLeftRight("Alt", KeyTable.XK_Alt_L, KeyTable.XK_Alt_R);
|
||||
addStandard("AltGraph", KeyTable.XK_ISO_Level3_Shift);
|
||||
addStandard("CapsLock", KeyTable.XK_Caps_Lock);
|
||||
addLeftRight("Control", KeyTable.XK_Control_L, KeyTable.XK_Control_R);
|
||||
// - Fn
|
||||
// - FnLock
|
||||
addLeftRight("Meta", KeyTable.XK_Super_L, KeyTable.XK_Super_R);
|
||||
addStandard("NumLock", KeyTable.XK_Num_Lock);
|
||||
addStandard("ScrollLock", KeyTable.XK_Scroll_Lock);
|
||||
addLeftRight("Shift", KeyTable.XK_Shift_L, KeyTable.XK_Shift_R);
|
||||
// - Symbol
|
||||
// - SymbolLock
|
||||
// - Hyper
|
||||
// - Super
|
||||
|
||||
// 3.3. Whitespace Keys
|
||||
|
||||
addNumpad("Enter", KeyTable.XK_Return, KeyTable.XK_KP_Enter);
|
||||
addStandard("Tab", KeyTable.XK_Tab);
|
||||
addNumpad(" ", KeyTable.XK_space, KeyTable.XK_KP_Space);
|
||||
|
||||
// 3.4. Navigation Keys
|
||||
|
||||
addNumpad("ArrowDown", KeyTable.XK_Down, KeyTable.XK_KP_Down);
|
||||
addNumpad("ArrowLeft", KeyTable.XK_Left, KeyTable.XK_KP_Left);
|
||||
addNumpad("ArrowRight", KeyTable.XK_Right, KeyTable.XK_KP_Right);
|
||||
addNumpad("ArrowUp", KeyTable.XK_Up, KeyTable.XK_KP_Up);
|
||||
addNumpad("End", KeyTable.XK_End, KeyTable.XK_KP_End);
|
||||
addNumpad("Home", KeyTable.XK_Home, KeyTable.XK_KP_Home);
|
||||
addNumpad("PageDown", KeyTable.XK_Next, KeyTable.XK_KP_Next);
|
||||
addNumpad("PageUp", KeyTable.XK_Prior, KeyTable.XK_KP_Prior);
|
||||
|
||||
// 3.5. Editing Keys
|
||||
|
||||
addStandard("Backspace", KeyTable.XK_BackSpace);
|
||||
// Browsers send "Clear" for the numpad 5 without NumLock because
|
||||
// Windows uses VK_Clear for that key. But Unix expects KP_Begin for
|
||||
// that scenario.
|
||||
addNumpad("Clear", KeyTable.XK_Clear, KeyTable.XK_KP_Begin);
|
||||
addStandard("Copy", KeyTable.XF86XK_Copy);
|
||||
// - CrSel
|
||||
addStandard("Cut", KeyTable.XF86XK_Cut);
|
||||
addNumpad("Delete", KeyTable.XK_Delete, KeyTable.XK_KP_Delete);
|
||||
// - EraseEof
|
||||
// - ExSel
|
||||
addNumpad("Insert", KeyTable.XK_Insert, KeyTable.XK_KP_Insert);
|
||||
addStandard("Paste", KeyTable.XF86XK_Paste);
|
||||
addStandard("Redo", KeyTable.XK_Redo);
|
||||
addStandard("Undo", KeyTable.XK_Undo);
|
||||
|
||||
// 3.6. UI Keys
|
||||
|
||||
// - Accept
|
||||
// - Again (could just be XK_Redo)
|
||||
// - Attn
|
||||
addStandard("Cancel", KeyTable.XK_Cancel);
|
||||
addStandard("ContextMenu", KeyTable.XK_Menu);
|
||||
addStandard("Escape", KeyTable.XK_Escape);
|
||||
addStandard("Execute", KeyTable.XK_Execute);
|
||||
addStandard("Find", KeyTable.XK_Find);
|
||||
addStandard("Help", KeyTable.XK_Help);
|
||||
addStandard("Pause", KeyTable.XK_Pause);
|
||||
// - Play
|
||||
// - Props
|
||||
addStandard("Select", KeyTable.XK_Select);
|
||||
addStandard("ZoomIn", KeyTable.XF86XK_ZoomIn);
|
||||
addStandard("ZoomOut", KeyTable.XF86XK_ZoomOut);
|
||||
|
||||
// 3.7. Device Keys
|
||||
|
||||
addStandard("BrightnessDown", KeyTable.XF86XK_MonBrightnessDown);
|
||||
addStandard("BrightnessUp", KeyTable.XF86XK_MonBrightnessUp);
|
||||
addStandard("Eject", KeyTable.XF86XK_Eject);
|
||||
addStandard("LogOff", KeyTable.XF86XK_LogOff);
|
||||
addStandard("Power", KeyTable.XF86XK_PowerOff);
|
||||
addStandard("PowerOff", KeyTable.XF86XK_PowerDown);
|
||||
addStandard("PrintScreen", KeyTable.XK_Print);
|
||||
addStandard("Hibernate", KeyTable.XF86XK_Hibernate);
|
||||
addStandard("Standby", KeyTable.XF86XK_Standby);
|
||||
addStandard("WakeUp", KeyTable.XF86XK_WakeUp);
|
||||
|
||||
// 3.8. IME and Composition Keys
|
||||
|
||||
addStandard("AllCandidates", KeyTable.XK_MultipleCandidate);
|
||||
addStandard("Alphanumeric", KeyTable.XK_Eisu_toggle);
|
||||
addStandard("CodeInput", KeyTable.XK_Codeinput);
|
||||
addStandard("Compose", KeyTable.XK_Multi_key);
|
||||
addStandard("Convert", KeyTable.XK_Henkan);
|
||||
// - Dead
|
||||
// - FinalMode
|
||||
addStandard("GroupFirst", KeyTable.XK_ISO_First_Group);
|
||||
addStandard("GroupLast", KeyTable.XK_ISO_Last_Group);
|
||||
addStandard("GroupNext", KeyTable.XK_ISO_Next_Group);
|
||||
addStandard("GroupPrevious", KeyTable.XK_ISO_Prev_Group);
|
||||
// - ModeChange (XK_Mode_switch is often used for AltGr)
|
||||
// - NextCandidate
|
||||
addStandard("NonConvert", KeyTable.XK_Muhenkan);
|
||||
addStandard("PreviousCandidate", KeyTable.XK_PreviousCandidate);
|
||||
// - Process
|
||||
addStandard("SingleCandidate", KeyTable.XK_SingleCandidate);
|
||||
addStandard("HangulMode", KeyTable.XK_Hangul);
|
||||
addStandard("HanjaMode", KeyTable.XK_Hangul_Hanja);
|
||||
addStandard("JunjaMode", KeyTable.XK_Hangul_Jeonja);
|
||||
addStandard("Eisu", KeyTable.XK_Eisu_toggle);
|
||||
addStandard("Hankaku", KeyTable.XK_Hankaku);
|
||||
addStandard("Hiragana", KeyTable.XK_Hiragana);
|
||||
addStandard("HiraganaKatakana", KeyTable.XK_Hiragana_Katakana);
|
||||
addStandard("KanaMode", KeyTable.XK_Kana_Shift); // could also be _Kana_Lock
|
||||
addStandard("KanjiMode", KeyTable.XK_Kanji);
|
||||
addStandard("Katakana", KeyTable.XK_Katakana);
|
||||
addStandard("Romaji", KeyTable.XK_Romaji);
|
||||
addStandard("Zenkaku", KeyTable.XK_Zenkaku);
|
||||
addStandard("ZenkakuHankaku", KeyTable.XK_Zenkaku_Hankaku);
|
||||
|
||||
// 3.9. General-Purpose Function Keys
|
||||
|
||||
addStandard("F1", KeyTable.XK_F1);
|
||||
addStandard("F2", KeyTable.XK_F2);
|
||||
addStandard("F3", KeyTable.XK_F3);
|
||||
addStandard("F4", KeyTable.XK_F4);
|
||||
addStandard("F5", KeyTable.XK_F5);
|
||||
addStandard("F6", KeyTable.XK_F6);
|
||||
addStandard("F7", KeyTable.XK_F7);
|
||||
addStandard("F8", KeyTable.XK_F8);
|
||||
addStandard("F9", KeyTable.XK_F9);
|
||||
addStandard("F10", KeyTable.XK_F10);
|
||||
addStandard("F11", KeyTable.XK_F11);
|
||||
addStandard("F12", KeyTable.XK_F12);
|
||||
addStandard("F13", KeyTable.XK_F13);
|
||||
addStandard("F14", KeyTable.XK_F14);
|
||||
addStandard("F15", KeyTable.XK_F15);
|
||||
addStandard("F16", KeyTable.XK_F16);
|
||||
addStandard("F17", KeyTable.XK_F17);
|
||||
addStandard("F18", KeyTable.XK_F18);
|
||||
addStandard("F19", KeyTable.XK_F19);
|
||||
addStandard("F20", KeyTable.XK_F20);
|
||||
addStandard("F21", KeyTable.XK_F21);
|
||||
addStandard("F22", KeyTable.XK_F22);
|
||||
addStandard("F23", KeyTable.XK_F23);
|
||||
addStandard("F24", KeyTable.XK_F24);
|
||||
addStandard("F25", KeyTable.XK_F25);
|
||||
addStandard("F26", KeyTable.XK_F26);
|
||||
addStandard("F27", KeyTable.XK_F27);
|
||||
addStandard("F28", KeyTable.XK_F28);
|
||||
addStandard("F29", KeyTable.XK_F29);
|
||||
addStandard("F30", KeyTable.XK_F30);
|
||||
addStandard("F31", KeyTable.XK_F31);
|
||||
addStandard("F32", KeyTable.XK_F32);
|
||||
addStandard("F33", KeyTable.XK_F33);
|
||||
addStandard("F34", KeyTable.XK_F34);
|
||||
addStandard("F35", KeyTable.XK_F35);
|
||||
// - Soft1...
|
||||
|
||||
// 3.10. Multimedia Keys
|
||||
|
||||
// - ChannelDown
|
||||
// - ChannelUp
|
||||
addStandard("Close", KeyTable.XF86XK_Close);
|
||||
addStandard("MailForward", KeyTable.XF86XK_MailForward);
|
||||
addStandard("MailReply", KeyTable.XF86XK_Reply);
|
||||
addStandard("MailSend", KeyTable.XF86XK_Send);
|
||||
// - MediaClose
|
||||
addStandard("MediaFastForward", KeyTable.XF86XK_AudioForward);
|
||||
addStandard("MediaPause", KeyTable.XF86XK_AudioPause);
|
||||
addStandard("MediaPlay", KeyTable.XF86XK_AudioPlay);
|
||||
// - MediaPlayPause
|
||||
addStandard("MediaRecord", KeyTable.XF86XK_AudioRecord);
|
||||
addStandard("MediaRewind", KeyTable.XF86XK_AudioRewind);
|
||||
addStandard("MediaStop", KeyTable.XF86XK_AudioStop);
|
||||
addStandard("MediaTrackNext", KeyTable.XF86XK_AudioNext);
|
||||
addStandard("MediaTrackPrevious", KeyTable.XF86XK_AudioPrev);
|
||||
addStandard("New", KeyTable.XF86XK_New);
|
||||
addStandard("Open", KeyTable.XF86XK_Open);
|
||||
addStandard("Print", KeyTable.XK_Print);
|
||||
addStandard("Save", KeyTable.XF86XK_Save);
|
||||
addStandard("SpellCheck", KeyTable.XF86XK_Spell);
|
||||
|
||||
// 3.11. Multimedia Numpad Keys
|
||||
|
||||
// - Key11
|
||||
// - Key12
|
||||
|
||||
// 3.12. Audio Keys
|
||||
|
||||
// - AudioBalanceLeft
|
||||
// - AudioBalanceRight
|
||||
// - AudioBassBoostDown
|
||||
// - AudioBassBoostToggle
|
||||
// - AudioBassBoostUp
|
||||
// - AudioFaderFront
|
||||
// - AudioFaderRear
|
||||
// - AudioSurroundModeNext
|
||||
// - AudioTrebleDown
|
||||
// - AudioTrebleUp
|
||||
addStandard("AudioVolumeDown", KeyTable.XF86XK_AudioLowerVolume);
|
||||
addStandard("AudioVolumeUp", KeyTable.XF86XK_AudioRaiseVolume);
|
||||
addStandard("AudioVolumeMute", KeyTable.XF86XK_AudioMute);
|
||||
// - MicrophoneToggle
|
||||
// - MicrophoneVolumeDown
|
||||
// - MicrophoneVolumeUp
|
||||
addStandard("MicrophoneVolumeMute", KeyTable.XF86XK_AudioMicMute);
|
||||
|
||||
// 3.13. Speech Keys
|
||||
|
||||
// - SpeechCorrectionList
|
||||
// - SpeechInputToggle
|
||||
|
||||
// 3.14. Application Keys
|
||||
|
||||
addStandard("LaunchApplication1", KeyTable.XF86XK_MyComputer);
|
||||
addStandard("LaunchApplication2", KeyTable.XF86XK_Calculator);
|
||||
addStandard("LaunchCalendar", KeyTable.XF86XK_Calendar);
|
||||
// - LaunchContacts
|
||||
addStandard("LaunchMail", KeyTable.XF86XK_Mail);
|
||||
addStandard("LaunchMediaPlayer", KeyTable.XF86XK_AudioMedia);
|
||||
addStandard("LaunchMusicPlayer", KeyTable.XF86XK_Music);
|
||||
addStandard("LaunchPhone", KeyTable.XF86XK_Phone);
|
||||
addStandard("LaunchScreenSaver", KeyTable.XF86XK_ScreenSaver);
|
||||
addStandard("LaunchSpreadsheet", KeyTable.XF86XK_Excel);
|
||||
addStandard("LaunchWebBrowser", KeyTable.XF86XK_WWW);
|
||||
addStandard("LaunchWebCam", KeyTable.XF86XK_WebCam);
|
||||
addStandard("LaunchWordProcessor", KeyTable.XF86XK_Word);
|
||||
|
||||
// 3.15. Browser Keys
|
||||
|
||||
addStandard("BrowserBack", KeyTable.XF86XK_Back);
|
||||
addStandard("BrowserFavorites", KeyTable.XF86XK_Favorites);
|
||||
addStandard("BrowserForward", KeyTable.XF86XK_Forward);
|
||||
addStandard("BrowserHome", KeyTable.XF86XK_HomePage);
|
||||
addStandard("BrowserRefresh", KeyTable.XF86XK_Refresh);
|
||||
addStandard("BrowserSearch", KeyTable.XF86XK_Search);
|
||||
addStandard("BrowserStop", KeyTable.XF86XK_Stop);
|
||||
|
||||
// 3.16. Mobile Phone Keys
|
||||
|
||||
// - A whole bunch...
|
||||
|
||||
// 3.17. TV Keys
|
||||
|
||||
// - A whole bunch...
|
||||
|
||||
// 3.18. Media Controller Keys
|
||||
|
||||
// - A whole bunch...
|
||||
addStandard("Dimmer", KeyTable.XF86XK_BrightnessAdjust);
|
||||
addStandard("MediaAudioTrack", KeyTable.XF86XK_AudioCycleTrack);
|
||||
addStandard("RandomToggle", KeyTable.XF86XK_AudioRandomPlay);
|
||||
addStandard("SplitScreenToggle", KeyTable.XF86XK_SplitScreen);
|
||||
addStandard("Subtitle", KeyTable.XF86XK_Subtitle);
|
||||
addStandard("VideoModeNext", KeyTable.XF86XK_Next_VMode);
|
||||
|
||||
// Extra: Numpad
|
||||
|
||||
addNumpad("=", KeyTable.XK_equal, KeyTable.XK_KP_Equal);
|
||||
addNumpad("+", KeyTable.XK_plus, KeyTable.XK_KP_Add);
|
||||
addNumpad("-", KeyTable.XK_minus, KeyTable.XK_KP_Subtract);
|
||||
addNumpad("*", KeyTable.XK_asterisk, KeyTable.XK_KP_Multiply);
|
||||
addNumpad("/", KeyTable.XK_slash, KeyTable.XK_KP_Divide);
|
||||
addNumpad(".", KeyTable.XK_period, KeyTable.XK_KP_Decimal);
|
||||
addNumpad(",", KeyTable.XK_comma, KeyTable.XK_KP_Separator);
|
||||
addNumpad("0", KeyTable.XK_0, KeyTable.XK_KP_0);
|
||||
addNumpad("1", KeyTable.XK_1, KeyTable.XK_KP_1);
|
||||
addNumpad("2", KeyTable.XK_2, KeyTable.XK_KP_2);
|
||||
addNumpad("3", KeyTable.XK_3, KeyTable.XK_KP_3);
|
||||
addNumpad("4", KeyTable.XK_4, KeyTable.XK_KP_4);
|
||||
addNumpad("5", KeyTable.XK_5, KeyTable.XK_KP_5);
|
||||
addNumpad("6", KeyTable.XK_6, KeyTable.XK_KP_6);
|
||||
addNumpad("7", KeyTable.XK_7, KeyTable.XK_KP_7);
|
||||
addNumpad("8", KeyTable.XK_8, KeyTable.XK_KP_8);
|
||||
addNumpad("9", KeyTable.XK_9, KeyTable.XK_KP_9);
|
||||
|
||||
export default DOMKeyTable;
|
||||
129
backend/app/static/novnc/core/input/fixedkeys.js
Normal file
129
backend/app/static/novnc/core/input/fixedkeys.js
Normal file
@@ -0,0 +1,129 @@
|
||||
/*
|
||||
* noVNC: HTML5 VNC client
|
||||
* Copyright (C) 2018 The noVNC Authors
|
||||
* Licensed under MPL 2.0 or any later version (see LICENSE.txt)
|
||||
*/
|
||||
|
||||
/*
|
||||
* Fallback mapping between HTML key codes (physical keys) and
|
||||
* HTML key values. This only works for keys that don't vary
|
||||
* between layouts. We also omit those who manage fine by mapping the
|
||||
* Unicode representation.
|
||||
*
|
||||
* See https://www.w3.org/TR/uievents-code/ for possible codes.
|
||||
* See https://www.w3.org/TR/uievents-key/ for possible values.
|
||||
*/
|
||||
|
||||
/* eslint-disable key-spacing */
|
||||
|
||||
export default {
|
||||
|
||||
// 3.1.1.1. Writing System Keys
|
||||
|
||||
'Backspace': 'Backspace',
|
||||
|
||||
// 3.1.1.2. Functional Keys
|
||||
|
||||
'AltLeft': 'Alt',
|
||||
'AltRight': 'Alt', // This could also be 'AltGraph'
|
||||
'CapsLock': 'CapsLock',
|
||||
'ContextMenu': 'ContextMenu',
|
||||
'ControlLeft': 'Control',
|
||||
'ControlRight': 'Control',
|
||||
'Enter': 'Enter',
|
||||
'MetaLeft': 'Meta',
|
||||
'MetaRight': 'Meta',
|
||||
'ShiftLeft': 'Shift',
|
||||
'ShiftRight': 'Shift',
|
||||
'Tab': 'Tab',
|
||||
// FIXME: Japanese/Korean keys
|
||||
|
||||
// 3.1.2. Control Pad Section
|
||||
|
||||
'Delete': 'Delete',
|
||||
'End': 'End',
|
||||
'Help': 'Help',
|
||||
'Home': 'Home',
|
||||
'Insert': 'Insert',
|
||||
'PageDown': 'PageDown',
|
||||
'PageUp': 'PageUp',
|
||||
|
||||
// 3.1.3. Arrow Pad Section
|
||||
|
||||
'ArrowDown': 'ArrowDown',
|
||||
'ArrowLeft': 'ArrowLeft',
|
||||
'ArrowRight': 'ArrowRight',
|
||||
'ArrowUp': 'ArrowUp',
|
||||
|
||||
// 3.1.4. Numpad Section
|
||||
|
||||
'NumLock': 'NumLock',
|
||||
'NumpadBackspace': 'Backspace',
|
||||
'NumpadClear': 'Clear',
|
||||
|
||||
// 3.1.5. Function Section
|
||||
|
||||
'Escape': 'Escape',
|
||||
'F1': 'F1',
|
||||
'F2': 'F2',
|
||||
'F3': 'F3',
|
||||
'F4': 'F4',
|
||||
'F5': 'F5',
|
||||
'F6': 'F6',
|
||||
'F7': 'F7',
|
||||
'F8': 'F8',
|
||||
'F9': 'F9',
|
||||
'F10': 'F10',
|
||||
'F11': 'F11',
|
||||
'F12': 'F12',
|
||||
'F13': 'F13',
|
||||
'F14': 'F14',
|
||||
'F15': 'F15',
|
||||
'F16': 'F16',
|
||||
'F17': 'F17',
|
||||
'F18': 'F18',
|
||||
'F19': 'F19',
|
||||
'F20': 'F20',
|
||||
'F21': 'F21',
|
||||
'F22': 'F22',
|
||||
'F23': 'F23',
|
||||
'F24': 'F24',
|
||||
'F25': 'F25',
|
||||
'F26': 'F26',
|
||||
'F27': 'F27',
|
||||
'F28': 'F28',
|
||||
'F29': 'F29',
|
||||
'F30': 'F30',
|
||||
'F31': 'F31',
|
||||
'F32': 'F32',
|
||||
'F33': 'F33',
|
||||
'F34': 'F34',
|
||||
'F35': 'F35',
|
||||
'PrintScreen': 'PrintScreen',
|
||||
'ScrollLock': 'ScrollLock',
|
||||
'Pause': 'Pause',
|
||||
|
||||
// 3.1.6. Media Keys
|
||||
|
||||
'BrowserBack': 'BrowserBack',
|
||||
'BrowserFavorites': 'BrowserFavorites',
|
||||
'BrowserForward': 'BrowserForward',
|
||||
'BrowserHome': 'BrowserHome',
|
||||
'BrowserRefresh': 'BrowserRefresh',
|
||||
'BrowserSearch': 'BrowserSearch',
|
||||
'BrowserStop': 'BrowserStop',
|
||||
'Eject': 'Eject',
|
||||
'LaunchApp1': 'LaunchMyComputer',
|
||||
'LaunchApp2': 'LaunchCalendar',
|
||||
'LaunchMail': 'LaunchMail',
|
||||
'MediaPlayPause': 'MediaPlay',
|
||||
'MediaStop': 'MediaStop',
|
||||
'MediaTrackNext': 'MediaTrackNext',
|
||||
'MediaTrackPrevious': 'MediaTrackPrevious',
|
||||
'Power': 'Power',
|
||||
'Sleep': 'Sleep',
|
||||
'AudioVolumeDown': 'AudioVolumeDown',
|
||||
'AudioVolumeMute': 'AudioVolumeMute',
|
||||
'AudioVolumeUp': 'AudioVolumeUp',
|
||||
'WakeUp': 'WakeUp',
|
||||
};
|
||||
567
backend/app/static/novnc/core/input/gesturehandler.js
Normal file
567
backend/app/static/novnc/core/input/gesturehandler.js
Normal file
@@ -0,0 +1,567 @@
|
||||
/*
|
||||
* noVNC: HTML5 VNC client
|
||||
* Copyright (C) 2020 The noVNC Authors
|
||||
* Licensed under MPL 2.0 (see LICENSE.txt)
|
||||
*
|
||||
* See README.md for usage and integration instructions.
|
||||
*
|
||||
*/
|
||||
|
||||
const GH_NOGESTURE = 0;
|
||||
const GH_ONETAP = 1;
|
||||
const GH_TWOTAP = 2;
|
||||
const GH_THREETAP = 4;
|
||||
const GH_DRAG = 8;
|
||||
const GH_LONGPRESS = 16;
|
||||
const GH_TWODRAG = 32;
|
||||
const GH_PINCH = 64;
|
||||
|
||||
const GH_INITSTATE = 127;
|
||||
|
||||
const GH_MOVE_THRESHOLD = 50;
|
||||
const GH_ANGLE_THRESHOLD = 90; // Degrees
|
||||
|
||||
// Timeout when waiting for gestures (ms)
|
||||
const GH_MULTITOUCH_TIMEOUT = 250;
|
||||
|
||||
// Maximum time between press and release for a tap (ms)
|
||||
const GH_TAP_TIMEOUT = 1000;
|
||||
|
||||
// Timeout when waiting for longpress (ms)
|
||||
const GH_LONGPRESS_TIMEOUT = 1000;
|
||||
|
||||
// Timeout when waiting to decide between PINCH and TWODRAG (ms)
|
||||
const GH_TWOTOUCH_TIMEOUT = 50;
|
||||
|
||||
export default class GestureHandler {
|
||||
constructor() {
|
||||
this._target = null;
|
||||
|
||||
this._state = GH_INITSTATE;
|
||||
|
||||
this._tracked = [];
|
||||
this._ignored = [];
|
||||
|
||||
this._waitingRelease = false;
|
||||
this._releaseStart = 0.0;
|
||||
|
||||
this._longpressTimeoutId = null;
|
||||
this._twoTouchTimeoutId = null;
|
||||
|
||||
this._boundEventHandler = this._eventHandler.bind(this);
|
||||
}
|
||||
|
||||
attach(target) {
|
||||
this.detach();
|
||||
|
||||
this._target = target;
|
||||
this._target.addEventListener('touchstart',
|
||||
this._boundEventHandler);
|
||||
this._target.addEventListener('touchmove',
|
||||
this._boundEventHandler);
|
||||
this._target.addEventListener('touchend',
|
||||
this._boundEventHandler);
|
||||
this._target.addEventListener('touchcancel',
|
||||
this._boundEventHandler);
|
||||
}
|
||||
|
||||
detach() {
|
||||
if (!this._target) {
|
||||
return;
|
||||
}
|
||||
|
||||
this._stopLongpressTimeout();
|
||||
this._stopTwoTouchTimeout();
|
||||
|
||||
this._target.removeEventListener('touchstart',
|
||||
this._boundEventHandler);
|
||||
this._target.removeEventListener('touchmove',
|
||||
this._boundEventHandler);
|
||||
this._target.removeEventListener('touchend',
|
||||
this._boundEventHandler);
|
||||
this._target.removeEventListener('touchcancel',
|
||||
this._boundEventHandler);
|
||||
this._target = null;
|
||||
}
|
||||
|
||||
_eventHandler(e) {
|
||||
let fn;
|
||||
|
||||
e.stopPropagation();
|
||||
e.preventDefault();
|
||||
|
||||
switch (e.type) {
|
||||
case 'touchstart':
|
||||
fn = this._touchStart;
|
||||
break;
|
||||
case 'touchmove':
|
||||
fn = this._touchMove;
|
||||
break;
|
||||
case 'touchend':
|
||||
case 'touchcancel':
|
||||
fn = this._touchEnd;
|
||||
break;
|
||||
}
|
||||
|
||||
for (let i = 0; i < e.changedTouches.length; i++) {
|
||||
let touch = e.changedTouches[i];
|
||||
fn.call(this, touch.identifier, touch.clientX, touch.clientY);
|
||||
}
|
||||
}
|
||||
|
||||
_touchStart(id, x, y) {
|
||||
// Ignore any new touches if there is already an active gesture,
|
||||
// or we're in a cleanup state
|
||||
if (this._hasDetectedGesture() || (this._state === GH_NOGESTURE)) {
|
||||
this._ignored.push(id);
|
||||
return;
|
||||
}
|
||||
|
||||
// Did it take too long between touches that we should no longer
|
||||
// consider this a single gesture?
|
||||
if ((this._tracked.length > 0) &&
|
||||
((Date.now() - this._tracked[0].started) > GH_MULTITOUCH_TIMEOUT)) {
|
||||
this._state = GH_NOGESTURE;
|
||||
this._ignored.push(id);
|
||||
return;
|
||||
}
|
||||
|
||||
// If we're waiting for fingers to release then we should no longer
|
||||
// recognize new touches
|
||||
if (this._waitingRelease) {
|
||||
this._state = GH_NOGESTURE;
|
||||
this._ignored.push(id);
|
||||
return;
|
||||
}
|
||||
|
||||
this._tracked.push({
|
||||
id: id,
|
||||
started: Date.now(),
|
||||
active: true,
|
||||
firstX: x,
|
||||
firstY: y,
|
||||
lastX: x,
|
||||
lastY: y,
|
||||
angle: 0
|
||||
});
|
||||
|
||||
switch (this._tracked.length) {
|
||||
case 1:
|
||||
this._startLongpressTimeout();
|
||||
break;
|
||||
|
||||
case 2:
|
||||
this._state &= ~(GH_ONETAP | GH_DRAG | GH_LONGPRESS);
|
||||
this._stopLongpressTimeout();
|
||||
break;
|
||||
|
||||
case 3:
|
||||
this._state &= ~(GH_TWOTAP | GH_TWODRAG | GH_PINCH);
|
||||
break;
|
||||
|
||||
default:
|
||||
this._state = GH_NOGESTURE;
|
||||
}
|
||||
}
|
||||
|
||||
_touchMove(id, x, y) {
|
||||
let touch = this._tracked.find(t => t.id === id);
|
||||
|
||||
// If this is an update for a touch we're not tracking, ignore it
|
||||
if (touch === undefined) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Update the touches last position with the event coordinates
|
||||
touch.lastX = x;
|
||||
touch.lastY = y;
|
||||
|
||||
let deltaX = x - touch.firstX;
|
||||
let deltaY = y - touch.firstY;
|
||||
|
||||
// Update angle when the touch has moved
|
||||
if ((touch.firstX !== touch.lastX) ||
|
||||
(touch.firstY !== touch.lastY)) {
|
||||
touch.angle = Math.atan2(deltaY, deltaX) * 180 / Math.PI;
|
||||
}
|
||||
|
||||
if (!this._hasDetectedGesture()) {
|
||||
// Ignore moves smaller than the minimum threshold
|
||||
if (Math.hypot(deltaX, deltaY) < GH_MOVE_THRESHOLD) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Can't be a tap or long press as we've seen movement
|
||||
this._state &= ~(GH_ONETAP | GH_TWOTAP | GH_THREETAP | GH_LONGPRESS);
|
||||
this._stopLongpressTimeout();
|
||||
|
||||
if (this._tracked.length !== 1) {
|
||||
this._state &= ~(GH_DRAG);
|
||||
}
|
||||
if (this._tracked.length !== 2) {
|
||||
this._state &= ~(GH_TWODRAG | GH_PINCH);
|
||||
}
|
||||
|
||||
// We need to figure out which of our different two touch gestures
|
||||
// this might be
|
||||
if (this._tracked.length === 2) {
|
||||
|
||||
// The other touch is the one where the id doesn't match
|
||||
let prevTouch = this._tracked.find(t => t.id !== id);
|
||||
|
||||
// How far the previous touch point has moved since start
|
||||
let prevDeltaMove = Math.hypot(prevTouch.firstX - prevTouch.lastX,
|
||||
prevTouch.firstY - prevTouch.lastY);
|
||||
|
||||
// We know that the current touch moved far enough,
|
||||
// but unless both touches moved further than their
|
||||
// threshold we don't want to disqualify any gestures
|
||||
if (prevDeltaMove > GH_MOVE_THRESHOLD) {
|
||||
|
||||
// The angle difference between the direction of the touch points
|
||||
let deltaAngle = Math.abs(touch.angle - prevTouch.angle);
|
||||
deltaAngle = Math.abs(((deltaAngle + 180) % 360) - 180);
|
||||
|
||||
// PINCH or TWODRAG can be eliminated depending on the angle
|
||||
if (deltaAngle > GH_ANGLE_THRESHOLD) {
|
||||
this._state &= ~GH_TWODRAG;
|
||||
} else {
|
||||
this._state &= ~GH_PINCH;
|
||||
}
|
||||
|
||||
if (this._isTwoTouchTimeoutRunning()) {
|
||||
this._stopTwoTouchTimeout();
|
||||
}
|
||||
} else if (!this._isTwoTouchTimeoutRunning()) {
|
||||
// We can't determine the gesture right now, let's
|
||||
// wait and see if more events are on their way
|
||||
this._startTwoTouchTimeout();
|
||||
}
|
||||
}
|
||||
|
||||
if (!this._hasDetectedGesture()) {
|
||||
return;
|
||||
}
|
||||
|
||||
this._pushEvent('gesturestart');
|
||||
}
|
||||
|
||||
this._pushEvent('gesturemove');
|
||||
}
|
||||
|
||||
_touchEnd(id, x, y) {
|
||||
// Check if this is an ignored touch
|
||||
if (this._ignored.indexOf(id) !== -1) {
|
||||
// Remove this touch from ignored
|
||||
this._ignored.splice(this._ignored.indexOf(id), 1);
|
||||
|
||||
// And reset the state if there are no more touches
|
||||
if ((this._ignored.length === 0) &&
|
||||
(this._tracked.length === 0)) {
|
||||
this._state = GH_INITSTATE;
|
||||
this._waitingRelease = false;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// We got a touchend before the timer triggered,
|
||||
// this cannot result in a gesture anymore.
|
||||
if (!this._hasDetectedGesture() &&
|
||||
this._isTwoTouchTimeoutRunning()) {
|
||||
this._stopTwoTouchTimeout();
|
||||
this._state = GH_NOGESTURE;
|
||||
}
|
||||
|
||||
// Some gestures don't trigger until a touch is released
|
||||
if (!this._hasDetectedGesture()) {
|
||||
// Can't be a gesture that relies on movement
|
||||
this._state &= ~(GH_DRAG | GH_TWODRAG | GH_PINCH);
|
||||
// Or something that relies on more time
|
||||
this._state &= ~GH_LONGPRESS;
|
||||
this._stopLongpressTimeout();
|
||||
|
||||
if (!this._waitingRelease) {
|
||||
this._releaseStart = Date.now();
|
||||
this._waitingRelease = true;
|
||||
|
||||
// Can't be a tap that requires more touches than we current have
|
||||
switch (this._tracked.length) {
|
||||
case 1:
|
||||
this._state &= ~(GH_TWOTAP | GH_THREETAP);
|
||||
break;
|
||||
|
||||
case 2:
|
||||
this._state &= ~(GH_ONETAP | GH_THREETAP);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Waiting for all touches to release? (i.e. some tap)
|
||||
if (this._waitingRelease) {
|
||||
// Were all touches released at roughly the same time?
|
||||
if ((Date.now() - this._releaseStart) > GH_MULTITOUCH_TIMEOUT) {
|
||||
this._state = GH_NOGESTURE;
|
||||
}
|
||||
|
||||
// Did too long time pass between press and release?
|
||||
if (this._tracked.some(t => (Date.now() - t.started) > GH_TAP_TIMEOUT)) {
|
||||
this._state = GH_NOGESTURE;
|
||||
}
|
||||
|
||||
let touch = this._tracked.find(t => t.id === id);
|
||||
touch.active = false;
|
||||
|
||||
// Are we still waiting for more releases?
|
||||
if (this._hasDetectedGesture()) {
|
||||
this._pushEvent('gesturestart');
|
||||
} else {
|
||||
// Have we reached a dead end?
|
||||
if (this._state !== GH_NOGESTURE) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (this._hasDetectedGesture()) {
|
||||
this._pushEvent('gestureend');
|
||||
}
|
||||
|
||||
// Ignore any remaining touches until they are ended
|
||||
for (let i = 0; i < this._tracked.length; i++) {
|
||||
if (this._tracked[i].active) {
|
||||
this._ignored.push(this._tracked[i].id);
|
||||
}
|
||||
}
|
||||
this._tracked = [];
|
||||
|
||||
this._state = GH_NOGESTURE;
|
||||
|
||||
// Remove this touch from ignored if it's in there
|
||||
if (this._ignored.indexOf(id) !== -1) {
|
||||
this._ignored.splice(this._ignored.indexOf(id), 1);
|
||||
}
|
||||
|
||||
// We reset the state if ignored is empty
|
||||
if ((this._ignored.length === 0)) {
|
||||
this._state = GH_INITSTATE;
|
||||
this._waitingRelease = false;
|
||||
}
|
||||
}
|
||||
|
||||
_hasDetectedGesture() {
|
||||
if (this._state === GH_NOGESTURE) {
|
||||
return false;
|
||||
}
|
||||
// Check to see if the bitmask value is a power of 2
|
||||
// (i.e. only one bit set). If it is, we have a state.
|
||||
if (this._state & (this._state - 1)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// For taps we also need to have all touches released
|
||||
// before we've fully detected the gesture
|
||||
if (this._state & (GH_ONETAP | GH_TWOTAP | GH_THREETAP)) {
|
||||
if (this._tracked.some(t => t.active)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
_startLongpressTimeout() {
|
||||
this._stopLongpressTimeout();
|
||||
this._longpressTimeoutId = setTimeout(() => this._longpressTimeout(),
|
||||
GH_LONGPRESS_TIMEOUT);
|
||||
}
|
||||
|
||||
_stopLongpressTimeout() {
|
||||
clearTimeout(this._longpressTimeoutId);
|
||||
this._longpressTimeoutId = null;
|
||||
}
|
||||
|
||||
_longpressTimeout() {
|
||||
if (this._hasDetectedGesture()) {
|
||||
throw new Error("A longpress gesture failed, conflict with a different gesture");
|
||||
}
|
||||
|
||||
this._state = GH_LONGPRESS;
|
||||
this._pushEvent('gesturestart');
|
||||
}
|
||||
|
||||
_startTwoTouchTimeout() {
|
||||
this._stopTwoTouchTimeout();
|
||||
this._twoTouchTimeoutId = setTimeout(() => this._twoTouchTimeout(),
|
||||
GH_TWOTOUCH_TIMEOUT);
|
||||
}
|
||||
|
||||
_stopTwoTouchTimeout() {
|
||||
clearTimeout(this._twoTouchTimeoutId);
|
||||
this._twoTouchTimeoutId = null;
|
||||
}
|
||||
|
||||
_isTwoTouchTimeoutRunning() {
|
||||
return this._twoTouchTimeoutId !== null;
|
||||
}
|
||||
|
||||
_twoTouchTimeout() {
|
||||
if (this._tracked.length === 0) {
|
||||
throw new Error("A pinch or two drag gesture failed, no tracked touches");
|
||||
}
|
||||
|
||||
// How far each touch point has moved since start
|
||||
let avgM = this._getAverageMovement();
|
||||
let avgMoveH = Math.abs(avgM.x);
|
||||
let avgMoveV = Math.abs(avgM.y);
|
||||
|
||||
// The difference in the distance between where
|
||||
// the touch points started and where they are now
|
||||
let avgD = this._getAverageDistance();
|
||||
let deltaTouchDistance = Math.abs(Math.hypot(avgD.first.x, avgD.first.y) -
|
||||
Math.hypot(avgD.last.x, avgD.last.y));
|
||||
|
||||
if ((avgMoveV < deltaTouchDistance) &&
|
||||
(avgMoveH < deltaTouchDistance)) {
|
||||
this._state = GH_PINCH;
|
||||
} else {
|
||||
this._state = GH_TWODRAG;
|
||||
}
|
||||
|
||||
this._pushEvent('gesturestart');
|
||||
this._pushEvent('gesturemove');
|
||||
}
|
||||
|
||||
_pushEvent(type) {
|
||||
let detail = { type: this._stateToGesture(this._state) };
|
||||
|
||||
// For most gesture events the current (average) position is the
|
||||
// most useful
|
||||
let avg = this._getPosition();
|
||||
let pos = avg.last;
|
||||
|
||||
// However we have a slight distance to detect gestures, so for the
|
||||
// first gesture event we want to use the first positions we saw
|
||||
if (type === 'gesturestart') {
|
||||
pos = avg.first;
|
||||
}
|
||||
|
||||
// For these gestures, we always want the event coordinates
|
||||
// to be where the gesture began, not the current touch location.
|
||||
switch (this._state) {
|
||||
case GH_TWODRAG:
|
||||
case GH_PINCH:
|
||||
pos = avg.first;
|
||||
break;
|
||||
}
|
||||
|
||||
detail['clientX'] = pos.x;
|
||||
detail['clientY'] = pos.y;
|
||||
|
||||
// FIXME: other coordinates?
|
||||
|
||||
// Some gestures also have a magnitude
|
||||
if (this._state === GH_PINCH) {
|
||||
let distance = this._getAverageDistance();
|
||||
if (type === 'gesturestart') {
|
||||
detail['magnitudeX'] = distance.first.x;
|
||||
detail['magnitudeY'] = distance.first.y;
|
||||
} else {
|
||||
detail['magnitudeX'] = distance.last.x;
|
||||
detail['magnitudeY'] = distance.last.y;
|
||||
}
|
||||
} else if (this._state === GH_TWODRAG) {
|
||||
if (type === 'gesturestart') {
|
||||
detail['magnitudeX'] = 0.0;
|
||||
detail['magnitudeY'] = 0.0;
|
||||
} else {
|
||||
let movement = this._getAverageMovement();
|
||||
detail['magnitudeX'] = movement.x;
|
||||
detail['magnitudeY'] = movement.y;
|
||||
}
|
||||
}
|
||||
|
||||
let gev = new CustomEvent(type, { detail: detail });
|
||||
this._target.dispatchEvent(gev);
|
||||
}
|
||||
|
||||
_stateToGesture(state) {
|
||||
switch (state) {
|
||||
case GH_ONETAP:
|
||||
return 'onetap';
|
||||
case GH_TWOTAP:
|
||||
return 'twotap';
|
||||
case GH_THREETAP:
|
||||
return 'threetap';
|
||||
case GH_DRAG:
|
||||
return 'drag';
|
||||
case GH_LONGPRESS:
|
||||
return 'longpress';
|
||||
case GH_TWODRAG:
|
||||
return 'twodrag';
|
||||
case GH_PINCH:
|
||||
return 'pinch';
|
||||
}
|
||||
|
||||
throw new Error("Unknown gesture state: " + state);
|
||||
}
|
||||
|
||||
_getPosition() {
|
||||
if (this._tracked.length === 0) {
|
||||
throw new Error("Failed to get gesture position, no tracked touches");
|
||||
}
|
||||
|
||||
let size = this._tracked.length;
|
||||
let fx = 0, fy = 0, lx = 0, ly = 0;
|
||||
|
||||
for (let i = 0; i < this._tracked.length; i++) {
|
||||
fx += this._tracked[i].firstX;
|
||||
fy += this._tracked[i].firstY;
|
||||
lx += this._tracked[i].lastX;
|
||||
ly += this._tracked[i].lastY;
|
||||
}
|
||||
|
||||
return { first: { x: fx / size,
|
||||
y: fy / size },
|
||||
last: { x: lx / size,
|
||||
y: ly / size } };
|
||||
}
|
||||
|
||||
_getAverageMovement() {
|
||||
if (this._tracked.length === 0) {
|
||||
throw new Error("Failed to get gesture movement, no tracked touches");
|
||||
}
|
||||
|
||||
let totalH, totalV;
|
||||
totalH = totalV = 0;
|
||||
let size = this._tracked.length;
|
||||
|
||||
for (let i = 0; i < this._tracked.length; i++) {
|
||||
totalH += this._tracked[i].lastX - this._tracked[i].firstX;
|
||||
totalV += this._tracked[i].lastY - this._tracked[i].firstY;
|
||||
}
|
||||
|
||||
return { x: totalH / size,
|
||||
y: totalV / size };
|
||||
}
|
||||
|
||||
_getAverageDistance() {
|
||||
if (this._tracked.length === 0) {
|
||||
throw new Error("Failed to get gesture distance, no tracked touches");
|
||||
}
|
||||
|
||||
// Distance between the first and last tracked touches
|
||||
|
||||
let first = this._tracked[0];
|
||||
let last = this._tracked[this._tracked.length - 1];
|
||||
|
||||
let fdx = Math.abs(last.firstX - first.firstX);
|
||||
let fdy = Math.abs(last.firstY - first.firstY);
|
||||
|
||||
let ldx = Math.abs(last.lastX - first.lastX);
|
||||
let ldy = Math.abs(last.lastY - first.lastY);
|
||||
|
||||
return { first: { x: fdx, y: fdy },
|
||||
last: { x: ldx, y: ldy } };
|
||||
}
|
||||
}
|
||||
283
backend/app/static/novnc/core/input/keyboard.js
Normal file
283
backend/app/static/novnc/core/input/keyboard.js
Normal file
@@ -0,0 +1,283 @@
|
||||
/*
|
||||
* noVNC: HTML5 VNC client
|
||||
* Copyright (C) 2019 The noVNC Authors
|
||||
* Licensed under MPL 2.0 or any later version (see LICENSE.txt)
|
||||
*/
|
||||
|
||||
import * as Log from '../util/logging.js';
|
||||
import { stopEvent } from '../util/events.js';
|
||||
import * as KeyboardUtil from "./util.js";
|
||||
import KeyTable from "./keysym.js";
|
||||
import * as browser from "../util/browser.js";
|
||||
|
||||
//
|
||||
// Keyboard event handler
|
||||
//
|
||||
|
||||
export default class Keyboard {
|
||||
constructor(target) {
|
||||
this._target = target || null;
|
||||
|
||||
this._keyDownList = {}; // List of depressed keys
|
||||
// (even if they are happy)
|
||||
this._altGrArmed = false; // Windows AltGr detection
|
||||
|
||||
// keep these here so we can refer to them later
|
||||
this._eventHandlers = {
|
||||
'keyup': this._handleKeyUp.bind(this),
|
||||
'keydown': this._handleKeyDown.bind(this),
|
||||
'blur': this._allKeysUp.bind(this),
|
||||
};
|
||||
|
||||
// ===== EVENT HANDLERS =====
|
||||
|
||||
this.onkeyevent = () => {}; // Handler for key press/release
|
||||
}
|
||||
|
||||
// ===== PRIVATE METHODS =====
|
||||
|
||||
_sendKeyEvent(keysym, code, down) {
|
||||
if (down) {
|
||||
this._keyDownList[code] = keysym;
|
||||
} else {
|
||||
// Do we really think this key is down?
|
||||
if (!(code in this._keyDownList)) {
|
||||
return;
|
||||
}
|
||||
delete this._keyDownList[code];
|
||||
}
|
||||
|
||||
Log.Debug("onkeyevent " + (down ? "down" : "up") +
|
||||
", keysym: " + keysym, ", code: " + code);
|
||||
this.onkeyevent(keysym, code, down);
|
||||
}
|
||||
|
||||
_getKeyCode(e) {
|
||||
const code = KeyboardUtil.getKeycode(e);
|
||||
if (code !== 'Unidentified') {
|
||||
return code;
|
||||
}
|
||||
|
||||
// Unstable, but we don't have anything else to go on
|
||||
if (e.keyCode) {
|
||||
// 229 is used for composition events
|
||||
if (e.keyCode !== 229) {
|
||||
return 'Platform' + e.keyCode;
|
||||
}
|
||||
}
|
||||
|
||||
// A precursor to the final DOM3 standard. Unfortunately it
|
||||
// is not layout independent, so it is as bad as using keyCode
|
||||
if (e.keyIdentifier) {
|
||||
// Non-character key?
|
||||
if (e.keyIdentifier.substr(0, 2) !== 'U+') {
|
||||
return e.keyIdentifier;
|
||||
}
|
||||
|
||||
const codepoint = parseInt(e.keyIdentifier.substr(2), 16);
|
||||
const char = String.fromCharCode(codepoint).toUpperCase();
|
||||
|
||||
return 'Platform' + char.charCodeAt();
|
||||
}
|
||||
|
||||
return 'Unidentified';
|
||||
}
|
||||
|
||||
_handleKeyDown(e) {
|
||||
const code = this._getKeyCode(e);
|
||||
let keysym = KeyboardUtil.getKeysym(e);
|
||||
|
||||
// Windows doesn't have a proper AltGr, but handles it using
|
||||
// fake Ctrl+Alt. However the remote end might not be Windows,
|
||||
// so we need to merge those in to a single AltGr event. We
|
||||
// detect this case by seeing the two key events directly after
|
||||
// each other with a very short time between them (<50ms).
|
||||
if (this._altGrArmed) {
|
||||
this._altGrArmed = false;
|
||||
clearTimeout(this._altGrTimeout);
|
||||
|
||||
if ((code === "AltRight") &&
|
||||
((e.timeStamp - this._altGrCtrlTime) < 50)) {
|
||||
// FIXME: We fail to detect this if either Ctrl key is
|
||||
// first manually pressed as Windows then no
|
||||
// longer sends the fake Ctrl down event. It
|
||||
// does however happily send real Ctrl events
|
||||
// even when AltGr is already down. Some
|
||||
// browsers detect this for us though and set the
|
||||
// key to "AltGraph".
|
||||
keysym = KeyTable.XK_ISO_Level3_Shift;
|
||||
} else {
|
||||
this._sendKeyEvent(KeyTable.XK_Control_L, "ControlLeft", true);
|
||||
}
|
||||
}
|
||||
|
||||
// We cannot handle keys we cannot track, but we also need
|
||||
// to deal with virtual keyboards which omit key info
|
||||
if (code === 'Unidentified') {
|
||||
if (keysym) {
|
||||
// If it's a virtual keyboard then it should be
|
||||
// sufficient to just send press and release right
|
||||
// after each other
|
||||
this._sendKeyEvent(keysym, code, true);
|
||||
this._sendKeyEvent(keysym, code, false);
|
||||
}
|
||||
|
||||
stopEvent(e);
|
||||
return;
|
||||
}
|
||||
|
||||
// Alt behaves more like AltGraph on macOS, so shuffle the
|
||||
// keys around a bit to make things more sane for the remote
|
||||
// server. This method is used by RealVNC and TigerVNC (and
|
||||
// possibly others).
|
||||
if (browser.isMac() || browser.isIOS()) {
|
||||
switch (keysym) {
|
||||
case KeyTable.XK_Super_L:
|
||||
keysym = KeyTable.XK_Alt_L;
|
||||
break;
|
||||
case KeyTable.XK_Super_R:
|
||||
keysym = KeyTable.XK_Super_L;
|
||||
break;
|
||||
case KeyTable.XK_Alt_L:
|
||||
keysym = KeyTable.XK_Mode_switch;
|
||||
break;
|
||||
case KeyTable.XK_Alt_R:
|
||||
keysym = KeyTable.XK_ISO_Level3_Shift;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Is this key already pressed? If so, then we must use the
|
||||
// same keysym or we'll confuse the server
|
||||
if (code in this._keyDownList) {
|
||||
keysym = this._keyDownList[code];
|
||||
}
|
||||
|
||||
// macOS doesn't send proper key releases if a key is pressed
|
||||
// while meta is held down
|
||||
if ((browser.isMac() || browser.isIOS()) &&
|
||||
(e.metaKey && code !== 'MetaLeft' && code !== 'MetaRight')) {
|
||||
this._sendKeyEvent(keysym, code, true);
|
||||
this._sendKeyEvent(keysym, code, false);
|
||||
stopEvent(e);
|
||||
return;
|
||||
}
|
||||
|
||||
// macOS doesn't send proper key events for modifiers, only
|
||||
// state change events. That gets extra confusing for CapsLock
|
||||
// which toggles on each press, but not on release. So pretend
|
||||
// it was a quick press and release of the button.
|
||||
if ((browser.isMac() || browser.isIOS()) && (code === 'CapsLock')) {
|
||||
this._sendKeyEvent(KeyTable.XK_Caps_Lock, 'CapsLock', true);
|
||||
this._sendKeyEvent(KeyTable.XK_Caps_Lock, 'CapsLock', false);
|
||||
stopEvent(e);
|
||||
return;
|
||||
}
|
||||
|
||||
// Windows doesn't send proper key releases for a bunch of
|
||||
// Japanese IM keys so we have to fake the release right away
|
||||
const jpBadKeys = [ KeyTable.XK_Zenkaku_Hankaku,
|
||||
KeyTable.XK_Eisu_toggle,
|
||||
KeyTable.XK_Katakana,
|
||||
KeyTable.XK_Hiragana,
|
||||
KeyTable.XK_Romaji ];
|
||||
if (browser.isWindows() && jpBadKeys.includes(keysym)) {
|
||||
this._sendKeyEvent(keysym, code, true);
|
||||
this._sendKeyEvent(keysym, code, false);
|
||||
stopEvent(e);
|
||||
return;
|
||||
}
|
||||
|
||||
stopEvent(e);
|
||||
|
||||
// Possible start of AltGr sequence? (see above)
|
||||
if ((code === "ControlLeft") && browser.isWindows() &&
|
||||
!("ControlLeft" in this._keyDownList)) {
|
||||
this._altGrArmed = true;
|
||||
this._altGrTimeout = setTimeout(this._handleAltGrTimeout.bind(this), 100);
|
||||
this._altGrCtrlTime = e.timeStamp;
|
||||
return;
|
||||
}
|
||||
|
||||
this._sendKeyEvent(keysym, code, true);
|
||||
}
|
||||
|
||||
_handleKeyUp(e) {
|
||||
stopEvent(e);
|
||||
|
||||
const code = this._getKeyCode(e);
|
||||
|
||||
// We can't get a release in the middle of an AltGr sequence, so
|
||||
// abort that detection
|
||||
if (this._altGrArmed) {
|
||||
this._altGrArmed = false;
|
||||
clearTimeout(this._altGrTimeout);
|
||||
this._sendKeyEvent(KeyTable.XK_Control_L, "ControlLeft", true);
|
||||
}
|
||||
|
||||
// See comment in _handleKeyDown()
|
||||
if ((browser.isMac() || browser.isIOS()) && (code === 'CapsLock')) {
|
||||
this._sendKeyEvent(KeyTable.XK_Caps_Lock, 'CapsLock', true);
|
||||
this._sendKeyEvent(KeyTable.XK_Caps_Lock, 'CapsLock', false);
|
||||
return;
|
||||
}
|
||||
|
||||
this._sendKeyEvent(this._keyDownList[code], code, false);
|
||||
|
||||
// Windows has a rather nasty bug where it won't send key
|
||||
// release events for a Shift button if the other Shift is still
|
||||
// pressed
|
||||
if (browser.isWindows() && ((code === 'ShiftLeft') ||
|
||||
(code === 'ShiftRight'))) {
|
||||
if ('ShiftRight' in this._keyDownList) {
|
||||
this._sendKeyEvent(this._keyDownList['ShiftRight'],
|
||||
'ShiftRight', false);
|
||||
}
|
||||
if ('ShiftLeft' in this._keyDownList) {
|
||||
this._sendKeyEvent(this._keyDownList['ShiftLeft'],
|
||||
'ShiftLeft', false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
_handleAltGrTimeout() {
|
||||
this._altGrArmed = false;
|
||||
clearTimeout(this._altGrTimeout);
|
||||
this._sendKeyEvent(KeyTable.XK_Control_L, "ControlLeft", true);
|
||||
}
|
||||
|
||||
_allKeysUp() {
|
||||
Log.Debug(">> Keyboard.allKeysUp");
|
||||
for (let code in this._keyDownList) {
|
||||
this._sendKeyEvent(this._keyDownList[code], code, false);
|
||||
}
|
||||
Log.Debug("<< Keyboard.allKeysUp");
|
||||
}
|
||||
|
||||
// ===== PUBLIC METHODS =====
|
||||
|
||||
grab() {
|
||||
//Log.Debug(">> Keyboard.grab");
|
||||
|
||||
this._target.addEventListener('keydown', this._eventHandlers.keydown);
|
||||
this._target.addEventListener('keyup', this._eventHandlers.keyup);
|
||||
|
||||
// Release (key up) if window loses focus
|
||||
window.addEventListener('blur', this._eventHandlers.blur);
|
||||
|
||||
//Log.Debug("<< Keyboard.grab");
|
||||
}
|
||||
|
||||
ungrab() {
|
||||
//Log.Debug(">> Keyboard.ungrab");
|
||||
|
||||
this._target.removeEventListener('keydown', this._eventHandlers.keydown);
|
||||
this._target.removeEventListener('keyup', this._eventHandlers.keyup);
|
||||
window.removeEventListener('blur', this._eventHandlers.blur);
|
||||
|
||||
// Release (key up) all keys that are in a down state
|
||||
this._allKeysUp();
|
||||
|
||||
//Log.Debug(">> Keyboard.ungrab");
|
||||
}
|
||||
}
|
||||
616
backend/app/static/novnc/core/input/keysym.js
Normal file
616
backend/app/static/novnc/core/input/keysym.js
Normal file
@@ -0,0 +1,616 @@
|
||||
/* eslint-disable key-spacing */
|
||||
|
||||
export default {
|
||||
XK_VoidSymbol: 0xffffff, /* Void symbol */
|
||||
|
||||
XK_BackSpace: 0xff08, /* Back space, back char */
|
||||
XK_Tab: 0xff09,
|
||||
XK_Linefeed: 0xff0a, /* Linefeed, LF */
|
||||
XK_Clear: 0xff0b,
|
||||
XK_Return: 0xff0d, /* Return, enter */
|
||||
XK_Pause: 0xff13, /* Pause, hold */
|
||||
XK_Scroll_Lock: 0xff14,
|
||||
XK_Sys_Req: 0xff15,
|
||||
XK_Escape: 0xff1b,
|
||||
XK_Delete: 0xffff, /* Delete, rubout */
|
||||
|
||||
/* International & multi-key character composition */
|
||||
|
||||
XK_Multi_key: 0xff20, /* Multi-key character compose */
|
||||
XK_Codeinput: 0xff37,
|
||||
XK_SingleCandidate: 0xff3c,
|
||||
XK_MultipleCandidate: 0xff3d,
|
||||
XK_PreviousCandidate: 0xff3e,
|
||||
|
||||
/* Japanese keyboard support */
|
||||
|
||||
XK_Kanji: 0xff21, /* Kanji, Kanji convert */
|
||||
XK_Muhenkan: 0xff22, /* Cancel Conversion */
|
||||
XK_Henkan_Mode: 0xff23, /* Start/Stop Conversion */
|
||||
XK_Henkan: 0xff23, /* Alias for Henkan_Mode */
|
||||
XK_Romaji: 0xff24, /* to Romaji */
|
||||
XK_Hiragana: 0xff25, /* to Hiragana */
|
||||
XK_Katakana: 0xff26, /* to Katakana */
|
||||
XK_Hiragana_Katakana: 0xff27, /* Hiragana/Katakana toggle */
|
||||
XK_Zenkaku: 0xff28, /* to Zenkaku */
|
||||
XK_Hankaku: 0xff29, /* to Hankaku */
|
||||
XK_Zenkaku_Hankaku: 0xff2a, /* Zenkaku/Hankaku toggle */
|
||||
XK_Touroku: 0xff2b, /* Add to Dictionary */
|
||||
XK_Massyo: 0xff2c, /* Delete from Dictionary */
|
||||
XK_Kana_Lock: 0xff2d, /* Kana Lock */
|
||||
XK_Kana_Shift: 0xff2e, /* Kana Shift */
|
||||
XK_Eisu_Shift: 0xff2f, /* Alphanumeric Shift */
|
||||
XK_Eisu_toggle: 0xff30, /* Alphanumeric toggle */
|
||||
XK_Kanji_Bangou: 0xff37, /* Codeinput */
|
||||
XK_Zen_Koho: 0xff3d, /* Multiple/All Candidate(s) */
|
||||
XK_Mae_Koho: 0xff3e, /* Previous Candidate */
|
||||
|
||||
/* Cursor control & motion */
|
||||
|
||||
XK_Home: 0xff50,
|
||||
XK_Left: 0xff51, /* Move left, left arrow */
|
||||
XK_Up: 0xff52, /* Move up, up arrow */
|
||||
XK_Right: 0xff53, /* Move right, right arrow */
|
||||
XK_Down: 0xff54, /* Move down, down arrow */
|
||||
XK_Prior: 0xff55, /* Prior, previous */
|
||||
XK_Page_Up: 0xff55,
|
||||
XK_Next: 0xff56, /* Next */
|
||||
XK_Page_Down: 0xff56,
|
||||
XK_End: 0xff57, /* EOL */
|
||||
XK_Begin: 0xff58, /* BOL */
|
||||
|
||||
|
||||
/* Misc functions */
|
||||
|
||||
XK_Select: 0xff60, /* Select, mark */
|
||||
XK_Print: 0xff61,
|
||||
XK_Execute: 0xff62, /* Execute, run, do */
|
||||
XK_Insert: 0xff63, /* Insert, insert here */
|
||||
XK_Undo: 0xff65,
|
||||
XK_Redo: 0xff66, /* Redo, again */
|
||||
XK_Menu: 0xff67,
|
||||
XK_Find: 0xff68, /* Find, search */
|
||||
XK_Cancel: 0xff69, /* Cancel, stop, abort, exit */
|
||||
XK_Help: 0xff6a, /* Help */
|
||||
XK_Break: 0xff6b,
|
||||
XK_Mode_switch: 0xff7e, /* Character set switch */
|
||||
XK_script_switch: 0xff7e, /* Alias for mode_switch */
|
||||
XK_Num_Lock: 0xff7f,
|
||||
|
||||
/* Keypad functions, keypad numbers cleverly chosen to map to ASCII */
|
||||
|
||||
XK_KP_Space: 0xff80, /* Space */
|
||||
XK_KP_Tab: 0xff89,
|
||||
XK_KP_Enter: 0xff8d, /* Enter */
|
||||
XK_KP_F1: 0xff91, /* PF1, KP_A, ... */
|
||||
XK_KP_F2: 0xff92,
|
||||
XK_KP_F3: 0xff93,
|
||||
XK_KP_F4: 0xff94,
|
||||
XK_KP_Home: 0xff95,
|
||||
XK_KP_Left: 0xff96,
|
||||
XK_KP_Up: 0xff97,
|
||||
XK_KP_Right: 0xff98,
|
||||
XK_KP_Down: 0xff99,
|
||||
XK_KP_Prior: 0xff9a,
|
||||
XK_KP_Page_Up: 0xff9a,
|
||||
XK_KP_Next: 0xff9b,
|
||||
XK_KP_Page_Down: 0xff9b,
|
||||
XK_KP_End: 0xff9c,
|
||||
XK_KP_Begin: 0xff9d,
|
||||
XK_KP_Insert: 0xff9e,
|
||||
XK_KP_Delete: 0xff9f,
|
||||
XK_KP_Equal: 0xffbd, /* Equals */
|
||||
XK_KP_Multiply: 0xffaa,
|
||||
XK_KP_Add: 0xffab,
|
||||
XK_KP_Separator: 0xffac, /* Separator, often comma */
|
||||
XK_KP_Subtract: 0xffad,
|
||||
XK_KP_Decimal: 0xffae,
|
||||
XK_KP_Divide: 0xffaf,
|
||||
|
||||
XK_KP_0: 0xffb0,
|
||||
XK_KP_1: 0xffb1,
|
||||
XK_KP_2: 0xffb2,
|
||||
XK_KP_3: 0xffb3,
|
||||
XK_KP_4: 0xffb4,
|
||||
XK_KP_5: 0xffb5,
|
||||
XK_KP_6: 0xffb6,
|
||||
XK_KP_7: 0xffb7,
|
||||
XK_KP_8: 0xffb8,
|
||||
XK_KP_9: 0xffb9,
|
||||
|
||||
/*
|
||||
* Auxiliary functions; note the duplicate definitions for left and right
|
||||
* function keys; Sun keyboards and a few other manufacturers have such
|
||||
* function key groups on the left and/or right sides of the keyboard.
|
||||
* We've not found a keyboard with more than 35 function keys total.
|
||||
*/
|
||||
|
||||
XK_F1: 0xffbe,
|
||||
XK_F2: 0xffbf,
|
||||
XK_F3: 0xffc0,
|
||||
XK_F4: 0xffc1,
|
||||
XK_F5: 0xffc2,
|
||||
XK_F6: 0xffc3,
|
||||
XK_F7: 0xffc4,
|
||||
XK_F8: 0xffc5,
|
||||
XK_F9: 0xffc6,
|
||||
XK_F10: 0xffc7,
|
||||
XK_F11: 0xffc8,
|
||||
XK_L1: 0xffc8,
|
||||
XK_F12: 0xffc9,
|
||||
XK_L2: 0xffc9,
|
||||
XK_F13: 0xffca,
|
||||
XK_L3: 0xffca,
|
||||
XK_F14: 0xffcb,
|
||||
XK_L4: 0xffcb,
|
||||
XK_F15: 0xffcc,
|
||||
XK_L5: 0xffcc,
|
||||
XK_F16: 0xffcd,
|
||||
XK_L6: 0xffcd,
|
||||
XK_F17: 0xffce,
|
||||
XK_L7: 0xffce,
|
||||
XK_F18: 0xffcf,
|
||||
XK_L8: 0xffcf,
|
||||
XK_F19: 0xffd0,
|
||||
XK_L9: 0xffd0,
|
||||
XK_F20: 0xffd1,
|
||||
XK_L10: 0xffd1,
|
||||
XK_F21: 0xffd2,
|
||||
XK_R1: 0xffd2,
|
||||
XK_F22: 0xffd3,
|
||||
XK_R2: 0xffd3,
|
||||
XK_F23: 0xffd4,
|
||||
XK_R3: 0xffd4,
|
||||
XK_F24: 0xffd5,
|
||||
XK_R4: 0xffd5,
|
||||
XK_F25: 0xffd6,
|
||||
XK_R5: 0xffd6,
|
||||
XK_F26: 0xffd7,
|
||||
XK_R6: 0xffd7,
|
||||
XK_F27: 0xffd8,
|
||||
XK_R7: 0xffd8,
|
||||
XK_F28: 0xffd9,
|
||||
XK_R8: 0xffd9,
|
||||
XK_F29: 0xffda,
|
||||
XK_R9: 0xffda,
|
||||
XK_F30: 0xffdb,
|
||||
XK_R10: 0xffdb,
|
||||
XK_F31: 0xffdc,
|
||||
XK_R11: 0xffdc,
|
||||
XK_F32: 0xffdd,
|
||||
XK_R12: 0xffdd,
|
||||
XK_F33: 0xffde,
|
||||
XK_R13: 0xffde,
|
||||
XK_F34: 0xffdf,
|
||||
XK_R14: 0xffdf,
|
||||
XK_F35: 0xffe0,
|
||||
XK_R15: 0xffe0,
|
||||
|
||||
/* Modifiers */
|
||||
|
||||
XK_Shift_L: 0xffe1, /* Left shift */
|
||||
XK_Shift_R: 0xffe2, /* Right shift */
|
||||
XK_Control_L: 0xffe3, /* Left control */
|
||||
XK_Control_R: 0xffe4, /* Right control */
|
||||
XK_Caps_Lock: 0xffe5, /* Caps lock */
|
||||
XK_Shift_Lock: 0xffe6, /* Shift lock */
|
||||
|
||||
XK_Meta_L: 0xffe7, /* Left meta */
|
||||
XK_Meta_R: 0xffe8, /* Right meta */
|
||||
XK_Alt_L: 0xffe9, /* Left alt */
|
||||
XK_Alt_R: 0xffea, /* Right alt */
|
||||
XK_Super_L: 0xffeb, /* Left super */
|
||||
XK_Super_R: 0xffec, /* Right super */
|
||||
XK_Hyper_L: 0xffed, /* Left hyper */
|
||||
XK_Hyper_R: 0xffee, /* Right hyper */
|
||||
|
||||
/*
|
||||
* Keyboard (XKB) Extension function and modifier keys
|
||||
* (from Appendix C of "The X Keyboard Extension: Protocol Specification")
|
||||
* Byte 3 = 0xfe
|
||||
*/
|
||||
|
||||
XK_ISO_Level3_Shift: 0xfe03, /* AltGr */
|
||||
XK_ISO_Next_Group: 0xfe08,
|
||||
XK_ISO_Prev_Group: 0xfe0a,
|
||||
XK_ISO_First_Group: 0xfe0c,
|
||||
XK_ISO_Last_Group: 0xfe0e,
|
||||
|
||||
/*
|
||||
* Latin 1
|
||||
* (ISO/IEC 8859-1: Unicode U+0020..U+00FF)
|
||||
* Byte 3: 0
|
||||
*/
|
||||
|
||||
XK_space: 0x0020, /* U+0020 SPACE */
|
||||
XK_exclam: 0x0021, /* U+0021 EXCLAMATION MARK */
|
||||
XK_quotedbl: 0x0022, /* U+0022 QUOTATION MARK */
|
||||
XK_numbersign: 0x0023, /* U+0023 NUMBER SIGN */
|
||||
XK_dollar: 0x0024, /* U+0024 DOLLAR SIGN */
|
||||
XK_percent: 0x0025, /* U+0025 PERCENT SIGN */
|
||||
XK_ampersand: 0x0026, /* U+0026 AMPERSAND */
|
||||
XK_apostrophe: 0x0027, /* U+0027 APOSTROPHE */
|
||||
XK_quoteright: 0x0027, /* deprecated */
|
||||
XK_parenleft: 0x0028, /* U+0028 LEFT PARENTHESIS */
|
||||
XK_parenright: 0x0029, /* U+0029 RIGHT PARENTHESIS */
|
||||
XK_asterisk: 0x002a, /* U+002A ASTERISK */
|
||||
XK_plus: 0x002b, /* U+002B PLUS SIGN */
|
||||
XK_comma: 0x002c, /* U+002C COMMA */
|
||||
XK_minus: 0x002d, /* U+002D HYPHEN-MINUS */
|
||||
XK_period: 0x002e, /* U+002E FULL STOP */
|
||||
XK_slash: 0x002f, /* U+002F SOLIDUS */
|
||||
XK_0: 0x0030, /* U+0030 DIGIT ZERO */
|
||||
XK_1: 0x0031, /* U+0031 DIGIT ONE */
|
||||
XK_2: 0x0032, /* U+0032 DIGIT TWO */
|
||||
XK_3: 0x0033, /* U+0033 DIGIT THREE */
|
||||
XK_4: 0x0034, /* U+0034 DIGIT FOUR */
|
||||
XK_5: 0x0035, /* U+0035 DIGIT FIVE */
|
||||
XK_6: 0x0036, /* U+0036 DIGIT SIX */
|
||||
XK_7: 0x0037, /* U+0037 DIGIT SEVEN */
|
||||
XK_8: 0x0038, /* U+0038 DIGIT EIGHT */
|
||||
XK_9: 0x0039, /* U+0039 DIGIT NINE */
|
||||
XK_colon: 0x003a, /* U+003A COLON */
|
||||
XK_semicolon: 0x003b, /* U+003B SEMICOLON */
|
||||
XK_less: 0x003c, /* U+003C LESS-THAN SIGN */
|
||||
XK_equal: 0x003d, /* U+003D EQUALS SIGN */
|
||||
XK_greater: 0x003e, /* U+003E GREATER-THAN SIGN */
|
||||
XK_question: 0x003f, /* U+003F QUESTION MARK */
|
||||
XK_at: 0x0040, /* U+0040 COMMERCIAL AT */
|
||||
XK_A: 0x0041, /* U+0041 LATIN CAPITAL LETTER A */
|
||||
XK_B: 0x0042, /* U+0042 LATIN CAPITAL LETTER B */
|
||||
XK_C: 0x0043, /* U+0043 LATIN CAPITAL LETTER C */
|
||||
XK_D: 0x0044, /* U+0044 LATIN CAPITAL LETTER D */
|
||||
XK_E: 0x0045, /* U+0045 LATIN CAPITAL LETTER E */
|
||||
XK_F: 0x0046, /* U+0046 LATIN CAPITAL LETTER F */
|
||||
XK_G: 0x0047, /* U+0047 LATIN CAPITAL LETTER G */
|
||||
XK_H: 0x0048, /* U+0048 LATIN CAPITAL LETTER H */
|
||||
XK_I: 0x0049, /* U+0049 LATIN CAPITAL LETTER I */
|
||||
XK_J: 0x004a, /* U+004A LATIN CAPITAL LETTER J */
|
||||
XK_K: 0x004b, /* U+004B LATIN CAPITAL LETTER K */
|
||||
XK_L: 0x004c, /* U+004C LATIN CAPITAL LETTER L */
|
||||
XK_M: 0x004d, /* U+004D LATIN CAPITAL LETTER M */
|
||||
XK_N: 0x004e, /* U+004E LATIN CAPITAL LETTER N */
|
||||
XK_O: 0x004f, /* U+004F LATIN CAPITAL LETTER O */
|
||||
XK_P: 0x0050, /* U+0050 LATIN CAPITAL LETTER P */
|
||||
XK_Q: 0x0051, /* U+0051 LATIN CAPITAL LETTER Q */
|
||||
XK_R: 0x0052, /* U+0052 LATIN CAPITAL LETTER R */
|
||||
XK_S: 0x0053, /* U+0053 LATIN CAPITAL LETTER S */
|
||||
XK_T: 0x0054, /* U+0054 LATIN CAPITAL LETTER T */
|
||||
XK_U: 0x0055, /* U+0055 LATIN CAPITAL LETTER U */
|
||||
XK_V: 0x0056, /* U+0056 LATIN CAPITAL LETTER V */
|
||||
XK_W: 0x0057, /* U+0057 LATIN CAPITAL LETTER W */
|
||||
XK_X: 0x0058, /* U+0058 LATIN CAPITAL LETTER X */
|
||||
XK_Y: 0x0059, /* U+0059 LATIN CAPITAL LETTER Y */
|
||||
XK_Z: 0x005a, /* U+005A LATIN CAPITAL LETTER Z */
|
||||
XK_bracketleft: 0x005b, /* U+005B LEFT SQUARE BRACKET */
|
||||
XK_backslash: 0x005c, /* U+005C REVERSE SOLIDUS */
|
||||
XK_bracketright: 0x005d, /* U+005D RIGHT SQUARE BRACKET */
|
||||
XK_asciicircum: 0x005e, /* U+005E CIRCUMFLEX ACCENT */
|
||||
XK_underscore: 0x005f, /* U+005F LOW LINE */
|
||||
XK_grave: 0x0060, /* U+0060 GRAVE ACCENT */
|
||||
XK_quoteleft: 0x0060, /* deprecated */
|
||||
XK_a: 0x0061, /* U+0061 LATIN SMALL LETTER A */
|
||||
XK_b: 0x0062, /* U+0062 LATIN SMALL LETTER B */
|
||||
XK_c: 0x0063, /* U+0063 LATIN SMALL LETTER C */
|
||||
XK_d: 0x0064, /* U+0064 LATIN SMALL LETTER D */
|
||||
XK_e: 0x0065, /* U+0065 LATIN SMALL LETTER E */
|
||||
XK_f: 0x0066, /* U+0066 LATIN SMALL LETTER F */
|
||||
XK_g: 0x0067, /* U+0067 LATIN SMALL LETTER G */
|
||||
XK_h: 0x0068, /* U+0068 LATIN SMALL LETTER H */
|
||||
XK_i: 0x0069, /* U+0069 LATIN SMALL LETTER I */
|
||||
XK_j: 0x006a, /* U+006A LATIN SMALL LETTER J */
|
||||
XK_k: 0x006b, /* U+006B LATIN SMALL LETTER K */
|
||||
XK_l: 0x006c, /* U+006C LATIN SMALL LETTER L */
|
||||
XK_m: 0x006d, /* U+006D LATIN SMALL LETTER M */
|
||||
XK_n: 0x006e, /* U+006E LATIN SMALL LETTER N */
|
||||
XK_o: 0x006f, /* U+006F LATIN SMALL LETTER O */
|
||||
XK_p: 0x0070, /* U+0070 LATIN SMALL LETTER P */
|
||||
XK_q: 0x0071, /* U+0071 LATIN SMALL LETTER Q */
|
||||
XK_r: 0x0072, /* U+0072 LATIN SMALL LETTER R */
|
||||
XK_s: 0x0073, /* U+0073 LATIN SMALL LETTER S */
|
||||
XK_t: 0x0074, /* U+0074 LATIN SMALL LETTER T */
|
||||
XK_u: 0x0075, /* U+0075 LATIN SMALL LETTER U */
|
||||
XK_v: 0x0076, /* U+0076 LATIN SMALL LETTER V */
|
||||
XK_w: 0x0077, /* U+0077 LATIN SMALL LETTER W */
|
||||
XK_x: 0x0078, /* U+0078 LATIN SMALL LETTER X */
|
||||
XK_y: 0x0079, /* U+0079 LATIN SMALL LETTER Y */
|
||||
XK_z: 0x007a, /* U+007A LATIN SMALL LETTER Z */
|
||||
XK_braceleft: 0x007b, /* U+007B LEFT CURLY BRACKET */
|
||||
XK_bar: 0x007c, /* U+007C VERTICAL LINE */
|
||||
XK_braceright: 0x007d, /* U+007D RIGHT CURLY BRACKET */
|
||||
XK_asciitilde: 0x007e, /* U+007E TILDE */
|
||||
|
||||
XK_nobreakspace: 0x00a0, /* U+00A0 NO-BREAK SPACE */
|
||||
XK_exclamdown: 0x00a1, /* U+00A1 INVERTED EXCLAMATION MARK */
|
||||
XK_cent: 0x00a2, /* U+00A2 CENT SIGN */
|
||||
XK_sterling: 0x00a3, /* U+00A3 POUND SIGN */
|
||||
XK_currency: 0x00a4, /* U+00A4 CURRENCY SIGN */
|
||||
XK_yen: 0x00a5, /* U+00A5 YEN SIGN */
|
||||
XK_brokenbar: 0x00a6, /* U+00A6 BROKEN BAR */
|
||||
XK_section: 0x00a7, /* U+00A7 SECTION SIGN */
|
||||
XK_diaeresis: 0x00a8, /* U+00A8 DIAERESIS */
|
||||
XK_copyright: 0x00a9, /* U+00A9 COPYRIGHT SIGN */
|
||||
XK_ordfeminine: 0x00aa, /* U+00AA FEMININE ORDINAL INDICATOR */
|
||||
XK_guillemotleft: 0x00ab, /* U+00AB LEFT-POINTING DOUBLE ANGLE QUOTATION MARK */
|
||||
XK_notsign: 0x00ac, /* U+00AC NOT SIGN */
|
||||
XK_hyphen: 0x00ad, /* U+00AD SOFT HYPHEN */
|
||||
XK_registered: 0x00ae, /* U+00AE REGISTERED SIGN */
|
||||
XK_macron: 0x00af, /* U+00AF MACRON */
|
||||
XK_degree: 0x00b0, /* U+00B0 DEGREE SIGN */
|
||||
XK_plusminus: 0x00b1, /* U+00B1 PLUS-MINUS SIGN */
|
||||
XK_twosuperior: 0x00b2, /* U+00B2 SUPERSCRIPT TWO */
|
||||
XK_threesuperior: 0x00b3, /* U+00B3 SUPERSCRIPT THREE */
|
||||
XK_acute: 0x00b4, /* U+00B4 ACUTE ACCENT */
|
||||
XK_mu: 0x00b5, /* U+00B5 MICRO SIGN */
|
||||
XK_paragraph: 0x00b6, /* U+00B6 PILCROW SIGN */
|
||||
XK_periodcentered: 0x00b7, /* U+00B7 MIDDLE DOT */
|
||||
XK_cedilla: 0x00b8, /* U+00B8 CEDILLA */
|
||||
XK_onesuperior: 0x00b9, /* U+00B9 SUPERSCRIPT ONE */
|
||||
XK_masculine: 0x00ba, /* U+00BA MASCULINE ORDINAL INDICATOR */
|
||||
XK_guillemotright: 0x00bb, /* U+00BB RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK */
|
||||
XK_onequarter: 0x00bc, /* U+00BC VULGAR FRACTION ONE QUARTER */
|
||||
XK_onehalf: 0x00bd, /* U+00BD VULGAR FRACTION ONE HALF */
|
||||
XK_threequarters: 0x00be, /* U+00BE VULGAR FRACTION THREE QUARTERS */
|
||||
XK_questiondown: 0x00bf, /* U+00BF INVERTED QUESTION MARK */
|
||||
XK_Agrave: 0x00c0, /* U+00C0 LATIN CAPITAL LETTER A WITH GRAVE */
|
||||
XK_Aacute: 0x00c1, /* U+00C1 LATIN CAPITAL LETTER A WITH ACUTE */
|
||||
XK_Acircumflex: 0x00c2, /* U+00C2 LATIN CAPITAL LETTER A WITH CIRCUMFLEX */
|
||||
XK_Atilde: 0x00c3, /* U+00C3 LATIN CAPITAL LETTER A WITH TILDE */
|
||||
XK_Adiaeresis: 0x00c4, /* U+00C4 LATIN CAPITAL LETTER A WITH DIAERESIS */
|
||||
XK_Aring: 0x00c5, /* U+00C5 LATIN CAPITAL LETTER A WITH RING ABOVE */
|
||||
XK_AE: 0x00c6, /* U+00C6 LATIN CAPITAL LETTER AE */
|
||||
XK_Ccedilla: 0x00c7, /* U+00C7 LATIN CAPITAL LETTER C WITH CEDILLA */
|
||||
XK_Egrave: 0x00c8, /* U+00C8 LATIN CAPITAL LETTER E WITH GRAVE */
|
||||
XK_Eacute: 0x00c9, /* U+00C9 LATIN CAPITAL LETTER E WITH ACUTE */
|
||||
XK_Ecircumflex: 0x00ca, /* U+00CA LATIN CAPITAL LETTER E WITH CIRCUMFLEX */
|
||||
XK_Ediaeresis: 0x00cb, /* U+00CB LATIN CAPITAL LETTER E WITH DIAERESIS */
|
||||
XK_Igrave: 0x00cc, /* U+00CC LATIN CAPITAL LETTER I WITH GRAVE */
|
||||
XK_Iacute: 0x00cd, /* U+00CD LATIN CAPITAL LETTER I WITH ACUTE */
|
||||
XK_Icircumflex: 0x00ce, /* U+00CE LATIN CAPITAL LETTER I WITH CIRCUMFLEX */
|
||||
XK_Idiaeresis: 0x00cf, /* U+00CF LATIN CAPITAL LETTER I WITH DIAERESIS */
|
||||
XK_ETH: 0x00d0, /* U+00D0 LATIN CAPITAL LETTER ETH */
|
||||
XK_Eth: 0x00d0, /* deprecated */
|
||||
XK_Ntilde: 0x00d1, /* U+00D1 LATIN CAPITAL LETTER N WITH TILDE */
|
||||
XK_Ograve: 0x00d2, /* U+00D2 LATIN CAPITAL LETTER O WITH GRAVE */
|
||||
XK_Oacute: 0x00d3, /* U+00D3 LATIN CAPITAL LETTER O WITH ACUTE */
|
||||
XK_Ocircumflex: 0x00d4, /* U+00D4 LATIN CAPITAL LETTER O WITH CIRCUMFLEX */
|
||||
XK_Otilde: 0x00d5, /* U+00D5 LATIN CAPITAL LETTER O WITH TILDE */
|
||||
XK_Odiaeresis: 0x00d6, /* U+00D6 LATIN CAPITAL LETTER O WITH DIAERESIS */
|
||||
XK_multiply: 0x00d7, /* U+00D7 MULTIPLICATION SIGN */
|
||||
XK_Oslash: 0x00d8, /* U+00D8 LATIN CAPITAL LETTER O WITH STROKE */
|
||||
XK_Ooblique: 0x00d8, /* U+00D8 LATIN CAPITAL LETTER O WITH STROKE */
|
||||
XK_Ugrave: 0x00d9, /* U+00D9 LATIN CAPITAL LETTER U WITH GRAVE */
|
||||
XK_Uacute: 0x00da, /* U+00DA LATIN CAPITAL LETTER U WITH ACUTE */
|
||||
XK_Ucircumflex: 0x00db, /* U+00DB LATIN CAPITAL LETTER U WITH CIRCUMFLEX */
|
||||
XK_Udiaeresis: 0x00dc, /* U+00DC LATIN CAPITAL LETTER U WITH DIAERESIS */
|
||||
XK_Yacute: 0x00dd, /* U+00DD LATIN CAPITAL LETTER Y WITH ACUTE */
|
||||
XK_THORN: 0x00de, /* U+00DE LATIN CAPITAL LETTER THORN */
|
||||
XK_Thorn: 0x00de, /* deprecated */
|
||||
XK_ssharp: 0x00df, /* U+00DF LATIN SMALL LETTER SHARP S */
|
||||
XK_agrave: 0x00e0, /* U+00E0 LATIN SMALL LETTER A WITH GRAVE */
|
||||
XK_aacute: 0x00e1, /* U+00E1 LATIN SMALL LETTER A WITH ACUTE */
|
||||
XK_acircumflex: 0x00e2, /* U+00E2 LATIN SMALL LETTER A WITH CIRCUMFLEX */
|
||||
XK_atilde: 0x00e3, /* U+00E3 LATIN SMALL LETTER A WITH TILDE */
|
||||
XK_adiaeresis: 0x00e4, /* U+00E4 LATIN SMALL LETTER A WITH DIAERESIS */
|
||||
XK_aring: 0x00e5, /* U+00E5 LATIN SMALL LETTER A WITH RING ABOVE */
|
||||
XK_ae: 0x00e6, /* U+00E6 LATIN SMALL LETTER AE */
|
||||
XK_ccedilla: 0x00e7, /* U+00E7 LATIN SMALL LETTER C WITH CEDILLA */
|
||||
XK_egrave: 0x00e8, /* U+00E8 LATIN SMALL LETTER E WITH GRAVE */
|
||||
XK_eacute: 0x00e9, /* U+00E9 LATIN SMALL LETTER E WITH ACUTE */
|
||||
XK_ecircumflex: 0x00ea, /* U+00EA LATIN SMALL LETTER E WITH CIRCUMFLEX */
|
||||
XK_ediaeresis: 0x00eb, /* U+00EB LATIN SMALL LETTER E WITH DIAERESIS */
|
||||
XK_igrave: 0x00ec, /* U+00EC LATIN SMALL LETTER I WITH GRAVE */
|
||||
XK_iacute: 0x00ed, /* U+00ED LATIN SMALL LETTER I WITH ACUTE */
|
||||
XK_icircumflex: 0x00ee, /* U+00EE LATIN SMALL LETTER I WITH CIRCUMFLEX */
|
||||
XK_idiaeresis: 0x00ef, /* U+00EF LATIN SMALL LETTER I WITH DIAERESIS */
|
||||
XK_eth: 0x00f0, /* U+00F0 LATIN SMALL LETTER ETH */
|
||||
XK_ntilde: 0x00f1, /* U+00F1 LATIN SMALL LETTER N WITH TILDE */
|
||||
XK_ograve: 0x00f2, /* U+00F2 LATIN SMALL LETTER O WITH GRAVE */
|
||||
XK_oacute: 0x00f3, /* U+00F3 LATIN SMALL LETTER O WITH ACUTE */
|
||||
XK_ocircumflex: 0x00f4, /* U+00F4 LATIN SMALL LETTER O WITH CIRCUMFLEX */
|
||||
XK_otilde: 0x00f5, /* U+00F5 LATIN SMALL LETTER O WITH TILDE */
|
||||
XK_odiaeresis: 0x00f6, /* U+00F6 LATIN SMALL LETTER O WITH DIAERESIS */
|
||||
XK_division: 0x00f7, /* U+00F7 DIVISION SIGN */
|
||||
XK_oslash: 0x00f8, /* U+00F8 LATIN SMALL LETTER O WITH STROKE */
|
||||
XK_ooblique: 0x00f8, /* U+00F8 LATIN SMALL LETTER O WITH STROKE */
|
||||
XK_ugrave: 0x00f9, /* U+00F9 LATIN SMALL LETTER U WITH GRAVE */
|
||||
XK_uacute: 0x00fa, /* U+00FA LATIN SMALL LETTER U WITH ACUTE */
|
||||
XK_ucircumflex: 0x00fb, /* U+00FB LATIN SMALL LETTER U WITH CIRCUMFLEX */
|
||||
XK_udiaeresis: 0x00fc, /* U+00FC LATIN SMALL LETTER U WITH DIAERESIS */
|
||||
XK_yacute: 0x00fd, /* U+00FD LATIN SMALL LETTER Y WITH ACUTE */
|
||||
XK_thorn: 0x00fe, /* U+00FE LATIN SMALL LETTER THORN */
|
||||
XK_ydiaeresis: 0x00ff, /* U+00FF LATIN SMALL LETTER Y WITH DIAERESIS */
|
||||
|
||||
/*
|
||||
* Korean
|
||||
* Byte 3 = 0x0e
|
||||
*/
|
||||
|
||||
XK_Hangul: 0xff31, /* Hangul start/stop(toggle) */
|
||||
XK_Hangul_Hanja: 0xff34, /* Start Hangul->Hanja Conversion */
|
||||
XK_Hangul_Jeonja: 0xff38, /* Jeonja mode */
|
||||
|
||||
/*
|
||||
* XFree86 vendor specific keysyms.
|
||||
*
|
||||
* The XFree86 keysym range is 0x10080001 - 0x1008FFFF.
|
||||
*/
|
||||
|
||||
XF86XK_ModeLock: 0x1008FF01,
|
||||
XF86XK_MonBrightnessUp: 0x1008FF02,
|
||||
XF86XK_MonBrightnessDown: 0x1008FF03,
|
||||
XF86XK_KbdLightOnOff: 0x1008FF04,
|
||||
XF86XK_KbdBrightnessUp: 0x1008FF05,
|
||||
XF86XK_KbdBrightnessDown: 0x1008FF06,
|
||||
XF86XK_Standby: 0x1008FF10,
|
||||
XF86XK_AudioLowerVolume: 0x1008FF11,
|
||||
XF86XK_AudioMute: 0x1008FF12,
|
||||
XF86XK_AudioRaiseVolume: 0x1008FF13,
|
||||
XF86XK_AudioPlay: 0x1008FF14,
|
||||
XF86XK_AudioStop: 0x1008FF15,
|
||||
XF86XK_AudioPrev: 0x1008FF16,
|
||||
XF86XK_AudioNext: 0x1008FF17,
|
||||
XF86XK_HomePage: 0x1008FF18,
|
||||
XF86XK_Mail: 0x1008FF19,
|
||||
XF86XK_Start: 0x1008FF1A,
|
||||
XF86XK_Search: 0x1008FF1B,
|
||||
XF86XK_AudioRecord: 0x1008FF1C,
|
||||
XF86XK_Calculator: 0x1008FF1D,
|
||||
XF86XK_Memo: 0x1008FF1E,
|
||||
XF86XK_ToDoList: 0x1008FF1F,
|
||||
XF86XK_Calendar: 0x1008FF20,
|
||||
XF86XK_PowerDown: 0x1008FF21,
|
||||
XF86XK_ContrastAdjust: 0x1008FF22,
|
||||
XF86XK_RockerUp: 0x1008FF23,
|
||||
XF86XK_RockerDown: 0x1008FF24,
|
||||
XF86XK_RockerEnter: 0x1008FF25,
|
||||
XF86XK_Back: 0x1008FF26,
|
||||
XF86XK_Forward: 0x1008FF27,
|
||||
XF86XK_Stop: 0x1008FF28,
|
||||
XF86XK_Refresh: 0x1008FF29,
|
||||
XF86XK_PowerOff: 0x1008FF2A,
|
||||
XF86XK_WakeUp: 0x1008FF2B,
|
||||
XF86XK_Eject: 0x1008FF2C,
|
||||
XF86XK_ScreenSaver: 0x1008FF2D,
|
||||
XF86XK_WWW: 0x1008FF2E,
|
||||
XF86XK_Sleep: 0x1008FF2F,
|
||||
XF86XK_Favorites: 0x1008FF30,
|
||||
XF86XK_AudioPause: 0x1008FF31,
|
||||
XF86XK_AudioMedia: 0x1008FF32,
|
||||
XF86XK_MyComputer: 0x1008FF33,
|
||||
XF86XK_VendorHome: 0x1008FF34,
|
||||
XF86XK_LightBulb: 0x1008FF35,
|
||||
XF86XK_Shop: 0x1008FF36,
|
||||
XF86XK_History: 0x1008FF37,
|
||||
XF86XK_OpenURL: 0x1008FF38,
|
||||
XF86XK_AddFavorite: 0x1008FF39,
|
||||
XF86XK_HotLinks: 0x1008FF3A,
|
||||
XF86XK_BrightnessAdjust: 0x1008FF3B,
|
||||
XF86XK_Finance: 0x1008FF3C,
|
||||
XF86XK_Community: 0x1008FF3D,
|
||||
XF86XK_AudioRewind: 0x1008FF3E,
|
||||
XF86XK_BackForward: 0x1008FF3F,
|
||||
XF86XK_Launch0: 0x1008FF40,
|
||||
XF86XK_Launch1: 0x1008FF41,
|
||||
XF86XK_Launch2: 0x1008FF42,
|
||||
XF86XK_Launch3: 0x1008FF43,
|
||||
XF86XK_Launch4: 0x1008FF44,
|
||||
XF86XK_Launch5: 0x1008FF45,
|
||||
XF86XK_Launch6: 0x1008FF46,
|
||||
XF86XK_Launch7: 0x1008FF47,
|
||||
XF86XK_Launch8: 0x1008FF48,
|
||||
XF86XK_Launch9: 0x1008FF49,
|
||||
XF86XK_LaunchA: 0x1008FF4A,
|
||||
XF86XK_LaunchB: 0x1008FF4B,
|
||||
XF86XK_LaunchC: 0x1008FF4C,
|
||||
XF86XK_LaunchD: 0x1008FF4D,
|
||||
XF86XK_LaunchE: 0x1008FF4E,
|
||||
XF86XK_LaunchF: 0x1008FF4F,
|
||||
XF86XK_ApplicationLeft: 0x1008FF50,
|
||||
XF86XK_ApplicationRight: 0x1008FF51,
|
||||
XF86XK_Book: 0x1008FF52,
|
||||
XF86XK_CD: 0x1008FF53,
|
||||
XF86XK_Calculater: 0x1008FF54,
|
||||
XF86XK_Clear: 0x1008FF55,
|
||||
XF86XK_Close: 0x1008FF56,
|
||||
XF86XK_Copy: 0x1008FF57,
|
||||
XF86XK_Cut: 0x1008FF58,
|
||||
XF86XK_Display: 0x1008FF59,
|
||||
XF86XK_DOS: 0x1008FF5A,
|
||||
XF86XK_Documents: 0x1008FF5B,
|
||||
XF86XK_Excel: 0x1008FF5C,
|
||||
XF86XK_Explorer: 0x1008FF5D,
|
||||
XF86XK_Game: 0x1008FF5E,
|
||||
XF86XK_Go: 0x1008FF5F,
|
||||
XF86XK_iTouch: 0x1008FF60,
|
||||
XF86XK_LogOff: 0x1008FF61,
|
||||
XF86XK_Market: 0x1008FF62,
|
||||
XF86XK_Meeting: 0x1008FF63,
|
||||
XF86XK_MenuKB: 0x1008FF65,
|
||||
XF86XK_MenuPB: 0x1008FF66,
|
||||
XF86XK_MySites: 0x1008FF67,
|
||||
XF86XK_New: 0x1008FF68,
|
||||
XF86XK_News: 0x1008FF69,
|
||||
XF86XK_OfficeHome: 0x1008FF6A,
|
||||
XF86XK_Open: 0x1008FF6B,
|
||||
XF86XK_Option: 0x1008FF6C,
|
||||
XF86XK_Paste: 0x1008FF6D,
|
||||
XF86XK_Phone: 0x1008FF6E,
|
||||
XF86XK_Q: 0x1008FF70,
|
||||
XF86XK_Reply: 0x1008FF72,
|
||||
XF86XK_Reload: 0x1008FF73,
|
||||
XF86XK_RotateWindows: 0x1008FF74,
|
||||
XF86XK_RotationPB: 0x1008FF75,
|
||||
XF86XK_RotationKB: 0x1008FF76,
|
||||
XF86XK_Save: 0x1008FF77,
|
||||
XF86XK_ScrollUp: 0x1008FF78,
|
||||
XF86XK_ScrollDown: 0x1008FF79,
|
||||
XF86XK_ScrollClick: 0x1008FF7A,
|
||||
XF86XK_Send: 0x1008FF7B,
|
||||
XF86XK_Spell: 0x1008FF7C,
|
||||
XF86XK_SplitScreen: 0x1008FF7D,
|
||||
XF86XK_Support: 0x1008FF7E,
|
||||
XF86XK_TaskPane: 0x1008FF7F,
|
||||
XF86XK_Terminal: 0x1008FF80,
|
||||
XF86XK_Tools: 0x1008FF81,
|
||||
XF86XK_Travel: 0x1008FF82,
|
||||
XF86XK_UserPB: 0x1008FF84,
|
||||
XF86XK_User1KB: 0x1008FF85,
|
||||
XF86XK_User2KB: 0x1008FF86,
|
||||
XF86XK_Video: 0x1008FF87,
|
||||
XF86XK_WheelButton: 0x1008FF88,
|
||||
XF86XK_Word: 0x1008FF89,
|
||||
XF86XK_Xfer: 0x1008FF8A,
|
||||
XF86XK_ZoomIn: 0x1008FF8B,
|
||||
XF86XK_ZoomOut: 0x1008FF8C,
|
||||
XF86XK_Away: 0x1008FF8D,
|
||||
XF86XK_Messenger: 0x1008FF8E,
|
||||
XF86XK_WebCam: 0x1008FF8F,
|
||||
XF86XK_MailForward: 0x1008FF90,
|
||||
XF86XK_Pictures: 0x1008FF91,
|
||||
XF86XK_Music: 0x1008FF92,
|
||||
XF86XK_Battery: 0x1008FF93,
|
||||
XF86XK_Bluetooth: 0x1008FF94,
|
||||
XF86XK_WLAN: 0x1008FF95,
|
||||
XF86XK_UWB: 0x1008FF96,
|
||||
XF86XK_AudioForward: 0x1008FF97,
|
||||
XF86XK_AudioRepeat: 0x1008FF98,
|
||||
XF86XK_AudioRandomPlay: 0x1008FF99,
|
||||
XF86XK_Subtitle: 0x1008FF9A,
|
||||
XF86XK_AudioCycleTrack: 0x1008FF9B,
|
||||
XF86XK_CycleAngle: 0x1008FF9C,
|
||||
XF86XK_FrameBack: 0x1008FF9D,
|
||||
XF86XK_FrameForward: 0x1008FF9E,
|
||||
XF86XK_Time: 0x1008FF9F,
|
||||
XF86XK_Select: 0x1008FFA0,
|
||||
XF86XK_View: 0x1008FFA1,
|
||||
XF86XK_TopMenu: 0x1008FFA2,
|
||||
XF86XK_Red: 0x1008FFA3,
|
||||
XF86XK_Green: 0x1008FFA4,
|
||||
XF86XK_Yellow: 0x1008FFA5,
|
||||
XF86XK_Blue: 0x1008FFA6,
|
||||
XF86XK_Suspend: 0x1008FFA7,
|
||||
XF86XK_Hibernate: 0x1008FFA8,
|
||||
XF86XK_TouchpadToggle: 0x1008FFA9,
|
||||
XF86XK_TouchpadOn: 0x1008FFB0,
|
||||
XF86XK_TouchpadOff: 0x1008FFB1,
|
||||
XF86XK_AudioMicMute: 0x1008FFB2,
|
||||
XF86XK_Switch_VT_1: 0x1008FE01,
|
||||
XF86XK_Switch_VT_2: 0x1008FE02,
|
||||
XF86XK_Switch_VT_3: 0x1008FE03,
|
||||
XF86XK_Switch_VT_4: 0x1008FE04,
|
||||
XF86XK_Switch_VT_5: 0x1008FE05,
|
||||
XF86XK_Switch_VT_6: 0x1008FE06,
|
||||
XF86XK_Switch_VT_7: 0x1008FE07,
|
||||
XF86XK_Switch_VT_8: 0x1008FE08,
|
||||
XF86XK_Switch_VT_9: 0x1008FE09,
|
||||
XF86XK_Switch_VT_10: 0x1008FE0A,
|
||||
XF86XK_Switch_VT_11: 0x1008FE0B,
|
||||
XF86XK_Switch_VT_12: 0x1008FE0C,
|
||||
XF86XK_Ungrab: 0x1008FE20,
|
||||
XF86XK_ClearGrab: 0x1008FE21,
|
||||
XF86XK_Next_VMode: 0x1008FE22,
|
||||
XF86XK_Prev_VMode: 0x1008FE23,
|
||||
XF86XK_LogWindowTree: 0x1008FE24,
|
||||
XF86XK_LogGrabInfo: 0x1008FE25,
|
||||
};
|
||||
688
backend/app/static/novnc/core/input/keysymdef.js
Normal file
688
backend/app/static/novnc/core/input/keysymdef.js
Normal file
@@ -0,0 +1,688 @@
|
||||
/*
|
||||
* Mapping from Unicode codepoints to X11/RFB keysyms
|
||||
*
|
||||
* This file was automatically generated from keysymdef.h
|
||||
* DO NOT EDIT!
|
||||
*/
|
||||
|
||||
/* Functions at the bottom */
|
||||
|
||||
const codepoints = {
|
||||
0x0100: 0x03c0, // XK_Amacron
|
||||
0x0101: 0x03e0, // XK_amacron
|
||||
0x0102: 0x01c3, // XK_Abreve
|
||||
0x0103: 0x01e3, // XK_abreve
|
||||
0x0104: 0x01a1, // XK_Aogonek
|
||||
0x0105: 0x01b1, // XK_aogonek
|
||||
0x0106: 0x01c6, // XK_Cacute
|
||||
0x0107: 0x01e6, // XK_cacute
|
||||
0x0108: 0x02c6, // XK_Ccircumflex
|
||||
0x0109: 0x02e6, // XK_ccircumflex
|
||||
0x010a: 0x02c5, // XK_Cabovedot
|
||||
0x010b: 0x02e5, // XK_cabovedot
|
||||
0x010c: 0x01c8, // XK_Ccaron
|
||||
0x010d: 0x01e8, // XK_ccaron
|
||||
0x010e: 0x01cf, // XK_Dcaron
|
||||
0x010f: 0x01ef, // XK_dcaron
|
||||
0x0110: 0x01d0, // XK_Dstroke
|
||||
0x0111: 0x01f0, // XK_dstroke
|
||||
0x0112: 0x03aa, // XK_Emacron
|
||||
0x0113: 0x03ba, // XK_emacron
|
||||
0x0116: 0x03cc, // XK_Eabovedot
|
||||
0x0117: 0x03ec, // XK_eabovedot
|
||||
0x0118: 0x01ca, // XK_Eogonek
|
||||
0x0119: 0x01ea, // XK_eogonek
|
||||
0x011a: 0x01cc, // XK_Ecaron
|
||||
0x011b: 0x01ec, // XK_ecaron
|
||||
0x011c: 0x02d8, // XK_Gcircumflex
|
||||
0x011d: 0x02f8, // XK_gcircumflex
|
||||
0x011e: 0x02ab, // XK_Gbreve
|
||||
0x011f: 0x02bb, // XK_gbreve
|
||||
0x0120: 0x02d5, // XK_Gabovedot
|
||||
0x0121: 0x02f5, // XK_gabovedot
|
||||
0x0122: 0x03ab, // XK_Gcedilla
|
||||
0x0123: 0x03bb, // XK_gcedilla
|
||||
0x0124: 0x02a6, // XK_Hcircumflex
|
||||
0x0125: 0x02b6, // XK_hcircumflex
|
||||
0x0126: 0x02a1, // XK_Hstroke
|
||||
0x0127: 0x02b1, // XK_hstroke
|
||||
0x0128: 0x03a5, // XK_Itilde
|
||||
0x0129: 0x03b5, // XK_itilde
|
||||
0x012a: 0x03cf, // XK_Imacron
|
||||
0x012b: 0x03ef, // XK_imacron
|
||||
0x012e: 0x03c7, // XK_Iogonek
|
||||
0x012f: 0x03e7, // XK_iogonek
|
||||
0x0130: 0x02a9, // XK_Iabovedot
|
||||
0x0131: 0x02b9, // XK_idotless
|
||||
0x0134: 0x02ac, // XK_Jcircumflex
|
||||
0x0135: 0x02bc, // XK_jcircumflex
|
||||
0x0136: 0x03d3, // XK_Kcedilla
|
||||
0x0137: 0x03f3, // XK_kcedilla
|
||||
0x0138: 0x03a2, // XK_kra
|
||||
0x0139: 0x01c5, // XK_Lacute
|
||||
0x013a: 0x01e5, // XK_lacute
|
||||
0x013b: 0x03a6, // XK_Lcedilla
|
||||
0x013c: 0x03b6, // XK_lcedilla
|
||||
0x013d: 0x01a5, // XK_Lcaron
|
||||
0x013e: 0x01b5, // XK_lcaron
|
||||
0x0141: 0x01a3, // XK_Lstroke
|
||||
0x0142: 0x01b3, // XK_lstroke
|
||||
0x0143: 0x01d1, // XK_Nacute
|
||||
0x0144: 0x01f1, // XK_nacute
|
||||
0x0145: 0x03d1, // XK_Ncedilla
|
||||
0x0146: 0x03f1, // XK_ncedilla
|
||||
0x0147: 0x01d2, // XK_Ncaron
|
||||
0x0148: 0x01f2, // XK_ncaron
|
||||
0x014a: 0x03bd, // XK_ENG
|
||||
0x014b: 0x03bf, // XK_eng
|
||||
0x014c: 0x03d2, // XK_Omacron
|
||||
0x014d: 0x03f2, // XK_omacron
|
||||
0x0150: 0x01d5, // XK_Odoubleacute
|
||||
0x0151: 0x01f5, // XK_odoubleacute
|
||||
0x0152: 0x13bc, // XK_OE
|
||||
0x0153: 0x13bd, // XK_oe
|
||||
0x0154: 0x01c0, // XK_Racute
|
||||
0x0155: 0x01e0, // XK_racute
|
||||
0x0156: 0x03a3, // XK_Rcedilla
|
||||
0x0157: 0x03b3, // XK_rcedilla
|
||||
0x0158: 0x01d8, // XK_Rcaron
|
||||
0x0159: 0x01f8, // XK_rcaron
|
||||
0x015a: 0x01a6, // XK_Sacute
|
||||
0x015b: 0x01b6, // XK_sacute
|
||||
0x015c: 0x02de, // XK_Scircumflex
|
||||
0x015d: 0x02fe, // XK_scircumflex
|
||||
0x015e: 0x01aa, // XK_Scedilla
|
||||
0x015f: 0x01ba, // XK_scedilla
|
||||
0x0160: 0x01a9, // XK_Scaron
|
||||
0x0161: 0x01b9, // XK_scaron
|
||||
0x0162: 0x01de, // XK_Tcedilla
|
||||
0x0163: 0x01fe, // XK_tcedilla
|
||||
0x0164: 0x01ab, // XK_Tcaron
|
||||
0x0165: 0x01bb, // XK_tcaron
|
||||
0x0166: 0x03ac, // XK_Tslash
|
||||
0x0167: 0x03bc, // XK_tslash
|
||||
0x0168: 0x03dd, // XK_Utilde
|
||||
0x0169: 0x03fd, // XK_utilde
|
||||
0x016a: 0x03de, // XK_Umacron
|
||||
0x016b: 0x03fe, // XK_umacron
|
||||
0x016c: 0x02dd, // XK_Ubreve
|
||||
0x016d: 0x02fd, // XK_ubreve
|
||||
0x016e: 0x01d9, // XK_Uring
|
||||
0x016f: 0x01f9, // XK_uring
|
||||
0x0170: 0x01db, // XK_Udoubleacute
|
||||
0x0171: 0x01fb, // XK_udoubleacute
|
||||
0x0172: 0x03d9, // XK_Uogonek
|
||||
0x0173: 0x03f9, // XK_uogonek
|
||||
0x0178: 0x13be, // XK_Ydiaeresis
|
||||
0x0179: 0x01ac, // XK_Zacute
|
||||
0x017a: 0x01bc, // XK_zacute
|
||||
0x017b: 0x01af, // XK_Zabovedot
|
||||
0x017c: 0x01bf, // XK_zabovedot
|
||||
0x017d: 0x01ae, // XK_Zcaron
|
||||
0x017e: 0x01be, // XK_zcaron
|
||||
0x0192: 0x08f6, // XK_function
|
||||
0x01d2: 0x10001d1, // XK_Ocaron
|
||||
0x02c7: 0x01b7, // XK_caron
|
||||
0x02d8: 0x01a2, // XK_breve
|
||||
0x02d9: 0x01ff, // XK_abovedot
|
||||
0x02db: 0x01b2, // XK_ogonek
|
||||
0x02dd: 0x01bd, // XK_doubleacute
|
||||
0x0385: 0x07ae, // XK_Greek_accentdieresis
|
||||
0x0386: 0x07a1, // XK_Greek_ALPHAaccent
|
||||
0x0388: 0x07a2, // XK_Greek_EPSILONaccent
|
||||
0x0389: 0x07a3, // XK_Greek_ETAaccent
|
||||
0x038a: 0x07a4, // XK_Greek_IOTAaccent
|
||||
0x038c: 0x07a7, // XK_Greek_OMICRONaccent
|
||||
0x038e: 0x07a8, // XK_Greek_UPSILONaccent
|
||||
0x038f: 0x07ab, // XK_Greek_OMEGAaccent
|
||||
0x0390: 0x07b6, // XK_Greek_iotaaccentdieresis
|
||||
0x0391: 0x07c1, // XK_Greek_ALPHA
|
||||
0x0392: 0x07c2, // XK_Greek_BETA
|
||||
0x0393: 0x07c3, // XK_Greek_GAMMA
|
||||
0x0394: 0x07c4, // XK_Greek_DELTA
|
||||
0x0395: 0x07c5, // XK_Greek_EPSILON
|
||||
0x0396: 0x07c6, // XK_Greek_ZETA
|
||||
0x0397: 0x07c7, // XK_Greek_ETA
|
||||
0x0398: 0x07c8, // XK_Greek_THETA
|
||||
0x0399: 0x07c9, // XK_Greek_IOTA
|
||||
0x039a: 0x07ca, // XK_Greek_KAPPA
|
||||
0x039b: 0x07cb, // XK_Greek_LAMDA
|
||||
0x039c: 0x07cc, // XK_Greek_MU
|
||||
0x039d: 0x07cd, // XK_Greek_NU
|
||||
0x039e: 0x07ce, // XK_Greek_XI
|
||||
0x039f: 0x07cf, // XK_Greek_OMICRON
|
||||
0x03a0: 0x07d0, // XK_Greek_PI
|
||||
0x03a1: 0x07d1, // XK_Greek_RHO
|
||||
0x03a3: 0x07d2, // XK_Greek_SIGMA
|
||||
0x03a4: 0x07d4, // XK_Greek_TAU
|
||||
0x03a5: 0x07d5, // XK_Greek_UPSILON
|
||||
0x03a6: 0x07d6, // XK_Greek_PHI
|
||||
0x03a7: 0x07d7, // XK_Greek_CHI
|
||||
0x03a8: 0x07d8, // XK_Greek_PSI
|
||||
0x03a9: 0x07d9, // XK_Greek_OMEGA
|
||||
0x03aa: 0x07a5, // XK_Greek_IOTAdieresis
|
||||
0x03ab: 0x07a9, // XK_Greek_UPSILONdieresis
|
||||
0x03ac: 0x07b1, // XK_Greek_alphaaccent
|
||||
0x03ad: 0x07b2, // XK_Greek_epsilonaccent
|
||||
0x03ae: 0x07b3, // XK_Greek_etaaccent
|
||||
0x03af: 0x07b4, // XK_Greek_iotaaccent
|
||||
0x03b0: 0x07ba, // XK_Greek_upsilonaccentdieresis
|
||||
0x03b1: 0x07e1, // XK_Greek_alpha
|
||||
0x03b2: 0x07e2, // XK_Greek_beta
|
||||
0x03b3: 0x07e3, // XK_Greek_gamma
|
||||
0x03b4: 0x07e4, // XK_Greek_delta
|
||||
0x03b5: 0x07e5, // XK_Greek_epsilon
|
||||
0x03b6: 0x07e6, // XK_Greek_zeta
|
||||
0x03b7: 0x07e7, // XK_Greek_eta
|
||||
0x03b8: 0x07e8, // XK_Greek_theta
|
||||
0x03b9: 0x07e9, // XK_Greek_iota
|
||||
0x03ba: 0x07ea, // XK_Greek_kappa
|
||||
0x03bb: 0x07eb, // XK_Greek_lamda
|
||||
0x03bc: 0x07ec, // XK_Greek_mu
|
||||
0x03bd: 0x07ed, // XK_Greek_nu
|
||||
0x03be: 0x07ee, // XK_Greek_xi
|
||||
0x03bf: 0x07ef, // XK_Greek_omicron
|
||||
0x03c0: 0x07f0, // XK_Greek_pi
|
||||
0x03c1: 0x07f1, // XK_Greek_rho
|
||||
0x03c2: 0x07f3, // XK_Greek_finalsmallsigma
|
||||
0x03c3: 0x07f2, // XK_Greek_sigma
|
||||
0x03c4: 0x07f4, // XK_Greek_tau
|
||||
0x03c5: 0x07f5, // XK_Greek_upsilon
|
||||
0x03c6: 0x07f6, // XK_Greek_phi
|
||||
0x03c7: 0x07f7, // XK_Greek_chi
|
||||
0x03c8: 0x07f8, // XK_Greek_psi
|
||||
0x03c9: 0x07f9, // XK_Greek_omega
|
||||
0x03ca: 0x07b5, // XK_Greek_iotadieresis
|
||||
0x03cb: 0x07b9, // XK_Greek_upsilondieresis
|
||||
0x03cc: 0x07b7, // XK_Greek_omicronaccent
|
||||
0x03cd: 0x07b8, // XK_Greek_upsilonaccent
|
||||
0x03ce: 0x07bb, // XK_Greek_omegaaccent
|
||||
0x0401: 0x06b3, // XK_Cyrillic_IO
|
||||
0x0402: 0x06b1, // XK_Serbian_DJE
|
||||
0x0403: 0x06b2, // XK_Macedonia_GJE
|
||||
0x0404: 0x06b4, // XK_Ukrainian_IE
|
||||
0x0405: 0x06b5, // XK_Macedonia_DSE
|
||||
0x0406: 0x06b6, // XK_Ukrainian_I
|
||||
0x0407: 0x06b7, // XK_Ukrainian_YI
|
||||
0x0408: 0x06b8, // XK_Cyrillic_JE
|
||||
0x0409: 0x06b9, // XK_Cyrillic_LJE
|
||||
0x040a: 0x06ba, // XK_Cyrillic_NJE
|
||||
0x040b: 0x06bb, // XK_Serbian_TSHE
|
||||
0x040c: 0x06bc, // XK_Macedonia_KJE
|
||||
0x040e: 0x06be, // XK_Byelorussian_SHORTU
|
||||
0x040f: 0x06bf, // XK_Cyrillic_DZHE
|
||||
0x0410: 0x06e1, // XK_Cyrillic_A
|
||||
0x0411: 0x06e2, // XK_Cyrillic_BE
|
||||
0x0412: 0x06f7, // XK_Cyrillic_VE
|
||||
0x0413: 0x06e7, // XK_Cyrillic_GHE
|
||||
0x0414: 0x06e4, // XK_Cyrillic_DE
|
||||
0x0415: 0x06e5, // XK_Cyrillic_IE
|
||||
0x0416: 0x06f6, // XK_Cyrillic_ZHE
|
||||
0x0417: 0x06fa, // XK_Cyrillic_ZE
|
||||
0x0418: 0x06e9, // XK_Cyrillic_I
|
||||
0x0419: 0x06ea, // XK_Cyrillic_SHORTI
|
||||
0x041a: 0x06eb, // XK_Cyrillic_KA
|
||||
0x041b: 0x06ec, // XK_Cyrillic_EL
|
||||
0x041c: 0x06ed, // XK_Cyrillic_EM
|
||||
0x041d: 0x06ee, // XK_Cyrillic_EN
|
||||
0x041e: 0x06ef, // XK_Cyrillic_O
|
||||
0x041f: 0x06f0, // XK_Cyrillic_PE
|
||||
0x0420: 0x06f2, // XK_Cyrillic_ER
|
||||
0x0421: 0x06f3, // XK_Cyrillic_ES
|
||||
0x0422: 0x06f4, // XK_Cyrillic_TE
|
||||
0x0423: 0x06f5, // XK_Cyrillic_U
|
||||
0x0424: 0x06e6, // XK_Cyrillic_EF
|
||||
0x0425: 0x06e8, // XK_Cyrillic_HA
|
||||
0x0426: 0x06e3, // XK_Cyrillic_TSE
|
||||
0x0427: 0x06fe, // XK_Cyrillic_CHE
|
||||
0x0428: 0x06fb, // XK_Cyrillic_SHA
|
||||
0x0429: 0x06fd, // XK_Cyrillic_SHCHA
|
||||
0x042a: 0x06ff, // XK_Cyrillic_HARDSIGN
|
||||
0x042b: 0x06f9, // XK_Cyrillic_YERU
|
||||
0x042c: 0x06f8, // XK_Cyrillic_SOFTSIGN
|
||||
0x042d: 0x06fc, // XK_Cyrillic_E
|
||||
0x042e: 0x06e0, // XK_Cyrillic_YU
|
||||
0x042f: 0x06f1, // XK_Cyrillic_YA
|
||||
0x0430: 0x06c1, // XK_Cyrillic_a
|
||||
0x0431: 0x06c2, // XK_Cyrillic_be
|
||||
0x0432: 0x06d7, // XK_Cyrillic_ve
|
||||
0x0433: 0x06c7, // XK_Cyrillic_ghe
|
||||
0x0434: 0x06c4, // XK_Cyrillic_de
|
||||
0x0435: 0x06c5, // XK_Cyrillic_ie
|
||||
0x0436: 0x06d6, // XK_Cyrillic_zhe
|
||||
0x0437: 0x06da, // XK_Cyrillic_ze
|
||||
0x0438: 0x06c9, // XK_Cyrillic_i
|
||||
0x0439: 0x06ca, // XK_Cyrillic_shorti
|
||||
0x043a: 0x06cb, // XK_Cyrillic_ka
|
||||
0x043b: 0x06cc, // XK_Cyrillic_el
|
||||
0x043c: 0x06cd, // XK_Cyrillic_em
|
||||
0x043d: 0x06ce, // XK_Cyrillic_en
|
||||
0x043e: 0x06cf, // XK_Cyrillic_o
|
||||
0x043f: 0x06d0, // XK_Cyrillic_pe
|
||||
0x0440: 0x06d2, // XK_Cyrillic_er
|
||||
0x0441: 0x06d3, // XK_Cyrillic_es
|
||||
0x0442: 0x06d4, // XK_Cyrillic_te
|
||||
0x0443: 0x06d5, // XK_Cyrillic_u
|
||||
0x0444: 0x06c6, // XK_Cyrillic_ef
|
||||
0x0445: 0x06c8, // XK_Cyrillic_ha
|
||||
0x0446: 0x06c3, // XK_Cyrillic_tse
|
||||
0x0447: 0x06de, // XK_Cyrillic_che
|
||||
0x0448: 0x06db, // XK_Cyrillic_sha
|
||||
0x0449: 0x06dd, // XK_Cyrillic_shcha
|
||||
0x044a: 0x06df, // XK_Cyrillic_hardsign
|
||||
0x044b: 0x06d9, // XK_Cyrillic_yeru
|
||||
0x044c: 0x06d8, // XK_Cyrillic_softsign
|
||||
0x044d: 0x06dc, // XK_Cyrillic_e
|
||||
0x044e: 0x06c0, // XK_Cyrillic_yu
|
||||
0x044f: 0x06d1, // XK_Cyrillic_ya
|
||||
0x0451: 0x06a3, // XK_Cyrillic_io
|
||||
0x0452: 0x06a1, // XK_Serbian_dje
|
||||
0x0453: 0x06a2, // XK_Macedonia_gje
|
||||
0x0454: 0x06a4, // XK_Ukrainian_ie
|
||||
0x0455: 0x06a5, // XK_Macedonia_dse
|
||||
0x0456: 0x06a6, // XK_Ukrainian_i
|
||||
0x0457: 0x06a7, // XK_Ukrainian_yi
|
||||
0x0458: 0x06a8, // XK_Cyrillic_je
|
||||
0x0459: 0x06a9, // XK_Cyrillic_lje
|
||||
0x045a: 0x06aa, // XK_Cyrillic_nje
|
||||
0x045b: 0x06ab, // XK_Serbian_tshe
|
||||
0x045c: 0x06ac, // XK_Macedonia_kje
|
||||
0x045e: 0x06ae, // XK_Byelorussian_shortu
|
||||
0x045f: 0x06af, // XK_Cyrillic_dzhe
|
||||
0x0490: 0x06bd, // XK_Ukrainian_GHE_WITH_UPTURN
|
||||
0x0491: 0x06ad, // XK_Ukrainian_ghe_with_upturn
|
||||
0x05d0: 0x0ce0, // XK_hebrew_aleph
|
||||
0x05d1: 0x0ce1, // XK_hebrew_bet
|
||||
0x05d2: 0x0ce2, // XK_hebrew_gimel
|
||||
0x05d3: 0x0ce3, // XK_hebrew_dalet
|
||||
0x05d4: 0x0ce4, // XK_hebrew_he
|
||||
0x05d5: 0x0ce5, // XK_hebrew_waw
|
||||
0x05d6: 0x0ce6, // XK_hebrew_zain
|
||||
0x05d7: 0x0ce7, // XK_hebrew_chet
|
||||
0x05d8: 0x0ce8, // XK_hebrew_tet
|
||||
0x05d9: 0x0ce9, // XK_hebrew_yod
|
||||
0x05da: 0x0cea, // XK_hebrew_finalkaph
|
||||
0x05db: 0x0ceb, // XK_hebrew_kaph
|
||||
0x05dc: 0x0cec, // XK_hebrew_lamed
|
||||
0x05dd: 0x0ced, // XK_hebrew_finalmem
|
||||
0x05de: 0x0cee, // XK_hebrew_mem
|
||||
0x05df: 0x0cef, // XK_hebrew_finalnun
|
||||
0x05e0: 0x0cf0, // XK_hebrew_nun
|
||||
0x05e1: 0x0cf1, // XK_hebrew_samech
|
||||
0x05e2: 0x0cf2, // XK_hebrew_ayin
|
||||
0x05e3: 0x0cf3, // XK_hebrew_finalpe
|
||||
0x05e4: 0x0cf4, // XK_hebrew_pe
|
||||
0x05e5: 0x0cf5, // XK_hebrew_finalzade
|
||||
0x05e6: 0x0cf6, // XK_hebrew_zade
|
||||
0x05e7: 0x0cf7, // XK_hebrew_qoph
|
||||
0x05e8: 0x0cf8, // XK_hebrew_resh
|
||||
0x05e9: 0x0cf9, // XK_hebrew_shin
|
||||
0x05ea: 0x0cfa, // XK_hebrew_taw
|
||||
0x060c: 0x05ac, // XK_Arabic_comma
|
||||
0x061b: 0x05bb, // XK_Arabic_semicolon
|
||||
0x061f: 0x05bf, // XK_Arabic_question_mark
|
||||
0x0621: 0x05c1, // XK_Arabic_hamza
|
||||
0x0622: 0x05c2, // XK_Arabic_maddaonalef
|
||||
0x0623: 0x05c3, // XK_Arabic_hamzaonalef
|
||||
0x0624: 0x05c4, // XK_Arabic_hamzaonwaw
|
||||
0x0625: 0x05c5, // XK_Arabic_hamzaunderalef
|
||||
0x0626: 0x05c6, // XK_Arabic_hamzaonyeh
|
||||
0x0627: 0x05c7, // XK_Arabic_alef
|
||||
0x0628: 0x05c8, // XK_Arabic_beh
|
||||
0x0629: 0x05c9, // XK_Arabic_tehmarbuta
|
||||
0x062a: 0x05ca, // XK_Arabic_teh
|
||||
0x062b: 0x05cb, // XK_Arabic_theh
|
||||
0x062c: 0x05cc, // XK_Arabic_jeem
|
||||
0x062d: 0x05cd, // XK_Arabic_hah
|
||||
0x062e: 0x05ce, // XK_Arabic_khah
|
||||
0x062f: 0x05cf, // XK_Arabic_dal
|
||||
0x0630: 0x05d0, // XK_Arabic_thal
|
||||
0x0631: 0x05d1, // XK_Arabic_ra
|
||||
0x0632: 0x05d2, // XK_Arabic_zain
|
||||
0x0633: 0x05d3, // XK_Arabic_seen
|
||||
0x0634: 0x05d4, // XK_Arabic_sheen
|
||||
0x0635: 0x05d5, // XK_Arabic_sad
|
||||
0x0636: 0x05d6, // XK_Arabic_dad
|
||||
0x0637: 0x05d7, // XK_Arabic_tah
|
||||
0x0638: 0x05d8, // XK_Arabic_zah
|
||||
0x0639: 0x05d9, // XK_Arabic_ain
|
||||
0x063a: 0x05da, // XK_Arabic_ghain
|
||||
0x0640: 0x05e0, // XK_Arabic_tatweel
|
||||
0x0641: 0x05e1, // XK_Arabic_feh
|
||||
0x0642: 0x05e2, // XK_Arabic_qaf
|
||||
0x0643: 0x05e3, // XK_Arabic_kaf
|
||||
0x0644: 0x05e4, // XK_Arabic_lam
|
||||
0x0645: 0x05e5, // XK_Arabic_meem
|
||||
0x0646: 0x05e6, // XK_Arabic_noon
|
||||
0x0647: 0x05e7, // XK_Arabic_ha
|
||||
0x0648: 0x05e8, // XK_Arabic_waw
|
||||
0x0649: 0x05e9, // XK_Arabic_alefmaksura
|
||||
0x064a: 0x05ea, // XK_Arabic_yeh
|
||||
0x064b: 0x05eb, // XK_Arabic_fathatan
|
||||
0x064c: 0x05ec, // XK_Arabic_dammatan
|
||||
0x064d: 0x05ed, // XK_Arabic_kasratan
|
||||
0x064e: 0x05ee, // XK_Arabic_fatha
|
||||
0x064f: 0x05ef, // XK_Arabic_damma
|
||||
0x0650: 0x05f0, // XK_Arabic_kasra
|
||||
0x0651: 0x05f1, // XK_Arabic_shadda
|
||||
0x0652: 0x05f2, // XK_Arabic_sukun
|
||||
0x0e01: 0x0da1, // XK_Thai_kokai
|
||||
0x0e02: 0x0da2, // XK_Thai_khokhai
|
||||
0x0e03: 0x0da3, // XK_Thai_khokhuat
|
||||
0x0e04: 0x0da4, // XK_Thai_khokhwai
|
||||
0x0e05: 0x0da5, // XK_Thai_khokhon
|
||||
0x0e06: 0x0da6, // XK_Thai_khorakhang
|
||||
0x0e07: 0x0da7, // XK_Thai_ngongu
|
||||
0x0e08: 0x0da8, // XK_Thai_chochan
|
||||
0x0e09: 0x0da9, // XK_Thai_choching
|
||||
0x0e0a: 0x0daa, // XK_Thai_chochang
|
||||
0x0e0b: 0x0dab, // XK_Thai_soso
|
||||
0x0e0c: 0x0dac, // XK_Thai_chochoe
|
||||
0x0e0d: 0x0dad, // XK_Thai_yoying
|
||||
0x0e0e: 0x0dae, // XK_Thai_dochada
|
||||
0x0e0f: 0x0daf, // XK_Thai_topatak
|
||||
0x0e10: 0x0db0, // XK_Thai_thothan
|
||||
0x0e11: 0x0db1, // XK_Thai_thonangmontho
|
||||
0x0e12: 0x0db2, // XK_Thai_thophuthao
|
||||
0x0e13: 0x0db3, // XK_Thai_nonen
|
||||
0x0e14: 0x0db4, // XK_Thai_dodek
|
||||
0x0e15: 0x0db5, // XK_Thai_totao
|
||||
0x0e16: 0x0db6, // XK_Thai_thothung
|
||||
0x0e17: 0x0db7, // XK_Thai_thothahan
|
||||
0x0e18: 0x0db8, // XK_Thai_thothong
|
||||
0x0e19: 0x0db9, // XK_Thai_nonu
|
||||
0x0e1a: 0x0dba, // XK_Thai_bobaimai
|
||||
0x0e1b: 0x0dbb, // XK_Thai_popla
|
||||
0x0e1c: 0x0dbc, // XK_Thai_phophung
|
||||
0x0e1d: 0x0dbd, // XK_Thai_fofa
|
||||
0x0e1e: 0x0dbe, // XK_Thai_phophan
|
||||
0x0e1f: 0x0dbf, // XK_Thai_fofan
|
||||
0x0e20: 0x0dc0, // XK_Thai_phosamphao
|
||||
0x0e21: 0x0dc1, // XK_Thai_moma
|
||||
0x0e22: 0x0dc2, // XK_Thai_yoyak
|
||||
0x0e23: 0x0dc3, // XK_Thai_rorua
|
||||
0x0e24: 0x0dc4, // XK_Thai_ru
|
||||
0x0e25: 0x0dc5, // XK_Thai_loling
|
||||
0x0e26: 0x0dc6, // XK_Thai_lu
|
||||
0x0e27: 0x0dc7, // XK_Thai_wowaen
|
||||
0x0e28: 0x0dc8, // XK_Thai_sosala
|
||||
0x0e29: 0x0dc9, // XK_Thai_sorusi
|
||||
0x0e2a: 0x0dca, // XK_Thai_sosua
|
||||
0x0e2b: 0x0dcb, // XK_Thai_hohip
|
||||
0x0e2c: 0x0dcc, // XK_Thai_lochula
|
||||
0x0e2d: 0x0dcd, // XK_Thai_oang
|
||||
0x0e2e: 0x0dce, // XK_Thai_honokhuk
|
||||
0x0e2f: 0x0dcf, // XK_Thai_paiyannoi
|
||||
0x0e30: 0x0dd0, // XK_Thai_saraa
|
||||
0x0e31: 0x0dd1, // XK_Thai_maihanakat
|
||||
0x0e32: 0x0dd2, // XK_Thai_saraaa
|
||||
0x0e33: 0x0dd3, // XK_Thai_saraam
|
||||
0x0e34: 0x0dd4, // XK_Thai_sarai
|
||||
0x0e35: 0x0dd5, // XK_Thai_saraii
|
||||
0x0e36: 0x0dd6, // XK_Thai_saraue
|
||||
0x0e37: 0x0dd7, // XK_Thai_sarauee
|
||||
0x0e38: 0x0dd8, // XK_Thai_sarau
|
||||
0x0e39: 0x0dd9, // XK_Thai_sarauu
|
||||
0x0e3a: 0x0dda, // XK_Thai_phinthu
|
||||
0x0e3f: 0x0ddf, // XK_Thai_baht
|
||||
0x0e40: 0x0de0, // XK_Thai_sarae
|
||||
0x0e41: 0x0de1, // XK_Thai_saraae
|
||||
0x0e42: 0x0de2, // XK_Thai_sarao
|
||||
0x0e43: 0x0de3, // XK_Thai_saraaimaimuan
|
||||
0x0e44: 0x0de4, // XK_Thai_saraaimaimalai
|
||||
0x0e45: 0x0de5, // XK_Thai_lakkhangyao
|
||||
0x0e46: 0x0de6, // XK_Thai_maiyamok
|
||||
0x0e47: 0x0de7, // XK_Thai_maitaikhu
|
||||
0x0e48: 0x0de8, // XK_Thai_maiek
|
||||
0x0e49: 0x0de9, // XK_Thai_maitho
|
||||
0x0e4a: 0x0dea, // XK_Thai_maitri
|
||||
0x0e4b: 0x0deb, // XK_Thai_maichattawa
|
||||
0x0e4c: 0x0dec, // XK_Thai_thanthakhat
|
||||
0x0e4d: 0x0ded, // XK_Thai_nikhahit
|
||||
0x0e50: 0x0df0, // XK_Thai_leksun
|
||||
0x0e51: 0x0df1, // XK_Thai_leknung
|
||||
0x0e52: 0x0df2, // XK_Thai_leksong
|
||||
0x0e53: 0x0df3, // XK_Thai_leksam
|
||||
0x0e54: 0x0df4, // XK_Thai_leksi
|
||||
0x0e55: 0x0df5, // XK_Thai_lekha
|
||||
0x0e56: 0x0df6, // XK_Thai_lekhok
|
||||
0x0e57: 0x0df7, // XK_Thai_lekchet
|
||||
0x0e58: 0x0df8, // XK_Thai_lekpaet
|
||||
0x0e59: 0x0df9, // XK_Thai_lekkao
|
||||
0x2002: 0x0aa2, // XK_enspace
|
||||
0x2003: 0x0aa1, // XK_emspace
|
||||
0x2004: 0x0aa3, // XK_em3space
|
||||
0x2005: 0x0aa4, // XK_em4space
|
||||
0x2007: 0x0aa5, // XK_digitspace
|
||||
0x2008: 0x0aa6, // XK_punctspace
|
||||
0x2009: 0x0aa7, // XK_thinspace
|
||||
0x200a: 0x0aa8, // XK_hairspace
|
||||
0x2012: 0x0abb, // XK_figdash
|
||||
0x2013: 0x0aaa, // XK_endash
|
||||
0x2014: 0x0aa9, // XK_emdash
|
||||
0x2015: 0x07af, // XK_Greek_horizbar
|
||||
0x2017: 0x0cdf, // XK_hebrew_doublelowline
|
||||
0x2018: 0x0ad0, // XK_leftsinglequotemark
|
||||
0x2019: 0x0ad1, // XK_rightsinglequotemark
|
||||
0x201a: 0x0afd, // XK_singlelowquotemark
|
||||
0x201c: 0x0ad2, // XK_leftdoublequotemark
|
||||
0x201d: 0x0ad3, // XK_rightdoublequotemark
|
||||
0x201e: 0x0afe, // XK_doublelowquotemark
|
||||
0x2020: 0x0af1, // XK_dagger
|
||||
0x2021: 0x0af2, // XK_doubledagger
|
||||
0x2022: 0x0ae6, // XK_enfilledcircbullet
|
||||
0x2025: 0x0aaf, // XK_doubbaselinedot
|
||||
0x2026: 0x0aae, // XK_ellipsis
|
||||
0x2030: 0x0ad5, // XK_permille
|
||||
0x2032: 0x0ad6, // XK_minutes
|
||||
0x2033: 0x0ad7, // XK_seconds
|
||||
0x2038: 0x0afc, // XK_caret
|
||||
0x203e: 0x047e, // XK_overline
|
||||
0x20a9: 0x0eff, // XK_Korean_Won
|
||||
0x20ac: 0x20ac, // XK_EuroSign
|
||||
0x2105: 0x0ab8, // XK_careof
|
||||
0x2116: 0x06b0, // XK_numerosign
|
||||
0x2117: 0x0afb, // XK_phonographcopyright
|
||||
0x211e: 0x0ad4, // XK_prescription
|
||||
0x2122: 0x0ac9, // XK_trademark
|
||||
0x2153: 0x0ab0, // XK_onethird
|
||||
0x2154: 0x0ab1, // XK_twothirds
|
||||
0x2155: 0x0ab2, // XK_onefifth
|
||||
0x2156: 0x0ab3, // XK_twofifths
|
||||
0x2157: 0x0ab4, // XK_threefifths
|
||||
0x2158: 0x0ab5, // XK_fourfifths
|
||||
0x2159: 0x0ab6, // XK_onesixth
|
||||
0x215a: 0x0ab7, // XK_fivesixths
|
||||
0x215b: 0x0ac3, // XK_oneeighth
|
||||
0x215c: 0x0ac4, // XK_threeeighths
|
||||
0x215d: 0x0ac5, // XK_fiveeighths
|
||||
0x215e: 0x0ac6, // XK_seveneighths
|
||||
0x2190: 0x08fb, // XK_leftarrow
|
||||
0x2191: 0x08fc, // XK_uparrow
|
||||
0x2192: 0x08fd, // XK_rightarrow
|
||||
0x2193: 0x08fe, // XK_downarrow
|
||||
0x21d2: 0x08ce, // XK_implies
|
||||
0x21d4: 0x08cd, // XK_ifonlyif
|
||||
0x2202: 0x08ef, // XK_partialderivative
|
||||
0x2207: 0x08c5, // XK_nabla
|
||||
0x2218: 0x0bca, // XK_jot
|
||||
0x221a: 0x08d6, // XK_radical
|
||||
0x221d: 0x08c1, // XK_variation
|
||||
0x221e: 0x08c2, // XK_infinity
|
||||
0x2227: 0x08de, // XK_logicaland
|
||||
0x2228: 0x08df, // XK_logicalor
|
||||
0x2229: 0x08dc, // XK_intersection
|
||||
0x222a: 0x08dd, // XK_union
|
||||
0x222b: 0x08bf, // XK_integral
|
||||
0x2234: 0x08c0, // XK_therefore
|
||||
0x223c: 0x08c8, // XK_approximate
|
||||
0x2243: 0x08c9, // XK_similarequal
|
||||
0x2245: 0x1002248, // XK_approxeq
|
||||
0x2260: 0x08bd, // XK_notequal
|
||||
0x2261: 0x08cf, // XK_identical
|
||||
0x2264: 0x08bc, // XK_lessthanequal
|
||||
0x2265: 0x08be, // XK_greaterthanequal
|
||||
0x2282: 0x08da, // XK_includedin
|
||||
0x2283: 0x08db, // XK_includes
|
||||
0x22a2: 0x0bfc, // XK_righttack
|
||||
0x22a3: 0x0bdc, // XK_lefttack
|
||||
0x22a4: 0x0bc2, // XK_downtack
|
||||
0x22a5: 0x0bce, // XK_uptack
|
||||
0x2308: 0x0bd3, // XK_upstile
|
||||
0x230a: 0x0bc4, // XK_downstile
|
||||
0x2315: 0x0afa, // XK_telephonerecorder
|
||||
0x2320: 0x08a4, // XK_topintegral
|
||||
0x2321: 0x08a5, // XK_botintegral
|
||||
0x2395: 0x0bcc, // XK_quad
|
||||
0x239b: 0x08ab, // XK_topleftparens
|
||||
0x239d: 0x08ac, // XK_botleftparens
|
||||
0x239e: 0x08ad, // XK_toprightparens
|
||||
0x23a0: 0x08ae, // XK_botrightparens
|
||||
0x23a1: 0x08a7, // XK_topleftsqbracket
|
||||
0x23a3: 0x08a8, // XK_botleftsqbracket
|
||||
0x23a4: 0x08a9, // XK_toprightsqbracket
|
||||
0x23a6: 0x08aa, // XK_botrightsqbracket
|
||||
0x23a8: 0x08af, // XK_leftmiddlecurlybrace
|
||||
0x23ac: 0x08b0, // XK_rightmiddlecurlybrace
|
||||
0x23b7: 0x08a1, // XK_leftradical
|
||||
0x23ba: 0x09ef, // XK_horizlinescan1
|
||||
0x23bb: 0x09f0, // XK_horizlinescan3
|
||||
0x23bc: 0x09f2, // XK_horizlinescan7
|
||||
0x23bd: 0x09f3, // XK_horizlinescan9
|
||||
0x2409: 0x09e2, // XK_ht
|
||||
0x240a: 0x09e5, // XK_lf
|
||||
0x240b: 0x09e9, // XK_vt
|
||||
0x240c: 0x09e3, // XK_ff
|
||||
0x240d: 0x09e4, // XK_cr
|
||||
0x2423: 0x0aac, // XK_signifblank
|
||||
0x2424: 0x09e8, // XK_nl
|
||||
0x2500: 0x08a3, // XK_horizconnector
|
||||
0x2502: 0x08a6, // XK_vertconnector
|
||||
0x250c: 0x08a2, // XK_topleftradical
|
||||
0x2510: 0x09eb, // XK_uprightcorner
|
||||
0x2514: 0x09ed, // XK_lowleftcorner
|
||||
0x2518: 0x09ea, // XK_lowrightcorner
|
||||
0x251c: 0x09f4, // XK_leftt
|
||||
0x2524: 0x09f5, // XK_rightt
|
||||
0x252c: 0x09f7, // XK_topt
|
||||
0x2534: 0x09f6, // XK_bott
|
||||
0x253c: 0x09ee, // XK_crossinglines
|
||||
0x2592: 0x09e1, // XK_checkerboard
|
||||
0x25aa: 0x0ae7, // XK_enfilledsqbullet
|
||||
0x25ab: 0x0ae1, // XK_enopensquarebullet
|
||||
0x25ac: 0x0adb, // XK_filledrectbullet
|
||||
0x25ad: 0x0ae2, // XK_openrectbullet
|
||||
0x25ae: 0x0adf, // XK_emfilledrect
|
||||
0x25af: 0x0acf, // XK_emopenrectangle
|
||||
0x25b2: 0x0ae8, // XK_filledtribulletup
|
||||
0x25b3: 0x0ae3, // XK_opentribulletup
|
||||
0x25b6: 0x0add, // XK_filledrighttribullet
|
||||
0x25b7: 0x0acd, // XK_rightopentriangle
|
||||
0x25bc: 0x0ae9, // XK_filledtribulletdown
|
||||
0x25bd: 0x0ae4, // XK_opentribulletdown
|
||||
0x25c0: 0x0adc, // XK_filledlefttribullet
|
||||
0x25c1: 0x0acc, // XK_leftopentriangle
|
||||
0x25c6: 0x09e0, // XK_soliddiamond
|
||||
0x25cb: 0x0ace, // XK_emopencircle
|
||||
0x25cf: 0x0ade, // XK_emfilledcircle
|
||||
0x25e6: 0x0ae0, // XK_enopencircbullet
|
||||
0x2606: 0x0ae5, // XK_openstar
|
||||
0x260e: 0x0af9, // XK_telephone
|
||||
0x2613: 0x0aca, // XK_signaturemark
|
||||
0x261c: 0x0aea, // XK_leftpointer
|
||||
0x261e: 0x0aeb, // XK_rightpointer
|
||||
0x2640: 0x0af8, // XK_femalesymbol
|
||||
0x2642: 0x0af7, // XK_malesymbol
|
||||
0x2663: 0x0aec, // XK_club
|
||||
0x2665: 0x0aee, // XK_heart
|
||||
0x2666: 0x0aed, // XK_diamond
|
||||
0x266d: 0x0af6, // XK_musicalflat
|
||||
0x266f: 0x0af5, // XK_musicalsharp
|
||||
0x2713: 0x0af3, // XK_checkmark
|
||||
0x2717: 0x0af4, // XK_ballotcross
|
||||
0x271d: 0x0ad9, // XK_latincross
|
||||
0x2720: 0x0af0, // XK_maltesecross
|
||||
0x27e8: 0x0abc, // XK_leftanglebracket
|
||||
0x27e9: 0x0abe, // XK_rightanglebracket
|
||||
0x3001: 0x04a4, // XK_kana_comma
|
||||
0x3002: 0x04a1, // XK_kana_fullstop
|
||||
0x300c: 0x04a2, // XK_kana_openingbracket
|
||||
0x300d: 0x04a3, // XK_kana_closingbracket
|
||||
0x309b: 0x04de, // XK_voicedsound
|
||||
0x309c: 0x04df, // XK_semivoicedsound
|
||||
0x30a1: 0x04a7, // XK_kana_a
|
||||
0x30a2: 0x04b1, // XK_kana_A
|
||||
0x30a3: 0x04a8, // XK_kana_i
|
||||
0x30a4: 0x04b2, // XK_kana_I
|
||||
0x30a5: 0x04a9, // XK_kana_u
|
||||
0x30a6: 0x04b3, // XK_kana_U
|
||||
0x30a7: 0x04aa, // XK_kana_e
|
||||
0x30a8: 0x04b4, // XK_kana_E
|
||||
0x30a9: 0x04ab, // XK_kana_o
|
||||
0x30aa: 0x04b5, // XK_kana_O
|
||||
0x30ab: 0x04b6, // XK_kana_KA
|
||||
0x30ad: 0x04b7, // XK_kana_KI
|
||||
0x30af: 0x04b8, // XK_kana_KU
|
||||
0x30b1: 0x04b9, // XK_kana_KE
|
||||
0x30b3: 0x04ba, // XK_kana_KO
|
||||
0x30b5: 0x04bb, // XK_kana_SA
|
||||
0x30b7: 0x04bc, // XK_kana_SHI
|
||||
0x30b9: 0x04bd, // XK_kana_SU
|
||||
0x30bb: 0x04be, // XK_kana_SE
|
||||
0x30bd: 0x04bf, // XK_kana_SO
|
||||
0x30bf: 0x04c0, // XK_kana_TA
|
||||
0x30c1: 0x04c1, // XK_kana_CHI
|
||||
0x30c3: 0x04af, // XK_kana_tsu
|
||||
0x30c4: 0x04c2, // XK_kana_TSU
|
||||
0x30c6: 0x04c3, // XK_kana_TE
|
||||
0x30c8: 0x04c4, // XK_kana_TO
|
||||
0x30ca: 0x04c5, // XK_kana_NA
|
||||
0x30cb: 0x04c6, // XK_kana_NI
|
||||
0x30cc: 0x04c7, // XK_kana_NU
|
||||
0x30cd: 0x04c8, // XK_kana_NE
|
||||
0x30ce: 0x04c9, // XK_kana_NO
|
||||
0x30cf: 0x04ca, // XK_kana_HA
|
||||
0x30d2: 0x04cb, // XK_kana_HI
|
||||
0x30d5: 0x04cc, // XK_kana_FU
|
||||
0x30d8: 0x04cd, // XK_kana_HE
|
||||
0x30db: 0x04ce, // XK_kana_HO
|
||||
0x30de: 0x04cf, // XK_kana_MA
|
||||
0x30df: 0x04d0, // XK_kana_MI
|
||||
0x30e0: 0x04d1, // XK_kana_MU
|
||||
0x30e1: 0x04d2, // XK_kana_ME
|
||||
0x30e2: 0x04d3, // XK_kana_MO
|
||||
0x30e3: 0x04ac, // XK_kana_ya
|
||||
0x30e4: 0x04d4, // XK_kana_YA
|
||||
0x30e5: 0x04ad, // XK_kana_yu
|
||||
0x30e6: 0x04d5, // XK_kana_YU
|
||||
0x30e7: 0x04ae, // XK_kana_yo
|
||||
0x30e8: 0x04d6, // XK_kana_YO
|
||||
0x30e9: 0x04d7, // XK_kana_RA
|
||||
0x30ea: 0x04d8, // XK_kana_RI
|
||||
0x30eb: 0x04d9, // XK_kana_RU
|
||||
0x30ec: 0x04da, // XK_kana_RE
|
||||
0x30ed: 0x04db, // XK_kana_RO
|
||||
0x30ef: 0x04dc, // XK_kana_WA
|
||||
0x30f2: 0x04a6, // XK_kana_WO
|
||||
0x30f3: 0x04dd, // XK_kana_N
|
||||
0x30fb: 0x04a5, // XK_kana_conjunctive
|
||||
0x30fc: 0x04b0, // XK_prolongedsound
|
||||
};
|
||||
|
||||
export default {
|
||||
lookup(u) {
|
||||
// Latin-1 is one-to-one mapping
|
||||
if ((u >= 0x20) && (u <= 0xff)) {
|
||||
return u;
|
||||
}
|
||||
|
||||
// Lookup table (fairly random)
|
||||
const keysym = codepoints[u];
|
||||
if (keysym !== undefined) {
|
||||
return keysym;
|
||||
}
|
||||
|
||||
// General mapping as final fallback
|
||||
return 0x01000000 | u;
|
||||
},
|
||||
};
|
||||
191
backend/app/static/novnc/core/input/util.js
Normal file
191
backend/app/static/novnc/core/input/util.js
Normal file
@@ -0,0 +1,191 @@
|
||||
import KeyTable from "./keysym.js";
|
||||
import keysyms from "./keysymdef.js";
|
||||
import vkeys from "./vkeys.js";
|
||||
import fixedkeys from "./fixedkeys.js";
|
||||
import DOMKeyTable from "./domkeytable.js";
|
||||
import * as browser from "../util/browser.js";
|
||||
|
||||
// Get 'KeyboardEvent.code', handling legacy browsers
|
||||
export function getKeycode(evt) {
|
||||
// Are we getting proper key identifiers?
|
||||
// (unfortunately Firefox and Chrome are crappy here and gives
|
||||
// us an empty string on some platforms, rather than leaving it
|
||||
// undefined)
|
||||
if (evt.code) {
|
||||
// Mozilla isn't fully in sync with the spec yet
|
||||
switch (evt.code) {
|
||||
case 'OSLeft': return 'MetaLeft';
|
||||
case 'OSRight': return 'MetaRight';
|
||||
}
|
||||
|
||||
return evt.code;
|
||||
}
|
||||
|
||||
// The de-facto standard is to use Windows Virtual-Key codes
|
||||
// in the 'keyCode' field for non-printable characters
|
||||
if (evt.keyCode in vkeys) {
|
||||
let code = vkeys[evt.keyCode];
|
||||
|
||||
// macOS has messed up this code for some reason
|
||||
if (browser.isMac() && (code === 'ContextMenu')) {
|
||||
code = 'MetaRight';
|
||||
}
|
||||
|
||||
// The keyCode doesn't distinguish between left and right
|
||||
// for the standard modifiers
|
||||
if (evt.location === 2) {
|
||||
switch (code) {
|
||||
case 'ShiftLeft': return 'ShiftRight';
|
||||
case 'ControlLeft': return 'ControlRight';
|
||||
case 'AltLeft': return 'AltRight';
|
||||
}
|
||||
}
|
||||
|
||||
// Nor a bunch of the numpad keys
|
||||
if (evt.location === 3) {
|
||||
switch (code) {
|
||||
case 'Delete': return 'NumpadDecimal';
|
||||
case 'Insert': return 'Numpad0';
|
||||
case 'End': return 'Numpad1';
|
||||
case 'ArrowDown': return 'Numpad2';
|
||||
case 'PageDown': return 'Numpad3';
|
||||
case 'ArrowLeft': return 'Numpad4';
|
||||
case 'ArrowRight': return 'Numpad6';
|
||||
case 'Home': return 'Numpad7';
|
||||
case 'ArrowUp': return 'Numpad8';
|
||||
case 'PageUp': return 'Numpad9';
|
||||
case 'Enter': return 'NumpadEnter';
|
||||
}
|
||||
}
|
||||
|
||||
return code;
|
||||
}
|
||||
|
||||
return 'Unidentified';
|
||||
}
|
||||
|
||||
// Get 'KeyboardEvent.key', handling legacy browsers
|
||||
export function getKey(evt) {
|
||||
// Are we getting a proper key value?
|
||||
if (evt.key !== undefined) {
|
||||
// Mozilla isn't fully in sync with the spec yet
|
||||
switch (evt.key) {
|
||||
case 'OS': return 'Meta';
|
||||
case 'LaunchMyComputer': return 'LaunchApplication1';
|
||||
case 'LaunchCalculator': return 'LaunchApplication2';
|
||||
}
|
||||
|
||||
// iOS leaks some OS names
|
||||
switch (evt.key) {
|
||||
case 'UIKeyInputUpArrow': return 'ArrowUp';
|
||||
case 'UIKeyInputDownArrow': return 'ArrowDown';
|
||||
case 'UIKeyInputLeftArrow': return 'ArrowLeft';
|
||||
case 'UIKeyInputRightArrow': return 'ArrowRight';
|
||||
case 'UIKeyInputEscape': return 'Escape';
|
||||
}
|
||||
|
||||
// Broken behaviour in Chrome
|
||||
if ((evt.key === '\x00') && (evt.code === 'NumpadDecimal')) {
|
||||
return 'Delete';
|
||||
}
|
||||
|
||||
return evt.key;
|
||||
}
|
||||
|
||||
// Try to deduce it based on the physical key
|
||||
const code = getKeycode(evt);
|
||||
if (code in fixedkeys) {
|
||||
return fixedkeys[code];
|
||||
}
|
||||
|
||||
// If that failed, then see if we have a printable character
|
||||
if (evt.charCode) {
|
||||
return String.fromCharCode(evt.charCode);
|
||||
}
|
||||
|
||||
// At this point we have nothing left to go on
|
||||
return 'Unidentified';
|
||||
}
|
||||
|
||||
// Get the most reliable keysym value we can get from a key event
|
||||
export function getKeysym(evt) {
|
||||
const key = getKey(evt);
|
||||
|
||||
if (key === 'Unidentified') {
|
||||
return null;
|
||||
}
|
||||
|
||||
// First look up special keys
|
||||
if (key in DOMKeyTable) {
|
||||
let location = evt.location;
|
||||
|
||||
// Safari screws up location for the right cmd key
|
||||
if ((key === 'Meta') && (location === 0)) {
|
||||
location = 2;
|
||||
}
|
||||
|
||||
// And for Clear
|
||||
if ((key === 'Clear') && (location === 3)) {
|
||||
let code = getKeycode(evt);
|
||||
if (code === 'NumLock') {
|
||||
location = 0;
|
||||
}
|
||||
}
|
||||
|
||||
if ((location === undefined) || (location > 3)) {
|
||||
location = 0;
|
||||
}
|
||||
|
||||
// The original Meta key now gets confused with the Windows key
|
||||
// https://bugs.chromium.org/p/chromium/issues/detail?id=1020141
|
||||
// https://bugzilla.mozilla.org/show_bug.cgi?id=1232918
|
||||
if (key === 'Meta') {
|
||||
let code = getKeycode(evt);
|
||||
if (code === 'AltLeft') {
|
||||
return KeyTable.XK_Meta_L;
|
||||
} else if (code === 'AltRight') {
|
||||
return KeyTable.XK_Meta_R;
|
||||
}
|
||||
}
|
||||
|
||||
// macOS has Clear instead of NumLock, but the remote system is
|
||||
// probably not macOS, so lying here is probably best...
|
||||
if (key === 'Clear') {
|
||||
let code = getKeycode(evt);
|
||||
if (code === 'NumLock') {
|
||||
return KeyTable.XK_Num_Lock;
|
||||
}
|
||||
}
|
||||
|
||||
// Windows sends alternating symbols for some keys when using a
|
||||
// Japanese layout. We have no way of synchronising with the IM
|
||||
// running on the remote system, so we send some combined keysym
|
||||
// instead and hope for the best.
|
||||
if (browser.isWindows()) {
|
||||
switch (key) {
|
||||
case 'Zenkaku':
|
||||
case 'Hankaku':
|
||||
return KeyTable.XK_Zenkaku_Hankaku;
|
||||
case 'Romaji':
|
||||
case 'KanaMode':
|
||||
return KeyTable.XK_Romaji;
|
||||
}
|
||||
}
|
||||
|
||||
return DOMKeyTable[key][location];
|
||||
}
|
||||
|
||||
// Now we need to look at the Unicode symbol instead
|
||||
|
||||
// Special key? (FIXME: Should have been caught earlier)
|
||||
if (key.length !== 1) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const codepoint = key.charCodeAt();
|
||||
if (codepoint) {
|
||||
return keysyms.lookup(codepoint);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
116
backend/app/static/novnc/core/input/vkeys.js
Normal file
116
backend/app/static/novnc/core/input/vkeys.js
Normal file
@@ -0,0 +1,116 @@
|
||||
/*
|
||||
* noVNC: HTML5 VNC client
|
||||
* Copyright (C) 2018 The noVNC Authors
|
||||
* Licensed under MPL 2.0 or any later version (see LICENSE.txt)
|
||||
*/
|
||||
|
||||
/*
|
||||
* Mapping between Microsoft® Windows® Virtual-Key codes and
|
||||
* HTML key codes.
|
||||
*/
|
||||
|
||||
export default {
|
||||
0x08: 'Backspace',
|
||||
0x09: 'Tab',
|
||||
0x0a: 'NumpadClear',
|
||||
0x0d: 'Enter',
|
||||
0x10: 'ShiftLeft',
|
||||
0x11: 'ControlLeft',
|
||||
0x12: 'AltLeft',
|
||||
0x13: 'Pause',
|
||||
0x14: 'CapsLock',
|
||||
0x15: 'Lang1',
|
||||
0x19: 'Lang2',
|
||||
0x1b: 'Escape',
|
||||
0x1c: 'Convert',
|
||||
0x1d: 'NonConvert',
|
||||
0x20: 'Space',
|
||||
0x21: 'PageUp',
|
||||
0x22: 'PageDown',
|
||||
0x23: 'End',
|
||||
0x24: 'Home',
|
||||
0x25: 'ArrowLeft',
|
||||
0x26: 'ArrowUp',
|
||||
0x27: 'ArrowRight',
|
||||
0x28: 'ArrowDown',
|
||||
0x29: 'Select',
|
||||
0x2c: 'PrintScreen',
|
||||
0x2d: 'Insert',
|
||||
0x2e: 'Delete',
|
||||
0x2f: 'Help',
|
||||
0x30: 'Digit0',
|
||||
0x31: 'Digit1',
|
||||
0x32: 'Digit2',
|
||||
0x33: 'Digit3',
|
||||
0x34: 'Digit4',
|
||||
0x35: 'Digit5',
|
||||
0x36: 'Digit6',
|
||||
0x37: 'Digit7',
|
||||
0x38: 'Digit8',
|
||||
0x39: 'Digit9',
|
||||
0x5b: 'MetaLeft',
|
||||
0x5c: 'MetaRight',
|
||||
0x5d: 'ContextMenu',
|
||||
0x5f: 'Sleep',
|
||||
0x60: 'Numpad0',
|
||||
0x61: 'Numpad1',
|
||||
0x62: 'Numpad2',
|
||||
0x63: 'Numpad3',
|
||||
0x64: 'Numpad4',
|
||||
0x65: 'Numpad5',
|
||||
0x66: 'Numpad6',
|
||||
0x67: 'Numpad7',
|
||||
0x68: 'Numpad8',
|
||||
0x69: 'Numpad9',
|
||||
0x6a: 'NumpadMultiply',
|
||||
0x6b: 'NumpadAdd',
|
||||
0x6c: 'NumpadDecimal',
|
||||
0x6d: 'NumpadSubtract',
|
||||
0x6e: 'NumpadDecimal', // Duplicate, because buggy on Windows
|
||||
0x6f: 'NumpadDivide',
|
||||
0x70: 'F1',
|
||||
0x71: 'F2',
|
||||
0x72: 'F3',
|
||||
0x73: 'F4',
|
||||
0x74: 'F5',
|
||||
0x75: 'F6',
|
||||
0x76: 'F7',
|
||||
0x77: 'F8',
|
||||
0x78: 'F9',
|
||||
0x79: 'F10',
|
||||
0x7a: 'F11',
|
||||
0x7b: 'F12',
|
||||
0x7c: 'F13',
|
||||
0x7d: 'F14',
|
||||
0x7e: 'F15',
|
||||
0x7f: 'F16',
|
||||
0x80: 'F17',
|
||||
0x81: 'F18',
|
||||
0x82: 'F19',
|
||||
0x83: 'F20',
|
||||
0x84: 'F21',
|
||||
0x85: 'F22',
|
||||
0x86: 'F23',
|
||||
0x87: 'F24',
|
||||
0x90: 'NumLock',
|
||||
0x91: 'ScrollLock',
|
||||
0xa6: 'BrowserBack',
|
||||
0xa7: 'BrowserForward',
|
||||
0xa8: 'BrowserRefresh',
|
||||
0xa9: 'BrowserStop',
|
||||
0xaa: 'BrowserSearch',
|
||||
0xab: 'BrowserFavorites',
|
||||
0xac: 'BrowserHome',
|
||||
0xad: 'AudioVolumeMute',
|
||||
0xae: 'AudioVolumeDown',
|
||||
0xaf: 'AudioVolumeUp',
|
||||
0xb0: 'MediaTrackNext',
|
||||
0xb1: 'MediaTrackPrevious',
|
||||
0xb2: 'MediaStop',
|
||||
0xb3: 'MediaPlayPause',
|
||||
0xb4: 'LaunchMail',
|
||||
0xb5: 'MediaSelect',
|
||||
0xb6: 'LaunchApp1',
|
||||
0xb7: 'LaunchApp2',
|
||||
0xe1: 'AltRight', // Only when it is AltGraph
|
||||
};
|
||||
173
backend/app/static/novnc/core/input/xtscancodes.js
Normal file
173
backend/app/static/novnc/core/input/xtscancodes.js
Normal file
@@ -0,0 +1,173 @@
|
||||
/*
|
||||
* This file is auto-generated from keymaps.csv
|
||||
* Database checksum sha256(76d68c10e97d37fe2ea459e210125ae41796253fb217e900bf2983ade13a7920)
|
||||
* To re-generate, run:
|
||||
* keymap-gen code-map --lang=js keymaps.csv html atset1
|
||||
*/
|
||||
export default {
|
||||
"Again": 0xe005, /* html:Again (Again) -> linux:129 (KEY_AGAIN) -> atset1:57349 */
|
||||
"AltLeft": 0x38, /* html:AltLeft (AltLeft) -> linux:56 (KEY_LEFTALT) -> atset1:56 */
|
||||
"AltRight": 0xe038, /* html:AltRight (AltRight) -> linux:100 (KEY_RIGHTALT) -> atset1:57400 */
|
||||
"ArrowDown": 0xe050, /* html:ArrowDown (ArrowDown) -> linux:108 (KEY_DOWN) -> atset1:57424 */
|
||||
"ArrowLeft": 0xe04b, /* html:ArrowLeft (ArrowLeft) -> linux:105 (KEY_LEFT) -> atset1:57419 */
|
||||
"ArrowRight": 0xe04d, /* html:ArrowRight (ArrowRight) -> linux:106 (KEY_RIGHT) -> atset1:57421 */
|
||||
"ArrowUp": 0xe048, /* html:ArrowUp (ArrowUp) -> linux:103 (KEY_UP) -> atset1:57416 */
|
||||
"AudioVolumeDown": 0xe02e, /* html:AudioVolumeDown (AudioVolumeDown) -> linux:114 (KEY_VOLUMEDOWN) -> atset1:57390 */
|
||||
"AudioVolumeMute": 0xe020, /* html:AudioVolumeMute (AudioVolumeMute) -> linux:113 (KEY_MUTE) -> atset1:57376 */
|
||||
"AudioVolumeUp": 0xe030, /* html:AudioVolumeUp (AudioVolumeUp) -> linux:115 (KEY_VOLUMEUP) -> atset1:57392 */
|
||||
"Backquote": 0x29, /* html:Backquote (Backquote) -> linux:41 (KEY_GRAVE) -> atset1:41 */
|
||||
"Backslash": 0x2b, /* html:Backslash (Backslash) -> linux:43 (KEY_BACKSLASH) -> atset1:43 */
|
||||
"Backspace": 0xe, /* html:Backspace (Backspace) -> linux:14 (KEY_BACKSPACE) -> atset1:14 */
|
||||
"BracketLeft": 0x1a, /* html:BracketLeft (BracketLeft) -> linux:26 (KEY_LEFTBRACE) -> atset1:26 */
|
||||
"BracketRight": 0x1b, /* html:BracketRight (BracketRight) -> linux:27 (KEY_RIGHTBRACE) -> atset1:27 */
|
||||
"BrowserBack": 0xe06a, /* html:BrowserBack (BrowserBack) -> linux:158 (KEY_BACK) -> atset1:57450 */
|
||||
"BrowserFavorites": 0xe066, /* html:BrowserFavorites (BrowserFavorites) -> linux:156 (KEY_BOOKMARKS) -> atset1:57446 */
|
||||
"BrowserForward": 0xe069, /* html:BrowserForward (BrowserForward) -> linux:159 (KEY_FORWARD) -> atset1:57449 */
|
||||
"BrowserHome": 0xe032, /* html:BrowserHome (BrowserHome) -> linux:172 (KEY_HOMEPAGE) -> atset1:57394 */
|
||||
"BrowserRefresh": 0xe067, /* html:BrowserRefresh (BrowserRefresh) -> linux:173 (KEY_REFRESH) -> atset1:57447 */
|
||||
"BrowserSearch": 0xe065, /* html:BrowserSearch (BrowserSearch) -> linux:217 (KEY_SEARCH) -> atset1:57445 */
|
||||
"BrowserStop": 0xe068, /* html:BrowserStop (BrowserStop) -> linux:128 (KEY_STOP) -> atset1:57448 */
|
||||
"CapsLock": 0x3a, /* html:CapsLock (CapsLock) -> linux:58 (KEY_CAPSLOCK) -> atset1:58 */
|
||||
"Comma": 0x33, /* html:Comma (Comma) -> linux:51 (KEY_COMMA) -> atset1:51 */
|
||||
"ContextMenu": 0xe05d, /* html:ContextMenu (ContextMenu) -> linux:127 (KEY_COMPOSE) -> atset1:57437 */
|
||||
"ControlLeft": 0x1d, /* html:ControlLeft (ControlLeft) -> linux:29 (KEY_LEFTCTRL) -> atset1:29 */
|
||||
"ControlRight": 0xe01d, /* html:ControlRight (ControlRight) -> linux:97 (KEY_RIGHTCTRL) -> atset1:57373 */
|
||||
"Convert": 0x79, /* html:Convert (Convert) -> linux:92 (KEY_HENKAN) -> atset1:121 */
|
||||
"Copy": 0xe078, /* html:Copy (Copy) -> linux:133 (KEY_COPY) -> atset1:57464 */
|
||||
"Cut": 0xe03c, /* html:Cut (Cut) -> linux:137 (KEY_CUT) -> atset1:57404 */
|
||||
"Delete": 0xe053, /* html:Delete (Delete) -> linux:111 (KEY_DELETE) -> atset1:57427 */
|
||||
"Digit0": 0xb, /* html:Digit0 (Digit0) -> linux:11 (KEY_0) -> atset1:11 */
|
||||
"Digit1": 0x2, /* html:Digit1 (Digit1) -> linux:2 (KEY_1) -> atset1:2 */
|
||||
"Digit2": 0x3, /* html:Digit2 (Digit2) -> linux:3 (KEY_2) -> atset1:3 */
|
||||
"Digit3": 0x4, /* html:Digit3 (Digit3) -> linux:4 (KEY_3) -> atset1:4 */
|
||||
"Digit4": 0x5, /* html:Digit4 (Digit4) -> linux:5 (KEY_4) -> atset1:5 */
|
||||
"Digit5": 0x6, /* html:Digit5 (Digit5) -> linux:6 (KEY_5) -> atset1:6 */
|
||||
"Digit6": 0x7, /* html:Digit6 (Digit6) -> linux:7 (KEY_6) -> atset1:7 */
|
||||
"Digit7": 0x8, /* html:Digit7 (Digit7) -> linux:8 (KEY_7) -> atset1:8 */
|
||||
"Digit8": 0x9, /* html:Digit8 (Digit8) -> linux:9 (KEY_8) -> atset1:9 */
|
||||
"Digit9": 0xa, /* html:Digit9 (Digit9) -> linux:10 (KEY_9) -> atset1:10 */
|
||||
"Eject": 0xe07d, /* html:Eject (Eject) -> linux:162 (KEY_EJECTCLOSECD) -> atset1:57469 */
|
||||
"End": 0xe04f, /* html:End (End) -> linux:107 (KEY_END) -> atset1:57423 */
|
||||
"Enter": 0x1c, /* html:Enter (Enter) -> linux:28 (KEY_ENTER) -> atset1:28 */
|
||||
"Equal": 0xd, /* html:Equal (Equal) -> linux:13 (KEY_EQUAL) -> atset1:13 */
|
||||
"Escape": 0x1, /* html:Escape (Escape) -> linux:1 (KEY_ESC) -> atset1:1 */
|
||||
"F1": 0x3b, /* html:F1 (F1) -> linux:59 (KEY_F1) -> atset1:59 */
|
||||
"F10": 0x44, /* html:F10 (F10) -> linux:68 (KEY_F10) -> atset1:68 */
|
||||
"F11": 0x57, /* html:F11 (F11) -> linux:87 (KEY_F11) -> atset1:87 */
|
||||
"F12": 0x58, /* html:F12 (F12) -> linux:88 (KEY_F12) -> atset1:88 */
|
||||
"F13": 0x5d, /* html:F13 (F13) -> linux:183 (KEY_F13) -> atset1:93 */
|
||||
"F14": 0x5e, /* html:F14 (F14) -> linux:184 (KEY_F14) -> atset1:94 */
|
||||
"F15": 0x5f, /* html:F15 (F15) -> linux:185 (KEY_F15) -> atset1:95 */
|
||||
"F16": 0x55, /* html:F16 (F16) -> linux:186 (KEY_F16) -> atset1:85 */
|
||||
"F17": 0xe003, /* html:F17 (F17) -> linux:187 (KEY_F17) -> atset1:57347 */
|
||||
"F18": 0xe077, /* html:F18 (F18) -> linux:188 (KEY_F18) -> atset1:57463 */
|
||||
"F19": 0xe004, /* html:F19 (F19) -> linux:189 (KEY_F19) -> atset1:57348 */
|
||||
"F2": 0x3c, /* html:F2 (F2) -> linux:60 (KEY_F2) -> atset1:60 */
|
||||
"F20": 0x5a, /* html:F20 (F20) -> linux:190 (KEY_F20) -> atset1:90 */
|
||||
"F21": 0x74, /* html:F21 (F21) -> linux:191 (KEY_F21) -> atset1:116 */
|
||||
"F22": 0xe079, /* html:F22 (F22) -> linux:192 (KEY_F22) -> atset1:57465 */
|
||||
"F23": 0x6d, /* html:F23 (F23) -> linux:193 (KEY_F23) -> atset1:109 */
|
||||
"F24": 0x6f, /* html:F24 (F24) -> linux:194 (KEY_F24) -> atset1:111 */
|
||||
"F3": 0x3d, /* html:F3 (F3) -> linux:61 (KEY_F3) -> atset1:61 */
|
||||
"F4": 0x3e, /* html:F4 (F4) -> linux:62 (KEY_F4) -> atset1:62 */
|
||||
"F5": 0x3f, /* html:F5 (F5) -> linux:63 (KEY_F5) -> atset1:63 */
|
||||
"F6": 0x40, /* html:F6 (F6) -> linux:64 (KEY_F6) -> atset1:64 */
|
||||
"F7": 0x41, /* html:F7 (F7) -> linux:65 (KEY_F7) -> atset1:65 */
|
||||
"F8": 0x42, /* html:F8 (F8) -> linux:66 (KEY_F8) -> atset1:66 */
|
||||
"F9": 0x43, /* html:F9 (F9) -> linux:67 (KEY_F9) -> atset1:67 */
|
||||
"Find": 0xe041, /* html:Find (Find) -> linux:136 (KEY_FIND) -> atset1:57409 */
|
||||
"Help": 0xe075, /* html:Help (Help) -> linux:138 (KEY_HELP) -> atset1:57461 */
|
||||
"Hiragana": 0x77, /* html:Hiragana (Lang4) -> linux:91 (KEY_HIRAGANA) -> atset1:119 */
|
||||
"Home": 0xe047, /* html:Home (Home) -> linux:102 (KEY_HOME) -> atset1:57415 */
|
||||
"Insert": 0xe052, /* html:Insert (Insert) -> linux:110 (KEY_INSERT) -> atset1:57426 */
|
||||
"IntlBackslash": 0x56, /* html:IntlBackslash (IntlBackslash) -> linux:86 (KEY_102ND) -> atset1:86 */
|
||||
"IntlRo": 0x73, /* html:IntlRo (IntlRo) -> linux:89 (KEY_RO) -> atset1:115 */
|
||||
"IntlYen": 0x7d, /* html:IntlYen (IntlYen) -> linux:124 (KEY_YEN) -> atset1:125 */
|
||||
"KanaMode": 0x70, /* html:KanaMode (KanaMode) -> linux:93 (KEY_KATAKANAHIRAGANA) -> atset1:112 */
|
||||
"Katakana": 0x78, /* html:Katakana (Lang3) -> linux:90 (KEY_KATAKANA) -> atset1:120 */
|
||||
"KeyA": 0x1e, /* html:KeyA (KeyA) -> linux:30 (KEY_A) -> atset1:30 */
|
||||
"KeyB": 0x30, /* html:KeyB (KeyB) -> linux:48 (KEY_B) -> atset1:48 */
|
||||
"KeyC": 0x2e, /* html:KeyC (KeyC) -> linux:46 (KEY_C) -> atset1:46 */
|
||||
"KeyD": 0x20, /* html:KeyD (KeyD) -> linux:32 (KEY_D) -> atset1:32 */
|
||||
"KeyE": 0x12, /* html:KeyE (KeyE) -> linux:18 (KEY_E) -> atset1:18 */
|
||||
"KeyF": 0x21, /* html:KeyF (KeyF) -> linux:33 (KEY_F) -> atset1:33 */
|
||||
"KeyG": 0x22, /* html:KeyG (KeyG) -> linux:34 (KEY_G) -> atset1:34 */
|
||||
"KeyH": 0x23, /* html:KeyH (KeyH) -> linux:35 (KEY_H) -> atset1:35 */
|
||||
"KeyI": 0x17, /* html:KeyI (KeyI) -> linux:23 (KEY_I) -> atset1:23 */
|
||||
"KeyJ": 0x24, /* html:KeyJ (KeyJ) -> linux:36 (KEY_J) -> atset1:36 */
|
||||
"KeyK": 0x25, /* html:KeyK (KeyK) -> linux:37 (KEY_K) -> atset1:37 */
|
||||
"KeyL": 0x26, /* html:KeyL (KeyL) -> linux:38 (KEY_L) -> atset1:38 */
|
||||
"KeyM": 0x32, /* html:KeyM (KeyM) -> linux:50 (KEY_M) -> atset1:50 */
|
||||
"KeyN": 0x31, /* html:KeyN (KeyN) -> linux:49 (KEY_N) -> atset1:49 */
|
||||
"KeyO": 0x18, /* html:KeyO (KeyO) -> linux:24 (KEY_O) -> atset1:24 */
|
||||
"KeyP": 0x19, /* html:KeyP (KeyP) -> linux:25 (KEY_P) -> atset1:25 */
|
||||
"KeyQ": 0x10, /* html:KeyQ (KeyQ) -> linux:16 (KEY_Q) -> atset1:16 */
|
||||
"KeyR": 0x13, /* html:KeyR (KeyR) -> linux:19 (KEY_R) -> atset1:19 */
|
||||
"KeyS": 0x1f, /* html:KeyS (KeyS) -> linux:31 (KEY_S) -> atset1:31 */
|
||||
"KeyT": 0x14, /* html:KeyT (KeyT) -> linux:20 (KEY_T) -> atset1:20 */
|
||||
"KeyU": 0x16, /* html:KeyU (KeyU) -> linux:22 (KEY_U) -> atset1:22 */
|
||||
"KeyV": 0x2f, /* html:KeyV (KeyV) -> linux:47 (KEY_V) -> atset1:47 */
|
||||
"KeyW": 0x11, /* html:KeyW (KeyW) -> linux:17 (KEY_W) -> atset1:17 */
|
||||
"KeyX": 0x2d, /* html:KeyX (KeyX) -> linux:45 (KEY_X) -> atset1:45 */
|
||||
"KeyY": 0x15, /* html:KeyY (KeyY) -> linux:21 (KEY_Y) -> atset1:21 */
|
||||
"KeyZ": 0x2c, /* html:KeyZ (KeyZ) -> linux:44 (KEY_Z) -> atset1:44 */
|
||||
"Lang1": 0x72, /* html:Lang1 (Lang1) -> linux:122 (KEY_HANGEUL) -> atset1:114 */
|
||||
"Lang2": 0x71, /* html:Lang2 (Lang2) -> linux:123 (KEY_HANJA) -> atset1:113 */
|
||||
"Lang3": 0x78, /* html:Lang3 (Lang3) -> linux:90 (KEY_KATAKANA) -> atset1:120 */
|
||||
"Lang4": 0x77, /* html:Lang4 (Lang4) -> linux:91 (KEY_HIRAGANA) -> atset1:119 */
|
||||
"Lang5": 0x76, /* html:Lang5 (Lang5) -> linux:85 (KEY_ZENKAKUHANKAKU) -> atset1:118 */
|
||||
"LaunchApp1": 0xe06b, /* html:LaunchApp1 (LaunchApp1) -> linux:157 (KEY_COMPUTER) -> atset1:57451 */
|
||||
"LaunchApp2": 0xe021, /* html:LaunchApp2 (LaunchApp2) -> linux:140 (KEY_CALC) -> atset1:57377 */
|
||||
"LaunchMail": 0xe06c, /* html:LaunchMail (LaunchMail) -> linux:155 (KEY_MAIL) -> atset1:57452 */
|
||||
"MediaPlayPause": 0xe022, /* html:MediaPlayPause (MediaPlayPause) -> linux:164 (KEY_PLAYPAUSE) -> atset1:57378 */
|
||||
"MediaSelect": 0xe06d, /* html:MediaSelect (MediaSelect) -> linux:226 (KEY_MEDIA) -> atset1:57453 */
|
||||
"MediaStop": 0xe024, /* html:MediaStop (MediaStop) -> linux:166 (KEY_STOPCD) -> atset1:57380 */
|
||||
"MediaTrackNext": 0xe019, /* html:MediaTrackNext (MediaTrackNext) -> linux:163 (KEY_NEXTSONG) -> atset1:57369 */
|
||||
"MediaTrackPrevious": 0xe010, /* html:MediaTrackPrevious (MediaTrackPrevious) -> linux:165 (KEY_PREVIOUSSONG) -> atset1:57360 */
|
||||
"MetaLeft": 0xe05b, /* html:MetaLeft (MetaLeft) -> linux:125 (KEY_LEFTMETA) -> atset1:57435 */
|
||||
"MetaRight": 0xe05c, /* html:MetaRight (MetaRight) -> linux:126 (KEY_RIGHTMETA) -> atset1:57436 */
|
||||
"Minus": 0xc, /* html:Minus (Minus) -> linux:12 (KEY_MINUS) -> atset1:12 */
|
||||
"NonConvert": 0x7b, /* html:NonConvert (NonConvert) -> linux:94 (KEY_MUHENKAN) -> atset1:123 */
|
||||
"NumLock": 0x45, /* html:NumLock (NumLock) -> linux:69 (KEY_NUMLOCK) -> atset1:69 */
|
||||
"Numpad0": 0x52, /* html:Numpad0 (Numpad0) -> linux:82 (KEY_KP0) -> atset1:82 */
|
||||
"Numpad1": 0x4f, /* html:Numpad1 (Numpad1) -> linux:79 (KEY_KP1) -> atset1:79 */
|
||||
"Numpad2": 0x50, /* html:Numpad2 (Numpad2) -> linux:80 (KEY_KP2) -> atset1:80 */
|
||||
"Numpad3": 0x51, /* html:Numpad3 (Numpad3) -> linux:81 (KEY_KP3) -> atset1:81 */
|
||||
"Numpad4": 0x4b, /* html:Numpad4 (Numpad4) -> linux:75 (KEY_KP4) -> atset1:75 */
|
||||
"Numpad5": 0x4c, /* html:Numpad5 (Numpad5) -> linux:76 (KEY_KP5) -> atset1:76 */
|
||||
"Numpad6": 0x4d, /* html:Numpad6 (Numpad6) -> linux:77 (KEY_KP6) -> atset1:77 */
|
||||
"Numpad7": 0x47, /* html:Numpad7 (Numpad7) -> linux:71 (KEY_KP7) -> atset1:71 */
|
||||
"Numpad8": 0x48, /* html:Numpad8 (Numpad8) -> linux:72 (KEY_KP8) -> atset1:72 */
|
||||
"Numpad9": 0x49, /* html:Numpad9 (Numpad9) -> linux:73 (KEY_KP9) -> atset1:73 */
|
||||
"NumpadAdd": 0x4e, /* html:NumpadAdd (NumpadAdd) -> linux:78 (KEY_KPPLUS) -> atset1:78 */
|
||||
"NumpadComma": 0x7e, /* html:NumpadComma (NumpadComma) -> linux:121 (KEY_KPCOMMA) -> atset1:126 */
|
||||
"NumpadDecimal": 0x53, /* html:NumpadDecimal (NumpadDecimal) -> linux:83 (KEY_KPDOT) -> atset1:83 */
|
||||
"NumpadDivide": 0xe035, /* html:NumpadDivide (NumpadDivide) -> linux:98 (KEY_KPSLASH) -> atset1:57397 */
|
||||
"NumpadEnter": 0xe01c, /* html:NumpadEnter (NumpadEnter) -> linux:96 (KEY_KPENTER) -> atset1:57372 */
|
||||
"NumpadEqual": 0x59, /* html:NumpadEqual (NumpadEqual) -> linux:117 (KEY_KPEQUAL) -> atset1:89 */
|
||||
"NumpadMultiply": 0x37, /* html:NumpadMultiply (NumpadMultiply) -> linux:55 (KEY_KPASTERISK) -> atset1:55 */
|
||||
"NumpadParenLeft": 0xe076, /* html:NumpadParenLeft (NumpadParenLeft) -> linux:179 (KEY_KPLEFTPAREN) -> atset1:57462 */
|
||||
"NumpadParenRight": 0xe07b, /* html:NumpadParenRight (NumpadParenRight) -> linux:180 (KEY_KPRIGHTPAREN) -> atset1:57467 */
|
||||
"NumpadSubtract": 0x4a, /* html:NumpadSubtract (NumpadSubtract) -> linux:74 (KEY_KPMINUS) -> atset1:74 */
|
||||
"Open": 0x64, /* html:Open (Open) -> linux:134 (KEY_OPEN) -> atset1:100 */
|
||||
"PageDown": 0xe051, /* html:PageDown (PageDown) -> linux:109 (KEY_PAGEDOWN) -> atset1:57425 */
|
||||
"PageUp": 0xe049, /* html:PageUp (PageUp) -> linux:104 (KEY_PAGEUP) -> atset1:57417 */
|
||||
"Paste": 0x65, /* html:Paste (Paste) -> linux:135 (KEY_PASTE) -> atset1:101 */
|
||||
"Pause": 0xe046, /* html:Pause (Pause) -> linux:119 (KEY_PAUSE) -> atset1:57414 */
|
||||
"Period": 0x34, /* html:Period (Period) -> linux:52 (KEY_DOT) -> atset1:52 */
|
||||
"Power": 0xe05e, /* html:Power (Power) -> linux:116 (KEY_POWER) -> atset1:57438 */
|
||||
"PrintScreen": 0x54, /* html:PrintScreen (PrintScreen) -> linux:99 (KEY_SYSRQ) -> atset1:84 */
|
||||
"Props": 0xe006, /* html:Props (Props) -> linux:130 (KEY_PROPS) -> atset1:57350 */
|
||||
"Quote": 0x28, /* html:Quote (Quote) -> linux:40 (KEY_APOSTROPHE) -> atset1:40 */
|
||||
"ScrollLock": 0x46, /* html:ScrollLock (ScrollLock) -> linux:70 (KEY_SCROLLLOCK) -> atset1:70 */
|
||||
"Semicolon": 0x27, /* html:Semicolon (Semicolon) -> linux:39 (KEY_SEMICOLON) -> atset1:39 */
|
||||
"ShiftLeft": 0x2a, /* html:ShiftLeft (ShiftLeft) -> linux:42 (KEY_LEFTSHIFT) -> atset1:42 */
|
||||
"ShiftRight": 0x36, /* html:ShiftRight (ShiftRight) -> linux:54 (KEY_RIGHTSHIFT) -> atset1:54 */
|
||||
"Slash": 0x35, /* html:Slash (Slash) -> linux:53 (KEY_SLASH) -> atset1:53 */
|
||||
"Sleep": 0xe05f, /* html:Sleep (Sleep) -> linux:142 (KEY_SLEEP) -> atset1:57439 */
|
||||
"Space": 0x39, /* html:Space (Space) -> linux:57 (KEY_SPACE) -> atset1:57 */
|
||||
"Suspend": 0xe025, /* html:Suspend (Suspend) -> linux:205 (KEY_SUSPEND) -> atset1:57381 */
|
||||
"Tab": 0xf, /* html:Tab (Tab) -> linux:15 (KEY_TAB) -> atset1:15 */
|
||||
"Undo": 0xe007, /* html:Undo (Undo) -> linux:131 (KEY_UNDO) -> atset1:57351 */
|
||||
"WakeUp": 0xe063, /* html:WakeUp (WakeUp) -> linux:143 (KEY_WAKEUP) -> atset1:57443 */
|
||||
};
|
||||
567
backend/app/static/novnc/core/ra2.js
Normal file
567
backend/app/static/novnc/core/ra2.js
Normal file
@@ -0,0 +1,567 @@
|
||||
import Base64 from './base64.js';
|
||||
import { encodeUTF8 } from './util/strings.js';
|
||||
import EventTargetMixin from './util/eventtarget.js';
|
||||
|
||||
export class AESEAXCipher {
|
||||
constructor() {
|
||||
this._rawKey = null;
|
||||
this._ctrKey = null;
|
||||
this._cbcKey = null;
|
||||
this._zeroBlock = new Uint8Array(16);
|
||||
this._prefixBlock0 = this._zeroBlock;
|
||||
this._prefixBlock1 = new Uint8Array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]);
|
||||
this._prefixBlock2 = new Uint8Array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2]);
|
||||
}
|
||||
|
||||
async _encryptBlock(block) {
|
||||
const encrypted = await window.crypto.subtle.encrypt({
|
||||
name: "AES-CBC",
|
||||
iv: this._zeroBlock,
|
||||
}, this._cbcKey, block);
|
||||
return new Uint8Array(encrypted).slice(0, 16);
|
||||
}
|
||||
|
||||
async _initCMAC() {
|
||||
const k1 = await this._encryptBlock(this._zeroBlock);
|
||||
const k2 = new Uint8Array(16);
|
||||
const v = k1[0] >>> 6;
|
||||
for (let i = 0; i < 15; i++) {
|
||||
k2[i] = (k1[i + 1] >> 6) | (k1[i] << 2);
|
||||
k1[i] = (k1[i + 1] >> 7) | (k1[i] << 1);
|
||||
}
|
||||
const lut = [0x0, 0x87, 0x0e, 0x89];
|
||||
k2[14] ^= v >>> 1;
|
||||
k2[15] = (k1[15] << 2) ^ lut[v];
|
||||
k1[15] = (k1[15] << 1) ^ lut[v >> 1];
|
||||
this._k1 = k1;
|
||||
this._k2 = k2;
|
||||
}
|
||||
|
||||
async _encryptCTR(data, counter) {
|
||||
const encrypted = await window.crypto.subtle.encrypt({
|
||||
"name": "AES-CTR",
|
||||
counter: counter,
|
||||
length: 128
|
||||
}, this._ctrKey, data);
|
||||
return new Uint8Array(encrypted);
|
||||
}
|
||||
|
||||
async _decryptCTR(data, counter) {
|
||||
const decrypted = await window.crypto.subtle.decrypt({
|
||||
"name": "AES-CTR",
|
||||
counter: counter,
|
||||
length: 128
|
||||
}, this._ctrKey, data);
|
||||
return new Uint8Array(decrypted);
|
||||
}
|
||||
|
||||
async _computeCMAC(data, prefixBlock) {
|
||||
if (prefixBlock.length !== 16) {
|
||||
return null;
|
||||
}
|
||||
const n = Math.floor(data.length / 16);
|
||||
const m = Math.ceil(data.length / 16);
|
||||
const r = data.length - n * 16;
|
||||
const cbcData = new Uint8Array((m + 1) * 16);
|
||||
cbcData.set(prefixBlock);
|
||||
cbcData.set(data, 16);
|
||||
if (r === 0) {
|
||||
for (let i = 0; i < 16; i++) {
|
||||
cbcData[n * 16 + i] ^= this._k1[i];
|
||||
}
|
||||
} else {
|
||||
cbcData[(n + 1) * 16 + r] = 0x80;
|
||||
for (let i = 0; i < 16; i++) {
|
||||
cbcData[(n + 1) * 16 + i] ^= this._k2[i];
|
||||
}
|
||||
}
|
||||
let cbcEncrypted = await window.crypto.subtle.encrypt({
|
||||
name: "AES-CBC",
|
||||
iv: this._zeroBlock,
|
||||
}, this._cbcKey, cbcData);
|
||||
|
||||
cbcEncrypted = new Uint8Array(cbcEncrypted);
|
||||
const mac = cbcEncrypted.slice(cbcEncrypted.length - 32, cbcEncrypted.length - 16);
|
||||
return mac;
|
||||
}
|
||||
|
||||
async setKey(key) {
|
||||
this._rawKey = key;
|
||||
this._ctrKey = await window.crypto.subtle.importKey(
|
||||
"raw", key, {"name": "AES-CTR"}, false, ["encrypt", "decrypt"]);
|
||||
this._cbcKey = await window.crypto.subtle.importKey(
|
||||
"raw", key, {"name": "AES-CBC"}, false, ["encrypt", "decrypt"]);
|
||||
await this._initCMAC();
|
||||
}
|
||||
|
||||
async encrypt(message, associatedData, nonce) {
|
||||
const nCMAC = await this._computeCMAC(nonce, this._prefixBlock0);
|
||||
const encrypted = await this._encryptCTR(message, nCMAC);
|
||||
const adCMAC = await this._computeCMAC(associatedData, this._prefixBlock1);
|
||||
const mac = await this._computeCMAC(encrypted, this._prefixBlock2);
|
||||
for (let i = 0; i < 16; i++) {
|
||||
mac[i] ^= nCMAC[i] ^ adCMAC[i];
|
||||
}
|
||||
const res = new Uint8Array(16 + encrypted.length);
|
||||
res.set(encrypted);
|
||||
res.set(mac, encrypted.length);
|
||||
return res;
|
||||
}
|
||||
|
||||
async decrypt(encrypted, associatedData, nonce, mac) {
|
||||
const nCMAC = await this._computeCMAC(nonce, this._prefixBlock0);
|
||||
const adCMAC = await this._computeCMAC(associatedData, this._prefixBlock1);
|
||||
const computedMac = await this._computeCMAC(encrypted, this._prefixBlock2);
|
||||
for (let i = 0; i < 16; i++) {
|
||||
computedMac[i] ^= nCMAC[i] ^ adCMAC[i];
|
||||
}
|
||||
if (computedMac.length !== mac.length) {
|
||||
return null;
|
||||
}
|
||||
for (let i = 0; i < mac.length; i++) {
|
||||
if (computedMac[i] !== mac[i]) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
const res = await this._decryptCTR(encrypted, nCMAC);
|
||||
return res;
|
||||
}
|
||||
}
|
||||
|
||||
export class RA2Cipher {
|
||||
constructor() {
|
||||
this._cipher = new AESEAXCipher();
|
||||
this._counter = new Uint8Array(16);
|
||||
}
|
||||
|
||||
async setKey(key) {
|
||||
await this._cipher.setKey(key);
|
||||
}
|
||||
|
||||
async makeMessage(message) {
|
||||
const ad = new Uint8Array([(message.length & 0xff00) >>> 8, message.length & 0xff]);
|
||||
const encrypted = await this._cipher.encrypt(message, ad, this._counter);
|
||||
for (let i = 0; i < 16 && this._counter[i]++ === 255; i++);
|
||||
const res = new Uint8Array(message.length + 2 + 16);
|
||||
res.set(ad);
|
||||
res.set(encrypted, 2);
|
||||
return res;
|
||||
}
|
||||
|
||||
async receiveMessage(length, encrypted, mac) {
|
||||
const ad = new Uint8Array([(length & 0xff00) >>> 8, length & 0xff]);
|
||||
const res = await this._cipher.decrypt(encrypted, ad, this._counter, mac);
|
||||
for (let i = 0; i < 16 && this._counter[i]++ === 255; i++);
|
||||
return res;
|
||||
}
|
||||
}
|
||||
|
||||
export class RSACipher {
|
||||
constructor(keyLength) {
|
||||
this._key = null;
|
||||
this._keyLength = keyLength;
|
||||
this._keyBytes = Math.ceil(keyLength / 8);
|
||||
this._n = null;
|
||||
this._e = null;
|
||||
this._d = null;
|
||||
this._nBigInt = null;
|
||||
this._eBigInt = null;
|
||||
this._dBigInt = null;
|
||||
}
|
||||
|
||||
_base64urlDecode(data) {
|
||||
data = data.replace(/-/g, "+").replace(/_/g, "/");
|
||||
data = data.padEnd(Math.ceil(data.length / 4) * 4, "=");
|
||||
return Base64.decode(data);
|
||||
}
|
||||
|
||||
_u8ArrayToBigInt(arr) {
|
||||
let hex = '0x';
|
||||
for (let i = 0; i < arr.length; i++) {
|
||||
hex += arr[i].toString(16).padStart(2, '0');
|
||||
}
|
||||
return BigInt(hex);
|
||||
}
|
||||
|
||||
_padArray(arr, length) {
|
||||
const res = new Uint8Array(length);
|
||||
res.set(arr, length - arr.length);
|
||||
return res;
|
||||
}
|
||||
|
||||
_bigIntToU8Array(bigint, padLength=0) {
|
||||
let hex = bigint.toString(16);
|
||||
if (padLength === 0) {
|
||||
padLength = Math.ceil(hex.length / 2) * 2;
|
||||
}
|
||||
hex = hex.padStart(padLength * 2, '0');
|
||||
const length = hex.length / 2;
|
||||
const arr = new Uint8Array(length);
|
||||
for (let i = 0; i < length; i++) {
|
||||
arr[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
|
||||
}
|
||||
return arr;
|
||||
}
|
||||
|
||||
_modPow(b, e, m) {
|
||||
if (m === 1n) {
|
||||
return 0;
|
||||
}
|
||||
let r = 1n;
|
||||
b = b % m;
|
||||
while (e > 0) {
|
||||
if (e % 2n === 1n) {
|
||||
r = (r * b) % m;
|
||||
}
|
||||
e = e / 2n;
|
||||
b = (b * b) % m;
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
async generateKey() {
|
||||
this._key = await window.crypto.subtle.generateKey(
|
||||
{
|
||||
name: "RSA-OAEP",
|
||||
modulusLength: this._keyLength,
|
||||
publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
|
||||
hash: {name: "SHA-256"},
|
||||
},
|
||||
true, ["encrypt", "decrypt"]);
|
||||
const privateKey = await window.crypto.subtle.exportKey("jwk", this._key.privateKey);
|
||||
this._n = this._padArray(this._base64urlDecode(privateKey.n), this._keyBytes);
|
||||
this._nBigInt = this._u8ArrayToBigInt(this._n);
|
||||
this._e = this._padArray(this._base64urlDecode(privateKey.e), this._keyBytes);
|
||||
this._eBigInt = this._u8ArrayToBigInt(this._e);
|
||||
this._d = this._padArray(this._base64urlDecode(privateKey.d), this._keyBytes);
|
||||
this._dBigInt = this._u8ArrayToBigInt(this._d);
|
||||
}
|
||||
|
||||
setPublicKey(n, e) {
|
||||
if (n.length !== this._keyBytes || e.length !== this._keyBytes) {
|
||||
return;
|
||||
}
|
||||
this._n = new Uint8Array(this._keyBytes);
|
||||
this._e = new Uint8Array(this._keyBytes);
|
||||
this._n.set(n);
|
||||
this._e.set(e);
|
||||
this._nBigInt = this._u8ArrayToBigInt(this._n);
|
||||
this._eBigInt = this._u8ArrayToBigInt(this._e);
|
||||
}
|
||||
|
||||
encrypt(message) {
|
||||
if (message.length > this._keyBytes - 11) {
|
||||
return null;
|
||||
}
|
||||
const ps = new Uint8Array(this._keyBytes - message.length - 3);
|
||||
window.crypto.getRandomValues(ps);
|
||||
for (let i = 0; i < ps.length; i++) {
|
||||
ps[i] = Math.floor(ps[i] * 254 / 255 + 1);
|
||||
}
|
||||
const em = new Uint8Array(this._keyBytes);
|
||||
em[1] = 0x02;
|
||||
em.set(ps, 2);
|
||||
em.set(message, ps.length + 3);
|
||||
const emBigInt = this._u8ArrayToBigInt(em);
|
||||
const c = this._modPow(emBigInt, this._eBigInt, this._nBigInt);
|
||||
return this._bigIntToU8Array(c, this._keyBytes);
|
||||
}
|
||||
|
||||
decrypt(message) {
|
||||
if (message.length !== this._keyBytes) {
|
||||
return null;
|
||||
}
|
||||
const msgBigInt = this._u8ArrayToBigInt(message);
|
||||
const emBigInt = this._modPow(msgBigInt, this._dBigInt, this._nBigInt);
|
||||
const em = this._bigIntToU8Array(emBigInt, this._keyBytes);
|
||||
if (em[0] !== 0x00 || em[1] !== 0x02) {
|
||||
return null;
|
||||
}
|
||||
let i = 2;
|
||||
for (; i < em.length; i++) {
|
||||
if (em[i] === 0x00) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (i === em.length) {
|
||||
return null;
|
||||
}
|
||||
return em.slice(i + 1, em.length);
|
||||
}
|
||||
|
||||
get keyLength() {
|
||||
return this._keyLength;
|
||||
}
|
||||
|
||||
get n() {
|
||||
return this._n;
|
||||
}
|
||||
|
||||
get e() {
|
||||
return this._e;
|
||||
}
|
||||
|
||||
get d() {
|
||||
return this._d;
|
||||
}
|
||||
}
|
||||
|
||||
export default class RSAAESAuthenticationState extends EventTargetMixin {
|
||||
constructor(sock, getCredentials) {
|
||||
super();
|
||||
this._hasStarted = false;
|
||||
this._checkSock = null;
|
||||
this._checkCredentials = null;
|
||||
this._approveServerResolve = null;
|
||||
this._sockReject = null;
|
||||
this._credentialsReject = null;
|
||||
this._approveServerReject = null;
|
||||
this._sock = sock;
|
||||
this._getCredentials = getCredentials;
|
||||
}
|
||||
|
||||
_waitSockAsync(len) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const hasData = () => !this._sock.rQwait('RA2', len);
|
||||
if (hasData()) {
|
||||
resolve();
|
||||
} else {
|
||||
this._checkSock = () => {
|
||||
if (hasData()) {
|
||||
resolve();
|
||||
this._checkSock = null;
|
||||
this._sockReject = null;
|
||||
}
|
||||
};
|
||||
this._sockReject = reject;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
_waitApproveKeyAsync() {
|
||||
return new Promise((resolve, reject) => {
|
||||
this._approveServerResolve = resolve;
|
||||
this._approveServerReject = reject;
|
||||
});
|
||||
}
|
||||
|
||||
_waitCredentialsAsync(subtype) {
|
||||
const hasCredentials = () => {
|
||||
if (subtype === 1 && this._getCredentials().username !== undefined &&
|
||||
this._getCredentials().password !== undefined) {
|
||||
return true;
|
||||
} else if (subtype === 2 && this._getCredentials().password !== undefined) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
return new Promise((resolve, reject) => {
|
||||
if (hasCredentials()) {
|
||||
resolve();
|
||||
} else {
|
||||
this._checkCredentials = () => {
|
||||
if (hasCredentials()) {
|
||||
resolve();
|
||||
this._checkCredentials = null;
|
||||
this._credentialsReject = null;
|
||||
}
|
||||
};
|
||||
this._credentialsReject = reject;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
checkInternalEvents() {
|
||||
if (this._checkSock !== null) {
|
||||
this._checkSock();
|
||||
}
|
||||
if (this._checkCredentials !== null) {
|
||||
this._checkCredentials();
|
||||
}
|
||||
}
|
||||
|
||||
approveServer() {
|
||||
if (this._approveServerResolve !== null) {
|
||||
this._approveServerResolve();
|
||||
this._approveServerResolve = null;
|
||||
}
|
||||
}
|
||||
|
||||
disconnect() {
|
||||
if (this._sockReject !== null) {
|
||||
this._sockReject(new Error("disconnect normally"));
|
||||
this._sockReject = null;
|
||||
}
|
||||
if (this._credentialsReject !== null) {
|
||||
this._credentialsReject(new Error("disconnect normally"));
|
||||
this._credentialsReject = null;
|
||||
}
|
||||
if (this._approveServerReject !== null) {
|
||||
this._approveServerReject(new Error("disconnect normally"));
|
||||
this._approveServerReject = null;
|
||||
}
|
||||
}
|
||||
|
||||
async negotiateRA2neAuthAsync() {
|
||||
this._hasStarted = true;
|
||||
// 1: Receive server public key
|
||||
await this._waitSockAsync(4);
|
||||
const serverKeyLengthBuffer = this._sock.rQslice(0, 4);
|
||||
const serverKeyLength = this._sock.rQshift32();
|
||||
if (serverKeyLength < 1024) {
|
||||
throw new Error("RA2: server public key is too short: " + serverKeyLength);
|
||||
} else if (serverKeyLength > 8192) {
|
||||
throw new Error("RA2: server public key is too long: " + serverKeyLength);
|
||||
}
|
||||
const serverKeyBytes = Math.ceil(serverKeyLength / 8);
|
||||
await this._waitSockAsync(serverKeyBytes * 2);
|
||||
const serverN = this._sock.rQshiftBytes(serverKeyBytes);
|
||||
const serverE = this._sock.rQshiftBytes(serverKeyBytes);
|
||||
const serverRSACipher = new RSACipher(serverKeyLength);
|
||||
serverRSACipher.setPublicKey(serverN, serverE);
|
||||
const serverPublickey = new Uint8Array(4 + serverKeyBytes * 2);
|
||||
serverPublickey.set(serverKeyLengthBuffer);
|
||||
serverPublickey.set(serverN, 4);
|
||||
serverPublickey.set(serverE, 4 + serverKeyBytes);
|
||||
|
||||
// verify server public key
|
||||
this.dispatchEvent(new CustomEvent("serververification", {
|
||||
detail: { type: "RSA", publickey: serverPublickey }
|
||||
}));
|
||||
await this._waitApproveKeyAsync();
|
||||
|
||||
// 2: Send client public key
|
||||
const clientKeyLength = 2048;
|
||||
const clientKeyBytes = Math.ceil(clientKeyLength / 8);
|
||||
const clientRSACipher = new RSACipher(clientKeyLength);
|
||||
await clientRSACipher.generateKey();
|
||||
const clientN = clientRSACipher.n;
|
||||
const clientE = clientRSACipher.e;
|
||||
const clientPublicKey = new Uint8Array(4 + clientKeyBytes * 2);
|
||||
clientPublicKey[0] = (clientKeyLength & 0xff000000) >>> 24;
|
||||
clientPublicKey[1] = (clientKeyLength & 0xff0000) >>> 16;
|
||||
clientPublicKey[2] = (clientKeyLength & 0xff00) >>> 8;
|
||||
clientPublicKey[3] = clientKeyLength & 0xff;
|
||||
clientPublicKey.set(clientN, 4);
|
||||
clientPublicKey.set(clientE, 4 + clientKeyBytes);
|
||||
this._sock.send(clientPublicKey);
|
||||
|
||||
// 3: Send client random
|
||||
const clientRandom = new Uint8Array(16);
|
||||
window.crypto.getRandomValues(clientRandom);
|
||||
const clientEncryptedRandom = serverRSACipher.encrypt(clientRandom);
|
||||
const clientRandomMessage = new Uint8Array(2 + serverKeyBytes);
|
||||
clientRandomMessage[0] = (serverKeyBytes & 0xff00) >>> 8;
|
||||
clientRandomMessage[1] = serverKeyBytes & 0xff;
|
||||
clientRandomMessage.set(clientEncryptedRandom, 2);
|
||||
this._sock.send(clientRandomMessage);
|
||||
|
||||
// 4: Receive server random
|
||||
await this._waitSockAsync(2);
|
||||
if (this._sock.rQshift16() !== clientKeyBytes) {
|
||||
throw new Error("RA2: wrong encrypted message length");
|
||||
}
|
||||
const serverEncryptedRandom = this._sock.rQshiftBytes(clientKeyBytes);
|
||||
const serverRandom = clientRSACipher.decrypt(serverEncryptedRandom);
|
||||
if (serverRandom === null || serverRandom.length !== 16) {
|
||||
throw new Error("RA2: corrupted server encrypted random");
|
||||
}
|
||||
|
||||
// 5: Compute session keys and set ciphers
|
||||
let clientSessionKey = new Uint8Array(32);
|
||||
let serverSessionKey = new Uint8Array(32);
|
||||
clientSessionKey.set(serverRandom);
|
||||
clientSessionKey.set(clientRandom, 16);
|
||||
serverSessionKey.set(clientRandom);
|
||||
serverSessionKey.set(serverRandom, 16);
|
||||
clientSessionKey = await window.crypto.subtle.digest("SHA-1", clientSessionKey);
|
||||
clientSessionKey = new Uint8Array(clientSessionKey).slice(0, 16);
|
||||
serverSessionKey = await window.crypto.subtle.digest("SHA-1", serverSessionKey);
|
||||
serverSessionKey = new Uint8Array(serverSessionKey).slice(0, 16);
|
||||
const clientCipher = new RA2Cipher();
|
||||
await clientCipher.setKey(clientSessionKey);
|
||||
const serverCipher = new RA2Cipher();
|
||||
await serverCipher.setKey(serverSessionKey);
|
||||
|
||||
// 6: Compute and exchange hashes
|
||||
let serverHash = new Uint8Array(8 + serverKeyBytes * 2 + clientKeyBytes * 2);
|
||||
let clientHash = new Uint8Array(8 + serverKeyBytes * 2 + clientKeyBytes * 2);
|
||||
serverHash.set(serverPublickey);
|
||||
serverHash.set(clientPublicKey, 4 + serverKeyBytes * 2);
|
||||
clientHash.set(clientPublicKey);
|
||||
clientHash.set(serverPublickey, 4 + clientKeyBytes * 2);
|
||||
serverHash = await window.crypto.subtle.digest("SHA-1", serverHash);
|
||||
clientHash = await window.crypto.subtle.digest("SHA-1", clientHash);
|
||||
serverHash = new Uint8Array(serverHash);
|
||||
clientHash = new Uint8Array(clientHash);
|
||||
this._sock.send(await clientCipher.makeMessage(clientHash));
|
||||
await this._waitSockAsync(2 + 20 + 16);
|
||||
if (this._sock.rQshift16() !== 20) {
|
||||
throw new Error("RA2: wrong server hash");
|
||||
}
|
||||
const serverHashReceived = await serverCipher.receiveMessage(
|
||||
20, this._sock.rQshiftBytes(20), this._sock.rQshiftBytes(16));
|
||||
if (serverHashReceived === null) {
|
||||
throw new Error("RA2: failed to authenticate the message");
|
||||
}
|
||||
for (let i = 0; i < 20; i++) {
|
||||
if (serverHashReceived[i] !== serverHash[i]) {
|
||||
throw new Error("RA2: wrong server hash");
|
||||
}
|
||||
}
|
||||
|
||||
// 7: Receive subtype
|
||||
await this._waitSockAsync(2 + 1 + 16);
|
||||
if (this._sock.rQshift16() !== 1) {
|
||||
throw new Error("RA2: wrong subtype");
|
||||
}
|
||||
let subtype = (await serverCipher.receiveMessage(
|
||||
1, this._sock.rQshiftBytes(1), this._sock.rQshiftBytes(16)));
|
||||
if (subtype === null) {
|
||||
throw new Error("RA2: failed to authenticate the message");
|
||||
}
|
||||
subtype = subtype[0];
|
||||
if (subtype === 1) {
|
||||
if (this._getCredentials().username === undefined ||
|
||||
this._getCredentials().password === undefined) {
|
||||
this.dispatchEvent(new CustomEvent(
|
||||
"credentialsrequired",
|
||||
{ detail: { types: ["username", "password"] } }));
|
||||
}
|
||||
} else if (subtype === 2) {
|
||||
if (this._getCredentials().password === undefined) {
|
||||
this.dispatchEvent(new CustomEvent(
|
||||
"credentialsrequired",
|
||||
{ detail: { types: ["password"] } }));
|
||||
}
|
||||
} else {
|
||||
throw new Error("RA2: wrong subtype");
|
||||
}
|
||||
await this._waitCredentialsAsync(subtype);
|
||||
let username;
|
||||
if (subtype === 1) {
|
||||
username = encodeUTF8(this._getCredentials().username).slice(0, 255);
|
||||
} else {
|
||||
username = "";
|
||||
}
|
||||
const password = encodeUTF8(this._getCredentials().password).slice(0, 255);
|
||||
const credentials = new Uint8Array(username.length + password.length + 2);
|
||||
credentials[0] = username.length;
|
||||
credentials[username.length + 1] = password.length;
|
||||
for (let i = 0; i < username.length; i++) {
|
||||
credentials[i + 1] = username.charCodeAt(i);
|
||||
}
|
||||
for (let i = 0; i < password.length; i++) {
|
||||
credentials[username.length + 2 + i] = password.charCodeAt(i);
|
||||
}
|
||||
this._sock.send(await clientCipher.makeMessage(credentials));
|
||||
}
|
||||
|
||||
get hasStarted() {
|
||||
return this._hasStarted;
|
||||
}
|
||||
|
||||
set hasStarted(s) {
|
||||
this._hasStarted = s;
|
||||
}
|
||||
}
|
||||
3373
backend/app/static/novnc/core/rfb.js
Normal file
3373
backend/app/static/novnc/core/rfb.js
Normal file
File diff suppressed because it is too large
Load Diff
152
backend/app/static/novnc/core/util/browser.js
Normal file
152
backend/app/static/novnc/core/util/browser.js
Normal file
@@ -0,0 +1,152 @@
|
||||
/*
|
||||
* noVNC: HTML5 VNC client
|
||||
* Copyright (C) 2019 The noVNC Authors
|
||||
* Licensed under MPL 2.0 (see LICENSE.txt)
|
||||
*
|
||||
* See README.md for usage and integration instructions.
|
||||
*
|
||||
* Browser feature support detection
|
||||
*/
|
||||
|
||||
import * as Log from './logging.js';
|
||||
|
||||
// Touch detection
|
||||
export let isTouchDevice = ('ontouchstart' in document.documentElement) ||
|
||||
// requried for Chrome debugger
|
||||
(document.ontouchstart !== undefined) ||
|
||||
// required for MS Surface
|
||||
(navigator.maxTouchPoints > 0) ||
|
||||
(navigator.msMaxTouchPoints > 0);
|
||||
window.addEventListener('touchstart', function onFirstTouch() {
|
||||
isTouchDevice = true;
|
||||
window.removeEventListener('touchstart', onFirstTouch, false);
|
||||
}, false);
|
||||
|
||||
|
||||
// The goal is to find a certain physical width, the devicePixelRatio
|
||||
// brings us a bit closer but is not optimal.
|
||||
export let dragThreshold = 10 * (window.devicePixelRatio || 1);
|
||||
|
||||
let _supportsCursorURIs = false;
|
||||
|
||||
try {
|
||||
const target = document.createElement('canvas');
|
||||
target.style.cursor = 'url("data:image/x-icon;base64,AAACAAEACAgAAAIAAgA4AQAAFgAAACgAAAAIAAAAEAAAAAEAIAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAD/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////AAAAAAAAAAAAAAAAAAAAAA==") 2 2, default';
|
||||
|
||||
if (target.style.cursor.indexOf("url") === 0) {
|
||||
Log.Info("Data URI scheme cursor supported");
|
||||
_supportsCursorURIs = true;
|
||||
} else {
|
||||
Log.Warn("Data URI scheme cursor not supported");
|
||||
}
|
||||
} catch (exc) {
|
||||
Log.Error("Data URI scheme cursor test exception: " + exc);
|
||||
}
|
||||
|
||||
export const supportsCursorURIs = _supportsCursorURIs;
|
||||
|
||||
let _hasScrollbarGutter = true;
|
||||
try {
|
||||
// Create invisible container
|
||||
const container = document.createElement('div');
|
||||
container.style.visibility = 'hidden';
|
||||
container.style.overflow = 'scroll'; // forcing scrollbars
|
||||
document.body.appendChild(container);
|
||||
|
||||
// Create a div and place it in the container
|
||||
const child = document.createElement('div');
|
||||
container.appendChild(child);
|
||||
|
||||
// Calculate the difference between the container's full width
|
||||
// and the child's width - the difference is the scrollbars
|
||||
const scrollbarWidth = (container.offsetWidth - child.offsetWidth);
|
||||
|
||||
// Clean up
|
||||
container.parentNode.removeChild(container);
|
||||
|
||||
_hasScrollbarGutter = scrollbarWidth != 0;
|
||||
} catch (exc) {
|
||||
Log.Error("Scrollbar test exception: " + exc);
|
||||
}
|
||||
export const hasScrollbarGutter = _hasScrollbarGutter;
|
||||
|
||||
/*
|
||||
* The functions for detection of platforms and browsers below are exported
|
||||
* but the use of these should be minimized as much as possible.
|
||||
*
|
||||
* It's better to use feature detection than platform detection.
|
||||
*/
|
||||
|
||||
/* OS */
|
||||
|
||||
export function isMac() {
|
||||
return !!(/mac/i).exec(navigator.platform);
|
||||
}
|
||||
|
||||
export function isWindows() {
|
||||
return !!(/win/i).exec(navigator.platform);
|
||||
}
|
||||
|
||||
export function isIOS() {
|
||||
return (!!(/ipad/i).exec(navigator.platform) ||
|
||||
!!(/iphone/i).exec(navigator.platform) ||
|
||||
!!(/ipod/i).exec(navigator.platform));
|
||||
}
|
||||
|
||||
export function isAndroid() {
|
||||
/* Android sets navigator.platform to Linux :/ */
|
||||
return !!navigator.userAgent.match('Android ');
|
||||
}
|
||||
|
||||
export function isChromeOS() {
|
||||
/* ChromeOS sets navigator.platform to Linux :/ */
|
||||
return !!navigator.userAgent.match(' CrOS ');
|
||||
}
|
||||
|
||||
/* Browser */
|
||||
|
||||
export function isSafari() {
|
||||
return !!navigator.userAgent.match('Safari/...') &&
|
||||
!navigator.userAgent.match('Chrome/...') &&
|
||||
!navigator.userAgent.match('Chromium/...') &&
|
||||
!navigator.userAgent.match('Epiphany/...');
|
||||
}
|
||||
|
||||
export function isFirefox() {
|
||||
return !!navigator.userAgent.match('Firefox/...') &&
|
||||
!navigator.userAgent.match('Seamonkey/...');
|
||||
}
|
||||
|
||||
export function isChrome() {
|
||||
return !!navigator.userAgent.match('Chrome/...') &&
|
||||
!navigator.userAgent.match('Chromium/...') &&
|
||||
!navigator.userAgent.match('Edg/...') &&
|
||||
!navigator.userAgent.match('OPR/...');
|
||||
}
|
||||
|
||||
export function isChromium() {
|
||||
return !!navigator.userAgent.match('Chromium/...');
|
||||
}
|
||||
|
||||
export function isOpera() {
|
||||
return !!navigator.userAgent.match('OPR/...');
|
||||
}
|
||||
|
||||
export function isEdge() {
|
||||
return !!navigator.userAgent.match('Edg/...');
|
||||
}
|
||||
|
||||
/* Engine */
|
||||
|
||||
export function isGecko() {
|
||||
return !!navigator.userAgent.match('Gecko/...');
|
||||
}
|
||||
|
||||
export function isWebKit() {
|
||||
return !!navigator.userAgent.match('AppleWebKit/...') &&
|
||||
!navigator.userAgent.match('Chrome/...');
|
||||
}
|
||||
|
||||
export function isBlink() {
|
||||
return !!navigator.userAgent.match('Chrome/...');
|
||||
}
|
||||
247
backend/app/static/novnc/core/util/cursor.js
Normal file
247
backend/app/static/novnc/core/util/cursor.js
Normal file
@@ -0,0 +1,247 @@
|
||||
/*
|
||||
* noVNC: HTML5 VNC client
|
||||
* Copyright (C) 2019 The noVNC Authors
|
||||
* Licensed under MPL 2.0 or any later version (see LICENSE.txt)
|
||||
*/
|
||||
|
||||
import { supportsCursorURIs, isTouchDevice } from './browser.js';
|
||||
|
||||
const useFallback = !supportsCursorURIs || isTouchDevice;
|
||||
|
||||
export default class Cursor {
|
||||
constructor() {
|
||||
this._target = null;
|
||||
|
||||
this._canvas = document.createElement('canvas');
|
||||
|
||||
if (useFallback) {
|
||||
this._canvas.style.position = 'fixed';
|
||||
this._canvas.style.zIndex = '65535';
|
||||
this._canvas.style.pointerEvents = 'none';
|
||||
// Safari on iOS can select the cursor image
|
||||
// https://bugs.webkit.org/show_bug.cgi?id=249223
|
||||
this._canvas.style.userSelect = 'none';
|
||||
this._canvas.style.WebkitUserSelect = 'none';
|
||||
// Can't use "display" because of Firefox bug #1445997
|
||||
this._canvas.style.visibility = 'hidden';
|
||||
}
|
||||
|
||||
this._position = { x: 0, y: 0 };
|
||||
this._hotSpot = { x: 0, y: 0 };
|
||||
|
||||
this._eventHandlers = {
|
||||
'mouseover': this._handleMouseOver.bind(this),
|
||||
'mouseleave': this._handleMouseLeave.bind(this),
|
||||
'mousemove': this._handleMouseMove.bind(this),
|
||||
'mouseup': this._handleMouseUp.bind(this),
|
||||
};
|
||||
}
|
||||
|
||||
attach(target) {
|
||||
if (this._target) {
|
||||
this.detach();
|
||||
}
|
||||
|
||||
this._target = target;
|
||||
|
||||
if (useFallback) {
|
||||
document.body.appendChild(this._canvas);
|
||||
|
||||
const options = { capture: true, passive: true };
|
||||
this._target.addEventListener('mouseover', this._eventHandlers.mouseover, options);
|
||||
this._target.addEventListener('mouseleave', this._eventHandlers.mouseleave, options);
|
||||
this._target.addEventListener('mousemove', this._eventHandlers.mousemove, options);
|
||||
this._target.addEventListener('mouseup', this._eventHandlers.mouseup, options);
|
||||
}
|
||||
|
||||
this.clear();
|
||||
}
|
||||
|
||||
detach() {
|
||||
if (!this._target) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (useFallback) {
|
||||
const options = { capture: true, passive: true };
|
||||
this._target.removeEventListener('mouseover', this._eventHandlers.mouseover, options);
|
||||
this._target.removeEventListener('mouseleave', this._eventHandlers.mouseleave, options);
|
||||
this._target.removeEventListener('mousemove', this._eventHandlers.mousemove, options);
|
||||
this._target.removeEventListener('mouseup', this._eventHandlers.mouseup, options);
|
||||
|
||||
document.body.removeChild(this._canvas);
|
||||
}
|
||||
|
||||
this._target = null;
|
||||
}
|
||||
|
||||
change(rgba, hotx, hoty, w, h) {
|
||||
if ((w === 0) || (h === 0)) {
|
||||
this.clear();
|
||||
return;
|
||||
}
|
||||
|
||||
this._position.x = this._position.x + this._hotSpot.x - hotx;
|
||||
this._position.y = this._position.y + this._hotSpot.y - hoty;
|
||||
this._hotSpot.x = hotx;
|
||||
this._hotSpot.y = hoty;
|
||||
|
||||
let ctx = this._canvas.getContext('2d');
|
||||
|
||||
this._canvas.width = w;
|
||||
this._canvas.height = h;
|
||||
|
||||
let img = new ImageData(new Uint8ClampedArray(rgba), w, h);
|
||||
ctx.clearRect(0, 0, w, h);
|
||||
ctx.putImageData(img, 0, 0);
|
||||
|
||||
if (useFallback) {
|
||||
this._updatePosition();
|
||||
} else {
|
||||
let url = this._canvas.toDataURL();
|
||||
this._target.style.cursor = 'url(' + url + ')' + hotx + ' ' + hoty + ', default';
|
||||
}
|
||||
}
|
||||
|
||||
clear() {
|
||||
this._target.style.cursor = 'none';
|
||||
this._canvas.width = 0;
|
||||
this._canvas.height = 0;
|
||||
this._position.x = this._position.x + this._hotSpot.x;
|
||||
this._position.y = this._position.y + this._hotSpot.y;
|
||||
this._hotSpot.x = 0;
|
||||
this._hotSpot.y = 0;
|
||||
}
|
||||
|
||||
// Mouse events might be emulated, this allows
|
||||
// moving the cursor in such cases
|
||||
move(clientX, clientY) {
|
||||
if (!useFallback) {
|
||||
return;
|
||||
}
|
||||
// clientX/clientY are relative the _visual viewport_,
|
||||
// but our position is relative the _layout viewport_,
|
||||
// so try to compensate when we can
|
||||
if (window.visualViewport) {
|
||||
this._position.x = clientX + window.visualViewport.offsetLeft;
|
||||
this._position.y = clientY + window.visualViewport.offsetTop;
|
||||
} else {
|
||||
this._position.x = clientX;
|
||||
this._position.y = clientY;
|
||||
}
|
||||
this._updatePosition();
|
||||
let target = document.elementFromPoint(clientX, clientY);
|
||||
this._updateVisibility(target);
|
||||
}
|
||||
|
||||
_handleMouseOver(event) {
|
||||
// This event could be because we're entering the target, or
|
||||
// moving around amongst its sub elements. Let the move handler
|
||||
// sort things out.
|
||||
this._handleMouseMove(event);
|
||||
}
|
||||
|
||||
_handleMouseLeave(event) {
|
||||
// Check if we should show the cursor on the element we are leaving to
|
||||
this._updateVisibility(event.relatedTarget);
|
||||
}
|
||||
|
||||
_handleMouseMove(event) {
|
||||
this._updateVisibility(event.target);
|
||||
|
||||
this._position.x = event.clientX - this._hotSpot.x;
|
||||
this._position.y = event.clientY - this._hotSpot.y;
|
||||
|
||||
this._updatePosition();
|
||||
}
|
||||
|
||||
_handleMouseUp(event) {
|
||||
// We might get this event because of a drag operation that
|
||||
// moved outside of the target. Check what's under the cursor
|
||||
// now and adjust visibility based on that.
|
||||
let target = document.elementFromPoint(event.clientX, event.clientY);
|
||||
this._updateVisibility(target);
|
||||
|
||||
// Captures end with a mouseup but we can't know the event order of
|
||||
// mouseup vs releaseCapture.
|
||||
//
|
||||
// In the cases when releaseCapture comes first, the code above is
|
||||
// enough.
|
||||
//
|
||||
// In the cases when the mouseup comes first, we need wait for the
|
||||
// browser to flush all events and then check again if the cursor
|
||||
// should be visible.
|
||||
if (this._captureIsActive()) {
|
||||
window.setTimeout(() => {
|
||||
// We might have detached at this point
|
||||
if (!this._target) {
|
||||
return;
|
||||
}
|
||||
// Refresh the target from elementFromPoint since queued events
|
||||
// might have altered the DOM
|
||||
target = document.elementFromPoint(event.clientX,
|
||||
event.clientY);
|
||||
this._updateVisibility(target);
|
||||
}, 0);
|
||||
}
|
||||
}
|
||||
|
||||
_showCursor() {
|
||||
if (this._canvas.style.visibility === 'hidden') {
|
||||
this._canvas.style.visibility = '';
|
||||
}
|
||||
}
|
||||
|
||||
_hideCursor() {
|
||||
if (this._canvas.style.visibility !== 'hidden') {
|
||||
this._canvas.style.visibility = 'hidden';
|
||||
}
|
||||
}
|
||||
|
||||
// Should we currently display the cursor?
|
||||
// (i.e. are we over the target, or a child of the target without a
|
||||
// different cursor set)
|
||||
_shouldShowCursor(target) {
|
||||
if (!target) {
|
||||
return false;
|
||||
}
|
||||
// Easy case
|
||||
if (target === this._target) {
|
||||
return true;
|
||||
}
|
||||
// Other part of the DOM?
|
||||
if (!this._target.contains(target)) {
|
||||
return false;
|
||||
}
|
||||
// Has the child its own cursor?
|
||||
// FIXME: How can we tell that a sub element has an
|
||||
// explicit "cursor: none;"?
|
||||
if (window.getComputedStyle(target).cursor !== 'none') {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
_updateVisibility(target) {
|
||||
// When the cursor target has capture we want to show the cursor.
|
||||
// So, if a capture is active - look at the captured element instead.
|
||||
if (this._captureIsActive()) {
|
||||
target = document.captureElement;
|
||||
}
|
||||
if (this._shouldShowCursor(target)) {
|
||||
this._showCursor();
|
||||
} else {
|
||||
this._hideCursor();
|
||||
}
|
||||
}
|
||||
|
||||
_updatePosition() {
|
||||
this._canvas.style.left = this._position.x + "px";
|
||||
this._canvas.style.top = this._position.y + "px";
|
||||
}
|
||||
|
||||
_captureIsActive() {
|
||||
return document.captureElement &&
|
||||
document.documentElement.contains(document.captureElement);
|
||||
}
|
||||
}
|
||||
32
backend/app/static/novnc/core/util/element.js
Normal file
32
backend/app/static/novnc/core/util/element.js
Normal file
@@ -0,0 +1,32 @@
|
||||
/*
|
||||
* noVNC: HTML5 VNC client
|
||||
* Copyright (C) 2020 The noVNC Authors
|
||||
* Licensed under MPL 2.0 (see LICENSE.txt)
|
||||
*
|
||||
* See README.md for usage and integration instructions.
|
||||
*/
|
||||
|
||||
/*
|
||||
* HTML element utility functions
|
||||
*/
|
||||
|
||||
export function clientToElement(x, y, elem) {
|
||||
const bounds = elem.getBoundingClientRect();
|
||||
let pos = { x: 0, y: 0 };
|
||||
// Clip to target bounds
|
||||
if (x < bounds.left) {
|
||||
pos.x = 0;
|
||||
} else if (x >= bounds.right) {
|
||||
pos.x = bounds.width - 1;
|
||||
} else {
|
||||
pos.x = x - bounds.left;
|
||||
}
|
||||
if (y < bounds.top) {
|
||||
pos.y = 0;
|
||||
} else if (y >= bounds.bottom) {
|
||||
pos.y = bounds.height - 1;
|
||||
} else {
|
||||
pos.y = y - bounds.top;
|
||||
}
|
||||
return pos;
|
||||
}
|
||||
138
backend/app/static/novnc/core/util/events.js
Normal file
138
backend/app/static/novnc/core/util/events.js
Normal file
@@ -0,0 +1,138 @@
|
||||
/*
|
||||
* noVNC: HTML5 VNC client
|
||||
* Copyright (C) 2018 The noVNC Authors
|
||||
* Licensed under MPL 2.0 (see LICENSE.txt)
|
||||
*
|
||||
* See README.md for usage and integration instructions.
|
||||
*/
|
||||
|
||||
/*
|
||||
* Cross-browser event and position routines
|
||||
*/
|
||||
|
||||
export function getPointerEvent(e) {
|
||||
return e.changedTouches ? e.changedTouches[0] : e.touches ? e.touches[0] : e;
|
||||
}
|
||||
|
||||
export function stopEvent(e) {
|
||||
e.stopPropagation();
|
||||
e.preventDefault();
|
||||
}
|
||||
|
||||
// Emulate Element.setCapture() when not supported
|
||||
let _captureRecursion = false;
|
||||
let _elementForUnflushedEvents = null;
|
||||
document.captureElement = null;
|
||||
function _captureProxy(e) {
|
||||
// Recursion protection as we'll see our own event
|
||||
if (_captureRecursion) return;
|
||||
|
||||
// Clone the event as we cannot dispatch an already dispatched event
|
||||
const newEv = new e.constructor(e.type, e);
|
||||
|
||||
_captureRecursion = true;
|
||||
if (document.captureElement) {
|
||||
document.captureElement.dispatchEvent(newEv);
|
||||
} else {
|
||||
_elementForUnflushedEvents.dispatchEvent(newEv);
|
||||
}
|
||||
_captureRecursion = false;
|
||||
|
||||
// Avoid double events
|
||||
e.stopPropagation();
|
||||
|
||||
// Respect the wishes of the redirected event handlers
|
||||
if (newEv.defaultPrevented) {
|
||||
e.preventDefault();
|
||||
}
|
||||
|
||||
// Implicitly release the capture on button release
|
||||
if (e.type === "mouseup") {
|
||||
releaseCapture();
|
||||
}
|
||||
}
|
||||
|
||||
// Follow cursor style of target element
|
||||
function _capturedElemChanged() {
|
||||
const proxyElem = document.getElementById("noVNC_mouse_capture_elem");
|
||||
proxyElem.style.cursor = window.getComputedStyle(document.captureElement).cursor;
|
||||
}
|
||||
|
||||
const _captureObserver = new MutationObserver(_capturedElemChanged);
|
||||
|
||||
export function setCapture(target) {
|
||||
if (target.setCapture) {
|
||||
|
||||
target.setCapture();
|
||||
document.captureElement = target;
|
||||
} else {
|
||||
// Release any existing capture in case this method is
|
||||
// called multiple times without coordination
|
||||
releaseCapture();
|
||||
|
||||
let proxyElem = document.getElementById("noVNC_mouse_capture_elem");
|
||||
|
||||
if (proxyElem === null) {
|
||||
proxyElem = document.createElement("div");
|
||||
proxyElem.id = "noVNC_mouse_capture_elem";
|
||||
proxyElem.style.position = "fixed";
|
||||
proxyElem.style.top = "0px";
|
||||
proxyElem.style.left = "0px";
|
||||
proxyElem.style.width = "100%";
|
||||
proxyElem.style.height = "100%";
|
||||
proxyElem.style.zIndex = 10000;
|
||||
proxyElem.style.display = "none";
|
||||
document.body.appendChild(proxyElem);
|
||||
|
||||
// This is to make sure callers don't get confused by having
|
||||
// our blocking element as the target
|
||||
proxyElem.addEventListener('contextmenu', _captureProxy);
|
||||
|
||||
proxyElem.addEventListener('mousemove', _captureProxy);
|
||||
proxyElem.addEventListener('mouseup', _captureProxy);
|
||||
}
|
||||
|
||||
document.captureElement = target;
|
||||
|
||||
// Track cursor and get initial cursor
|
||||
_captureObserver.observe(target, {attributes: true});
|
||||
_capturedElemChanged();
|
||||
|
||||
proxyElem.style.display = "";
|
||||
|
||||
// We listen to events on window in order to keep tracking if it
|
||||
// happens to leave the viewport
|
||||
window.addEventListener('mousemove', _captureProxy);
|
||||
window.addEventListener('mouseup', _captureProxy);
|
||||
}
|
||||
}
|
||||
|
||||
export function releaseCapture() {
|
||||
if (document.releaseCapture) {
|
||||
|
||||
document.releaseCapture();
|
||||
document.captureElement = null;
|
||||
|
||||
} else {
|
||||
if (!document.captureElement) {
|
||||
return;
|
||||
}
|
||||
|
||||
// There might be events already queued. The event proxy needs
|
||||
// access to the captured element for these queued events.
|
||||
// E.g. contextmenu (right-click) in Microsoft Edge
|
||||
//
|
||||
// Before removing the capturedElem pointer we save it to a
|
||||
// temporary variable that the unflushed events can use.
|
||||
_elementForUnflushedEvents = document.captureElement;
|
||||
document.captureElement = null;
|
||||
|
||||
_captureObserver.disconnect();
|
||||
|
||||
const proxyElem = document.getElementById("noVNC_mouse_capture_elem");
|
||||
proxyElem.style.display = "none";
|
||||
|
||||
window.removeEventListener('mousemove', _captureProxy);
|
||||
window.removeEventListener('mouseup', _captureProxy);
|
||||
}
|
||||
}
|
||||
35
backend/app/static/novnc/core/util/eventtarget.js
Normal file
35
backend/app/static/novnc/core/util/eventtarget.js
Normal file
@@ -0,0 +1,35 @@
|
||||
/*
|
||||
* noVNC: HTML5 VNC client
|
||||
* Copyright (C) 2019 The noVNC Authors
|
||||
* Licensed under MPL 2.0 (see LICENSE.txt)
|
||||
*
|
||||
* See README.md for usage and integration instructions.
|
||||
*/
|
||||
|
||||
export default class EventTargetMixin {
|
||||
constructor() {
|
||||
this._listeners = new Map();
|
||||
}
|
||||
|
||||
addEventListener(type, callback) {
|
||||
if (!this._listeners.has(type)) {
|
||||
this._listeners.set(type, new Set());
|
||||
}
|
||||
this._listeners.get(type).add(callback);
|
||||
}
|
||||
|
||||
removeEventListener(type, callback) {
|
||||
if (this._listeners.has(type)) {
|
||||
this._listeners.get(type).delete(callback);
|
||||
}
|
||||
}
|
||||
|
||||
dispatchEvent(event) {
|
||||
if (!this._listeners.has(event.type)) {
|
||||
return true;
|
||||
}
|
||||
this._listeners.get(event.type)
|
||||
.forEach(callback => callback.call(this, event));
|
||||
return !event.defaultPrevented;
|
||||
}
|
||||
}
|
||||
15
backend/app/static/novnc/core/util/int.js
Normal file
15
backend/app/static/novnc/core/util/int.js
Normal file
@@ -0,0 +1,15 @@
|
||||
/*
|
||||
* noVNC: HTML5 VNC client
|
||||
* Copyright (C) 2020 The noVNC Authors
|
||||
* Licensed under MPL 2.0 (see LICENSE.txt)
|
||||
*
|
||||
* See README.md for usage and integration instructions.
|
||||
*/
|
||||
|
||||
export function toUnsigned32bit(toConvert) {
|
||||
return toConvert >>> 0;
|
||||
}
|
||||
|
||||
export function toSigned32bit(toConvert) {
|
||||
return toConvert | 0;
|
||||
}
|
||||
56
backend/app/static/novnc/core/util/logging.js
Normal file
56
backend/app/static/novnc/core/util/logging.js
Normal file
@@ -0,0 +1,56 @@
|
||||
/*
|
||||
* noVNC: HTML5 VNC client
|
||||
* Copyright (C) 2019 The noVNC Authors
|
||||
* Licensed under MPL 2.0 (see LICENSE.txt)
|
||||
*
|
||||
* See README.md for usage and integration instructions.
|
||||
*/
|
||||
|
||||
/*
|
||||
* Logging/debug routines
|
||||
*/
|
||||
|
||||
let _logLevel = 'warn';
|
||||
|
||||
let Debug = () => {};
|
||||
let Info = () => {};
|
||||
let Warn = () => {};
|
||||
let Error = () => {};
|
||||
|
||||
export function initLogging(level) {
|
||||
if (typeof level === 'undefined') {
|
||||
level = _logLevel;
|
||||
} else {
|
||||
_logLevel = level;
|
||||
}
|
||||
|
||||
Debug = Info = Warn = Error = () => {};
|
||||
|
||||
if (typeof window.console !== "undefined") {
|
||||
/* eslint-disable no-console, no-fallthrough */
|
||||
switch (level) {
|
||||
case 'debug':
|
||||
Debug = console.debug.bind(window.console);
|
||||
case 'info':
|
||||
Info = console.info.bind(window.console);
|
||||
case 'warn':
|
||||
Warn = console.warn.bind(window.console);
|
||||
case 'error':
|
||||
Error = console.error.bind(window.console);
|
||||
case 'none':
|
||||
break;
|
||||
default:
|
||||
throw new window.Error("invalid logging type '" + level + "'");
|
||||
}
|
||||
/* eslint-enable no-console, no-fallthrough */
|
||||
}
|
||||
}
|
||||
|
||||
export function getLogging() {
|
||||
return _logLevel;
|
||||
}
|
||||
|
||||
export { Debug, Info, Warn, Error };
|
||||
|
||||
// Initialize logging level
|
||||
initLogging();
|
||||
79
backend/app/static/novnc/core/util/md5.js
Normal file
79
backend/app/static/novnc/core/util/md5.js
Normal file
@@ -0,0 +1,79 @@
|
||||
/*
|
||||
* noVNC: HTML5 VNC client
|
||||
* Copyright (C) 2021 The noVNC Authors
|
||||
* Licensed under MPL 2.0 (see LICENSE.txt)
|
||||
*
|
||||
* See README.md for usage and integration instructions.
|
||||
*/
|
||||
|
||||
/*
|
||||
* Performs MD5 hashing on a string of binary characters, returns an array of bytes
|
||||
*/
|
||||
|
||||
export function MD5(d) {
|
||||
let r = M(V(Y(X(d), 8 * d.length)));
|
||||
return r;
|
||||
}
|
||||
|
||||
function M(d) {
|
||||
let f = new Uint8Array(d.length);
|
||||
for (let i=0;i<d.length;i++) {
|
||||
f[i] = d.charCodeAt(i);
|
||||
}
|
||||
return f;
|
||||
}
|
||||
|
||||
function X(d) {
|
||||
let r = Array(d.length >> 2);
|
||||
for (let m = 0; m < r.length; m++) r[m] = 0;
|
||||
for (let m = 0; m < 8 * d.length; m += 8) r[m >> 5] |= (255 & d.charCodeAt(m / 8)) << m % 32;
|
||||
return r;
|
||||
}
|
||||
|
||||
function V(d) {
|
||||
let r = "";
|
||||
for (let m = 0; m < 32 * d.length; m += 8) r += String.fromCharCode(d[m >> 5] >>> m % 32 & 255);
|
||||
return r;
|
||||
}
|
||||
|
||||
function Y(d, g) {
|
||||
d[g >> 5] |= 128 << g % 32, d[14 + (g + 64 >>> 9 << 4)] = g;
|
||||
let m = 1732584193, f = -271733879, r = -1732584194, i = 271733878;
|
||||
for (let n = 0; n < d.length; n += 16) {
|
||||
let h = m,
|
||||
t = f,
|
||||
g = r,
|
||||
e = i;
|
||||
f = ii(f = ii(f = ii(f = ii(f = hh(f = hh(f = hh(f = hh(f = gg(f = gg(f = gg(f = gg(f = ff(f = ff(f = ff(f = ff(f, r = ff(r, i = ff(i, m = ff(m, f, r, i, d[n + 0], 7, -680876936), f, r, d[n + 1], 12, -389564586), m, f, d[n + 2], 17, 606105819), i, m, d[n + 3], 22, -1044525330), r = ff(r, i = ff(i, m = ff(m, f, r, i, d[n + 4], 7, -176418897), f, r, d[n + 5], 12, 1200080426), m, f, d[n + 6], 17, -1473231341), i, m, d[n + 7], 22, -45705983), r = ff(r, i = ff(i, m = ff(m, f, r, i, d[n + 8], 7, 1770035416), f, r, d[n + 9], 12, -1958414417), m, f, d[n + 10], 17, -42063), i, m, d[n + 11], 22, -1990404162), r = ff(r, i = ff(i, m = ff(m, f, r, i, d[n + 12], 7, 1804603682), f, r, d[n + 13], 12, -40341101), m, f, d[n + 14], 17, -1502002290), i, m, d[n + 15], 22, 1236535329), r = gg(r, i = gg(i, m = gg(m, f, r, i, d[n + 1], 5, -165796510), f, r, d[n + 6], 9, -1069501632), m, f, d[n + 11], 14, 643717713), i, m, d[n + 0], 20, -373897302), r = gg(r, i = gg(i, m = gg(m, f, r, i, d[n + 5], 5, -701558691), f, r, d[n + 10], 9, 38016083), m, f, d[n + 15], 14, -660478335), i, m, d[n + 4], 20, -405537848), r = gg(r, i = gg(i, m = gg(m, f, r, i, d[n + 9], 5, 568446438), f, r, d[n + 14], 9, -1019803690), m, f, d[n + 3], 14, -187363961), i, m, d[n + 8], 20, 1163531501), r = gg(r, i = gg(i, m = gg(m, f, r, i, d[n + 13], 5, -1444681467), f, r, d[n + 2], 9, -51403784), m, f, d[n + 7], 14, 1735328473), i, m, d[n + 12], 20, -1926607734), r = hh(r, i = hh(i, m = hh(m, f, r, i, d[n + 5], 4, -378558), f, r, d[n + 8], 11, -2022574463), m, f, d[n + 11], 16, 1839030562), i, m, d[n + 14], 23, -35309556), r = hh(r, i = hh(i, m = hh(m, f, r, i, d[n + 1], 4, -1530992060), f, r, d[n + 4], 11, 1272893353), m, f, d[n + 7], 16, -155497632), i, m, d[n + 10], 23, -1094730640), r = hh(r, i = hh(i, m = hh(m, f, r, i, d[n + 13], 4, 681279174), f, r, d[n + 0], 11, -358537222), m, f, d[n + 3], 16, -722521979), i, m, d[n + 6], 23, 76029189), r = hh(r, i = hh(i, m = hh(m, f, r, i, d[n + 9], 4, -640364487), f, r, d[n + 12], 11, -421815835), m, f, d[n + 15], 16, 530742520), i, m, d[n + 2], 23, -995338651), r = ii(r, i = ii(i, m = ii(m, f, r, i, d[n + 0], 6, -198630844), f, r, d[n + 7], 10, 1126891415), m, f, d[n + 14], 15, -1416354905), i, m, d[n + 5], 21, -57434055), r = ii(r, i = ii(i, m = ii(m, f, r, i, d[n + 12], 6, 1700485571), f, r, d[n + 3], 10, -1894986606), m, f, d[n + 10], 15, -1051523), i, m, d[n + 1], 21, -2054922799), r = ii(r, i = ii(i, m = ii(m, f, r, i, d[n + 8], 6, 1873313359), f, r, d[n + 15], 10, -30611744), m, f, d[n + 6], 15, -1560198380), i, m, d[n + 13], 21, 1309151649), r = ii(r, i = ii(i, m = ii(m, f, r, i, d[n + 4], 6, -145523070), f, r, d[n + 11], 10, -1120210379), m, f, d[n + 2], 15, 718787259), i, m, d[n + 9], 21, -343485551), m = add(m, h), f = add(f, t), r = add(r, g), i = add(i, e);
|
||||
}
|
||||
return Array(m, f, r, i);
|
||||
}
|
||||
|
||||
function cmn(d, g, m, f, r, i) {
|
||||
return add(rol(add(add(g, d), add(f, i)), r), m);
|
||||
}
|
||||
|
||||
function ff(d, g, m, f, r, i, n) {
|
||||
return cmn(g & m | ~g & f, d, g, r, i, n);
|
||||
}
|
||||
|
||||
function gg(d, g, m, f, r, i, n) {
|
||||
return cmn(g & f | m & ~f, d, g, r, i, n);
|
||||
}
|
||||
|
||||
function hh(d, g, m, f, r, i, n) {
|
||||
return cmn(g ^ m ^ f, d, g, r, i, n);
|
||||
}
|
||||
|
||||
function ii(d, g, m, f, r, i, n) {
|
||||
return cmn(m ^ (g | ~f), d, g, r, i, n);
|
||||
}
|
||||
|
||||
function add(d, g) {
|
||||
let m = (65535 & d) + (65535 & g);
|
||||
return (d >> 16) + (g >> 16) + (m >> 16) << 16 | 65535 & m;
|
||||
}
|
||||
|
||||
function rol(d, g) {
|
||||
return d << g | d >>> 32 - g;
|
||||
}
|
||||
28
backend/app/static/novnc/core/util/strings.js
Normal file
28
backend/app/static/novnc/core/util/strings.js
Normal file
@@ -0,0 +1,28 @@
|
||||
/*
|
||||
* noVNC: HTML5 VNC client
|
||||
* Copyright (C) 2019 The noVNC Authors
|
||||
* Licensed under MPL 2.0 (see LICENSE.txt)
|
||||
*
|
||||
* See README.md for usage and integration instructions.
|
||||
*/
|
||||
|
||||
// Decode from UTF-8
|
||||
export function decodeUTF8(utf8string, allowLatin1=false) {
|
||||
try {
|
||||
return decodeURIComponent(escape(utf8string));
|
||||
} catch (e) {
|
||||
if (e instanceof URIError) {
|
||||
if (allowLatin1) {
|
||||
// If we allow Latin1 we can ignore any decoding fails
|
||||
// and in these cases return the original string
|
||||
return utf8string;
|
||||
}
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
// Encode to UTF-8
|
||||
export function encodeUTF8(DOMString) {
|
||||
return unescape(encodeURIComponent(DOMString));
|
||||
}
|
||||
353
backend/app/static/novnc/core/websock.js
Normal file
353
backend/app/static/novnc/core/websock.js
Normal file
@@ -0,0 +1,353 @@
|
||||
/*
|
||||
* Websock: high-performance buffering wrapper
|
||||
* Copyright (C) 2019 The noVNC Authors
|
||||
* Licensed under MPL 2.0 (see LICENSE.txt)
|
||||
*
|
||||
* Websock is similar to the standard WebSocket / RTCDataChannel object
|
||||
* but with extra buffer handling.
|
||||
*
|
||||
* Websock has built-in receive queue buffering; the message event
|
||||
* does not contain actual data but is simply a notification that
|
||||
* there is new data available. Several rQ* methods are available to
|
||||
* read binary data off of the receive queue.
|
||||
*/
|
||||
|
||||
import * as Log from './util/logging.js';
|
||||
|
||||
// this has performance issues in some versions Chromium, and
|
||||
// doesn't gain a tremendous amount of performance increase in Firefox
|
||||
// at the moment. It may be valuable to turn it on in the future.
|
||||
const MAX_RQ_GROW_SIZE = 40 * 1024 * 1024; // 40 MiB
|
||||
|
||||
// Constants pulled from RTCDataChannelState enum
|
||||
// https://developer.mozilla.org/en-US/docs/Web/API/RTCDataChannel/readyState#RTCDataChannelState_enum
|
||||
const DataChannel = {
|
||||
CONNECTING: "connecting",
|
||||
OPEN: "open",
|
||||
CLOSING: "closing",
|
||||
CLOSED: "closed"
|
||||
};
|
||||
|
||||
const ReadyStates = {
|
||||
CONNECTING: [WebSocket.CONNECTING, DataChannel.CONNECTING],
|
||||
OPEN: [WebSocket.OPEN, DataChannel.OPEN],
|
||||
CLOSING: [WebSocket.CLOSING, DataChannel.CLOSING],
|
||||
CLOSED: [WebSocket.CLOSED, DataChannel.CLOSED],
|
||||
};
|
||||
|
||||
// Properties a raw channel must have, WebSocket and RTCDataChannel are two examples
|
||||
const rawChannelProps = [
|
||||
"send",
|
||||
"close",
|
||||
"binaryType",
|
||||
"onerror",
|
||||
"onmessage",
|
||||
"onopen",
|
||||
"protocol",
|
||||
"readyState",
|
||||
];
|
||||
|
||||
export default class Websock {
|
||||
constructor() {
|
||||
this._websocket = null; // WebSocket or RTCDataChannel object
|
||||
|
||||
this._rQi = 0; // Receive queue index
|
||||
this._rQlen = 0; // Next write position in the receive queue
|
||||
this._rQbufferSize = 1024 * 1024 * 4; // Receive queue buffer size (4 MiB)
|
||||
// called in init: this._rQ = new Uint8Array(this._rQbufferSize);
|
||||
this._rQ = null; // Receive queue
|
||||
|
||||
this._sQbufferSize = 1024 * 10; // 10 KiB
|
||||
// called in init: this._sQ = new Uint8Array(this._sQbufferSize);
|
||||
this._sQlen = 0;
|
||||
this._sQ = null; // Send queue
|
||||
|
||||
this._eventHandlers = {
|
||||
message: () => {},
|
||||
open: () => {},
|
||||
close: () => {},
|
||||
error: () => {}
|
||||
};
|
||||
}
|
||||
|
||||
// Getters and Setters
|
||||
|
||||
get readyState() {
|
||||
let subState;
|
||||
|
||||
if (this._websocket === null) {
|
||||
return "unused";
|
||||
}
|
||||
|
||||
subState = this._websocket.readyState;
|
||||
|
||||
if (ReadyStates.CONNECTING.includes(subState)) {
|
||||
return "connecting";
|
||||
} else if (ReadyStates.OPEN.includes(subState)) {
|
||||
return "open";
|
||||
} else if (ReadyStates.CLOSING.includes(subState)) {
|
||||
return "closing";
|
||||
} else if (ReadyStates.CLOSED.includes(subState)) {
|
||||
return "closed";
|
||||
}
|
||||
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
get sQ() {
|
||||
return this._sQ;
|
||||
}
|
||||
|
||||
get rQ() {
|
||||
return this._rQ;
|
||||
}
|
||||
|
||||
get rQi() {
|
||||
return this._rQi;
|
||||
}
|
||||
|
||||
set rQi(val) {
|
||||
this._rQi = val;
|
||||
}
|
||||
|
||||
// Receive Queue
|
||||
get rQlen() {
|
||||
return this._rQlen - this._rQi;
|
||||
}
|
||||
|
||||
rQpeek8() {
|
||||
return this._rQ[this._rQi];
|
||||
}
|
||||
|
||||
rQskipBytes(bytes) {
|
||||
this._rQi += bytes;
|
||||
}
|
||||
|
||||
rQshift8() {
|
||||
return this._rQshift(1);
|
||||
}
|
||||
|
||||
rQshift16() {
|
||||
return this._rQshift(2);
|
||||
}
|
||||
|
||||
rQshift32() {
|
||||
return this._rQshift(4);
|
||||
}
|
||||
|
||||
// TODO(directxman12): test performance with these vs a DataView
|
||||
_rQshift(bytes) {
|
||||
let res = 0;
|
||||
for (let byte = bytes - 1; byte >= 0; byte--) {
|
||||
res += this._rQ[this._rQi++] << (byte * 8);
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
rQshiftStr(len) {
|
||||
if (typeof(len) === 'undefined') { len = this.rQlen; }
|
||||
let str = "";
|
||||
// Handle large arrays in steps to avoid long strings on the stack
|
||||
for (let i = 0; i < len; i += 4096) {
|
||||
let part = this.rQshiftBytes(Math.min(4096, len - i));
|
||||
str += String.fromCharCode.apply(null, part);
|
||||
}
|
||||
return str;
|
||||
}
|
||||
|
||||
rQshiftBytes(len) {
|
||||
if (typeof(len) === 'undefined') { len = this.rQlen; }
|
||||
this._rQi += len;
|
||||
return new Uint8Array(this._rQ.buffer, this._rQi - len, len);
|
||||
}
|
||||
|
||||
rQshiftTo(target, len) {
|
||||
if (len === undefined) { len = this.rQlen; }
|
||||
// TODO: make this just use set with views when using a ArrayBuffer to store the rQ
|
||||
target.set(new Uint8Array(this._rQ.buffer, this._rQi, len));
|
||||
this._rQi += len;
|
||||
}
|
||||
|
||||
rQslice(start, end = this.rQlen) {
|
||||
return new Uint8Array(this._rQ.buffer, this._rQi + start, end - start);
|
||||
}
|
||||
|
||||
// Check to see if we must wait for 'num' bytes (default to FBU.bytes)
|
||||
// to be available in the receive queue. Return true if we need to
|
||||
// wait (and possibly print a debug message), otherwise false.
|
||||
rQwait(msg, num, goback) {
|
||||
if (this.rQlen < num) {
|
||||
if (goback) {
|
||||
if (this._rQi < goback) {
|
||||
throw new Error("rQwait cannot backup " + goback + " bytes");
|
||||
}
|
||||
this._rQi -= goback;
|
||||
}
|
||||
return true; // true means need more data
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Send Queue
|
||||
|
||||
flush() {
|
||||
if (this._sQlen > 0 && this.readyState === 'open') {
|
||||
this._websocket.send(this._encodeMessage());
|
||||
this._sQlen = 0;
|
||||
}
|
||||
}
|
||||
|
||||
send(arr) {
|
||||
this._sQ.set(arr, this._sQlen);
|
||||
this._sQlen += arr.length;
|
||||
this.flush();
|
||||
}
|
||||
|
||||
sendString(str) {
|
||||
this.send(str.split('').map(chr => chr.charCodeAt(0)));
|
||||
}
|
||||
|
||||
// Event Handlers
|
||||
off(evt) {
|
||||
this._eventHandlers[evt] = () => {};
|
||||
}
|
||||
|
||||
on(evt, handler) {
|
||||
this._eventHandlers[evt] = handler;
|
||||
}
|
||||
|
||||
_allocateBuffers() {
|
||||
this._rQ = new Uint8Array(this._rQbufferSize);
|
||||
this._sQ = new Uint8Array(this._sQbufferSize);
|
||||
}
|
||||
|
||||
init() {
|
||||
this._allocateBuffers();
|
||||
this._rQi = 0;
|
||||
this._websocket = null;
|
||||
}
|
||||
|
||||
open(uri, protocols) {
|
||||
this.attach(new WebSocket(uri, protocols));
|
||||
}
|
||||
|
||||
attach(rawChannel) {
|
||||
this.init();
|
||||
|
||||
// Must get object and class methods to be compatible with the tests.
|
||||
const channelProps = [...Object.keys(rawChannel), ...Object.getOwnPropertyNames(Object.getPrototypeOf(rawChannel))];
|
||||
for (let i = 0; i < rawChannelProps.length; i++) {
|
||||
const prop = rawChannelProps[i];
|
||||
if (channelProps.indexOf(prop) < 0) {
|
||||
throw new Error('Raw channel missing property: ' + prop);
|
||||
}
|
||||
}
|
||||
|
||||
this._websocket = rawChannel;
|
||||
this._websocket.binaryType = "arraybuffer";
|
||||
this._websocket.onmessage = this._recvMessage.bind(this);
|
||||
|
||||
this._websocket.onopen = () => {
|
||||
Log.Debug('>> WebSock.onopen');
|
||||
if (this._websocket.protocol) {
|
||||
Log.Info("Server choose sub-protocol: " + this._websocket.protocol);
|
||||
}
|
||||
|
||||
this._eventHandlers.open();
|
||||
Log.Debug("<< WebSock.onopen");
|
||||
};
|
||||
|
||||
this._websocket.onclose = (e) => {
|
||||
Log.Debug(">> WebSock.onclose");
|
||||
this._eventHandlers.close(e);
|
||||
Log.Debug("<< WebSock.onclose");
|
||||
};
|
||||
|
||||
this._websocket.onerror = (e) => {
|
||||
Log.Debug(">> WebSock.onerror: " + e);
|
||||
this._eventHandlers.error(e);
|
||||
Log.Debug("<< WebSock.onerror: " + e);
|
||||
};
|
||||
}
|
||||
|
||||
close() {
|
||||
if (this._websocket) {
|
||||
if (this.readyState === 'connecting' ||
|
||||
this.readyState === 'open') {
|
||||
Log.Info("Closing WebSocket connection");
|
||||
this._websocket.close();
|
||||
}
|
||||
|
||||
this._websocket.onmessage = () => {};
|
||||
}
|
||||
}
|
||||
|
||||
// private methods
|
||||
_encodeMessage() {
|
||||
// Put in a binary arraybuffer
|
||||
// according to the spec, you can send ArrayBufferViews with the send method
|
||||
return new Uint8Array(this._sQ.buffer, 0, this._sQlen);
|
||||
}
|
||||
|
||||
// We want to move all the unread data to the start of the queue,
|
||||
// e.g. compacting.
|
||||
// The function also expands the receive que if needed, and for
|
||||
// performance reasons we combine these two actions to avoid
|
||||
// unneccessary copying.
|
||||
_expandCompactRQ(minFit) {
|
||||
// if we're using less than 1/8th of the buffer even with the incoming bytes, compact in place
|
||||
// instead of resizing
|
||||
const requiredBufferSize = (this._rQlen - this._rQi + minFit) * 8;
|
||||
const resizeNeeded = this._rQbufferSize < requiredBufferSize;
|
||||
|
||||
if (resizeNeeded) {
|
||||
// Make sure we always *at least* double the buffer size, and have at least space for 8x
|
||||
// the current amount of data
|
||||
this._rQbufferSize = Math.max(this._rQbufferSize * 2, requiredBufferSize);
|
||||
}
|
||||
|
||||
// we don't want to grow unboundedly
|
||||
if (this._rQbufferSize > MAX_RQ_GROW_SIZE) {
|
||||
this._rQbufferSize = MAX_RQ_GROW_SIZE;
|
||||
if (this._rQbufferSize - this.rQlen < minFit) {
|
||||
throw new Error("Receive Queue buffer exceeded " + MAX_RQ_GROW_SIZE + " bytes, and the new message could not fit");
|
||||
}
|
||||
}
|
||||
|
||||
if (resizeNeeded) {
|
||||
const oldRQbuffer = this._rQ.buffer;
|
||||
this._rQ = new Uint8Array(this._rQbufferSize);
|
||||
this._rQ.set(new Uint8Array(oldRQbuffer, this._rQi, this._rQlen - this._rQi));
|
||||
} else {
|
||||
this._rQ.copyWithin(0, this._rQi, this._rQlen);
|
||||
}
|
||||
|
||||
this._rQlen = this._rQlen - this._rQi;
|
||||
this._rQi = 0;
|
||||
}
|
||||
|
||||
// push arraybuffer values onto the end of the receive que
|
||||
_DecodeMessage(data) {
|
||||
const u8 = new Uint8Array(data);
|
||||
if (u8.length > this._rQbufferSize - this._rQlen) {
|
||||
this._expandCompactRQ(u8.length);
|
||||
}
|
||||
this._rQ.set(u8, this._rQlen);
|
||||
this._rQlen += u8.length;
|
||||
}
|
||||
|
||||
_recvMessage(e) {
|
||||
this._DecodeMessage(e.data);
|
||||
if (this.rQlen > 0) {
|
||||
this._eventHandlers.message();
|
||||
if (this._rQlen == this._rQi) {
|
||||
// All data has now been processed, this means we
|
||||
// can reset the receive queue.
|
||||
this._rQlen = 0;
|
||||
this._rQi = 0;
|
||||
}
|
||||
} else {
|
||||
Log.Debug("Ignoring empty message");
|
||||
}
|
||||
}
|
||||
}
|
||||
21
backend/app/static/novnc/vendor/pako/LICENSE
vendored
Normal file
21
backend/app/static/novnc/vendor/pako/LICENSE
vendored
Normal file
@@ -0,0 +1,21 @@
|
||||
(The MIT License)
|
||||
|
||||
Copyright (C) 2014-2016 by Vitaly Puzrin
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
6
backend/app/static/novnc/vendor/pako/README.md
vendored
Normal file
6
backend/app/static/novnc/vendor/pako/README.md
vendored
Normal file
@@ -0,0 +1,6 @@
|
||||
This is an ES6-modules-compatible version of
|
||||
https://github.com/nodeca/pako, based on pako version 1.0.3.
|
||||
|
||||
It's more-or-less a direct translation of the original, with unused parts
|
||||
removed, and the dynamic support for non-typed arrays removed (since ES6
|
||||
modules don't work well with dynamic exports).
|
||||
45
backend/app/static/novnc/vendor/pako/lib/utils/common.js
vendored
Normal file
45
backend/app/static/novnc/vendor/pako/lib/utils/common.js
vendored
Normal file
@@ -0,0 +1,45 @@
|
||||
// reduce buffer size, avoiding mem copy
|
||||
export function shrinkBuf (buf, size) {
|
||||
if (buf.length === size) { return buf; }
|
||||
if (buf.subarray) { return buf.subarray(0, size); }
|
||||
buf.length = size;
|
||||
return buf;
|
||||
};
|
||||
|
||||
|
||||
export function arraySet (dest, src, src_offs, len, dest_offs) {
|
||||
if (src.subarray && dest.subarray) {
|
||||
dest.set(src.subarray(src_offs, src_offs + len), dest_offs);
|
||||
return;
|
||||
}
|
||||
// Fallback to ordinary array
|
||||
for (var i = 0; i < len; i++) {
|
||||
dest[dest_offs + i] = src[src_offs + i];
|
||||
}
|
||||
}
|
||||
|
||||
// Join array of chunks to single array.
|
||||
export function flattenChunks (chunks) {
|
||||
var i, l, len, pos, chunk, result;
|
||||
|
||||
// calculate data length
|
||||
len = 0;
|
||||
for (i = 0, l = chunks.length; i < l; i++) {
|
||||
len += chunks[i].length;
|
||||
}
|
||||
|
||||
// join chunks
|
||||
result = new Uint8Array(len);
|
||||
pos = 0;
|
||||
for (i = 0, l = chunks.length; i < l; i++) {
|
||||
chunk = chunks[i];
|
||||
result.set(chunk, pos);
|
||||
pos += chunk.length;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
export var Buf8 = Uint8Array;
|
||||
export var Buf16 = Uint16Array;
|
||||
export var Buf32 = Int32Array;
|
||||
27
backend/app/static/novnc/vendor/pako/lib/zlib/adler32.js
vendored
Normal file
27
backend/app/static/novnc/vendor/pako/lib/zlib/adler32.js
vendored
Normal file
@@ -0,0 +1,27 @@
|
||||
// Note: adler32 takes 12% for level 0 and 2% for level 6.
|
||||
// It doesn't worth to make additional optimizationa as in original.
|
||||
// Small size is preferable.
|
||||
|
||||
export default function adler32(adler, buf, len, pos) {
|
||||
var s1 = (adler & 0xffff) |0,
|
||||
s2 = ((adler >>> 16) & 0xffff) |0,
|
||||
n = 0;
|
||||
|
||||
while (len !== 0) {
|
||||
// Set limit ~ twice less than 5552, to keep
|
||||
// s2 in 31-bits, because we force signed ints.
|
||||
// in other case %= will fail.
|
||||
n = len > 2000 ? 2000 : len;
|
||||
len -= n;
|
||||
|
||||
do {
|
||||
s1 = (s1 + buf[pos++]) |0;
|
||||
s2 = (s2 + s1) |0;
|
||||
} while (--n);
|
||||
|
||||
s1 %= 65521;
|
||||
s2 %= 65521;
|
||||
}
|
||||
|
||||
return (s1 | (s2 << 16)) |0;
|
||||
}
|
||||
47
backend/app/static/novnc/vendor/pako/lib/zlib/constants.js
vendored
Normal file
47
backend/app/static/novnc/vendor/pako/lib/zlib/constants.js
vendored
Normal file
@@ -0,0 +1,47 @@
|
||||
export default {
|
||||
|
||||
/* Allowed flush values; see deflate() and inflate() below for details */
|
||||
Z_NO_FLUSH: 0,
|
||||
Z_PARTIAL_FLUSH: 1,
|
||||
Z_SYNC_FLUSH: 2,
|
||||
Z_FULL_FLUSH: 3,
|
||||
Z_FINISH: 4,
|
||||
Z_BLOCK: 5,
|
||||
Z_TREES: 6,
|
||||
|
||||
/* Return codes for the compression/decompression functions. Negative values
|
||||
* are errors, positive values are used for special but normal events.
|
||||
*/
|
||||
Z_OK: 0,
|
||||
Z_STREAM_END: 1,
|
||||
Z_NEED_DICT: 2,
|
||||
Z_ERRNO: -1,
|
||||
Z_STREAM_ERROR: -2,
|
||||
Z_DATA_ERROR: -3,
|
||||
//Z_MEM_ERROR: -4,
|
||||
Z_BUF_ERROR: -5,
|
||||
//Z_VERSION_ERROR: -6,
|
||||
|
||||
/* compression levels */
|
||||
Z_NO_COMPRESSION: 0,
|
||||
Z_BEST_SPEED: 1,
|
||||
Z_BEST_COMPRESSION: 9,
|
||||
Z_DEFAULT_COMPRESSION: -1,
|
||||
|
||||
|
||||
Z_FILTERED: 1,
|
||||
Z_HUFFMAN_ONLY: 2,
|
||||
Z_RLE: 3,
|
||||
Z_FIXED: 4,
|
||||
Z_DEFAULT_STRATEGY: 0,
|
||||
|
||||
/* Possible values of the data_type field (though see inflate()) */
|
||||
Z_BINARY: 0,
|
||||
Z_TEXT: 1,
|
||||
//Z_ASCII: 1, // = Z_TEXT (deprecated)
|
||||
Z_UNKNOWN: 2,
|
||||
|
||||
/* The deflate compression method */
|
||||
Z_DEFLATED: 8
|
||||
//Z_NULL: null // Use -1 or null inline, depending on var type
|
||||
};
|
||||
36
backend/app/static/novnc/vendor/pako/lib/zlib/crc32.js
vendored
Normal file
36
backend/app/static/novnc/vendor/pako/lib/zlib/crc32.js
vendored
Normal file
@@ -0,0 +1,36 @@
|
||||
// Note: we can't get significant speed boost here.
|
||||
// So write code to minimize size - no pregenerated tables
|
||||
// and array tools dependencies.
|
||||
|
||||
|
||||
// Use ordinary array, since untyped makes no boost here
|
||||
export default function makeTable() {
|
||||
var c, table = [];
|
||||
|
||||
for (var n = 0; n < 256; n++) {
|
||||
c = n;
|
||||
for (var k = 0; k < 8; k++) {
|
||||
c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
|
||||
}
|
||||
table[n] = c;
|
||||
}
|
||||
|
||||
return table;
|
||||
}
|
||||
|
||||
// Create table on load. Just 255 signed longs. Not a problem.
|
||||
var crcTable = makeTable();
|
||||
|
||||
|
||||
function crc32(crc, buf, len, pos) {
|
||||
var t = crcTable,
|
||||
end = pos + len;
|
||||
|
||||
crc ^= -1;
|
||||
|
||||
for (var i = pos; i < end; i++) {
|
||||
crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
|
||||
}
|
||||
|
||||
return (crc ^ (-1)); // >>> 0;
|
||||
}
|
||||
1846
backend/app/static/novnc/vendor/pako/lib/zlib/deflate.js
vendored
Normal file
1846
backend/app/static/novnc/vendor/pako/lib/zlib/deflate.js
vendored
Normal file
File diff suppressed because it is too large
Load Diff
35
backend/app/static/novnc/vendor/pako/lib/zlib/gzheader.js
vendored
Normal file
35
backend/app/static/novnc/vendor/pako/lib/zlib/gzheader.js
vendored
Normal file
@@ -0,0 +1,35 @@
|
||||
export default function GZheader() {
|
||||
/* true if compressed data believed to be text */
|
||||
this.text = 0;
|
||||
/* modification time */
|
||||
this.time = 0;
|
||||
/* extra flags (not used when writing a gzip file) */
|
||||
this.xflags = 0;
|
||||
/* operating system */
|
||||
this.os = 0;
|
||||
/* pointer to extra field or Z_NULL if none */
|
||||
this.extra = null;
|
||||
/* extra field length (valid if extra != Z_NULL) */
|
||||
this.extra_len = 0; // Actually, we don't need it in JS,
|
||||
// but leave for few code modifications
|
||||
|
||||
//
|
||||
// Setup limits is not necessary because in js we should not preallocate memory
|
||||
// for inflate use constant limit in 65536 bytes
|
||||
//
|
||||
|
||||
/* space at extra (only when reading header) */
|
||||
// this.extra_max = 0;
|
||||
/* pointer to zero-terminated file name or Z_NULL */
|
||||
this.name = '';
|
||||
/* space at name (only when reading header) */
|
||||
// this.name_max = 0;
|
||||
/* pointer to zero-terminated comment or Z_NULL */
|
||||
this.comment = '';
|
||||
/* space at comment (only when reading header) */
|
||||
// this.comm_max = 0;
|
||||
/* true if there was or will be a header crc */
|
||||
this.hcrc = 0;
|
||||
/* true when done reading gzip header (not used when writing a gzip file) */
|
||||
this.done = false;
|
||||
}
|
||||
324
backend/app/static/novnc/vendor/pako/lib/zlib/inffast.js
vendored
Normal file
324
backend/app/static/novnc/vendor/pako/lib/zlib/inffast.js
vendored
Normal file
@@ -0,0 +1,324 @@
|
||||
// See state defs from inflate.js
|
||||
var BAD = 30; /* got a data error -- remain here until reset */
|
||||
var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
|
||||
|
||||
/*
|
||||
Decode literal, length, and distance codes and write out the resulting
|
||||
literal and match bytes until either not enough input or output is
|
||||
available, an end-of-block is encountered, or a data error is encountered.
|
||||
When large enough input and output buffers are supplied to inflate(), for
|
||||
example, a 16K input buffer and a 64K output buffer, more than 95% of the
|
||||
inflate execution time is spent in this routine.
|
||||
|
||||
Entry assumptions:
|
||||
|
||||
state.mode === LEN
|
||||
strm.avail_in >= 6
|
||||
strm.avail_out >= 258
|
||||
start >= strm.avail_out
|
||||
state.bits < 8
|
||||
|
||||
On return, state.mode is one of:
|
||||
|
||||
LEN -- ran out of enough output space or enough available input
|
||||
TYPE -- reached end of block code, inflate() to interpret next block
|
||||
BAD -- error in block data
|
||||
|
||||
Notes:
|
||||
|
||||
- The maximum input bits used by a length/distance pair is 15 bits for the
|
||||
length code, 5 bits for the length extra, 15 bits for the distance code,
|
||||
and 13 bits for the distance extra. This totals 48 bits, or six bytes.
|
||||
Therefore if strm.avail_in >= 6, then there is enough input to avoid
|
||||
checking for available input while decoding.
|
||||
|
||||
- The maximum bytes that a single length/distance pair can output is 258
|
||||
bytes, which is the maximum length that can be coded. inflate_fast()
|
||||
requires strm.avail_out >= 258 for each loop to avoid checking for
|
||||
output space.
|
||||
*/
|
||||
export default function inflate_fast(strm, start) {
|
||||
var state;
|
||||
var _in; /* local strm.input */
|
||||
var last; /* have enough input while in < last */
|
||||
var _out; /* local strm.output */
|
||||
var beg; /* inflate()'s initial strm.output */
|
||||
var end; /* while out < end, enough space available */
|
||||
//#ifdef INFLATE_STRICT
|
||||
var dmax; /* maximum distance from zlib header */
|
||||
//#endif
|
||||
var wsize; /* window size or zero if not using window */
|
||||
var whave; /* valid bytes in the window */
|
||||
var wnext; /* window write index */
|
||||
// Use `s_window` instead `window`, avoid conflict with instrumentation tools
|
||||
var s_window; /* allocated sliding window, if wsize != 0 */
|
||||
var hold; /* local strm.hold */
|
||||
var bits; /* local strm.bits */
|
||||
var lcode; /* local strm.lencode */
|
||||
var dcode; /* local strm.distcode */
|
||||
var lmask; /* mask for first level of length codes */
|
||||
var dmask; /* mask for first level of distance codes */
|
||||
var here; /* retrieved table entry */
|
||||
var op; /* code bits, operation, extra bits, or */
|
||||
/* window position, window bytes to copy */
|
||||
var len; /* match length, unused bytes */
|
||||
var dist; /* match distance */
|
||||
var from; /* where to copy match from */
|
||||
var from_source;
|
||||
|
||||
|
||||
var input, output; // JS specific, because we have no pointers
|
||||
|
||||
/* copy state to local variables */
|
||||
state = strm.state;
|
||||
//here = state.here;
|
||||
_in = strm.next_in;
|
||||
input = strm.input;
|
||||
last = _in + (strm.avail_in - 5);
|
||||
_out = strm.next_out;
|
||||
output = strm.output;
|
||||
beg = _out - (start - strm.avail_out);
|
||||
end = _out + (strm.avail_out - 257);
|
||||
//#ifdef INFLATE_STRICT
|
||||
dmax = state.dmax;
|
||||
//#endif
|
||||
wsize = state.wsize;
|
||||
whave = state.whave;
|
||||
wnext = state.wnext;
|
||||
s_window = state.window;
|
||||
hold = state.hold;
|
||||
bits = state.bits;
|
||||
lcode = state.lencode;
|
||||
dcode = state.distcode;
|
||||
lmask = (1 << state.lenbits) - 1;
|
||||
dmask = (1 << state.distbits) - 1;
|
||||
|
||||
|
||||
/* decode literals and length/distances until end-of-block or not enough
|
||||
input data or output space */
|
||||
|
||||
top:
|
||||
do {
|
||||
if (bits < 15) {
|
||||
hold += input[_in++] << bits;
|
||||
bits += 8;
|
||||
hold += input[_in++] << bits;
|
||||
bits += 8;
|
||||
}
|
||||
|
||||
here = lcode[hold & lmask];
|
||||
|
||||
dolen:
|
||||
for (;;) { // Goto emulation
|
||||
op = here >>> 24/*here.bits*/;
|
||||
hold >>>= op;
|
||||
bits -= op;
|
||||
op = (here >>> 16) & 0xff/*here.op*/;
|
||||
if (op === 0) { /* literal */
|
||||
//Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
|
||||
// "inflate: literal '%c'\n" :
|
||||
// "inflate: literal 0x%02x\n", here.val));
|
||||
output[_out++] = here & 0xffff/*here.val*/;
|
||||
}
|
||||
else if (op & 16) { /* length base */
|
||||
len = here & 0xffff/*here.val*/;
|
||||
op &= 15; /* number of extra bits */
|
||||
if (op) {
|
||||
if (bits < op) {
|
||||
hold += input[_in++] << bits;
|
||||
bits += 8;
|
||||
}
|
||||
len += hold & ((1 << op) - 1);
|
||||
hold >>>= op;
|
||||
bits -= op;
|
||||
}
|
||||
//Tracevv((stderr, "inflate: length %u\n", len));
|
||||
if (bits < 15) {
|
||||
hold += input[_in++] << bits;
|
||||
bits += 8;
|
||||
hold += input[_in++] << bits;
|
||||
bits += 8;
|
||||
}
|
||||
here = dcode[hold & dmask];
|
||||
|
||||
dodist:
|
||||
for (;;) { // goto emulation
|
||||
op = here >>> 24/*here.bits*/;
|
||||
hold >>>= op;
|
||||
bits -= op;
|
||||
op = (here >>> 16) & 0xff/*here.op*/;
|
||||
|
||||
if (op & 16) { /* distance base */
|
||||
dist = here & 0xffff/*here.val*/;
|
||||
op &= 15; /* number of extra bits */
|
||||
if (bits < op) {
|
||||
hold += input[_in++] << bits;
|
||||
bits += 8;
|
||||
if (bits < op) {
|
||||
hold += input[_in++] << bits;
|
||||
bits += 8;
|
||||
}
|
||||
}
|
||||
dist += hold & ((1 << op) - 1);
|
||||
//#ifdef INFLATE_STRICT
|
||||
if (dist > dmax) {
|
||||
strm.msg = 'invalid distance too far back';
|
||||
state.mode = BAD;
|
||||
break top;
|
||||
}
|
||||
//#endif
|
||||
hold >>>= op;
|
||||
bits -= op;
|
||||
//Tracevv((stderr, "inflate: distance %u\n", dist));
|
||||
op = _out - beg; /* max distance in output */
|
||||
if (dist > op) { /* see if copy from window */
|
||||
op = dist - op; /* distance back in window */
|
||||
if (op > whave) {
|
||||
if (state.sane) {
|
||||
strm.msg = 'invalid distance too far back';
|
||||
state.mode = BAD;
|
||||
break top;
|
||||
}
|
||||
|
||||
// (!) This block is disabled in zlib defailts,
|
||||
// don't enable it for binary compatibility
|
||||
//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
|
||||
// if (len <= op - whave) {
|
||||
// do {
|
||||
// output[_out++] = 0;
|
||||
// } while (--len);
|
||||
// continue top;
|
||||
// }
|
||||
// len -= op - whave;
|
||||
// do {
|
||||
// output[_out++] = 0;
|
||||
// } while (--op > whave);
|
||||
// if (op === 0) {
|
||||
// from = _out - dist;
|
||||
// do {
|
||||
// output[_out++] = output[from++];
|
||||
// } while (--len);
|
||||
// continue top;
|
||||
// }
|
||||
//#endif
|
||||
}
|
||||
from = 0; // window index
|
||||
from_source = s_window;
|
||||
if (wnext === 0) { /* very common case */
|
||||
from += wsize - op;
|
||||
if (op < len) { /* some from window */
|
||||
len -= op;
|
||||
do {
|
||||
output[_out++] = s_window[from++];
|
||||
} while (--op);
|
||||
from = _out - dist; /* rest from output */
|
||||
from_source = output;
|
||||
}
|
||||
}
|
||||
else if (wnext < op) { /* wrap around window */
|
||||
from += wsize + wnext - op;
|
||||
op -= wnext;
|
||||
if (op < len) { /* some from end of window */
|
||||
len -= op;
|
||||
do {
|
||||
output[_out++] = s_window[from++];
|
||||
} while (--op);
|
||||
from = 0;
|
||||
if (wnext < len) { /* some from start of window */
|
||||
op = wnext;
|
||||
len -= op;
|
||||
do {
|
||||
output[_out++] = s_window[from++];
|
||||
} while (--op);
|
||||
from = _out - dist; /* rest from output */
|
||||
from_source = output;
|
||||
}
|
||||
}
|
||||
}
|
||||
else { /* contiguous in window */
|
||||
from += wnext - op;
|
||||
if (op < len) { /* some from window */
|
||||
len -= op;
|
||||
do {
|
||||
output[_out++] = s_window[from++];
|
||||
} while (--op);
|
||||
from = _out - dist; /* rest from output */
|
||||
from_source = output;
|
||||
}
|
||||
}
|
||||
while (len > 2) {
|
||||
output[_out++] = from_source[from++];
|
||||
output[_out++] = from_source[from++];
|
||||
output[_out++] = from_source[from++];
|
||||
len -= 3;
|
||||
}
|
||||
if (len) {
|
||||
output[_out++] = from_source[from++];
|
||||
if (len > 1) {
|
||||
output[_out++] = from_source[from++];
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
from = _out - dist; /* copy direct from output */
|
||||
do { /* minimum length is three */
|
||||
output[_out++] = output[from++];
|
||||
output[_out++] = output[from++];
|
||||
output[_out++] = output[from++];
|
||||
len -= 3;
|
||||
} while (len > 2);
|
||||
if (len) {
|
||||
output[_out++] = output[from++];
|
||||
if (len > 1) {
|
||||
output[_out++] = output[from++];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
else if ((op & 64) === 0) { /* 2nd level distance code */
|
||||
here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
|
||||
continue dodist;
|
||||
}
|
||||
else {
|
||||
strm.msg = 'invalid distance code';
|
||||
state.mode = BAD;
|
||||
break top;
|
||||
}
|
||||
|
||||
break; // need to emulate goto via "continue"
|
||||
}
|
||||
}
|
||||
else if ((op & 64) === 0) { /* 2nd level length code */
|
||||
here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
|
||||
continue dolen;
|
||||
}
|
||||
else if (op & 32) { /* end-of-block */
|
||||
//Tracevv((stderr, "inflate: end of block\n"));
|
||||
state.mode = TYPE;
|
||||
break top;
|
||||
}
|
||||
else {
|
||||
strm.msg = 'invalid literal/length code';
|
||||
state.mode = BAD;
|
||||
break top;
|
||||
}
|
||||
|
||||
break; // need to emulate goto via "continue"
|
||||
}
|
||||
} while (_in < last && _out < end);
|
||||
|
||||
/* return unused bytes (on entry, bits < 8, so in won't go too far back) */
|
||||
len = bits >> 3;
|
||||
_in -= len;
|
||||
bits -= len << 3;
|
||||
hold &= (1 << bits) - 1;
|
||||
|
||||
/* update state and return */
|
||||
strm.next_in = _in;
|
||||
strm.next_out = _out;
|
||||
strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
|
||||
strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
|
||||
state.hold = hold;
|
||||
state.bits = bits;
|
||||
return;
|
||||
};
|
||||
1527
backend/app/static/novnc/vendor/pako/lib/zlib/inflate.js
vendored
Normal file
1527
backend/app/static/novnc/vendor/pako/lib/zlib/inflate.js
vendored
Normal file
File diff suppressed because it is too large
Load Diff
322
backend/app/static/novnc/vendor/pako/lib/zlib/inftrees.js
vendored
Normal file
322
backend/app/static/novnc/vendor/pako/lib/zlib/inftrees.js
vendored
Normal file
@@ -0,0 +1,322 @@
|
||||
import * as utils from "../utils/common.js";
|
||||
|
||||
var MAXBITS = 15;
|
||||
var ENOUGH_LENS = 852;
|
||||
var ENOUGH_DISTS = 592;
|
||||
//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
|
||||
|
||||
var CODES = 0;
|
||||
var LENS = 1;
|
||||
var DISTS = 2;
|
||||
|
||||
var lbase = [ /* Length codes 257..285 base */
|
||||
3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
|
||||
35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
|
||||
];
|
||||
|
||||
var lext = [ /* Length codes 257..285 extra */
|
||||
16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
|
||||
19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
|
||||
];
|
||||
|
||||
var dbase = [ /* Distance codes 0..29 base */
|
||||
1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
|
||||
257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
|
||||
8193, 12289, 16385, 24577, 0, 0
|
||||
];
|
||||
|
||||
var dext = [ /* Distance codes 0..29 extra */
|
||||
16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
|
||||
23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
|
||||
28, 28, 29, 29, 64, 64
|
||||
];
|
||||
|
||||
export default function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
|
||||
{
|
||||
var bits = opts.bits;
|
||||
//here = opts.here; /* table entry for duplication */
|
||||
|
||||
var len = 0; /* a code's length in bits */
|
||||
var sym = 0; /* index of code symbols */
|
||||
var min = 0, max = 0; /* minimum and maximum code lengths */
|
||||
var root = 0; /* number of index bits for root table */
|
||||
var curr = 0; /* number of index bits for current table */
|
||||
var drop = 0; /* code bits to drop for sub-table */
|
||||
var left = 0; /* number of prefix codes available */
|
||||
var used = 0; /* code entries in table used */
|
||||
var huff = 0; /* Huffman code */
|
||||
var incr; /* for incrementing code, index */
|
||||
var fill; /* index for replicating entries */
|
||||
var low; /* low bits for current root entry */
|
||||
var mask; /* mask for low root bits */
|
||||
var next; /* next available space in table */
|
||||
var base = null; /* base value table to use */
|
||||
var base_index = 0;
|
||||
// var shoextra; /* extra bits table to use */
|
||||
var end; /* use base and extra for symbol > end */
|
||||
var count = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */
|
||||
var offs = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */
|
||||
var extra = null;
|
||||
var extra_index = 0;
|
||||
|
||||
var here_bits, here_op, here_val;
|
||||
|
||||
/*
|
||||
Process a set of code lengths to create a canonical Huffman code. The
|
||||
code lengths are lens[0..codes-1]. Each length corresponds to the
|
||||
symbols 0..codes-1. The Huffman code is generated by first sorting the
|
||||
symbols by length from short to long, and retaining the symbol order
|
||||
for codes with equal lengths. Then the code starts with all zero bits
|
||||
for the first code of the shortest length, and the codes are integer
|
||||
increments for the same length, and zeros are appended as the length
|
||||
increases. For the deflate format, these bits are stored backwards
|
||||
from their more natural integer increment ordering, and so when the
|
||||
decoding tables are built in the large loop below, the integer codes
|
||||
are incremented backwards.
|
||||
|
||||
This routine assumes, but does not check, that all of the entries in
|
||||
lens[] are in the range 0..MAXBITS. The caller must assure this.
|
||||
1..MAXBITS is interpreted as that code length. zero means that that
|
||||
symbol does not occur in this code.
|
||||
|
||||
The codes are sorted by computing a count of codes for each length,
|
||||
creating from that a table of starting indices for each length in the
|
||||
sorted table, and then entering the symbols in order in the sorted
|
||||
table. The sorted table is work[], with that space being provided by
|
||||
the caller.
|
||||
|
||||
The length counts are used for other purposes as well, i.e. finding
|
||||
the minimum and maximum length codes, determining if there are any
|
||||
codes at all, checking for a valid set of lengths, and looking ahead
|
||||
at length counts to determine sub-table sizes when building the
|
||||
decoding tables.
|
||||
*/
|
||||
|
||||
/* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
|
||||
for (len = 0; len <= MAXBITS; len++) {
|
||||
count[len] = 0;
|
||||
}
|
||||
for (sym = 0; sym < codes; sym++) {
|
||||
count[lens[lens_index + sym]]++;
|
||||
}
|
||||
|
||||
/* bound code lengths, force root to be within code lengths */
|
||||
root = bits;
|
||||
for (max = MAXBITS; max >= 1; max--) {
|
||||
if (count[max] !== 0) { break; }
|
||||
}
|
||||
if (root > max) {
|
||||
root = max;
|
||||
}
|
||||
if (max === 0) { /* no symbols to code at all */
|
||||
//table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
|
||||
//table.bits[opts.table_index] = 1; //here.bits = (var char)1;
|
||||
//table.val[opts.table_index++] = 0; //here.val = (var short)0;
|
||||
table[table_index++] = (1 << 24) | (64 << 16) | 0;
|
||||
|
||||
|
||||
//table.op[opts.table_index] = 64;
|
||||
//table.bits[opts.table_index] = 1;
|
||||
//table.val[opts.table_index++] = 0;
|
||||
table[table_index++] = (1 << 24) | (64 << 16) | 0;
|
||||
|
||||
opts.bits = 1;
|
||||
return 0; /* no symbols, but wait for decoding to report error */
|
||||
}
|
||||
for (min = 1; min < max; min++) {
|
||||
if (count[min] !== 0) { break; }
|
||||
}
|
||||
if (root < min) {
|
||||
root = min;
|
||||
}
|
||||
|
||||
/* check for an over-subscribed or incomplete set of lengths */
|
||||
left = 1;
|
||||
for (len = 1; len <= MAXBITS; len++) {
|
||||
left <<= 1;
|
||||
left -= count[len];
|
||||
if (left < 0) {
|
||||
return -1;
|
||||
} /* over-subscribed */
|
||||
}
|
||||
if (left > 0 && (type === CODES || max !== 1)) {
|
||||
return -1; /* incomplete set */
|
||||
}
|
||||
|
||||
/* generate offsets into symbol table for each length for sorting */
|
||||
offs[1] = 0;
|
||||
for (len = 1; len < MAXBITS; len++) {
|
||||
offs[len + 1] = offs[len] + count[len];
|
||||
}
|
||||
|
||||
/* sort symbols by length, by symbol order within each length */
|
||||
for (sym = 0; sym < codes; sym++) {
|
||||
if (lens[lens_index + sym] !== 0) {
|
||||
work[offs[lens[lens_index + sym]]++] = sym;
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
Create and fill in decoding tables. In this loop, the table being
|
||||
filled is at next and has curr index bits. The code being used is huff
|
||||
with length len. That code is converted to an index by dropping drop
|
||||
bits off of the bottom. For codes where len is less than drop + curr,
|
||||
those top drop + curr - len bits are incremented through all values to
|
||||
fill the table with replicated entries.
|
||||
|
||||
root is the number of index bits for the root table. When len exceeds
|
||||
root, sub-tables are created pointed to by the root entry with an index
|
||||
of the low root bits of huff. This is saved in low to check for when a
|
||||
new sub-table should be started. drop is zero when the root table is
|
||||
being filled, and drop is root when sub-tables are being filled.
|
||||
|
||||
When a new sub-table is needed, it is necessary to look ahead in the
|
||||
code lengths to determine what size sub-table is needed. The length
|
||||
counts are used for this, and so count[] is decremented as codes are
|
||||
entered in the tables.
|
||||
|
||||
used keeps track of how many table entries have been allocated from the
|
||||
provided *table space. It is checked for LENS and DIST tables against
|
||||
the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
|
||||
the initial root table size constants. See the comments in inftrees.h
|
||||
for more information.
|
||||
|
||||
sym increments through all symbols, and the loop terminates when
|
||||
all codes of length max, i.e. all codes, have been processed. This
|
||||
routine permits incomplete codes, so another loop after this one fills
|
||||
in the rest of the decoding tables with invalid code markers.
|
||||
*/
|
||||
|
||||
/* set up for code type */
|
||||
// poor man optimization - use if-else instead of switch,
|
||||
// to avoid deopts in old v8
|
||||
if (type === CODES) {
|
||||
base = extra = work; /* dummy value--not used */
|
||||
end = 19;
|
||||
|
||||
} else if (type === LENS) {
|
||||
base = lbase;
|
||||
base_index -= 257;
|
||||
extra = lext;
|
||||
extra_index -= 257;
|
||||
end = 256;
|
||||
|
||||
} else { /* DISTS */
|
||||
base = dbase;
|
||||
extra = dext;
|
||||
end = -1;
|
||||
}
|
||||
|
||||
/* initialize opts for loop */
|
||||
huff = 0; /* starting code */
|
||||
sym = 0; /* starting code symbol */
|
||||
len = min; /* starting code length */
|
||||
next = table_index; /* current table to fill in */
|
||||
curr = root; /* current table index bits */
|
||||
drop = 0; /* current bits to drop from code for index */
|
||||
low = -1; /* trigger new sub-table when len > root */
|
||||
used = 1 << root; /* use root table entries */
|
||||
mask = used - 1; /* mask for comparing low */
|
||||
|
||||
/* check available table space */
|
||||
if ((type === LENS && used > ENOUGH_LENS) ||
|
||||
(type === DISTS && used > ENOUGH_DISTS)) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* process all codes and make table entries */
|
||||
for (;;) {
|
||||
/* create table entry */
|
||||
here_bits = len - drop;
|
||||
if (work[sym] < end) {
|
||||
here_op = 0;
|
||||
here_val = work[sym];
|
||||
}
|
||||
else if (work[sym] > end) {
|
||||
here_op = extra[extra_index + work[sym]];
|
||||
here_val = base[base_index + work[sym]];
|
||||
}
|
||||
else {
|
||||
here_op = 32 + 64; /* end of block */
|
||||
here_val = 0;
|
||||
}
|
||||
|
||||
/* replicate for those indices with low len bits equal to huff */
|
||||
incr = 1 << (len - drop);
|
||||
fill = 1 << curr;
|
||||
min = fill; /* save offset to next table */
|
||||
do {
|
||||
fill -= incr;
|
||||
table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
|
||||
} while (fill !== 0);
|
||||
|
||||
/* backwards increment the len-bit code huff */
|
||||
incr = 1 << (len - 1);
|
||||
while (huff & incr) {
|
||||
incr >>= 1;
|
||||
}
|
||||
if (incr !== 0) {
|
||||
huff &= incr - 1;
|
||||
huff += incr;
|
||||
} else {
|
||||
huff = 0;
|
||||
}
|
||||
|
||||
/* go to next symbol, update count, len */
|
||||
sym++;
|
||||
if (--count[len] === 0) {
|
||||
if (len === max) { break; }
|
||||
len = lens[lens_index + work[sym]];
|
||||
}
|
||||
|
||||
/* create new sub-table if needed */
|
||||
if (len > root && (huff & mask) !== low) {
|
||||
/* if first time, transition to sub-tables */
|
||||
if (drop === 0) {
|
||||
drop = root;
|
||||
}
|
||||
|
||||
/* increment past last table */
|
||||
next += min; /* here min is 1 << curr */
|
||||
|
||||
/* determine length of next table */
|
||||
curr = len - drop;
|
||||
left = 1 << curr;
|
||||
while (curr + drop < max) {
|
||||
left -= count[curr + drop];
|
||||
if (left <= 0) { break; }
|
||||
curr++;
|
||||
left <<= 1;
|
||||
}
|
||||
|
||||
/* check for enough space */
|
||||
used += 1 << curr;
|
||||
if ((type === LENS && used > ENOUGH_LENS) ||
|
||||
(type === DISTS && used > ENOUGH_DISTS)) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* point entry in root table to sub-table */
|
||||
low = huff & mask;
|
||||
/*table.op[low] = curr;
|
||||
table.bits[low] = root;
|
||||
table.val[low] = next - opts.table_index;*/
|
||||
table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
|
||||
}
|
||||
}
|
||||
|
||||
/* fill in remaining table entry if code is incomplete (guaranteed to have
|
||||
at most one remaining entry, since if the code is incomplete, the
|
||||
maximum code length that was allowed to get this far is one bit) */
|
||||
if (huff !== 0) {
|
||||
//table.op[next + huff] = 64; /* invalid code marker */
|
||||
//table.bits[next + huff] = len - drop;
|
||||
//table.val[next + huff] = 0;
|
||||
table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
|
||||
}
|
||||
|
||||
/* set return parameters */
|
||||
//opts.table_index += used;
|
||||
opts.bits = root;
|
||||
return 0;
|
||||
};
|
||||
11
backend/app/static/novnc/vendor/pako/lib/zlib/messages.js
vendored
Normal file
11
backend/app/static/novnc/vendor/pako/lib/zlib/messages.js
vendored
Normal file
@@ -0,0 +1,11 @@
|
||||
export default {
|
||||
2: 'need dictionary', /* Z_NEED_DICT 2 */
|
||||
1: 'stream end', /* Z_STREAM_END 1 */
|
||||
0: '', /* Z_OK 0 */
|
||||
'-1': 'file error', /* Z_ERRNO (-1) */
|
||||
'-2': 'stream error', /* Z_STREAM_ERROR (-2) */
|
||||
'-3': 'data error', /* Z_DATA_ERROR (-3) */
|
||||
'-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
|
||||
'-5': 'buffer error', /* Z_BUF_ERROR (-5) */
|
||||
'-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
|
||||
};
|
||||
1195
backend/app/static/novnc/vendor/pako/lib/zlib/trees.js
vendored
Normal file
1195
backend/app/static/novnc/vendor/pako/lib/zlib/trees.js
vendored
Normal file
File diff suppressed because it is too large
Load Diff
24
backend/app/static/novnc/vendor/pako/lib/zlib/zstream.js
vendored
Normal file
24
backend/app/static/novnc/vendor/pako/lib/zlib/zstream.js
vendored
Normal file
@@ -0,0 +1,24 @@
|
||||
export default function ZStream() {
|
||||
/* next input byte */
|
||||
this.input = null; // JS specific, because we have no pointers
|
||||
this.next_in = 0;
|
||||
/* number of bytes available at input */
|
||||
this.avail_in = 0;
|
||||
/* total number of input bytes read so far */
|
||||
this.total_in = 0;
|
||||
/* next output byte should be put there */
|
||||
this.output = null; // JS specific, because we have no pointers
|
||||
this.next_out = 0;
|
||||
/* remaining free space at output */
|
||||
this.avail_out = 0;
|
||||
/* total number of bytes output so far */
|
||||
this.total_out = 0;
|
||||
/* last error message, NULL if no error */
|
||||
this.msg = ''/*Z_NULL*/;
|
||||
/* not visible by applications */
|
||||
this.state = null;
|
||||
/* best guess about the data type: binary or text */
|
||||
this.data_type = 2/*Z_UNKNOWN*/;
|
||||
/* adler32 value of the uncompressed data */
|
||||
this.adler = 0;
|
||||
}
|
||||
52
backend/app/template_helpers.py
Normal file
52
backend/app/template_helpers.py
Normal file
@@ -0,0 +1,52 @@
|
||||
"""
|
||||
Template helpers
|
||||
Jinja2 context processors and filters
|
||||
"""
|
||||
|
||||
import os
|
||||
from fastapi import Request
|
||||
from .i18n import I18nService
|
||||
from .config import settings
|
||||
|
||||
|
||||
# Path to custom logo
|
||||
CUSTOM_LOGO_PATH = os.path.join(os.path.dirname(__file__), "static", "img", "logo.png")
|
||||
|
||||
|
||||
def get_language(request: Request) -> str:
|
||||
"""Get current language from request state"""
|
||||
return getattr(request.state, 'lang', 'ru')
|
||||
|
||||
|
||||
def custom_logo_exists() -> bool:
|
||||
"""Check if custom logo file exists"""
|
||||
return os.path.isfile(CUSTOM_LOGO_PATH)
|
||||
|
||||
|
||||
def add_i18n_context(request: Request, context: dict) -> dict:
|
||||
"""
|
||||
Add i18n variables to template context
|
||||
|
||||
Args:
|
||||
request: FastAPI request
|
||||
context: Existing template context
|
||||
|
||||
Returns:
|
||||
Updated context with i18n variables
|
||||
"""
|
||||
lang = get_language(request)
|
||||
|
||||
# Add language info
|
||||
context['lang'] = lang
|
||||
context['translations'] = I18nService.get_all(lang)
|
||||
context['t'] = lambda key, **kwargs: I18nService.get(key, lang, **kwargs)
|
||||
context['_'] = context['t'] # Alias for templates using _()
|
||||
|
||||
# Add timezone
|
||||
context['timezone'] = settings.TZ
|
||||
|
||||
# Add panel name and custom logo check
|
||||
context['panel_name'] = settings.PANEL_NAME
|
||||
context['custom_logo_exists'] = custom_logo_exists()
|
||||
|
||||
return context
|
||||
1298
backend/app/templates/base.html
Normal file
1298
backend/app/templates/base.html
Normal file
File diff suppressed because it is too large
Load Diff
13
backend/app/templates/containers.html
Normal file
13
backend/app/templates/containers.html
Normal file
@@ -0,0 +1,13 @@
|
||||
{% extends "base.html" %}
|
||||
{% set page_title = t('docker_management') %}
|
||||
{% block content %}
|
||||
<div class="card">
|
||||
<h3><i class="fa-brands fa-docker"></i> {{ t('docker_containers') }}</h3>
|
||||
<p class="text-muted" style="margin-top: 1rem;">
|
||||
{{ t('section_in_development') }}
|
||||
</p>
|
||||
<div style="margin-top: 1.5rem;">
|
||||
<a href="/servers" class="btn btn-primary">← {{ t('to_servers') }}</a>
|
||||
</div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
270
backend/app/templates/dashboard.html
Normal file
270
backend/app/templates/dashboard.html
Normal file
@@ -0,0 +1,270 @@
|
||||
{% extends "base.html" %}
|
||||
{% set page_title = t('nav_dashboard') %}
|
||||
{% block content %}
|
||||
<div class="stats-grid">
|
||||
<div class="stat-card">
|
||||
<div class="stat-label">{{ t('proxmox_servers') }}</div>
|
||||
<div class="stat-value">{{ stats.total_servers }}</div>
|
||||
</div>
|
||||
<div class="stat-card">
|
||||
<div class="stat-label">{{ t('online') }}</div>
|
||||
<div class="stat-value text-success">{{ stats.online_servers }}</div>
|
||||
</div>
|
||||
<div class="stat-card">
|
||||
<div class="stat-label">{{ t('offline') }}</div>
|
||||
<div class="stat-value text-danger">{{ stats.offline_servers }}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Графики Proxmox нод -->
|
||||
<div class="card" id="proxmox-charts-section" style="display: none;">
|
||||
<h3><i class="fa-solid fa-chart-line"></i> {{ t('proxmox_nodes_load') }}</h3>
|
||||
<div class="dashboard-charts-grid" id="nodes-charts-grid"></div>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.dashboard-charts-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(350px, 1fr));
|
||||
gap: 1rem;
|
||||
margin-top: 1rem;
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.dashboard-charts-grid {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.stats-grid {
|
||||
grid-template-columns: 1fr !important;
|
||||
}
|
||||
|
||||
.stat-card {
|
||||
padding: 1rem;
|
||||
}
|
||||
|
||||
.stat-value {
|
||||
font-size: 1.75rem;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 480px) {
|
||||
.dashboard-charts-grid .card h4 {
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
<script>
|
||||
// Загрузка статистики и графиков Proxmox нод
|
||||
async function loadProxmoxNodesStats() {
|
||||
try {
|
||||
const response = await fetchWithAuth('/proxmox/api/servers');
|
||||
if (!response) return;
|
||||
|
||||
const servers = await response.json();
|
||||
const onlineServers = servers.filter(s => s.is_online);
|
||||
|
||||
if (onlineServers.length === 0) return;
|
||||
|
||||
const chartsSection = document.getElementById('proxmox-charts-section');
|
||||
const chartsGrid = document.getElementById('nodes-charts-grid');
|
||||
|
||||
chartsGrid.innerHTML = '';
|
||||
|
||||
// Собрать все данные сначала, потом отрисовать
|
||||
const chartsToRender = [];
|
||||
const seenNodes = new Set(); // Для дедупликации нод кластера
|
||||
|
||||
// Загрузить данные для каждого сервера
|
||||
for (const server of onlineServers) {
|
||||
try {
|
||||
// Получить список нод
|
||||
const nodesResponse = await fetchWithAuth(`/proxmox/api/${server.id}/nodes`);
|
||||
if (!nodesResponse || !nodesResponse.ok) {
|
||||
console.warn(`Failed to load nodes for ${server.name}`);
|
||||
continue;
|
||||
}
|
||||
|
||||
const nodesData = await nodesResponse.json();
|
||||
const nodes = nodesData.nodes || [];
|
||||
|
||||
if (nodes.length === 0) {
|
||||
console.warn(`No nodes found for ${server.name}`);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Для кластеров берём только ПЕРВУЮ ноду, т.к. все серверы кластера имеют одинаковые ноды
|
||||
// Используем IP сервера + имя ноды для дедупликации
|
||||
const node = nodes[0].node;
|
||||
const nodeKey = `${server.ip_address}-${node}`;
|
||||
|
||||
if (seenNodes.has(nodeKey)) {
|
||||
continue; // Уже показали эту ноду
|
||||
}
|
||||
seenNodes.add(nodeKey);
|
||||
|
||||
// Получить данные для графиков
|
||||
const rrdResponse = await fetchWithAuth(`/proxmox/api/${server.id}/node/rrddata?node=${node}&timeframe=hour`);
|
||||
if (!rrdResponse || !rrdResponse.ok) {
|
||||
console.warn(`Failed to load RRD data for ${server.name}/${node}, skipping chart`);
|
||||
continue;
|
||||
}
|
||||
|
||||
const rrdData = await rrdResponse.json();
|
||||
const data = rrdData.data || [];
|
||||
|
||||
if (data.length === 0) {
|
||||
console.warn(`No RRD data for ${server.name}/${node}`);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Сохранить данные для отрисовки
|
||||
chartsToRender.push({
|
||||
canvasId: `chart-${server.id}-${node}`,
|
||||
serverName: server.name,
|
||||
nodeName: node,
|
||||
data: data
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error(`Error loading stats for server ${server.id}:`, error);
|
||||
}
|
||||
}
|
||||
|
||||
// Теперь создать все canvas элементы
|
||||
if (chartsToRender.length > 0) {
|
||||
let html = '';
|
||||
for (const chart of chartsToRender) {
|
||||
// Извлекаем базовое имя сервера (убираем " - nodeX" если есть)
|
||||
let baseServerName = chart.serverName.trim();
|
||||
// Если имя сервера заканчивается на " - <nodeName>", убираем это
|
||||
const nodePattern = new RegExp(`\\s*-\\s*(pve\\d+|node\\d+|${chart.nodeName})$`, 'i');
|
||||
baseServerName = baseServerName.replace(nodePattern, '').trim();
|
||||
|
||||
// Формируем отображаемое имя
|
||||
// Если базовое имя пустое или равно имени ноды — просто показываем имя ноды
|
||||
let displayName;
|
||||
if (!baseServerName || baseServerName.toLowerCase() === chart.nodeName.toLowerCase()) {
|
||||
displayName = chart.nodeName;
|
||||
} else {
|
||||
displayName = `${baseServerName} - ${chart.nodeName}`;
|
||||
}
|
||||
html += `
|
||||
<div class="card">
|
||||
<h4 style="margin: 0 0 1rem 0;">${displayName}</h4>
|
||||
<canvas id="${chart.canvasId}" style="max-height: 250px;"></canvas>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
chartsGrid.innerHTML = html;
|
||||
chartsSection.style.display = 'block';
|
||||
|
||||
// Отрисовать все графики после того как DOM обновился
|
||||
requestAnimationFrame(() => {
|
||||
for (const chart of chartsToRender) {
|
||||
drawNodeChart(chart.canvasId, chart.data);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error loading Proxmox stats:', error);
|
||||
}
|
||||
}
|
||||
|
||||
// Отрисовка графика ноды
|
||||
function drawNodeChart(canvasId, data) {
|
||||
if (typeof Chart === 'undefined') {
|
||||
console.error('Chart.js not loaded');
|
||||
return;
|
||||
}
|
||||
|
||||
const ctx = document.getElementById(canvasId);
|
||||
if (!ctx) {
|
||||
console.error('Canvas not found:', canvasId);
|
||||
return;
|
||||
}
|
||||
|
||||
const locale = "{{ 'ru-RU' if lang == 'ru' else 'en-US' }}";
|
||||
const formatTime = (timestamp) => {
|
||||
const date = new Date(timestamp * 1000);
|
||||
return date.toLocaleTimeString(locale, { hour: '2-digit', minute: '2-digit' });
|
||||
};
|
||||
|
||||
new Chart(ctx, {
|
||||
type: 'line',
|
||||
data: {
|
||||
labels: data.map(d => formatTime(d.time)),
|
||||
datasets: [
|
||||
{
|
||||
label: '{{ t('cpu') }} %',
|
||||
data: data.map(d => ((d.cpu || 0) * 100).toFixed(2)),
|
||||
borderColor: '#60a5fa',
|
||||
backgroundColor: 'rgba(96,165,250,0.1)',
|
||||
borderWidth: 2,
|
||||
tension: 0.4,
|
||||
fill: true,
|
||||
pointRadius: 0,
|
||||
yAxisID: 'y'
|
||||
},
|
||||
{
|
||||
label: '{{ t('memory') }} {{ t('gb') }}',
|
||||
data: data.map(d => ((d.memused || 0) / (1024*1024*1024)).toFixed(2)),
|
||||
borderColor: '#f59e0b',
|
||||
backgroundColor: 'rgba(245,158,11,0.1)',
|
||||
borderWidth: 2,
|
||||
tension: 0.4,
|
||||
fill: true,
|
||||
pointRadius: 0,
|
||||
yAxisID: 'y1'
|
||||
}
|
||||
]
|
||||
},
|
||||
options: {
|
||||
responsive: true,
|
||||
maintainAspectRatio: true,
|
||||
plugins: {
|
||||
legend: {
|
||||
display: true,
|
||||
position: 'top',
|
||||
labels: { color: '#9ca3af', usePointStyle: true, padding: 10 }
|
||||
},
|
||||
tooltip: { enabled: true, mode: 'index', intersect: false }
|
||||
},
|
||||
scales: {
|
||||
x: {
|
||||
type: 'category',
|
||||
grid: { color: 'rgba(255,255,255,0.1)' },
|
||||
ticks: { color: '#9ca3af', maxTicksLimit: 10 }
|
||||
},
|
||||
y: {
|
||||
type: 'linear',
|
||||
display: true,
|
||||
position: 'left',
|
||||
beginAtZero: true,
|
||||
grid: { color: 'rgba(255,255,255,0.1)' },
|
||||
ticks: { color: '#9ca3af' },
|
||||
title: { display: true, text: '{{ t('cpu') }} %', color: '#60a5fa' }
|
||||
},
|
||||
y1: {
|
||||
type: 'linear',
|
||||
display: true,
|
||||
position: 'right',
|
||||
beginAtZero: true,
|
||||
grid: { drawOnChartArea: false },
|
||||
ticks: { color: '#9ca3af' },
|
||||
title: { display: true, text: '{{ t('memory') }} {{ t('gb') }}', color: '#f59e0b' }
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Инициализация при полной загрузке DOM
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
// Загрузить графики нод
|
||||
loadProxmoxNodesStats();
|
||||
});
|
||||
</script>
|
||||
{% endblock %}
|
||||
2152
backend/app/templates/instance_detail.html
Normal file
2152
backend/app/templates/instance_detail.html
Normal file
File diff suppressed because it is too large
Load Diff
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user