ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.
Python astracloudflarecontrol-panelcyberpaneldnsfablehosting-control-panelhosting-panelkimi-k3server-managementserverkitubuntu-web-panelwebserver
feat(git)!: split the Gitea self-host half into the serverkit-git extension (plan 52 Phase 6)
Juan Denisdb59ad2da621
diff --git a/backend/app/api/git.py b/backend/app/api/git.pyindex d7e20376..bdd1be0e 100644--- a/backend/app/api/git.py+++ b/backend/app/api/git.py@@ -2,7 +2,11 @@# visibility (require_app_member); webhook reads are scoped to the linked app's# visibility (an unlinked webhook stays panel-wide viewer-visible). Webhook# mutations and the Gitea host lifecycle stay admin-only.-"""Git Server API endpoints for managing integrated Gitea instance and webhooks."""+"""Git webhook + deployment API — the deploy-pipeline half.++The Gitea self-host surface (lifecycle + repo browsing) moved to the+serverkit-git extension (plan 52 Phase 6), which mounts it back at this same+/api/v1/git prefix when installed."""from flask import Blueprint, request, jsonify@@ -11,9 +15,7 @@ from ..middleware.rbac import (get_current_user, app_access_tier,)from ..models import Application, GitWebhook-from ..services.git_service import GitServicefrom ..services.webhook_service import WebhookService-from ..services.gitea_api_service import GiteaAPIServicefrom ..services.git_deploy_service import GitDeployServicegit_bp = Blueprint('git', __name__)@@ -34,85 +36,6 @@ def _webhook_visible_to(user, webhook):return app_access_tier(user, app) is not None-@git_bp.route('/status', methods=['GET'])-@viewer_required-def get_status():- """Get Gitea installation status."""- result = GitService.get_gitea_status()- return jsonify(result), 200---@git_bp.route('/requirements', methods=['GET'])-@viewer_required-def get_requirements():- """Get resource requirements for Gitea installation."""- result = GitService.get_gitea_resource_requirements()- return jsonify(result), 200---@git_bp.route('/install', methods=['POST'])-@admin_required-def install():- """Install Gitea with PostgreSQL."""- data = request.get_json() or {}-- result = GitService.install_gitea(- admin_user=data.get('adminUser', 'admin'),- admin_email=data.get('adminEmail'),- admin_password=data.get('adminPassword')- )-- if result.get('success'):- return jsonify(result), 201- return jsonify(result), 400---@git_bp.route('/uninstall', methods=['POST'])-@admin_required-def uninstall():- """Uninstall Gitea and optionally remove data."""- data = request.get_json() or {}-- result = GitService.uninstall_gitea(- remove_data=data.get('removeData', False)- )-- if result.get('success'):- return jsonify(result), 200- return jsonify(result), 400---@git_bp.route('/start', methods=['POST'])-@admin_required-def start():- """Start Gitea server."""- result = GitService.start_gitea()-- if result.get('success'):- return jsonify(result), 200- return jsonify(result), 400---@git_bp.route('/stop', methods=['POST'])-@admin_required-def stop():- """Stop Gitea server."""- result = GitService.stop_gitea()-- if result.get('success'):- return jsonify(result), 200- return jsonify(result), 400---@git_bp.route('/restart', methods=['POST'])-@admin_required-def restart():- """Restart Gitea server."""- result = GitService.restart_gitea()-- if result.get('success'):- return jsonify(result), 200- return jsonify(result), 400# ==================== WEBHOOK ENDPOINTS ====================@@ -276,163 +199,6 @@ def receive_webhook(token):return jsonify(result), 400-# ==================== REPOSITORY ENDPOINTS ====================--@git_bp.route('/repos', methods=['GET'])-@viewer_required-def list_repositories():- """List all repositories in Gitea."""- token = request.args.get('token')- limit = request.args.get('limit', 50, type=int)-- result = GiteaAPIService.list_repositories(token=token, limit=limit)-- if result.get('success'):- return jsonify(result), 200- return jsonify(result), 400---@git_bp.route('/repos/<owner>/<repo>', methods=['GET'])-@viewer_required-def get_repository(owner, repo):- """Get repository details."""- token = request.args.get('token')-- result = GiteaAPIService.get_repository(owner, repo, token=token)-- if result.get('success'):- return jsonify(result), 200- return jsonify(result), 404---@git_bp.route('/repos/<owner>/<repo>/stats', methods=['GET'])-@viewer_required-def get_repo_stats(owner, repo):- """Get repository statistics."""- token = request.args.get('token')-- result = GiteaAPIService.get_repo_stats(owner, repo, token=token)-- if result.get('success'):- return jsonify(result), 200- return jsonify(result), 400---@git_bp.route('/repos/<owner>/<repo>/branches', methods=['GET'])-@viewer_required-def list_branches(owner, repo):- """List repository branches."""- token = request.args.get('token')-- result = GiteaAPIService.list_branches(owner, repo, token=token)-- if result.get('success'):- return jsonify(result), 200- return jsonify(result), 400---@git_bp.route('/repos/<owner>/<repo>/branches/<branch>', methods=['GET'])-@viewer_required-def get_branch(owner, repo, branch):- """Get branch details."""- token = request.args.get('token')-- result = GiteaAPIService.get_branch(owner, repo, branch, token=token)-- if result.get('success'):- return jsonify(result), 200- return jsonify(result), 404---@git_bp.route('/repos/<owner>/<repo>/commits', methods=['GET'])-@viewer_required-def list_commits(owner, repo):- """List repository commits."""- token = request.args.get('token')- branch = request.args.get('branch')- page = request.args.get('page', 1, type=int)- limit = request.args.get('limit', 30, type=int)-- result = GiteaAPIService.list_commits(- owner, repo,- branch=branch,- page=page,- limit=limit,- token=token- )-- if result.get('success'):- return jsonify(result), 200- return jsonify(result), 400---@git_bp.route('/repos/<owner>/<repo>/commits/<sha>', methods=['GET'])-@viewer_required-def get_commit(owner, repo, sha):- """Get commit details."""- token = request.args.get('token')-- result = GiteaAPIService.get_commit(owner, repo, sha, token=token)-- if result.get('success'):- return jsonify(result), 200- return jsonify(result), 404---@git_bp.route('/repos/<owner>/<repo>/contents', methods=['GET'])-@viewer_required-def list_files(owner, repo):- """List files in repository directory."""- token = request.args.get('token')- ref = request.args.get('ref', 'main')- path = request.args.get('path', '')-- result = GiteaAPIService.list_files(owner, repo, ref=ref, path=path, token=token)-- if result.get('success'):- return jsonify(result), 200- return jsonify(result), 400---@git_bp.route('/repos/<owner>/<repo>/contents/<path:filepath>', methods=['GET'])-@viewer_required-def get_file_content(owner, repo, filepath):- """Get file content."""- token = request.args.get('token')- ref = request.args.get('ref', 'main')-- result = GiteaAPIService.get_file_content(owner, repo, filepath, ref=ref, token=token)-- if result.get('success'):- return jsonify(result), 200- return jsonify(result), 404---@git_bp.route('/repos/<owner>/<repo>/readme', methods=['GET'])-@viewer_required-def get_readme(owner, repo):- """Get repository README."""- token = request.args.get('token')- ref = request.args.get('ref')-- result = GiteaAPIService.get_readme(owner, repo, ref=ref, token=token)-- if result.get('success'):- return jsonify(result), 200- return jsonify(result), 404---@git_bp.route('/version', methods=['GET'])-@viewer_required-def get_gitea_version():- """Get Gitea server version."""- result = GiteaAPIService.get_server_version()-- if result.get('success'):- return jsonify(result), 200- return jsonify(result), 400--# ==================== DEPLOYMENT ENDPOINTS ====================@git_bp.route('/deployments/app/<int:app_id>', methods=['GET'])diff --git a/backend/app/services/extension_migration.py b/backend/app/services/extension_migration.pyindex bac27108..81cf3455 100644--- a/backend/app/services/extension_migration.py+++ b/backend/app/services/extension_migration.py@@ -76,6 +76,20 @@ def remove_retired_extensions():logger.warning(f'Could not remove retired extension row {slug}: {e}')+def _gitea_was_used():+ """True if this panel actually runs the self-hosted Gitea the git+ extension manages — the panel-managed application row exists. Gates+ serverkit-git auto-install after its backend split (plan 52 Phase 6) so+ only Gitea operators get the extension back automatically; deploys from+ external remotes never depended on it."""+ try:+ from app.models import Application+ return (Application.query.filter_by(name='serverkit-gitea').first()+ is not None)+ except Exception:+ return False++def _email_was_configured():"""True if this panel actually ran a mail server before the extraction — anyemail domain/account row exists. Used to gate serverkit-email auto-install so@@ -94,6 +108,7 @@ def _email_was_configured():# the feature just see it in the Marketplace.GATED_BUILTIN_SLUGS = {'serverkit-email': _email_was_configured,+ 'serverkit-git': _gitea_was_used,}@@ -333,7 +348,11 @@ def run_backend_acquisition():returnchanged = False- for slug in CONVERTED_BUILTIN_SLUGS:+ # Gated slugs join the sweep: acquisition only ever fires for a slug the+ # panel already INSTALLED whose builtin now ships a backend it lacks on+ # disk (serverkit-git gained one in the plan 52 Phase 6 split), so the+ # usage gate has already been answered by the install itself.+ for slug in list(CONVERTED_BUILTIN_SLUGS) + list(GATED_BUILTIN_SLUGS):if slug in done:continueentry = builtins.get(slug)diff --git a/backend/app/services/git_service.py b/backend/app/services/git_service.pyindex abdfdbcd..548b7dfb 100644--- a/backend/app/services/git_service.py+++ b/backend/app/services/git_service.py@@ -609,273 +609,12 @@ class GitService:return logs- # ========================================- # GITEA SERVER MANAGEMENT- # ========================================-- GITEA_APP_NAME = 'serverkit-gitea'- GITEA_CONFIG_FILE = os.path.join(CONFIG_DIR, 'gitea.json')-- @classmethod- def get_gitea_status(cls) -> Dict:- """Check if Gitea is installed and running."""- from app.models import Application-- app = Application.query.filter_by(name=cls.GITEA_APP_NAME).first()-- if not app:- return {- 'installed': False,- 'running': False,- 'http_port': None,- 'ssh_port': None,- 'url': None,- 'url_path': None- }-- # Check container status- running = cls._is_gitea_running()-- # Load config for ports- config = cls._load_gitea_config()-- # Prefer the panel's canonical origin so the link works through a domain- # and Cloudflare; fall back to the local port only when no domain is set.- from app.services.site_domain_service import SiteDomainService- panel_origin = SiteDomainService.panel_origin()- if panel_origin:- public_url = f"{panel_origin}/gitea"- elif app.port:- public_url = f"http://localhost:{app.port}"- else:- public_url = None-- return {- 'installed': True,- 'running': running,- 'http_port': app.port or config.get('http_port'),- 'ssh_port': config.get('ssh_port'),- 'url_path': '/gitea',- 'url': public_url,- 'app_id': app.id,- 'version': config.get('version', '1.21')- }-- @classmethod- def _is_gitea_running(cls) -> bool:- """Check if Gitea container is running."""- try:- result = run_checked(- ['docker', 'ps', '--filter', f'name={cls.GITEA_APP_NAME}',- '--format', '{{.Names}}'], timeout=10)- return cls.GITEA_APP_NAME in result['output']- except Exception:- return False-- @classmethod- def _load_gitea_config(cls) -> Dict:- """Load Gitea configuration."""- if os.path.exists(cls.GITEA_CONFIG_FILE):- try:- with open(cls.GITEA_CONFIG_FILE, 'r') as f:- return json.load(f)- except Exception:- pass- return {}-- @classmethod- def _save_gitea_config(cls, config: Dict) -> bool:- """Save Gitea configuration."""- try:- os.makedirs(cls.CONFIG_DIR, exist_ok=True)- with open(cls.GITEA_CONFIG_FILE, 'w') as f:- json.dump(config, f, indent=2)- return True- except Exception:- return False-- @classmethod- def get_gitea_resource_requirements(cls) -> Dict:- """Get resource requirements for Gitea installation."""- return {- 'memory_min': '512MB',- 'memory_recommended': '1GB',- 'storage_min': '5GB',- 'storage_recommended': '20GB',- 'components': [- {'name': 'Gitea', 'memory': '~300MB', 'storage': '~100MB + repos'},- {'name': 'PostgreSQL', 'memory': '~200MB', 'storage': '~1GB'}- ],- 'warning': 'Installation will spin up a PostgreSQL database container'- }-- @classmethod- def install_gitea(cls, admin_user: str = 'admin',- admin_email: str = None,- admin_password: str = None) -> Dict:- """Install Gitea as integrated ServerKit service."""- from app.services.template_service import TemplateService- from app.services.nginx_service import NginxService-- # Check if already installed- status = cls.get_gitea_status()- if status['installed']:- return {'success': False, 'error': 'Gitea is already installed'}-- # Generate secure password if not provided- generated_password = False- if not admin_password:- admin_password = secrets.token_urlsafe(16)- generated_password = True-- try:- # Install using template service- result = TemplateService.install_template(- template_id='gitea',- app_name=cls.GITEA_APP_NAME,- user_variables={},- user_id=1 # System user- )-- if not result.get('success'):- return result-- # Get the variables that were generated- variables = result.get('variables', {})- http_port = variables.get('HTTP_PORT')- ssh_port = variables.get('SSH_PORT')-- # Create nginx config for /gitea path- nginx_result = NginxService.create_gitea_config(int(http_port))- if not nginx_result.get('success'):- # Log warning but don't fail - Gitea still works via port- print(f"Warning: Failed to create Gitea nginx config: {nginx_result.get('error')}")-- # Save config with admin credentials and ports- config = {- 'admin_user': admin_user,- 'admin_email': admin_email,- 'http_port': http_port,- 'ssh_port': ssh_port,- 'db_password': variables.get('DB_PASSWORD'),- 'installed_at': datetime.now().isoformat(),- 'version': '1.21',- 'url_path': '/gitea'- }- cls._save_gitea_config(config)-- response = {- 'success': True,- 'message': 'Gitea installed successfully',- 'http_port': http_port,- 'ssh_port': ssh_port,- 'url_path': '/gitea',- 'admin_user': admin_user- }-- # Only include password in response if it was generated- if generated_password:- response['admin_password'] = admin_password- response['warning'] = 'Save these credentials - password shown only once!'-- return response-- except Exception as e:- return {'success': False, 'error': str(e)}-- @classmethod- def uninstall_gitea(cls, remove_data: bool = False) -> Dict:- """Uninstall Gitea."""- from app import db- from app.models import Application- from app.services.docker_service import DockerService- from app.services.nginx_service import NginxService-- app = Application.query.filter_by(name=cls.GITEA_APP_NAME).first()- if not app:- return {'success': False, 'error': 'Gitea is not installed'}-- try:- # Remove nginx config- NginxService.remove_gitea_config()-- # Stop and remove containers- if app.root_path and os.path.exists(app.root_path):- DockerService.compose_down(app.root_path, remove_volumes=remove_data)-- if remove_data:- import shutil- shutil.rmtree(app.root_path, ignore_errors=True)-- # Remove from database- db.session.delete(app)- db.session.commit()-- # Remove config- if os.path.exists(cls.GITEA_CONFIG_FILE):- os.remove(cls.GITEA_CONFIG_FILE)-- return {- 'success': True,- 'message': 'Gitea uninstalled successfully',- 'data_removed': remove_data- }-- except Exception as e:- return {'success': False, 'error': str(e)}-- @classmethod- def start_gitea(cls) -> Dict:- """Start Gitea containers."""- from app import db- from app.models import Application- from app.services.docker_service import DockerService-- app = Application.query.filter_by(name=cls.GITEA_APP_NAME).first()- if not app:- return {'success': False, 'error': 'Gitea is not installed'}-- if not app.root_path or not os.path.exists(app.root_path):- return {'success': False, 'error': 'Gitea installation path not found'}-- try:- result = DockerService.compose_up(app.root_path, detach=True)- if result.get('success'):- app.status = 'running'- db.session.commit()- return {'success': True, 'message': 'Gitea started'}- return result- except Exception as e:- return {'success': False, 'error': str(e)}-- @classmethod- def stop_gitea(cls) -> Dict:- """Stop Gitea containers."""- from app import db- from app.models import Application- from app.services.docker_service import DockerService-- app = Application.query.filter_by(name=cls.GITEA_APP_NAME).first()- if not app:- return {'success': False, 'error': 'Gitea is not installed'}-- if not app.root_path or not os.path.exists(app.root_path):- return {'success': False, 'error': 'Gitea installation path not found'}-- try:- result = DockerService.compose_stop(app.root_path)- if result.get('success'):- app.status = 'stopped'- db.session.commit()- return {'success': True, 'message': 'Gitea stopped'}- return result- except Exception as e:- return {'success': False, 'error': str(e)}-- @classmethod- def restart_gitea(cls) -> Dict:- """Restart Gitea containers."""- stop_result = cls.stop_gitea()- if not stop_result.get('success'):- return stop_result- return cls.start_gitea()+ # ------------------------------------------------------------------+ # The Gitea self-host half (install/lifecycle/config + repo browsing+ # via GiteaAPIService) moved to the serverkit-git extension (plan 52+ # Phase 6). Everything above IS the deploy pipeline and stays core:+ # apps.py / buildpacks.py / deploy.py / deployment_service.py /+ # manifest_apply_service.py import it, extension installed or not.+ # NginxService.create/remove/get_gitea_config remain core helpers the+ # extension calls (the WP two-speed seam shape).+ # ------------------------------------------------------------------diff --git a/backend/tests/test_git_split.py b/backend/tests/test_git_split.pynew file mode 100644index 00000000..3c2c2cf4--- /dev/null+++ b/backend/tests/test_git_split.py@@ -0,0 +1,79 @@+"""Prove the serverkit-git backend split (plan 52 Phase 6).++The Gitea self-host half (server lifecycle + repo browsing) moved into the+serverkit-git extension; the deploy-side git CLI operations and the webhook ++deployment routes stay core — they ARE the deploy pipeline and must never+depend on the extension. These tests pin the absent-extension shape.+"""+from app.services.git_service import GitService+++GITEA_ROUTES = [+ '/api/v1/git/status',+ '/api/v1/git/requirements',+ '/api/v1/git/install',+ '/api/v1/git/repos',+ '/api/v1/git/version',+]++CORE_GIT_ROUTES = [+ '/api/v1/git/webhooks',+ '/api/v1/git/webhooks/receive/<token>',+ '/api/v1/git/deployments/app/<int:app_id>',+ '/api/v1/git/deployments/<int:deployment_id>',+]+++def test_gitea_routes_are_unrouted_without_extension(app):+ rules = {r.rule for r in app.url_map.iter_rules()}+ for path in GITEA_ROUTES:+ assert path not in rules, f'{path}: Gitea route still in core'+++def test_deploy_pipeline_routes_stay_core(app):+ rules = {r.rule for r in app.url_map.iter_rules()}+ for path in CORE_GIT_ROUTES:+ assert path in rules, f'{path}: deploy-pipeline route missing from core'+++def test_gitea_routes_404_before_auth(client):+ for path in ('/api/v1/git/status', '/api/v1/git/repos'):+ resp = client.get(path)+ assert resp.status_code == 404, f'{path} -> {resp.status_code}'+++def test_git_service_shed_the_gitea_half():+ for gone in [+ 'get_gitea_status', 'install_gitea', 'uninstall_gitea',+ 'start_gitea', 'stop_gitea', 'restart_gitea',+ 'get_gitea_resource_requirements', 'GITEA_APP_NAME',+ ]:+ assert not hasattr(GitService, gone), f'GitService.{gone} still exists'+++def test_git_service_keeps_the_deploy_half():+ """The 5 core importers (apps/buildpacks/deploy/deployment/manifest_apply)+ keep every method they call."""+ for kept in [+ 'get_config', 'save_config', 'get_app_config', 'configure_deployment',+ 'remove_deployment', 'clone_repository', 'pull_changes',+ 'get_commit_info', 'deploy', '_run_script', 'verify_webhook',+ 'get_remote_branches', 'get_remote_branches_from_url', 'handle_webhook',+ 'get_deployment_history', 'get_git_status', 'log_webhook',+ 'get_webhook_logs',+ ]:+ assert hasattr(GitService, kept), f'GitService.{kept} missing'+++def test_gitea_api_service_left_core():+ import pytest+ with pytest.raises(ImportError):+ __import__('app.services.gitea_api_service')+++def test_nginx_gitea_helpers_stay_core():+ """Deliberate core seam (the WP two-speed shape): the extension's+ install/uninstall call these; they must keep existing in core."""+ from app.services.nginx_service import NginxService+ for kept in ('create_gitea_config', 'remove_gitea_config', 'get_gitea_config'):+ assert hasattr(NginxService, kept)diff --git a/builtin-extensions/serverkit-git/backend/__init__.py b/builtin-extensions/serverkit-git/backend/__init__.pynew file mode 100644index 00000000..e69de29bdiff --git a/builtin-extensions/serverkit-git/backend/gitea.py b/builtin-extensions/serverkit-git/backend/gitea.pynew file mode 100644index 00000000..fa4502d3--- /dev/null+++ b/builtin-extensions/serverkit-git/backend/gitea.py@@ -0,0 +1,256 @@+"""Gitea self-host routes — the serverkit-git extension's blueprint.++Moved verbatim out of core ``app/api/git.py`` (plan 52 Phase 6) and mounted+back at the same ``/api/v1/git`` prefix when the extension is installed, so+route shapes never change. The webhook receiver and deployment routes STAY+core on ``git_bp`` — they are the deploy pipeline.+"""+from flask import Blueprint, request, jsonify++from app.middleware.rbac import admin_required, viewer_required++from .gitea_service import GiteaServerService+from .gitea_api_service import GiteaAPIService++gitea_bp = Blueprint('git_gitea', __name__)+++@gitea_bp.route('/status', methods=['GET'])+@viewer_required+def get_status():+ """Get Gitea installation status."""+ result = GiteaServerService.get_gitea_status()+ return jsonify(result), 200+++@gitea_bp.route('/requirements', methods=['GET'])+@viewer_required+def get_requirements():+ """Get resource requirements for Gitea installation."""+ result = GiteaServerService.get_gitea_resource_requirements()+ return jsonify(result), 200+++@gitea_bp.route('/install', methods=['POST'])+@admin_required+def install():+ """Install Gitea with PostgreSQL."""+ data = request.get_json() or {}++ result = GiteaServerService.install_gitea(+ admin_user=data.get('adminUser', 'admin'),+ admin_email=data.get('adminEmail'),+ admin_password=data.get('adminPassword')+ )++ if result.get('success'):+ return jsonify(result), 201+ return jsonify(result), 400+++@gitea_bp.route('/uninstall', methods=['POST'])+@admin_required+def uninstall():+ """Uninstall Gitea and optionally remove data."""+ data = request.get_json() or {}++ result = GiteaServerService.uninstall_gitea(+ remove_data=data.get('removeData', False)+ )++ if result.get('success'):+ return jsonify(result), 200+ return jsonify(result), 400+++@gitea_bp.route('/start', methods=['POST'])+@admin_required+def start():+ """Start Gitea server."""+ result = GiteaServerService.start_gitea()++ if result.get('success'):+ return jsonify(result), 200+ return jsonify(result), 400+++@gitea_bp.route('/stop', methods=['POST'])+@admin_required+def stop():+ """Stop Gitea server."""+ result = GiteaServerService.stop_gitea()++ if result.get('success'):+ return jsonify(result), 200+ return jsonify(result), 400+++@gitea_bp.route('/restart', methods=['POST'])+@admin_required+def restart():+ """Restart Gitea server."""+ result = GiteaServerService.restart_gitea()++ if result.get('success'):+ return jsonify(result), 200+ return jsonify(result), 400+++# ==================== WEBHOOK ENDPOINTS ====================++@gitea_bp.route('/repos', methods=['GET'])+@viewer_required+def list_repositories():+ """List all repositories in Gitea."""+ token = request.args.get('token')+ limit = request.args.get('limit', 50, type=int)++ result = GiteaAPIService.list_repositories(token=token, limit=limit)++ if result.get('success'):+ return jsonify(result), 200+ return jsonify(result), 400+++@gitea_bp.route('/repos/<owner>/<repo>', methods=['GET'])+@viewer_required+def get_repository(owner, repo):+ """Get repository details."""+ token = request.args.get('token')++ result = GiteaAPIService.get_repository(owner, repo, token=token)++ if result.get('success'):+ return jsonify(result), 200+ return jsonify(result), 404+++@gitea_bp.route('/repos/<owner>/<repo>/stats', methods=['GET'])+@viewer_required+def get_repo_stats(owner, repo):+ """Get repository statistics."""+ token = request.args.get('token')++ result = GiteaAPIService.get_repo_stats(owner, repo, token=token)++ if result.get('success'):+ return jsonify(result), 200+ return jsonify(result), 400+++@gitea_bp.route('/repos/<owner>/<repo>/branches', methods=['GET'])+@viewer_required+def list_branches(owner, repo):+ """List repository branches."""+ token = request.args.get('token')++ result = GiteaAPIService.list_branches(owner, repo, token=token)++ if result.get('success'):+ return jsonify(result), 200+ return jsonify(result), 400+++@gitea_bp.route('/repos/<owner>/<repo>/branches/<branch>', methods=['GET'])+@viewer_required+def get_branch(owner, repo, branch):+ """Get branch details."""+ token = request.args.get('token')++ result = GiteaAPIService.get_branch(owner, repo, branch, token=token)++ if result.get('success'):+ return jsonify(result), 200+ return jsonify(result), 404+++@gitea_bp.route('/repos/<owner>/<repo>/commits', methods=['GET'])+@viewer_required+def list_commits(owner, repo):+ """List repository commits."""+ token = request.args.get('token')+ branch = request.args.get('branch')+ page = request.args.get('page', 1, type=int)+ limit = request.args.get('limit', 30, type=int)++ result = GiteaAPIService.list_commits(+ owner, repo,+ branch=branch,+ page=page,+ limit=limit,+ token=token+ )++ if result.get('success'):+ return jsonify(result), 200+ return jsonify(result), 400+++@gitea_bp.route('/repos/<owner>/<repo>/commits/<sha>', methods=['GET'])+@viewer_required+def get_commit(owner, repo, sha):+ """Get commit details."""+ token = request.args.get('token')++ result = GiteaAPIService.get_commit(owner, repo, sha, token=token)++ if result.get('success'):+ return jsonify(result), 200+ return jsonify(result), 404+++@gitea_bp.route('/repos/<owner>/<repo>/contents', methods=['GET'])+@viewer_required+def list_files(owner, repo):+ """List files in repository directory."""+ token = request.args.get('token')+ ref = request.args.get('ref', 'main')+ path = request.args.get('path', '')++ result = GiteaAPIService.list_files(owner, repo, ref=ref, path=path, token=token)++ if result.get('success'):+ return jsonify(result), 200+ return jsonify(result), 400+++@gitea_bp.route('/repos/<owner>/<repo>/contents/<path:filepath>', methods=['GET'])+@viewer_required+def get_file_content(owner, repo, filepath):+ """Get file content."""+ token = request.args.get('token')+ ref = request.args.get('ref', 'main')++ result = GiteaAPIService.get_file_content(owner, repo, filepath, ref=ref, token=token)++ if result.get('success'):+ return jsonify(result), 200+ return jsonify(result), 404+++@gitea_bp.route('/repos/<owner>/<repo>/readme', methods=['GET'])+@viewer_required+def get_readme(owner, repo):+ """Get repository README."""+ token = request.args.get('token')+ ref = request.args.get('ref')++ result = GiteaAPIService.get_readme(owner, repo, ref=ref, token=token)++ if result.get('success'):+ return jsonify(result), 200+ return jsonify(result), 404+++@gitea_bp.route('/version', methods=['GET'])+@viewer_required+def get_gitea_version():+ """Get Gitea server version."""+ result = GiteaAPIService.get_server_version()++ if result.get('success'):+ return jsonify(result), 200+ return jsonify(result), 400+++# ==================== DEPLOYMENT ENDPOINTS ====================diff --git a/backend/app/services/gitea_api_service.py b/builtin-extensions/serverkit-git/backend/gitea_api_service.pysimilarity index 99%rename from backend/app/services/gitea_api_service.pyrename to builtin-extensions/serverkit-git/backend/gitea_api_service.pyindex fc235abe..7547483d 100644--- a/backend/app/services/gitea_api_service.py+++ b/builtin-extensions/serverkit-git/backend/gitea_api_service.py@@ -11,9 +11,9 @@ class GiteaAPIService:@classmethoddef _get_base_url(cls) -> Optional[str]:"""Get the Gitea base URL from config."""- from app.services.git_service import GitService+ from .gitea_service import GiteaServerService- status = GitService.get_gitea_status()+ status = GiteaServerService.get_gitea_status()if not status.get('installed') or not status.get('running'):return Nonediff --git a/builtin-extensions/serverkit-git/backend/gitea_service.py b/builtin-extensions/serverkit-git/backend/gitea_service.pynew file mode 100644index 00000000..b25595f5--- /dev/null+++ b/builtin-extensions/serverkit-git/backend/gitea_service.py@@ -0,0 +1,292 @@+"""Gitea self-host management — the serverkit-git extension's backend half.++Moved verbatim out of core ``GitService`` (plan 52 Phase 6): install/lifecycle+for the panel-managed Gitea container plus its config file. The deploy-side+git CLI operations (clone/pull/deploy/webhooks) STAY core in+``app.services.git_service`` — they are the deploy pipeline and must never+depend on this extension.++Core seams kept on purpose: ``NginxService.create/remove/get_gitea_config``+(the /gitea location blocks) remain core helpers this service calls, the same+two-speed shape as the WP fail2ban filter text.+"""+import os+import json+import logging+from typing import Dict++from app import paths+from app.utils.system import run_checked++logger = logging.getLogger(__name__)+++class GiteaServerService:+ CONFIG_DIR = paths.SERVERKIT_CONFIG_DIR++ GITEA_APP_NAME = 'serverkit-gitea'+ GITEA_CONFIG_FILE = os.path.join(CONFIG_DIR, 'gitea.json')++ @classmethod+ def get_gitea_status(cls) -> Dict:+ """Check if Gitea is installed and running."""+ from app.models import Application++ app = Application.query.filter_by(name=cls.GITEA_APP_NAME).first()++ if not app:+ return {+ 'installed': False,+ 'running': False,+ 'http_port': None,+ 'ssh_port': None,+ 'url': None,+ 'url_path': None+ }++ # Check container status+ running = cls._is_gitea_running()++ # Load config for ports+ config = cls._load_gitea_config()++ # Prefer the panel's canonical origin so the link works through a domain+ # and Cloudflare; fall back to the local port only when no domain is set.+ from app.services.site_domain_service import SiteDomainService+ panel_origin = SiteDomainService.panel_origin()+ if panel_origin:+ public_url = f"{panel_origin}/gitea"+ elif app.port:+ public_url = f"http://localhost:{app.port}"+ else:+ public_url = None++ return {+ 'installed': True,+ 'running': running,+ 'http_port': app.port or config.get('http_port'),+ 'ssh_port': config.get('ssh_port'),+ 'url_path': '/gitea',+ 'url': public_url,+ 'app_id': app.id,+ 'version': config.get('version', '1.21')+ }++ @classmethod+ def _is_gitea_running(cls) -> bool:+ """Check if Gitea container is running."""+ try:+ result = run_checked(+ ['docker', 'ps', '--filter', f'name={cls.GITEA_APP_NAME}',+ '--format', '{{.Names}}'], timeout=10)+ return cls.GITEA_APP_NAME in result['output']+ except Exception:+ return False++ @classmethod+ def _load_gitea_config(cls) -> Dict:+ """Load Gitea configuration."""+ if os.path.exists(cls.GITEA_CONFIG_FILE):+ try:+ with open(cls.GITEA_CONFIG_FILE, 'r') as f:+ return json.load(f)+ except Exception:+ pass+ return {}++ @classmethod+ def _save_gitea_config(cls, config: Dict) -> bool:+ """Save Gitea configuration."""+ try:+ os.makedirs(cls.CONFIG_DIR, exist_ok=True)+ with open(cls.GITEA_CONFIG_FILE, 'w') as f:+ json.dump(config, f, indent=2)+ return True+ except Exception:+ return False++ @classmethod+ def get_gitea_resource_requirements(cls) -> Dict:+ """Get resource requirements for Gitea installation."""+ return {+ 'memory_min': '512MB',+ 'memory_recommended': '1GB',+ 'storage_min': '5GB',+ 'storage_recommended': '20GB',+ 'components': [+ {'name': 'Gitea', 'memory': '~300MB', 'storage': '~100MB + repos'},+ {'name': 'PostgreSQL', 'memory': '~200MB', 'storage': '~1GB'}+ ],+ 'warning': 'Installation will spin up a PostgreSQL database container'+ }++ @classmethod+ def install_gitea(cls, admin_user: str = 'admin',+ admin_email: str = None,+ admin_password: str = None) -> Dict:+ """Install Gitea as integrated ServerKit service."""+ from app.services.template_service import TemplateService+ from app.services.nginx_service import NginxService++ # Check if already installed+ status = cls.get_gitea_status()+ if status['installed']:+ return {'success': False, 'error': 'Gitea is already installed'}++ # Generate secure password if not provided+ generated_password = False+ if not admin_password:+ admin_password = secrets.token_urlsafe(16)+ generated_password = True++ try:+ # Install using template service+ result = TemplateService.install_template(+ template_id='gitea',+ app_name=cls.GITEA_APP_NAME,+ user_variables={},+ user_id=1 # System user+ )++ if not result.get('success'):+ return result++ # Get the variables that were generated+ variables = result.get('variables', {})+ http_port = variables.get('HTTP_PORT')+ ssh_port = variables.get('SSH_PORT')++ # Create nginx config for /gitea path+ nginx_result = NginxService.create_gitea_config(int(http_port))+ if not nginx_result.get('success'):+ # Log warning but don't fail - Gitea still works via port+ print(f"Warning: Failed to create Gitea nginx config: {nginx_result.get('error')}")++ # Save config with admin credentials and ports+ config = {+ 'admin_user': admin_user,+ 'admin_email': admin_email,+ 'http_port': http_port,+ 'ssh_port': ssh_port,+ 'db_password': variables.get('DB_PASSWORD'),+ 'installed_at': datetime.now().isoformat(),+ 'version': '1.21',+ 'url_path': '/gitea'+ }+ cls._save_gitea_config(config)++ response = {+ 'success': True,+ 'message': 'Gitea installed successfully',+ 'http_port': http_port,+ 'ssh_port': ssh_port,+ 'url_path': '/gitea',+ 'admin_user': admin_user+ }++ # Only include password in response if it was generated+ if generated_password:+ response['admin_password'] = admin_password+ response['warning'] = 'Save these credentials - password shown only once!'++ return response++ except Exception as e:+ return {'success': False, 'error': str(e)}++ @classmethod+ def uninstall_gitea(cls, remove_data: bool = False) -> Dict:+ """Uninstall Gitea."""+ from app import db+ from app.models import Application+ from app.services.docker_service import DockerService+ from app.services.nginx_service import NginxService++ app = Application.query.filter_by(name=cls.GITEA_APP_NAME).first()+ if not app:+ return {'success': False, 'error': 'Gitea is not installed'}++ try:+ # Remove nginx config+ NginxService.remove_gitea_config()++ # Stop and remove containers+ if app.root_path and os.path.exists(app.root_path):+ DockerService.compose_down(app.root_path, remove_volumes=remove_data)++ if remove_data:+ import shutil+ shutil.rmtree(app.root_path, ignore_errors=True)++ # Remove from database+ db.session.delete(app)+ db.session.commit()++ # Remove config+ if os.path.exists(cls.GITEA_CONFIG_FILE):+ os.remove(cls.GITEA_CONFIG_FILE)++ return {+ 'success': True,+ 'message': 'Gitea uninstalled successfully',+ 'data_removed': remove_data+ }++ except Exception as e:+ return {'success': False, 'error': str(e)}++ @classmethod+ def start_gitea(cls) -> Dict:+ """Start Gitea containers."""+ from app import db+ from app.models import Application+ from app.services.docker_service import DockerService++ app = Application.query.filter_by(name=cls.GITEA_APP_NAME).first()+ if not app:+ return {'success': False, 'error': 'Gitea is not installed'}++ if not app.root_path or not os.path.exists(app.root_path):+ return {'success': False, 'error': 'Gitea installation path not found'}++ try:+ result = DockerService.compose_up(app.root_path, detach=True)+ if result.get('success'):+ app.status = 'running'+ db.session.commit()+ return {'success': True, 'message': 'Gitea started'}+ return result+ except Exception as e:+ return {'success': False, 'error': str(e)}++ @classmethod+ def stop_gitea(cls) -> Dict:+ """Stop Gitea containers."""+ from app import db+ from app.models import Application+ from app.services.docker_service import DockerService++ app = Application.query.filter_by(name=cls.GITEA_APP_NAME).first()+ if not app:+ return {'success': False, 'error': 'Gitea is not installed'}++ if not app.root_path or not os.path.exists(app.root_path):+ return {'success': False, 'error': 'Gitea installation path not found'}++ try:+ result = DockerService.compose_stop(app.root_path)+ if result.get('success'):+ app.status = 'stopped'+ db.session.commit()+ return {'success': True, 'message': 'Gitea stopped'}+ return result+ except Exception as e:+ return {'success': False, 'error': str(e)}++ @classmethod+ def restart_gitea(cls) -> Dict:+ """Restart Gitea containers."""+ stop_result = cls.stop_gitea()+ if not stop_result.get('success'):+ return stop_result+ return cls.start_gitea()diff --git a/builtin-extensions/serverkit-git/plugin.json b/builtin-extensions/serverkit-git/plugin.jsonindex 181b4ea8..ab209f26 100644--- a/builtin-extensions/serverkit-git/plugin.json+++ b/builtin-extensions/serverkit-git/plugin.json@@ -1,37 +1,50 @@{- "name": "serverkit-git",- "display_name": "Git Server",- "version": "1.0.0",- "description": "Self-hosted Git server (Gitea) exposed through the ServerKit extension system.",- "author": "ServerKit",- "license": "MIT",- "category": "deployment",- "homepage": "https://github.com/jhd3197/ServerKit",- "permissions": ["docker", "filesystem"],- "contributions": {- "nav": [- {- "id": "git",- "label": "Git",- "route": "/git",- "category": "infrastructure",- "icon": "<circle cx=\"18\" cy=\"18\" r=\"3\"/><circle cx=\"6\" cy=\"6\" r=\"3\"/><path d=\"M6 21V9a9 9 0 0 0 9 9\"/>"- }- ],- "routes": [- { "path": "git", "component": "GitExtensionPage" },- { "path": "git/:tab", "component": "GitExtensionPage" }- ],- "page_titles": {- "/git": "Git Repositories"- },- "command_palette": [- {- "label": "Git",- "path": "/git",- "category": "Pages",- "keywords": "git repos deploy extension plugin"- }- ]- }+ "name": "serverkit-git",+ "display_name": "Git Server",+ "version": "1.0.0",+ "description": "Self-hosted Git server (Gitea) exposed through the ServerKit extension system.",+ "author": "ServerKit",+ "license": "MIT",+ "category": "deployment",+ "homepage": "https://github.com/jhd3197/ServerKit",+ "permissions": [+ "docker",+ "filesystem",+ "shell"+ ],+ "contributions": {+ "nav": [+ {+ "id": "git",+ "label": "Git",+ "route": "/git",+ "category": "infrastructure",+ "icon": "<circle cx=\"18\" cy=\"18\" r=\"3\"/><circle cx=\"6\" cy=\"6\" r=\"3\"/><path d=\"M6 21V9a9 9 0 0 0 9 9\"/>"+ }+ ],+ "routes": [+ {+ "path": "git",+ "component": "GitExtensionPage"+ },+ {+ "path": "git/:tab",+ "component": "GitExtensionPage"+ }+ ],+ "page_titles": {+ "/git": "Git Repositories"+ },+ "command_palette": [+ {+ "label": "Git",+ "path": "/git",+ "category": "Pages",+ "keywords": "git repos deploy extension plugin"+ }+ ]+ },+ "entry_point": "gitea:gitea_bp",+ "url_prefix": "/api/v1/git",+ "min_panel_version": "1.9.11"}diff --git a/docs/screenshots/git-repositories.png b/docs/screenshots/git-repositories.pngindex e4d02673..cd6a93b8 100644Binary files a/docs/screenshots/git-repositories.png and b/docs/screenshots/git-repositories.png differdiff --git a/docs/screenshots/git.png b/docs/screenshots/git.pngindex 111615e0..ef49c40d 100644Binary files a/docs/screenshots/git.png and b/docs/screenshots/git.png differdiff --git a/docs/screenshots/security-ip-lists.png b/docs/screenshots/security-ip-lists.pngindex aebe094b..7c001e3e 100644Binary files a/docs/screenshots/security-ip-lists.png and b/docs/screenshots/security-ip-lists.png differ