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
Add GitHub source connections & repo picker
Juan Denis96db8df5ad47
diff --git a/backend/app/__init__.py b/backend/app/__init__.pyindex e13cc84e..e405adfe 100644--- a/backend/app/__init__.py+++ b/backend/app/__init__.py@@ -197,11 +197,15 @@ def create_app(config_name=None):from app.api.two_factor import two_factor_bpapp.register_blueprint(two_factor_bp, url_prefix='/api/v1/auth/2fa')- # Register blueprints - SSO / OAuth- from app.api.sso import sso_bp- app.register_blueprint(sso_bp, url_prefix='/api/v1/sso')-- # Register blueprints - Database Migrations+ # Register blueprints - SSO / OAuth+ from app.api.sso import sso_bp+ app.register_blueprint(sso_bp, url_prefix='/api/v1/sso')++ # Register blueprints - Source provider connections+ from app.api.source_connections import source_connections_bp+ app.register_blueprint(source_connections_bp, url_prefix='/api/v1/source-connections')++ # Register blueprints - Database Migrationsfrom app.api.migrations import migrations_bpapp.register_blueprint(migrations_bp, url_prefix='/api/v1/migrations')diff --git a/backend/app/api/apps.py b/backend/app/api/apps.pyindex 8c204cf9..c100abbf 100644--- a/backend/app/api/apps.py+++ b/backend/app/api/apps.py@@ -9,6 +9,7 @@ from app.models import Application, Userfrom app.services.build_service import BuildServicefrom app.services.docker_service import DockerServicefrom app.services.git_service import GitService+from app.services.source_connection_service import SourceConnectionServicefrom app.services.remote_docker_service import RemoteDockerServicefrom app.services.log_service import LogServicefrom app import paths@@ -357,6 +358,8 @@ def create_app_from_repository():data = request.get_json() or {}name = _service_slug(data.get('name'))repo_url = (data.get('repo_url') or '').strip()+ source_connection_id = data.get('source_connection_id')+ repository_full_name = (data.get('repository_full_name') or '').strip()branch = (data.get('branch') or 'main').strip()app_type = (data.get('app_type') or 'auto').strip().lower()build_method = (data.get('build_method') or 'auto').strip().lower()@@ -365,7 +368,22 @@ def create_app_from_repository():if not name or len(name) < 2:return jsonify({'error': 'Service name must be at least 2 characters'}), 400- if not repo_url:+ if source_connection_id:+ try:+ source_repo = SourceConnectionService.get_authenticated_clone_url(+ user_id=current_user_id,+ connection_id=int(source_connection_id),+ full_name=repository_full_name,+ )+ clone_repo_url = source_repo['clone_url']+ deploy_repo_url = source_repo['public_url']+ except (TypeError, ValueError) as exc:+ return jsonify({'error': str(exc)}), 400+ else:+ clone_repo_url = repo_url+ deploy_repo_url = repo_url++ if not clone_repo_url:return jsonify({'error': 'repo_url is required'}), 400valid_app_types = ['auto', 'docker', 'flask', 'django', 'php', 'static']@@ -394,8 +412,10 @@ def create_app_from_repository():if os.path.exists(app_path):return jsonify({'error': f'App directory already exists: {app_path}'}), 400- clone_result = GitService.clone_repository(app_path, repo_url, branch or None)+ clone_result = GitService.clone_repository(app_path, clone_repo_url, branch or None)if not clone_result.get('success'):+ if clone_repo_url != deploy_repo_url and clone_result.get('error'):+ clone_result['error'] = clone_result['error'].replace(clone_repo_url, deploy_repo_url)return jsonify(clone_result), 400detection = BuildService.detect_build_method(app_path)@@ -417,7 +437,7 @@ def create_app_from_repository():deploy_result = GitService.configure_deployment(app_id=app.id,app_path=app.root_path,- repo_url=repo_url,+ repo_url=deploy_repo_url,branch=branch or 'main',auto_deploy=auto_deploy,)@@ -436,7 +456,7 @@ def create_app_from_repository():'message': 'Repository service created','app': _attach_deploy_config(app.to_dict(include_linked=True)),'deploy_config': {- 'repo_url': _safe_repo_url(repo_url),+ 'repo_url': _safe_repo_url(deploy_repo_url),'branch': branch or 'main','auto_deploy': auto_deploy,'webhook_url': deploy_result.get('webhook_url'),diff --git a/backend/app/api/source_connections.py b/backend/app/api/source_connections.pynew file mode 100644index 00000000..8bbb269e--- /dev/null+++ b/backend/app/api/source_connections.py@@ -0,0 +1,128 @@+"""Source provider connection API."""++from flask import Blueprint, jsonify, request+from flask_jwt_extended import jwt_required, get_jwt_identity+from requests import HTTPError++from app.models import User+from app.middleware.rbac import admin_required+from app.services.source_connection_service import SourceConnectionService++source_connections_bp = Blueprint('source_connections', __name__)+++@source_connections_bp.route('/github/status', methods=['GET'])+@jwt_required()+def github_status():+ user_id = int(get_jwt_identity())+ return jsonify(SourceConnectionService.get_status(user_id)), 200+++@source_connections_bp.route('/github/authorize', methods=['GET'])+@jwt_required()+def github_authorize():+ redirect_uri = request.args.get('redirect_uri', '')+ if not redirect_uri:+ return jsonify({'error': 'redirect_uri is required'}), 400++ try:+ auth_url, state = SourceConnectionService.generate_github_authorize_url(redirect_uri)+ return jsonify({'auth_url': auth_url, 'state': state}), 200+ except ValueError as exc:+ return jsonify({'error': str(exc)}), 400+++@source_connections_bp.route('/github/callback', methods=['POST'])+@jwt_required()+def github_callback():+ user_id = int(get_jwt_identity())+ data = request.get_json() or {}+ code = data.get('code', '')+ state = data.get('state', '')+ redirect_uri = data.get('redirect_uri', '')++ if not code or not state or not redirect_uri:+ return jsonify({'error': 'code, state, and redirect_uri are required'}), 400++ try:+ connection = SourceConnectionService.complete_github_callback(+ user_id=user_id,+ code=code,+ state=state,+ redirect_uri=redirect_uri,+ )+ return jsonify({'connection': connection.to_dict()}), 200+ except ValueError as exc:+ return jsonify({'error': str(exc)}), 400+ except HTTPError as exc:+ return jsonify({'error': _github_error(exc)}), 400+++@source_connections_bp.route('/github/repos', methods=['GET'])+@jwt_required()+def github_repositories():+ user_id = int(get_jwt_identity())+ search = request.args.get('search', '')+ page = request.args.get('page', 1, type=int)+ per_page = request.args.get('per_page', 50, type=int)++ try:+ repos = SourceConnectionService.list_github_repositories(user_id, search, page, per_page)+ return jsonify({'repos': repos}), 200+ except ValueError as exc:+ return jsonify({'error': str(exc)}), 400+ except HTTPError as exc:+ return jsonify({'error': _github_error(exc)}), 400+++@source_connections_bp.route('/github/repos/<path:full_name>/branches', methods=['GET'])+@jwt_required()+def github_branches(full_name):+ user_id = int(get_jwt_identity())++ try:+ branches = SourceConnectionService.list_github_branches(user_id, full_name)+ return jsonify({'branches': branches}), 200+ except ValueError as exc:+ return jsonify({'error': str(exc)}), 400+ except HTTPError as exc:+ return jsonify({'error': _github_error(exc)}), 400+++@source_connections_bp.route('/github', methods=['DELETE'])+@jwt_required()+def disconnect_github():+ user_id = int(get_jwt_identity())+ try:+ SourceConnectionService.disconnect(user_id, 'github')+ return jsonify({'message': 'GitHub disconnected'}), 200+ except ValueError as exc:+ return jsonify({'error': str(exc)}), 404+++@source_connections_bp.route('/admin/github', methods=['GET'])+@admin_required+def github_admin_config():+ return jsonify({'config': SourceConnectionService.get_github_config(redacted=True)}), 200+++@source_connections_bp.route('/admin/github', methods=['PUT'])+@admin_required+def update_github_admin_config():+ user = User.query.get(get_jwt_identity())+ result = SourceConnectionService.update_github_config(+ request.get_json() or {},+ user_id=user.id if user else None,+ )+ return jsonify(result), 200+++def _github_error(exc):+ response = getattr(exc, 'response', None)+ if response is None:+ return str(exc)+ try:+ data = response.json()+ return data.get('message') or str(exc)+ except Exception:+ return response.text or str(exc)diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.pyindex b39a4275..d8ea7bfd 100644--- a/backend/app/models/__init__.py+++ b/backend/app/models/__init__.py@@ -17,8 +17,9 @@ from app.models.environment_activity import EnvironmentActivityfrom app.models.promotion_job import PromotionJobfrom app.models.sanitization_profile import SanitizationProfilefrom app.models.email import EmailDomain, EmailAccount, EmailAlias, EmailForwardingRule, DNSProviderConfig-from app.models.oauth_identity import OAuthIdentity-from app.models.api_key import ApiKey+from app.models.oauth_identity import OAuthIdentity+from app.models.source_connection import SourceConnection+from app.models.api_key import ApiKeyfrom app.models.api_usage import ApiUsageLog, ApiUsageSummaryfrom app.models.event_subscription import EventSubscription, EventDeliveryfrom app.models.invitation import Invitation@@ -40,7 +41,7 @@ __all__ = ['WordPressSite', 'DatabaseSnapshot', 'SyncJob','EnvironmentActivity', 'PromotionJob', 'SanitizationProfile','EmailDomain', 'EmailAccount', 'EmailAlias', 'EmailForwardingRule', 'DNSProviderConfig',- 'OAuthIdentity', 'ApiKey', 'ApiUsageLog', 'ApiUsageSummary',+ 'OAuthIdentity', 'SourceConnection', 'ApiKey', 'ApiUsageLog', 'ApiUsageSummary','EventSubscription', 'EventDelivery', 'Invitation','ServerAlertThreshold', 'MetricAlert','AgentPlugin', 'AgentPluginInstall',diff --git a/backend/app/models/source_connection.py b/backend/app/models/source_connection.pynew file mode 100644index 00000000..48566e2d--- /dev/null+++ b/backend/app/models/source_connection.py@@ -0,0 +1,42 @@+from datetime import datetime++from app import db+++class SourceConnection(db.Model):+ """External source-code provider connection for repository imports."""++ __tablename__ = 'source_connections'++ id = db.Column(db.Integer, primary_key=True)+ user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False, index=True)+ provider = db.Column(db.String(40), nullable=False, index=True)+ provider_account_id = db.Column(db.String(120), nullable=True, index=True)+ provider_username = db.Column(db.String(120), nullable=True)+ display_name = db.Column(db.String(180), nullable=True)+ avatar_url = db.Column(db.String(500), nullable=True)+ access_token_encrypted = db.Column(db.Text, nullable=False)+ scope = db.Column(db.String(500), nullable=True)+ created_at = db.Column(db.DateTime, default=datetime.utcnow, index=True)+ updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)+ last_used_at = db.Column(db.DateTime, nullable=True)++ user = db.relationship('User', backref=db.backref('source_connections', lazy='dynamic'))++ __table_args__ = (+ db.UniqueConstraint('user_id', 'provider', name='uq_source_connection_user_provider'),+ )++ def to_dict(self):+ return {+ 'id': self.id,+ 'provider': self.provider,+ 'provider_account_id': self.provider_account_id,+ 'provider_username': self.provider_username,+ 'display_name': self.display_name,+ 'avatar_url': self.avatar_url,+ 'scope': self.scope,+ 'created_at': self.created_at.isoformat() if self.created_at else None,+ 'updated_at': self.updated_at.isoformat() if self.updated_at else None,+ 'last_used_at': self.last_used_at.isoformat() if self.last_used_at else None,+ }diff --git a/backend/app/services/settings_service.py b/backend/app/services/settings_service.pyindex 2515ccc6..465a29d8 100644--- a/backend/app/services/settings_service.py+++ b/backend/app/services/settings_service.py@@ -59,6 +59,17 @@ class SettingsService:'sso_default_role': {'value': 'developer', 'type': 'string', 'description': 'Default role for SSO-provisioned users'},'sso_force_sso': {'value': False, 'type': 'boolean', 'description': 'Disable password login (SSO only)'},'sso_allowed_domains': {'value': [], 'type': 'json', 'description': 'Restrict SSO to these email domains'},+ # Source provider connections+ 'source_github_client_id': {+ 'value': '',+ 'type': 'string',+ 'description': 'GitHub OAuth client ID for repository connections'+ },+ 'source_github_client_secret': {+ 'value': '',+ 'type': 'string',+ 'description': 'GitHub OAuth client secret for repository connections'+ },# Rate limiting settings'rate_limit_standard': {'value': '100 per minute', 'type': 'string', 'description': 'Rate limit for standard API keys'},'rate_limit_elevated': {'value': '500 per minute', 'type': 'string', 'description': 'Rate limit for elevated API keys'},diff --git a/backend/app/services/source_connection_service.py b/backend/app/services/source_connection_service.pynew file mode 100644index 00000000..e53b439c--- /dev/null+++ b/backend/app/services/source_connection_service.py@@ -0,0 +1,261 @@+"""Source provider connection service for GitHub repository imports."""++import os+import secrets+from datetime import datetime+from urllib.parse import urlencode, quote++import requests+from flask import session++from app import db+from app.models import SourceConnection+from app.services.settings_service import SettingsService+from app.utils.crypto import encrypt_secret, decrypt_secret+++class SourceConnectionService:+ """OAuth and API helpers for source-code provider connections."""++ GITHUB_AUTHORIZE_URL = 'https://github.com/login/oauth/authorize'+ GITHUB_TOKEN_URL = 'https://github.com/login/oauth/access_token'+ GITHUB_API_URL = 'https://api.github.com'+ GITHUB_SCOPES = ['repo', 'read:user', 'user:email']++ @classmethod+ def get_github_config(cls, redacted=False):+ client_id = (+ SettingsService.get('source_github_client_id', '')+ or os.environ.get('SOURCE_GITHUB_CLIENT_ID', '')+ or os.environ.get('SERVERKIT_GITHUB_CLIENT_ID', '')+ )+ client_secret = (+ SettingsService.get('source_github_client_secret', '')+ or os.environ.get('SOURCE_GITHUB_CLIENT_SECRET', '')+ or os.environ.get('SERVERKIT_GITHUB_CLIENT_SECRET', '')+ )++ if redacted and client_secret:+ client_secret = f'****{client_secret[-4:]}'++ return {+ 'client_id': client_id,+ 'client_secret': client_secret,+ 'configured': bool(client_id and client_secret),+ 'scopes': cls.GITHUB_SCOPES,+ }++ @classmethod+ def update_github_config(cls, data, user_id=None):+ updated = []+ if 'client_id' in data:+ SettingsService.set('source_github_client_id', data.get('client_id') or '', user_id=user_id)+ updated.append('client_id')+ if 'client_secret' in data:+ value = data.get('client_secret') or ''+ if not (isinstance(value, str) and value.startswith('****')):+ SettingsService.set('source_github_client_secret', value, user_id=user_id)+ updated.append('client_secret')+ return {'updated': updated, 'config': cls.get_github_config(redacted=True)}++ @classmethod+ def generate_github_authorize_url(cls, redirect_uri):+ config = cls.get_github_config()+ if not config['configured']:+ raise ValueError('GitHub source connection is not configured')++ state = secrets.token_urlsafe(32)+ session['source_github_state'] = state++ params = {+ 'client_id': config['client_id'],+ 'redirect_uri': redirect_uri,+ 'scope': ' '.join(cls.GITHUB_SCOPES),+ 'state': state,+ 'allow_signup': 'true',+ }+ return f'{cls.GITHUB_AUTHORIZE_URL}?{urlencode(params)}', state++ @classmethod+ def complete_github_callback(cls, user_id, code, state, redirect_uri):+ expected_state = session.pop('source_github_state', None)+ if not expected_state or state != expected_state:+ raise ValueError('Invalid GitHub OAuth state')++ config = cls.get_github_config()+ if not config['configured']:+ raise ValueError('GitHub source connection is not configured')++ token_response = requests.post(+ cls.GITHUB_TOKEN_URL,+ headers={'Accept': 'application/json'},+ data={+ 'client_id': config['client_id'],+ 'client_secret': config['client_secret'],+ 'code': code,+ 'redirect_uri': redirect_uri,+ },+ timeout=15,+ )+ token_response.raise_for_status()+ token_data = token_response.json()+ if token_data.get('error'):+ raise ValueError(token_data.get('error_description') or token_data['error'])++ access_token = token_data.get('access_token')+ if not access_token:+ raise ValueError('GitHub did not return an access token')++ profile = cls._github_get(access_token, '/user')+ connection = SourceConnection.query.filter_by(user_id=user_id, provider='github').first()+ if not connection:+ connection = SourceConnection(user_id=user_id, provider='github')+ db.session.add(connection)++ connection.provider_account_id = str(profile.get('id') or '')+ connection.provider_username = profile.get('login') or ''+ connection.display_name = profile.get('name') or profile.get('login') or ''+ connection.avatar_url = profile.get('avatar_url') or ''+ connection.access_token_encrypted = encrypt_secret(access_token)+ connection.scope = token_data.get('scope') or ' '.join(cls.GITHUB_SCOPES)+ connection.updated_at = datetime.utcnow()+ connection.last_used_at = datetime.utcnow()++ db.session.commit()+ return connection++ @classmethod+ def get_connection(cls, user_id, provider='github'):+ return SourceConnection.query.filter_by(user_id=user_id, provider=provider).first()++ @classmethod+ def get_status(cls, user_id):+ connection = cls.get_connection(user_id)+ return {+ 'configured': cls.get_github_config()['configured'],+ 'connection': connection.to_dict() if connection else None,+ }++ @classmethod+ def disconnect(cls, user_id, provider='github'):+ connection = cls.get_connection(user_id, provider)+ if not connection:+ raise ValueError('Connection not found')+ db.session.delete(connection)+ db.session.commit()++ @classmethod+ def list_github_repositories(cls, user_id, search='', page=1, per_page=50):+ token = cls._get_github_token(user_id)+ params = {+ 'visibility': 'all',+ 'affiliation': 'owner,collaborator,organization_member',+ 'sort': 'updated',+ 'direction': 'desc',+ 'page': max(int(page or 1), 1),+ 'per_page': min(max(int(per_page or 50), 1), 100),+ }+ repos = cls._github_get(token, f'/user/repos?{urlencode(params)}')+ search_text = (search or '').strip().lower()+ if search_text:+ repos = [+ repo for repo in repos+ if search_text in repo.get('full_name', '').lower()+ or search_text in (repo.get('description') or '').lower()+ ]++ connection = cls.get_connection(user_id)+ if connection:+ connection.last_used_at = datetime.utcnow()+ db.session.commit()++ return [cls._repo_payload(repo) for repo in repos]++ @classmethod+ def list_github_branches(cls, user_id, full_name):+ token = cls._get_github_token(user_id)+ owner, repo = cls._split_full_name(full_name)+ path = f'/repos/{quote(owner)}/{quote(repo)}/branches?per_page=100'+ branches = cls._github_get(token, path)+ return [+ {+ 'name': branch.get('name'),+ 'protected': branch.get('protected', False),+ }+ for branch in branches+ ]++ @classmethod+ def get_authenticated_clone_url(cls, user_id, connection_id, full_name):+ connection = SourceConnection.query.filter_by(+ id=connection_id,+ user_id=user_id,+ provider='github',+ ).first()+ if not connection:+ raise ValueError('GitHub connection not found')++ token = cls._decrypt_connection_token(connection)+ owner, repo = cls._split_full_name(full_name)+ public_url = f'https://github.com/{owner}/{repo}.git'+ auth_url = f'https://x-access-token:{quote(token, safe="")}@github.com/{owner}/{repo}.git'+ return {'clone_url': auth_url, 'public_url': public_url}++ @classmethod+ def _get_github_token(cls, user_id):+ connection = cls.get_connection(user_id, 'github')+ if not connection:+ raise ValueError('GitHub is not connected')+ return cls._decrypt_connection_token(connection)++ @staticmethod+ def _decrypt_connection_token(connection):+ token = decrypt_secret(connection.access_token_encrypted)+ if not token:+ raise ValueError('GitHub token could not be decrypted')+ return token++ @classmethod+ def _github_get(cls, token, path):+ response = requests.get(+ f'{cls.GITHUB_API_URL}{path}',+ headers=cls._github_headers(token),+ timeout=20,+ )+ response.raise_for_status()+ return response.json()++ @staticmethod+ def _github_headers(token):+ return {+ 'Accept': 'application/vnd.github+json',+ 'Authorization': f'Bearer {token}',+ 'X-GitHub-Api-Version': '2022-11-28',+ }++ @staticmethod+ def _split_full_name(full_name):+ parts = (full_name or '').strip().split('/')+ if len(parts) != 2 or not all(parts):+ raise ValueError('repository_full_name must be owner/repo')+ return parts[0], parts[1]++ @staticmethod+ def _repo_payload(repo):+ return {+ 'id': repo.get('id'),+ 'name': repo.get('name'),+ 'full_name': repo.get('full_name'),+ 'description': repo.get('description'),+ 'private': repo.get('private', False),+ 'fork': repo.get('fork', False),+ 'archived': repo.get('archived', False),+ 'default_branch': repo.get('default_branch') or 'main',+ 'html_url': repo.get('html_url'),+ 'language': repo.get('language'),+ 'updated_at': repo.get('updated_at'),+ 'owner': {+ 'login': (repo.get('owner') or {}).get('login'),+ 'avatar_url': (repo.get('owner') or {}).get('avatar_url'),+ },+ }diff --git a/frontend/src/App.jsx b/frontend/src/App.jsxindex 2c8df34a..cb811e6a 100644--- a/frontend/src/App.jsx+++ b/frontend/src/App.jsx@@ -41,7 +41,8 @@ import WordPressProjects from './pages/WordPressProjects';import WordPressProject from './pages/WordPressProject';import SSLCertificates from './pages/SSLCertificates';import Email from './pages/Email';-import SSOCallback from './pages/SSOCallback';+import SSOCallback from './pages/SSOCallback';+import SourceConnectionCallback from './pages/SourceConnectionCallback';import DatabaseMigration from './pages/DatabaseMigration';import AgentPlugins from './pages/AgentPlugins';import ServerTemplates from './pages/ServerTemplates';@@ -84,7 +85,8 @@ const PAGE_TITLES = {'/security': 'Security','/email': 'Email Server','/terminal': 'Terminal',- '/settings': 'Settings',+ '/settings': 'Settings',+ '/connections/callback/github': 'GitHub Connection','/migrate': 'Database Migration','/fleet': 'Agent Fleet','/fleet-monitor': 'Fleet Monitor',@@ -199,12 +201,17 @@ function AppRoutes() {<SSOCallback /></PublicRoute>} />- <Route path="/register" element={- <PublicRoute>- <Register />- </PublicRoute>- } />- <Route path="/" element={+ <Route path="/register" element={+ <PublicRoute>+ <Register />+ </PublicRoute>+ } />+ <Route path="/connections/callback/:provider" element={+ <PrivateRoute>+ <SourceConnectionCallback />+ </PrivateRoute>+ } />+ <Route path="/" element={<PrivateRoute><DashboardLayout /></PrivateRoute>diff --git a/frontend/src/components/settings/SourceConnectionsTab.jsx b/frontend/src/components/settings/SourceConnectionsTab.jsxnew file mode 100644index 00000000..cb5befaa--- /dev/null+++ b/frontend/src/components/settings/SourceConnectionsTab.jsx@@ -0,0 +1,194 @@+import { useCallback, useEffect, useState } from 'react';+import { CheckCircle2, Github, KeyRound, Link2, PlugZap, Shield, Trash2 } from 'lucide-react';+import api from '../../services/api';+import { useAuth } from '../../contexts/AuthContext';+import { useToast } from '../../contexts/ToastContext';+import { Button } from '@/components/ui/button';+import { Input } from '@/components/ui/input';+import { Label } from '@/components/ui/label';++const SourceConnectionsTab = () => {+ const { isAdmin } = useAuth();+ const toast = useToast();+ const [status, setStatus] = useState(null);+ const [config, setConfig] = useState({ client_id: '', client_secret: '' });+ const [loading, setLoading] = useState(true);+ const [saving, setSaving] = useState(false);+ const [connecting, setConnecting] = useState(false);++ const loadData = useCallback(async () => {+ setLoading(true);+ try {+ const statusData = await api.getGithubSourceStatus();+ setStatus(statusData);++ if (isAdmin) {+ const configData = await api.getGithubSourceConfig();+ setConfig({+ client_id: configData.config?.client_id || '',+ client_secret: configData.config?.client_secret || '',+ });+ }+ } catch (err) {+ toast.error(err.message || 'Failed to load source connections');+ } finally {+ setLoading(false);+ }+ }, [isAdmin, toast]);++ useEffect(() => {+ loadData();+ }, [loadData]);++ async function handleSaveConfig(e) {+ e.preventDefault();+ setSaving(true);+ try {+ const result = await api.updateGithubSourceConfig(config);+ setConfig({+ client_id: result.config?.client_id || '',+ client_secret: result.config?.client_secret || '',+ });+ toast.success('GitHub connection settings saved');+ await loadData();+ } catch (err) {+ toast.error(err.message || 'Failed to save GitHub settings');+ } finally {+ setSaving(false);+ }+ }++ async function handleConnect() {+ setConnecting(true);+ try {+ const redirectUri = `${window.location.origin}/connections/callback/github`;+ sessionStorage.setItem('sourceConnectionReturnTo', '/settings/connections');+ const { auth_url } = await api.startSourceConnection('github', redirectUri);+ window.location.href = auth_url;+ } catch (err) {+ toast.error(err.message || 'Failed to start GitHub connection');+ setConnecting(false);+ }+ }++ async function handleDisconnect() {+ try {+ await api.disconnectSourceConnection('github');+ toast.success('GitHub disconnected');+ await loadData();+ } catch (err) {+ toast.error(err.message || 'Failed to disconnect GitHub');+ }+ }++ const connection = status?.connection;+ const configured = status?.configured;++ if (loading) {+ return <div className="settings-section"><p>Loading source connections...</p></div>;+ }++ return (+ <div className="settings-section source-connections">+ <div className="section-header">+ <h2>Connections</h2>+ <p>Connect source providers so services can be created from repository pickers instead of clone URLs.</p>+ </div>++ <div className="settings-card source-connection-card">+ <div className="settings-card__header">+ <div className="settings-card__header-left">+ <Github size={22} />+ <div>+ <h3>GitHub</h3>+ <p>Use the GitHub API to list repositories and import selected branches.</p>+ </div>+ </div>+ <span className={`source-connection-status ${connection ? 'source-connection-status--connected' : ''}`}>+ {connection ? <CheckCircle2 size={14} /> : <PlugZap size={14} />}+ {connection ? 'Connected' : 'Not connected'}+ </span>+ </div>++ {connection ? (+ <div className="source-connection-profile">+ {connection.avatar_url && <img src={connection.avatar_url} alt="" />}+ <div>+ <strong>{connection.display_name || connection.provider_username}</strong>+ <span>@{connection.provider_username}</span>+ </div>+ <Button type="button" variant="outline" onClick={handleDisconnect}>+ <Trash2 size={16} />+ Disconnect+ </Button>+ </div>+ ) : (+ <div className="source-connection-empty">+ <Link2 size={20} />+ <div>+ <strong>{configured ? 'Connect your GitHub account' : 'GitHub OAuth is not configured'}</strong>+ <span>+ {configured+ ? 'Authorize ServerKit once, then pick repositories directly on the New Service page.'+ : 'An admin needs to add a GitHub OAuth client before users can connect.'}+ </span>+ </div>+ <Button type="button" onClick={handleConnect} disabled={!configured || connecting}>+ <Github size={16} />+ {connecting ? 'Redirecting...' : 'Connect GitHub'}+ </Button>+ </div>+ )}+ </div>++ {isAdmin && (+ <form className="settings-card source-oauth-config" onSubmit={handleSaveConfig}>+ <div className="settings-card__header">+ <div className="settings-card__header-left">+ <KeyRound size={22} />+ <div>+ <h3>GitHub OAuth App</h3>+ <p>Set the OAuth app credentials used for repository connections.</p>+ </div>+ </div>+ </div>++ <div className="source-oauth-config__grid">+ <div className="form-group">+ <Label htmlFor="github-source-client-id">Client ID</Label>+ <Input+ id="github-source-client-id"+ value={config.client_id}+ onChange={(e) => setConfig(prev => ({ ...prev, client_id: e.target.value }))}+ placeholder="GitHub OAuth client ID"+ />+ </div>+ <div className="form-group">+ <Label htmlFor="github-source-client-secret">Client Secret</Label>+ <Input+ id="github-source-client-secret"+ type="password"+ value={config.client_secret}+ onChange={(e) => setConfig(prev => ({ ...prev, client_secret: e.target.value }))}+ placeholder="GitHub OAuth client secret"+ />+ </div>+ </div>++ <div className="source-oauth-config__callback">+ <Shield size={16} />+ <span>Callback URL: {window.location.origin}/connections/callback/github</span>+ </div>++ <div className="form-actions">+ <Button type="submit" disabled={saving}>+ {saving ? 'Saving...' : 'Save GitHub OAuth App'}+ </Button>+ </div>+ </form>+ )}+ </div>+ );+};++export default SourceConnectionsTab;diff --git a/frontend/src/pages/NewService.jsx b/frontend/src/pages/NewService.jsxindex 6192c091..2a818df5 100644--- a/frontend/src/pages/NewService.jsx+++ b/frontend/src/pages/NewService.jsx@@ -1,14 +1,21 @@-import { useMemo, useState } from 'react';+import { useCallback, useEffect, useMemo, useState } from 'react';import { Link, useNavigate } from 'react-router-dom';import {ArrowRight,- Boxes,CheckCircle2,+ ChevronDown,+ Github,GitBranch,+ KeyRound,+ Link2,Lock,Package,+ RefreshCw,Rocket,+ Search,Server,+ Settings2,+ ShieldCheck,Zap,} from 'lucide-react';import api from '../services/api';@@ -45,10 +52,26 @@ function repoNameFromUrl(value) {return slugify(parts[parts.length - 1] || '');}+function normalizeManualRepo(value) {+ const trimmed = value.trim();+ if (!trimmed) return '';+ if (/^[\w.-]+\/[\w.-]+$/.test(trimmed)) return `https://github.com/${trimmed}.git`;+ if (/^github\.com\//i.test(trimmed)) return `https://${trimmed.replace(/\.git$/, '')}.git`;+ return trimmed;+}+const NewService = () => {const navigate = useNavigate();const toast = useToast();- const [repoUrl, setRepoUrl] = useState('');+ const [sourceMode, setSourceMode] = useState('github');+ const [githubStatus, setGithubStatus] = useState(null);+ const [repos, setRepos] = useState([]);+ const [reposLoading, setReposLoading] = useState(false);+ const [repoSearch, setRepoSearch] = useState('');+ const [selectedRepo, setSelectedRepo] = useState(null);+ const [branches, setBranches] = useState([]);+ const [branchesLoading, setBranchesLoading] = useState(false);+ const [manualRepoUrl, setManualRepoUrl] = useState('');const [name, setName] = useState('');const [nameTouched, setNameTouched] = useState(false);const [branch, setBranch] = useState('main');@@ -56,40 +79,125 @@ const NewService = () => {const [buildMethod, setBuildMethod] = useState('auto');const [port, setPort] = useState('');const [autoDeploy, setAutoDeploy] = useState(true);+ const [advancedOpen, setAdvancedOpen] = useState(false);const [submitting, setSubmitting] = useState(false);- const detectedName = useMemo(() => repoNameFromUrl(repoUrl), [repoUrl]);- const serviceName = name || detectedName;+ const githubConnection = githubStatus?.connection;+ const githubConfigured = githubStatus?.configured;+ const normalizedManualRepo = useMemo(() => normalizeManualRepo(manualRepoUrl), [manualRepoUrl]);+ const detectedServiceName = useMemo(() => {+ if (sourceMode === 'github' && selectedRepo) return slugify(selectedRepo.name || '');+ return repoNameFromUrl(normalizedManualRepo);+ }, [normalizedManualRepo, selectedRepo, sourceMode]);+ const serviceName = nameTouched ? name : detectedServiceName;+ const canSubmit = sourceMode === 'github'+ ? Boolean(githubConnection && selectedRepo && serviceName?.length >= 2)+ : Boolean(normalizedManualRepo && serviceName?.length >= 2);++ const loadGithubStatus = useCallback(async () => {+ try {+ const data = await api.getGithubSourceStatus();+ setGithubStatus(data);+ } catch (err) {+ toast.error(err.message || 'Failed to load GitHub connection');+ }+ }, [toast]);++ const loadGithubRepos = useCallback(async (search = '') => {+ setReposLoading(true);+ try {+ const data = await api.listGithubRepositories({ search, perPage: 80 });+ setRepos(data.repos || []);+ } catch (err) {+ toast.error(err.message || 'Failed to load GitHub repositories');+ } finally {+ setReposLoading(false);+ }+ }, [toast]);++ const loadBranches = useCallback(async (fullName) => {+ setBranchesLoading(true);+ try {+ const data = await api.listGithubBranches(fullName);+ setBranches(data.branches || []);+ } catch (err) {+ setBranches([]);+ toast.error(err.message || 'Failed to load branches');+ } finally {+ setBranchesLoading(false);+ }+ }, [toast]);++ useEffect(() => {+ loadGithubStatus();+ }, [loadGithubStatus]);++ useEffect(() => {+ if (sourceMode === 'github' && githubConnection) {+ loadGithubRepos();+ }+ }, [sourceMode, githubConnection, loadGithubRepos]);++ useEffect(() => {+ if (selectedRepo) {+ setBranch(selectedRepo.default_branch || 'main');+ loadBranches(selectedRepo.full_name);+ }+ }, [selectedRepo, loadBranches]);++ useEffect(() => {+ if (selectedRepo) {+ if (!nameTouched) {+ setName(slugify(selectedRepo.name || ''));+ }+ }+ }, [selectedRepo, nameTouched]);++ async function handleConnectGithub() {+ try {+ const redirectUri = `${window.location.origin}/connections/callback/github`;+ sessionStorage.setItem('sourceConnectionReturnTo', '/services/new');+ const { auth_url } = await api.startSourceConnection('github', redirectUri);+ window.location.href = auth_url;+ } catch (err) {+ toast.error(err.message || 'Failed to start GitHub connection');+ }+ }- function handleRepoChange(value) {- setRepoUrl(value);+ function handleManualRepoChange(value) {+ setManualRepoUrl(value);if (!nameTouched) {- setName(repoNameFromUrl(value));+ setName(repoNameFromUrl(normalizeManualRepo(value)));}}async function handleSubmit(e) {e.preventDefault();- if (!repoUrl.trim()) {- toast.error('Repository URL is required');+ if (!canSubmit) {+ toast.error(sourceMode === 'github' ? 'Select a GitHub repository' : 'Repository URL is required');return;}- if (!serviceName || serviceName.length < 2) {- toast.error('Service name must be at least 2 characters');- return;++ const payload = {+ name: serviceName,+ branch: branch.trim() || null,+ app_type: appType,+ build_method: buildMethod,+ port: port ? Number(port) : null,+ auto_deploy: autoDeploy,+ };++ if (sourceMode === 'github') {+ payload.source_connection_id = githubConnection.id;+ payload.repository_full_name = selectedRepo.full_name;+ payload.repo_url = `https://github.com/${selectedRepo.full_name}.git`;+ } else {+ payload.repo_url = normalizedManualRepo;}setSubmitting(true);try {- const result = await api.createAppFromRepository({- name: serviceName,- repo_url: repoUrl.trim(),- branch: branch.trim() || null,- app_type: appType,- build_method: buildMethod,- port: port ? Number(port) : null,- auto_deploy: autoDeploy,- });+ const result = await api.createAppFromRepository(payload);toast.success('Repository service created');navigate(`/services/${result.app.id}`);} catch (err) {@@ -110,184 +218,354 @@ const NewService = () => {<div className="new-service-page__header"><div><h1>New Service</h1>- <p>Create a service from an existing repository or start from a managed template.</p>+ <p>Connect GitHub, pick a repository, and let ServerKit prepare the deployable service.</p></div>+ <Button type="button" variant="outline" asChild>+ <Link to="/settings/connections">+ <Link2 size={16} />+ Connections+ </Link>+ </Button></div>- <div className="new-service-page__source-grid">- <button className="new-service-page__source-card new-service-page__source-card--active" type="button">- <span className="new-service-page__source-icon">- <GitBranch size={18} />+ <div className="new-service-page__mode-strip" aria-label="Service source options">+ <button+ className={`new-service-page__mode-card ${sourceMode === 'github' ? 'new-service-page__mode-card--active' : ''}`}+ type="button"+ onClick={() => setSourceMode('github')}+ >+ <span className="new-service-page__mode-icon">+ <Github size={18} /></span><span>- <strong>Repository</strong>- <small>GitHub, GitLab, Bitbucket, Gitea, or SSH remote</small>+ <strong>GitHub</strong>+ <small>Connect with OAuth and choose a repository</small></span>- <CheckCircle2 size={18} />+ {sourceMode === 'github' ? <CheckCircle2 size={18} /> : <ArrowRight size={18} />}</button>- <Link to="/templates" className="new-service-page__source-card">- <span className="new-service-page__source-icon">+ <button+ className={`new-service-page__mode-card ${sourceMode === 'manual' ? 'new-service-page__mode-card--active' : ''}`}+ type="button"+ onClick={() => setSourceMode('manual')}+ >+ <span className="new-service-page__mode-icon">+ <KeyRound size={18} />+ </span>+ <span>+ <strong>Other Git Remote</strong>+ <small>GitLab, Bitbucket, Gitea, or SSH</small>+ </span>+ {sourceMode === 'manual' ? <CheckCircle2 size={18} /> : <ArrowRight size={18} />}+ </button>+ <Link to="/templates" className="new-service-page__mode-card">+ <span className="new-service-page__mode-icon"><Package size={18} /></span><span><strong>Template</strong>- <small>One-click apps such as Gitea, Ghost, n8n, and Nextcloud</small>+ <small>Packaged apps and infrastructure services</small></span><ArrowRight size={18} /></Link></div>- <div className="new-service-page__layout">- <form className="new-service-page__panel new-service-page__form" onSubmit={handleSubmit}>- <div className="new-service-page__section">- <div className="new-service-page__section-heading">- <GitBranch size={16} />- <h2>Source</h2>- </div>- <div className="new-service-page__field">- <Label htmlFor="repo-url">Repository URL</Label>- <Input- id="repo-url"- value={repoUrl}- onChange={(e) => handleRepoChange(e.target.value)}- placeholder="[email protected]:owner/repo.git"- autoComplete="off"- required- />- <span className="new-service-page__hint">- Private repositories work with SSH URLs or HTTPS URLs your server can authenticate.- </span>+ <form className="new-service-page__wizard" onSubmit={handleSubmit}>+ <section className="new-service-page__panel new-service-page__provider-panel">+ <div className="new-service-page__section-heading">+ <Link2 size={16} />+ <h2>{sourceMode === 'github' ? 'Pick Repository' : 'Connect Source'}</h2>+ </div>++ {sourceMode === 'github' ? (+ <div className="new-service-page__connect-box">+ {githubConnection ? (+ <>+ <div className="new-service-page__github-account">+ {githubConnection.avatar_url && <img src={githubConnection.avatar_url} alt="" />}+ <div>+ <strong>{githubConnection.display_name || githubConnection.provider_username}</strong>+ <span>@{githubConnection.provider_username}</span>+ </div>+ <Button type="button" variant="outline" onClick={() => loadGithubRepos()}>+ <RefreshCw size={16} className={reposLoading ? 'spinning' : ''} />+ Refresh+ </Button>+ </div>++ <div className="new-service-page__repo-search">+ <Search size={16} />+ <Input+ value={repoSearch}+ onChange={(e) => setRepoSearch(e.target.value)}+ placeholder="Search repositories"+ />+ <Button type="button" variant="outline" onClick={() => loadGithubRepos(repoSearch)}>+ Search+ </Button>+ </div>++ <div className="new-service-page__repo-list">+ {reposLoading && <div className="new-service-page__repo-state">Loading repositories...</div>}+ {!reposLoading && repos.length === 0 && (+ <div className="new-service-page__repo-state">No repositories found.</div>+ )}+ {!reposLoading && repos.map(repo => (+ <button+ key={repo.id}+ type="button"+ className={`new-service-page__repo-row ${selectedRepo?.id === repo.id ? 'new-service-page__repo-row--active' : ''}`}+ onClick={() => setSelectedRepo(repo)}+ >+ <span>+ <strong>{repo.full_name}</strong>+ <small>{repo.description || repo.language || 'No description'}</small>+ </span>+ <em>{repo.private ? 'Private' : 'Public'}</em>+ </button>+ ))}+ </div>+ </>+ ) : (+ <div className="new-service-page__connect-empty">+ <span className="new-service-page__connect-icon">+ <Github size={20} />+ </span>+ <div>+ <h2>{githubConfigured ? 'Connect GitHub' : 'GitHub connection is not configured'}</h2>+ <p>+ {githubConfigured+ ? 'Authorize ServerKit once, then choose a repository from your GitHub account.'+ : 'Add the GitHub OAuth app credentials in Settings before connecting.'}+ </p>+ </div>+ <div className="new-service-page__connect-actions">+ <Button type="button" onClick={handleConnectGithub} disabled={!githubConfigured}>+ <Github size={16} />+ Connect GitHub+ </Button>+ <Button type="button" variant="outline" asChild>+ <Link to="/settings/connections">+ <Settings2 size={16} />+ Settings+ </Link>+ </Button>+ </div>+ </div>+ )}</div>- <div className="new-service-page__two-col">- <div className="new-service-page__field">- <Label htmlFor="branch">Branch</Label>- <Input- id="branch"- value={branch}- onChange={(e) => setBranch(e.target.value)}- placeholder="main"- />+ ) : (+ <div className="new-service-page__connect-box">+ <div className="new-service-page__connect-heading">+ <span className="new-service-page__connect-icon">+ <GitBranch size={18} />+ </span>+ <div>+ <strong>Git remote</strong>+ <span>Use this for providers that are not connected through the GitHub API.</span>+ </div></div><div className="new-service-page__field">- <Label htmlFor="service-name">Service name</Label>+ <Label htmlFor="manual-repo-url">Repository URL</Label><Input- id="service-name"- value={serviceName}- onChange={(e) => {- setNameTouched(true);- setName(slugify(e.target.value));- }}- placeholder="my-service"- minLength={2}- required+ id="manual-repo-url"+ value={manualRepoUrl}+ onChange={(e) => handleManualRepoChange(e.target.value)}+ placeholder="[email protected]:owner/repo.git"+ autoComplete="off"+ required={sourceMode === 'manual'}/></div></div>- </div>+ )}- <div className="new-service-page__section">- <div className="new-service-page__section-heading">- <Boxes size={16} />- <h2>Runtime</h2>- </div>- <div className="new-service-page__two-col">- <div className="new-service-page__field">- <Label htmlFor="app-type">Service type</Label>- <select- id="app-type"- value={appType}- onChange={(e) => setAppType(e.target.value)}- >- {APP_TYPE_OPTIONS.map(option => (- <option key={option.value} value={option.value}>{option.label}</option>- ))}- </select>- </div>- <div className="new-service-page__field">- <Label htmlFor="build-method">Build method</Label>- <select- id="build-method"- value={buildMethod}- onChange={(e) => setBuildMethod(e.target.value)}- >- {BUILD_METHOD_OPTIONS.map(option => (- <option key={option.value} value={option.value}>{option.label}</option>- ))}- </select>+ {(selectedRepo || sourceMode === 'manual') && (+ <div className="new-service-page__repo-preview">+ <div>+ <span>Service</span>+ <strong>{serviceName || 'Auto-named from repo'}</strong></div>- </div>- <div className="new-service-page__two-col">- <div className="new-service-page__field">- <Label htmlFor="port">Runtime port</Label>- <Input- id="port"- type="number"- value={port}- onChange={(e) => setPort(e.target.value)}- placeholder="3000"- min="1"- max="65535"- />+ <div>+ <span>Branch</span>+ <strong>{branch || 'main'}</strong></div>- <div className="new-service-page__toggle">- <div>- <Label>Auto-deploy</Label>- <span>Keep webhook deployment enabled for this branch.</span>- </div>- <Switch checked={autoDeploy} onCheckedChange={setAutoDeploy} />+ <div>+ <span>Build</span>+ <strong>{buildMethod === 'auto' ? 'Auto' : buildMethod}</strong></div></div>+ )}+ </section>++ <aside className="new-service-page__panel new-service-page__review-panel">+ <div className="new-service-page__deploy-card">+ <span className="new-service-page__deploy-icon">+ <Rocket size={18} />+ </span>+ <div>+ <h2>Ready to Import</h2>+ <p>ServerKit clones the selected repository, detects the runtime, configures builds, and records deployment settings.</p>+ </div></div>- <div className="new-service-page__actions">- <Button type="button" variant="outline" asChild>- <Link to="/services">Cancel</Link>- </Button>- <Button type="submit" disabled={submitting}>- <Rocket size={16} />- {submitting ? 'Creating...' : 'Create Service'}- </Button>+ <div className="new-service-page__flow">+ <div>+ <Github size={16} />+ <span>Connect</span>+ </div>+ <ArrowRight size={14} />+ <div>+ <Zap size={16} />+ <span>Detect</span>+ </div>+ <ArrowRight size={14} />+ <div>+ <Server size={16} />+ <span>Deploy</span>+ </div></div>- </form>- <aside className="new-service-page__panel new-service-page__aside">- <div className="new-service-page__aside-block">- <h2>Connection Flow</h2>- <div className="new-service-page__flow">- <div>- <GitBranch size={16} />- <span>Repo</span>+ <div className="new-service-page__summary">+ <div>+ <span>Source</span>+ <strong>{sourceMode === 'github' ? 'GitHub API' : 'Git remote'}</strong>+ </div>+ <div>+ <span>Repository</span>+ <strong>{selectedRepo?.full_name || normalizedManualRepo || 'Not selected'}</strong>+ </div>+ <div>+ <span>Auto-deploy</span>+ <strong>{autoDeploy ? 'On' : 'Off'}</strong>+ </div>+ </div>++ <button+ className="new-service-page__advanced-toggle"+ type="button"+ onClick={() => setAdvancedOpen(open => !open)}+ aria-expanded={advancedOpen}+ >+ <span>+ <Settings2 size={16} />+ Advanced settings+ </span>+ <ChevronDown size={16} />+ </button>++ {advancedOpen && (+ <div className="new-service-page__advanced">+ <div className="new-service-page__two-col">+ <div className="new-service-page__field">+ <Label htmlFor="branch">Branch</Label>+ {sourceMode === 'github' && branches.length > 0 ? (+ <select+ id="branch"+ value={branch}+ onChange={(e) => setBranch(e.target.value)}+ disabled={branchesLoading}+ >+ {branches.map(option => (+ <option key={option.name} value={option.name}>{option.name}</option>+ ))}+ </select>+ ) : (+ <Input+ id="branch"+ value={branch}+ onChange={(e) => setBranch(e.target.value)}+ placeholder="main"+ />+ )}+ </div>+ <div className="new-service-page__field">+ <Label htmlFor="service-name">Service name</Label>+ <Input+ id="service-name"+ value={serviceName}+ onChange={(e) => {+ setNameTouched(true);+ setName(slugify(e.target.value));+ }}+ placeholder="my-service"+ minLength={2}+ required+ />+ </div></div>- <ArrowRight size={14} />- <div>- <Zap size={16} />- <span>Build</span>++ <div className="new-service-page__two-col">+ <div className="new-service-page__field">+ <Label htmlFor="app-type">Service type</Label>+ <select+ id="app-type"+ value={appType}+ onChange={(e) => setAppType(e.target.value)}+ >+ {APP_TYPE_OPTIONS.map(option => (+ <option key={option.value} value={option.value}>{option.label}</option>+ ))}+ </select>+ </div>+ <div className="new-service-page__field">+ <Label htmlFor="build-method">Build method</Label>+ <select+ id="build-method"+ value={buildMethod}+ onChange={(e) => setBuildMethod(e.target.value)}+ >+ {BUILD_METHOD_OPTIONS.map(option => (+ <option key={option.value} value={option.value}>{option.label}</option>+ ))}+ </select>+ </div></div>- <ArrowRight size={14} />- <div>- <Server size={16} />- <span>Service</span>++ <div className="new-service-page__two-col">+ <div className="new-service-page__field">+ <Label htmlFor="port">Runtime port</Label>+ <Input+ id="port"+ type="number"+ value={port}+ onChange={(e) => setPort(e.target.value)}+ placeholder="3000"+ min="1"+ max="65535"+ />+ </div>+ <div className="new-service-page__toggle">+ <div>+ <Label>Auto-deploy</Label>+ <span>Webhook deployment for this branch.</span>+ </div>+ <Switch checked={autoDeploy} onCheckedChange={setAutoDeploy} />+ </div></div></div>- </div>+ )}- <div className="new-service-page__aside-block">- <h2>Private Access</h2>+ <div className="new-service-page__notes">+ <div className="new-service-page__note">+ <ShieldCheck size={16} />+ <span>GitHub repositories are listed through the API after account authorization.</span>+ </div><div className="new-service-page__note"><Lock size={16} />- <span>Use an SSH remote when the server already has a deploy key, or an HTTPS URL that includes a provider token.</span>+ <span>Other Git remotes still use server-side keys or authenticated URLs.</span></div></div>- <div className="new-service-page__aside-block">- <h2>Templates Stay Separate</h2>- <div className="new-service-page__note">- <Package size={16} />- <span>Templates are for packaged apps and infrastructure services. Repository services start here.</span>- </div>+ <div className="new-service-page__actions">+ <Button type="button" variant="outline" asChild>+ <Link to="/services">Cancel</Link>+ </Button>+ <Button type="submit" disabled={!canSubmit || submitting}>+ <Rocket size={16} />+ {submitting ? 'Importing...' : 'Import Repository'}+ </Button></div></aside>- </div>+ </form></div>);};diff --git a/frontend/src/pages/Settings.jsx b/frontend/src/pages/Settings.jsxindex 29f97ec4..d385eccb 100644--- a/frontend/src/pages/Settings.jsx+++ b/frontend/src/pages/Settings.jsx@@ -13,15 +13,16 @@ import UsersTab from '../components/settings/UsersTab';import ActivityTab from '../components/settings/ActivityTab';import SiteSettingsTab from '../components/settings/SiteSettingsTab';import SSOConfigTab from '../components/settings/SSOConfigTab';+import SourceConnectionsTab from '../components/settings/SourceConnectionsTab';import ApiSettingsTab from '../components/settings/ApiSettingsTab';import MigrationHistoryTab from '../components/settings/MigrationHistoryTab';import IconReferenceTab from '../components/settings/IconReferenceTab';import AboutTab from '../components/settings/AboutTab';-import { Activity, Code, Database, Layers, PaintBucket } from 'lucide-react';+import { Activity, Code, Database, Layers, Link2, PaintBucket } from 'lucide-react';import { Button } from '@/components/ui/button';import { useNavigate } from 'react-router-dom';-const VALID_TABS = ['profile', 'security', 'appearance', 'sidebar', 'whitelabel', 'notifications', 'system', 'users', 'activity', 'site', 'sso', 'api', 'migrations', 'developer', 'about'];+const VALID_TABS = ['profile', 'security', 'connections', 'appearance', 'sidebar', 'whitelabel', 'notifications', 'system', 'users', 'activity', 'site', 'sso', 'api', 'migrations', 'developer', 'about'];const Settings = () => {const [activeTab, setActiveTab] = useTabParam('/settings', VALID_TABS);@@ -82,6 +83,14 @@ const Settings = () => {</svg>Notifications</Button>+ <Button+ variant="ghost"+ className={`settings-nav-item ${activeTab === 'connections' ? 'active' : ''}`}+ onClick={() => setActiveTab('connections')}+ >+ <Link2 size={18} />+ Connections+ </Button><div className="settings-nav-divider">Preferences</div><Buttonvariant="ghost"@@ -248,6 +257,7 @@ const Settings = () => {<div className="settings-content">{activeTab === 'profile' && <ProfileTab />}{activeTab === 'security' && <SecuritySettingsTab />}+ {activeTab === 'connections' && <SourceConnectionsTab />}{activeTab === 'appearance' && <AppearanceTab />}{activeTab === 'sidebar' && <SidebarSettings />}{activeTab === 'whitelabel' && <WhiteLabelTab />}diff --git a/frontend/src/pages/SourceConnectionCallback.jsx b/frontend/src/pages/SourceConnectionCallback.jsxnew file mode 100644index 00000000..03b74337--- /dev/null+++ b/frontend/src/pages/SourceConnectionCallback.jsx@@ -0,0 +1,68 @@+import { useEffect, useRef, useState } from 'react';+import { useNavigate, useParams, useSearchParams } from 'react-router-dom';+import { Github, Loader2 } from 'lucide-react';+import api from '../services/api';+import { useToast } from '../contexts/ToastContext';++const SourceConnectionCallback = () => {+ const { provider } = useParams();+ const [searchParams] = useSearchParams();+ const navigate = useNavigate();+ const toast = useToast();+ const [error, setError] = useState('');+ const didComplete = useRef(false);++ useEffect(() => {+ if (didComplete.current) return;+ didComplete.current = true;++ async function completeConnection() {+ const code = searchParams.get('code');+ const state = searchParams.get('state');+ const redirectUri = `${window.location.origin}/connections/callback/${provider}`;+ const returnTo = sessionStorage.getItem('sourceConnectionReturnTo') || '/settings/connections';++ if (!code || !state) {+ setError('GitHub did not return a valid authorization response.');+ return;+ }++ try {+ await api.completeSourceConnection(provider, code, state, redirectUri);+ sessionStorage.removeItem('sourceConnectionReturnTo');+ toast.success('GitHub connected');+ navigate(returnTo, { replace: true });+ } catch (err) {+ setError(err.message || 'Failed to connect GitHub');+ }+ }++ completeConnection();+ }, [navigate, provider, searchParams, toast]);++ return (+ <div className="auth-page">+ <div className="auth-card">+ <div className="auth-logo">+ <Github size={32} />+ </div>+ <h1>Connecting GitHub</h1>+ {error ? (+ <>+ <p className="auth-error">{error}</p>+ <button className="btn btn-primary" onClick={() => navigate('/settings/connections')}>+ Back to Connections+ </button>+ </>+ ) : (+ <div className="sso-loading">+ <Loader2 size={24} className="spinning" />+ <p>Finishing provider authorization...</p>+ </div>+ )}+ </div>+ </div>+ );+};++export default SourceConnectionCallback;diff --git a/frontend/src/services/api/index.js b/frontend/src/services/api/index.jsindex 6ce54574..6af848ef 100644--- a/frontend/src/services/api/index.js+++ b/frontend/src/services/api/index.js@@ -12,6 +12,7 @@ import * as dnsMethods from './dns.js';import * as pluginMethods from './plugins.js';import * as deploymentJobMethods from './deploymentJobs.js';import * as pairingMethods from './pairing.js';+import * as sourceConnectionMethods from './sourceConnections.js';class ApiService extends ApiClient {constructor() {@@ -31,6 +32,7 @@ class ApiService extends ApiClient {pluginMethods,deploymentJobMethods,pairingMethods,+ sourceConnectionMethods,];for (const mod of modules) {for (const [key, fn] of Object.entries(mod)) {diff --git a/frontend/src/services/api/sourceConnections.js b/frontend/src/services/api/sourceConnections.jsnew file mode 100644index 00000000..ccf84dde--- /dev/null+++ b/frontend/src/services/api/sourceConnections.js@@ -0,0 +1,43 @@+// Source provider connections++export async function getGithubSourceStatus() {+ return this.request('/source-connections/github/status');+}++export async function startSourceConnection(provider, redirectUri) {+ return this.request(`/source-connections/${provider}/authorize?redirect_uri=${encodeURIComponent(redirectUri)}`);+}++export async function completeSourceConnection(provider, code, state, redirectUri) {+ return this.request(`/source-connections/${provider}/callback`, {+ method: 'POST',+ body: { code, state, redirect_uri: redirectUri },+ });+}++export async function disconnectSourceConnection(provider) {+ return this.request(`/source-connections/${provider}`, { method: 'DELETE' });+}++export async function listGithubRepositories({ search = '', page = 1, perPage = 50 } = {}) {+ const params = new URLSearchParams();+ if (search) params.set('search', search);+ params.set('page', page);+ params.set('per_page', perPage);+ return this.request(`/source-connections/github/repos?${params.toString()}`);+}++export async function listGithubBranches(fullName) {+ return this.request(`/source-connections/github/repos/${encodeURIComponent(fullName)}/branches`);+}++export async function getGithubSourceConfig() {+ return this.request('/source-connections/admin/github');+}++export async function updateGithubSourceConfig(config) {+ return this.request('/source-connections/admin/github', {+ method: 'PUT',+ body: config,+ });+}diff --git a/frontend/src/styles/pages/_new-service.scss b/frontend/src/styles/pages/_new-service.scssindex e31c7dd2..c2090207 100644--- a/frontend/src/styles/pages/_new-service.scss+++ b/frontend/src/styles/pages/_new-service.scss@@ -25,6 +25,7 @@&__header {display: flex;+ align-items: flex-start;justify-content: space-between;gap: $space-4;margin-bottom: $space-5;@@ -37,25 +38,27 @@}p {+ max-width: 620px;margin: $space-1 0 0;color: $text-tertiary;font-size: $font-size-sm;+ line-height: 1.5;}}- &__source-grid {+ &__mode-strip {display: grid;- grid-template-columns: repeat(2, minmax(0, 1fr));+ grid-template-columns: repeat(3, minmax(0, 1fr));gap: $space-3;margin-bottom: $space-4;}- &__source-card {+ &__mode-card {display: grid;grid-template-columns: auto minmax(0, 1fr) auto;align-items: center;gap: $space-3;- min-height: 74px;+ min-height: 72px;padding: $space-4;background: $bg-card;border: 1px solid $border-subtle;@@ -72,8 +75,10 @@}&--active {- border-color: rgba(45, 212, 191, 0.45);- background: linear-gradient(135deg, rgba(45, 212, 191, 0.09), rgba(99, 102, 241, 0.08));+ border-color: rgba(20, 184, 166, 0.5);+ background:+ linear-gradient(135deg, rgba(20, 184, 166, 0.1), rgba(99, 102, 241, 0.08)),+ $bg-card;}strong,@@ -94,10 +99,19 @@}}- &__source-icon {- display: flex;+ &__mode-icon,+ &__provider-title svg,+ &__connect-icon,+ &__deploy-icon {+ display: inline-flex;align-items: center;justify-content: center;+ flex-shrink: 0;+ }++ &__mode-icon,+ &__connect-icon,+ &__deploy-icon {width: 36px;height: 36px;border-radius: $radius-lg;@@ -105,9 +119,9 @@color: $accent-primary;}- &__layout {+ &__wizard {display: grid;- grid-template-columns: minmax(0, 1fr) minmax(320px, 380px);+ grid-template-columns: minmax(0, 1fr) minmax(340px, 390px);gap: $space-4;align-items: start;}@@ -118,15 +132,16 @@border-radius: $radius-lg;}- &__form {+ &__provider-panel,+ &__review-panel {display: grid;gap: $space-5;padding: $space-5;}- &__section {- display: grid;- gap: $space-4;+ &__review-panel {+ position: sticky;+ top: $space-4;}&__section-heading {@@ -146,6 +161,269 @@}}+ &__provider-grid {+ display: grid;+ grid-template-columns: repeat(4, minmax(0, 1fr));+ gap: $space-3;+ }++ &__provider-card {+ position: relative;+ display: grid;+ gap: $space-3;+ min-height: 160px;+ padding: $space-4;+ background: $bg-elevated;+ border: 1px solid $border-subtle;+ border-radius: $radius-lg;+ color: $text-primary;+ text-align: left;+ cursor: pointer;+ transition: border-color $transition-fast, background $transition-fast, transform $transition-fast;++ &:hover {+ background: $bg-hover;+ border-color: $border-hover;+ transform: translateY(-1px);+ }++ &--active {+ border-color: rgba(20, 184, 166, 0.55);+ box-shadow: inset 0 0 0 1px rgba(20, 184, 166, 0.18);+ }++ > svg {+ position: absolute;+ top: $space-4;+ right: $space-4;+ color: $success;+ }++ small {+ color: $text-tertiary;+ font-size: $font-size-xs;+ line-height: 1.5;+ }+ }++ &__provider-meta {+ width: max-content;+ padding: 3px $space-2;+ border: 1px solid $border-subtle;+ border-radius: $radius-full;+ color: $text-tertiary;+ font-size: $font-size-xs;+ line-height: 1;+ }++ &__provider-title {+ display: flex;+ align-items: center;+ gap: $space-2;++ svg {+ color: $accent-primary;+ }++ strong {+ font-size: $font-size-base;+ font-weight: $font-weight-semibold;+ }+ }++ &__connect-box {+ display: grid;+ gap: $space-4;+ padding: $space-4;+ background: linear-gradient(180deg, rgba(255, 255, 255, 0.02), rgba(255, 255, 255, 0));+ border: 1px solid $border-subtle;+ border-radius: $radius-lg;+ }++ &__connect-heading {+ display: flex;+ align-items: center;+ gap: $space-3;++ strong,+ span {+ display: block;+ }++ strong {+ color: $text-primary;+ font-size: $font-size-sm;+ font-weight: $font-weight-semibold;+ }++ span {+ margin-top: 2px;+ color: $text-tertiary;+ font-size: $font-size-xs;+ line-height: 1.4;+ }+ }++ &__github-account {+ display: grid;+ grid-template-columns: auto minmax(0, 1fr) auto;+ align-items: center;+ gap: $space-3;+ padding: $space-3;+ background: $bg-elevated;+ border: 1px solid $border-subtle;+ border-radius: $radius-md;++ img {+ width: 36px;+ height: 36px;+ border-radius: $radius-full;+ }++ strong,+ span {+ display: block;+ }++ strong {+ color: $text-primary;+ font-size: $font-size-sm;+ font-weight: $font-weight-semibold;+ }++ span {+ margin-top: 2px;+ color: $text-tertiary;+ font-size: $font-size-xs;+ }+ }++ &__repo-search {+ display: grid;+ grid-template-columns: auto minmax(0, 1fr) auto;+ align-items: center;+ gap: $space-2;+ padding: $space-2;+ background: $bg-elevated;+ border: 1px solid $border-subtle;+ border-radius: $radius-md;++ > svg {+ margin-left: $space-2;+ color: $text-tertiary;+ }+ }++ &__repo-list {+ display: grid;+ gap: $space-2;+ max-height: 430px;+ overflow-y: auto;+ padding-right: $space-1;+ }++ &__repo-row {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: $space-3;+ width: 100%;+ min-height: 64px;+ padding: $space-3;+ background: $bg-elevated;+ border: 1px solid $border-subtle;+ border-radius: $radius-md;+ color: $text-primary;+ text-align: left;+ cursor: pointer;+ transition: border-color $transition-fast, background $transition-fast;++ &:hover {+ background: $bg-hover;+ border-color: $border-hover;+ }++ &--active {+ border-color: rgba(20, 184, 166, 0.55);+ box-shadow: inset 0 0 0 1px rgba(20, 184, 166, 0.18);+ }++ span,+ strong,+ small {+ display: block;+ min-width: 0;+ }++ strong {+ color: $text-primary;+ font-size: $font-size-sm;+ font-weight: $font-weight-semibold;+ overflow-wrap: anywhere;+ }++ small {+ margin-top: 3px;+ color: $text-tertiary;+ font-size: $font-size-xs;+ line-height: 1.35;+ overflow-wrap: anywhere;+ }++ em {+ flex-shrink: 0;+ padding: 3px $space-2;+ border: 1px solid $border-subtle;+ border-radius: $radius-full;+ color: $text-tertiary;+ font-size: $font-size-xs;+ font-style: normal;+ }+ }++ &__repo-state {+ display: grid;+ place-items: center;+ min-height: 120px;+ padding: $space-4;+ background: $bg-elevated;+ border: 1px dashed $border-subtle;+ border-radius: $radius-md;+ color: $text-tertiary;+ font-size: $font-size-sm;+ }++ &__connect-empty {+ display: grid;+ justify-items: center;+ gap: $space-4;+ padding: $space-8 $space-4;+ text-align: center;++ h2 {+ margin: 0;+ color: $text-primary;+ font-size: $font-size-lg;+ font-weight: $font-weight-semibold;+ }++ p {+ max-width: 460px;+ margin: $space-2 auto 0;+ color: $text-tertiary;+ font-size: $font-size-sm;+ line-height: 1.5;+ }+ }++ &__connect-actions {+ display: flex;+ align-items: center;+ justify-content: center;+ gap: $space-2;+ flex-wrap: wrap;+ }+&__field {display: grid;gap: $space-2;@@ -179,73 +457,80 @@}}- &__hint {- color: $text-tertiary;- font-size: $font-size-xs;- line-height: 1.45;- }-- &__two-col {+ &__repo-preview,+ &__summary {display: grid;- grid-template-columns: repeat(2, minmax(0, 1fr));- gap: $space-4;- }-- &__toggle {- display: flex;- align-items: center;- justify-content: space-between;- gap: $space-4;- min-height: 72px;- padding: $space-3;- background: $bg-elevated;- border: 1px solid $border-subtle;- border-radius: $radius-md;+ gap: $space-2;- label,- span {- display: block;+ > div {+ display: flex;+ align-items: flex-start;+ justify-content: space-between;+ gap: $space-3;+ min-width: 0;+ padding: $space-3;+ background: $bg-elevated;+ border: 1px solid $border-subtle;+ border-radius: $radius-md;}- label {- color: $text-secondary;- font-size: $font-size-sm;- font-weight: $font-weight-medium;+ span,+ strong {+ display: block;}span {- margin-top: 3px;color: $text-tertiary;font-size: $font-size-xs;line-height: 1.4;}- }- &__actions {- display: flex;- justify-content: flex-end;- gap: $space-2;- padding-top: $space-1;+ strong {+ min-width: 0;+ color: $text-primary;+ font-size: $font-size-sm;+ font-weight: $font-weight-semibold;+ overflow-wrap: anywhere;+ text-align: right;+ }}- &__aside {- display: grid;- gap: $space-5;- padding: $space-5;- position: sticky;- top: $space-4;+ &__repo-preview {+ grid-template-columns: repeat(3, minmax(0, 1fr));++ > div {+ display: grid;+ justify-content: stretch;+ }++ strong {+ text-align: left;+ }}- &__aside-block {- display: grid;+ &__deploy-card {+ display: flex;gap: $space-3;+ align-items: flex-start;h2 {margin: 0;color: $text-primary;- font-size: $font-size-sm;+ font-size: $font-size-lg;font-weight: $font-weight-semibold;}++ p {+ margin: $space-1 0 0;+ color: $text-tertiary;+ font-size: $font-size-sm;+ line-height: 1.5;+ }+ }++ &__deploy-icon {+ background: rgba(16, 185, 129, 0.1);+ color: $success;}&__flow {@@ -259,7 +544,7 @@display: grid;place-items: center;gap: $space-2;- min-height: 70px;+ min-height: 68px;background: $bg-elevated;border: 1px solid $border-subtle;border-radius: $radius-md;@@ -269,6 +554,89 @@}}+ &__advanced-toggle {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: $space-3;+ min-height: 44px;+ padding: 0 $space-3;+ background: $bg-elevated;+ border: 1px solid $border-subtle;+ border-radius: $radius-md;+ color: $text-secondary;+ cursor: pointer;+ transition: border-color $transition-fast, background $transition-fast;++ &:hover {+ background: $bg-hover;+ border-color: $border-hover;+ }++ span {+ display: flex;+ align-items: center;+ gap: $space-2;+ font-size: $font-size-sm;+ font-weight: $font-weight-medium;+ }++ &[aria-expanded='true'] > svg {+ transform: rotate(180deg);+ }++ > svg {+ transition: transform $transition-fast;+ }+ }++ &__advanced {+ display: grid;+ gap: $space-4;+ padding-top: $space-1;+ }++ &__two-col {+ display: grid;+ grid-template-columns: repeat(2, minmax(0, 1fr));+ gap: $space-4;+ }++ &__toggle {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: $space-4;+ min-height: 72px;+ padding: $space-3;+ background: $bg-elevated;+ border: 1px solid $border-subtle;+ border-radius: $radius-md;++ label,+ span {+ display: block;+ }++ label {+ color: $text-secondary;+ font-size: $font-size-sm;+ font-weight: $font-weight-medium;+ }++ span {+ margin-top: 3px;+ color: $text-tertiary;+ font-size: $font-size-xs;+ line-height: 1.4;+ }+ }++ &__notes {+ display: grid;+ gap: $space-2;+ }+&__note {display: flex;align-items: flex-start;@@ -278,24 +646,39 @@border: 1px solid $border-subtle;border-radius: $radius-md;color: $text-tertiary;- font-size: $font-size-sm;+ font-size: $font-size-xs;line-height: 1.45;svg {- margin-top: 2px;+ margin-top: 1px;color: $text-secondary;flex-shrink: 0;}}++ &__actions {+ display: flex;+ justify-content: flex-end;+ gap: $space-2;+ padding-top: $space-1;+ }+}++@media (max-width: $breakpoint-xl) {+ .new-service-page {+ &__provider-grid {+ grid-template-columns: repeat(2, minmax(0, 1fr));+ }+ }}@media (max-width: $breakpoint-lg) {.new-service-page {- &__layout {+ &__wizard {grid-template-columns: 1fr;}- &__aside {+ &__review-panel {position: static;}}@@ -303,11 +686,37 @@@media (max-width: $breakpoint-md) {.new-service-page {- &__source-grid,+ &__header {+ display: grid;+ }++ &__mode-strip,+ &__provider-grid,+ &__repo-preview,+ &__repo-search,&__two-col {grid-template-columns: 1fr;}+ &__github-account {+ grid-template-columns: auto minmax(0, 1fr);++ .btn,+ button {+ grid-column: 1 / -1;+ width: 100%;+ }+ }++ &__flow {+ grid-template-columns: 1fr;++ > svg {+ justify-self: center;+ transform: rotate(90deg);+ }+ }+&__actions {flex-direction: column-reverse;diff --git a/frontend/src/styles/pages/_settings.scss b/frontend/src/styles/pages/_settings.scssindex 975b833d..d8d482ef 100644--- a/frontend/src/styles/pages/_settings.scss+++ b/frontend/src/styles/pages/_settings.scss@@ -225,6 +225,133 @@}}+// Source provider connections+.source-connections {+ .source-connection-status {+ display: inline-flex;+ align-items: center;+ gap: $space-1;+ padding: $space-1 $space-2;+ border: 1px solid $border-subtle;+ border-radius: $radius-full;+ color: $text-tertiary;+ font-size: $font-size-xs;+ font-weight: $font-weight-medium;++ &--connected {+ border-color: $success-border;+ background: $success-bg;+ color: $success;+ }+ }++ .source-connection-profile,+ .source-connection-empty {+ display: grid;+ grid-template-columns: auto minmax(0, 1fr) auto;+ align-items: center;+ gap: $space-3;+ padding: $space-4;+ background: $bg-elevated;+ border: 1px solid $border-subtle;+ border-radius: $radius-md;+ }++ .source-connection-profile {+ img {+ width: 42px;+ height: 42px;+ border-radius: $radius-full;+ }++ strong,+ span {+ display: block;+ }++ strong {+ color: $text-primary;+ font-size: $font-size-sm;+ font-weight: $font-weight-semibold;+ }++ span {+ margin-top: 2px;+ color: $text-tertiary;+ font-size: $font-size-xs;+ }+ }++ .source-connection-empty {+ > svg {+ color: $accent-primary;+ }++ strong,+ span {+ display: block;+ }++ strong {+ color: $text-primary;+ font-size: $font-size-sm;+ font-weight: $font-weight-semibold;+ }++ span {+ margin-top: 3px;+ color: $text-tertiary;+ font-size: $font-size-xs;+ line-height: 1.45;+ }+ }+}++.source-oauth-config {+ &__grid {+ display: grid;+ grid-template-columns: repeat(2, minmax(0, 1fr));+ gap: $space-4;+ margin-bottom: $space-4;+ }++ &__callback {+ display: flex;+ align-items: center;+ gap: $space-2;+ padding: $space-3;+ background: $bg-elevated;+ border: 1px solid $border-subtle;+ border-radius: $radius-md;+ color: $text-tertiary;+ font-size: $font-size-xs;+ overflow-wrap: anywhere;++ svg {+ flex-shrink: 0;+ color: $text-secondary;+ }+ }+}++@media (max-width: $breakpoint-md) {+ .source-connections {+ .source-connection-profile,+ .source-connection-empty {+ grid-template-columns: 1fr;++ .btn,+ button {+ width: 100%;+ }+ }+ }++ .source-oauth-config__grid {+ grid-template-columns: 1fr;+ }+}+.settings-card__loading {padding: $space-6;text-align: center;