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 branch selection and webhook logs to deploy tab
Juan Denisc358a8521740
diff --git a/backend/app/api/deploy.py b/backend/app/api/deploy.pyindex 7bdb1ce4..fe33272f 100644--- a/backend/app/api/deploy.py+++ b/backend/app/api/deploy.py@@ -195,15 +195,75 @@ def clone_repository():return jsonify(result), 201 if result['success'] else 400+@deploy_bp.route('/apps/<int:app_id>/branches', methods=['GET'])+@jwt_required()+def get_branches(app_id):+ """Get list of remote branches for an app's repository."""+ current_user_id = get_jwt_identity()+ user = User.query.get(current_user_id)+ app = Application.query.get(app_id)++ if not app:+ return jsonify({'error': 'Application not found'}), 404++ if user.role != 'admin' and app.user_id != current_user_id:+ return jsonify({'error': 'Access denied'}), 403++ result = GitService.get_remote_branches(app.path)+ return jsonify(result), 200 if result.get('success') else 400+++@deploy_bp.route('/branches', methods=['POST'])+@jwt_required()+def get_branches_from_url():+ """Get list of branches from a repository URL (before cloning)."""+ data = request.get_json()+ if not data or 'repo_url' not in data:+ return jsonify({'error': 'repo_url is required'}), 400++ result = GitService.get_remote_branches_from_url(data['repo_url'])+ return jsonify(result), 200 if result.get('success') else 400+++@deploy_bp.route('/webhook-logs', methods=['GET'])+@jwt_required()+def get_webhook_logs():+ """Get webhook logs for debugging."""+ app_id = request.args.get('app_id', type=int)+ limit = request.args.get('limit', 50, type=int)++ logs = GitService.get_webhook_logs(app_id, limit)+ return jsonify({'logs': logs}), 200++# Webhook endpoint (no auth required)@deploy_bp.route('/webhook/<int:app_id>/<token>', methods=['POST'])def webhook(app_id, token):"""Handle incoming webhook from Git provider."""- # Get signature if provided (GitHub style)- signature = request.headers.get('X-Hub-Signature-256')+ # Detect provider based on headers+ provider = 'github' # default+ signature = None++ if request.headers.get('X-Gitlab-Token'):+ provider = 'gitlab'+ signature = request.headers.get('X-Gitlab-Token')+ elif request.headers.get('X-Hub-Signature-256'):+ # Could be GitHub or Bitbucket+ if request.headers.get('X-Bitbucket-Type'):+ provider = 'bitbucket'+ else:+ provider = 'github'+ signature = request.headers.get('X-Hub-Signature-256')+ elif request.headers.get('X-Hub-Signature'):+ # Bitbucket uses X-Hub-Signature+ provider = 'bitbucket'+ signature = request.headers.get('X-Hub-Signature')++ # Log webhook for debugging+ GitService.log_webhook(app_id, provider, request.headers.to_wsgi_list(), request.data)# Verify webhook- if not GitService.verify_webhook(app_id, token, signature, request.data):+ if not GitService.verify_webhook(app_id, token, signature, request.data, provider):return jsonify({'error': 'Invalid webhook'}), 403# Parse payloaddiff --git a/backend/app/services/git_service.py b/backend/app/services/git_service.pyindex 68fe1e5d..b5d84dd6 100644--- a/backend/app/services/git_service.py+++ b/backend/app/services/git_service.py@@ -304,8 +304,12 @@ class GitService:@classmethoddef verify_webhook(cls, app_id: int, token: str,- signature: str = None, payload: bytes = None) -> bool:- """Verify webhook authenticity."""+ signature: str = None, payload: bytes = None,+ provider: str = 'github') -> bool:+ """Verify webhook authenticity.++ Supports GitHub, GitLab, and Bitbucket signature verification.+ """app_config = cls.get_app_config(app_id)if not app_config:return False@@ -314,15 +318,99 @@ class GitService:if token != app_config.get('webhook_token'):return False- # If signature provided (GitHub style), verify it+ # If signature provided, verify based on providerif signature and payload:config = cls.get_config()secret = config.get('webhook_secret', '').encode()- expected = 'sha256=' + hmac.new(secret, payload, hashlib.sha256).hexdigest()- return hmac.compare_digest(signature, expected)++ if provider == 'github':+ # GitHub: X-Hub-Signature-256 header with sha256=<hex>+ expected = 'sha256=' + hmac.new(secret, payload, hashlib.sha256).hexdigest()+ return hmac.compare_digest(signature, expected)++ elif provider == 'gitlab':+ # GitLab: X-Gitlab-Token header contains the secret directly+ return hmac.compare_digest(signature, config.get('webhook_secret', ''))++ elif provider == 'bitbucket':+ # Bitbucket: X-Hub-Signature header with sha256=<hex> (similar to GitHub)+ expected = 'sha256=' + hmac.new(secret, payload, hashlib.sha256).hexdigest()+ return hmac.compare_digest(signature, expected)return True+ @classmethod+ def get_remote_branches(cls, app_path: str) -> Dict:+ """Get list of remote branches for a repository."""+ if not os.path.exists(os.path.join(app_path, '.git')):+ return {'success': False, 'error': 'Not a Git repository'}++ try:+ # Fetch latest from remote+ fetch_cmd = ['git', '-C', app_path, 'fetch', '--all', '--prune']+ subprocess.run(fetch_cmd, capture_output=True, text=True, timeout=60)++ # Get remote branches+ cmd = ['git', '-C', app_path, 'branch', '-r', '--format=%(refname:short)']+ result = subprocess.run(cmd, capture_output=True, text=True, timeout=30)++ if result.returncode != 0:+ return {'success': False, 'error': result.stderr}++ branches = []+ for line in result.stdout.strip().split('\n'):+ branch = line.strip()+ if branch and not branch.endswith('/HEAD'):+ # Remove origin/ prefix+ if branch.startswith('origin/'):+ branch = branch[7:]+ branches.append(branch)++ # Get current branch+ cmd = ['git', '-C', app_path, 'rev-parse', '--abbrev-ref', 'HEAD']+ result = subprocess.run(cmd, capture_output=True, text=True)+ current_branch = result.stdout.strip() if result.returncode == 0 else None++ return {+ 'success': True,+ 'branches': sorted(set(branches)),+ 'current_branch': current_branch+ }++ except subprocess.TimeoutExpired:+ return {'success': False, 'error': 'Operation timed out'}+ except Exception as e:+ return {'success': False, 'error': str(e)}++ @classmethod+ def get_remote_branches_from_url(cls, repo_url: str) -> Dict:+ """Get list of branches from a remote repository URL without cloning."""+ try:+ cmd = ['git', 'ls-remote', '--heads', repo_url]+ result = subprocess.run(cmd, capture_output=True, text=True, timeout=30)++ if result.returncode != 0:+ return {'success': False, 'error': result.stderr or 'Failed to fetch branches'}++ branches = []+ for line in result.stdout.strip().split('\n'):+ if line:+ # Format: <hash>\trefs/heads/<branch>+ parts = line.split('\t')+ if len(parts) == 2 and parts[1].startswith('refs/heads/'):+ branch = parts[1].replace('refs/heads/', '')+ branches.append(branch)++ return {+ 'success': True,+ 'branches': sorted(branches)+ }++ except subprocess.TimeoutExpired:+ return {'success': False, 'error': 'Operation timed out'}+ except Exception as e:+ return {'success': False, 'error': str(e)}+@classmethoddef handle_webhook(cls, app_id: int, payload: Dict) -> Dict:"""Handle incoming webhook."""@@ -427,3 +515,62 @@ class GitService:except Exception as e:return {'error': str(e)}++ WEBHOOK_LOG = '/var/log/serverkit/webhooks.log'++ @classmethod+ def log_webhook(cls, app_id: int, provider: str, headers: List, payload: bytes) -> None:+ """Log incoming webhook for debugging."""+ try:+ log_dir = os.path.dirname(cls.WEBHOOK_LOG)+ os.makedirs(log_dir, exist_ok=True)++ # Sanitize headers (remove sensitive tokens)+ safe_headers = {}+ for key, value in headers:+ if 'token' in key.lower() or 'signature' in key.lower() or 'secret' in key.lower():+ safe_headers[key] = value[:10] + '...' if len(value) > 10 else '***'+ else:+ safe_headers[key] = value++ log_entry = {+ 'timestamp': datetime.now().isoformat(),+ 'app_id': app_id,+ 'provider': provider,+ 'headers': safe_headers,+ 'payload_size': len(payload),+ 'payload_preview': payload[:500].decode('utf-8', errors='replace') if payload else None+ }++ with open(cls.WEBHOOK_LOG, 'a') as f:+ f.write(json.dumps(log_entry) + '\n')++ except Exception:+ pass++ @classmethod+ def get_webhook_logs(cls, app_id: int = None, limit: int = 50) -> List[Dict]:+ """Get webhook logs for debugging."""+ logs = []++ if not os.path.exists(cls.WEBHOOK_LOG):+ return logs++ try:+ with open(cls.WEBHOOK_LOG, 'r') as f:+ lines = f.readlines()++ for line in reversed(lines[-limit * 2:]):+ try:+ entry = json.loads(line.strip())+ if app_id is None or entry.get('app_id') == app_id:+ logs.append(entry)+ if len(logs) >= limit:+ break+ except json.JSONDecodeError:+ pass++ except Exception:+ pass++ return logsdiff --git a/frontend/src/pages/ApplicationDetail.jsx b/frontend/src/pages/ApplicationDetail.jsxindex 3eedf494..913ee3de 100644--- a/frontend/src/pages/ApplicationDetail.jsx+++ b/frontend/src/pages/ApplicationDetail.jsx@@ -942,9 +942,13 @@ const DeployTab = ({ appId, appPath }) => {const [config, setConfig] = useState(null);const [gitStatus, setGitStatus] = useState(null);const [history, setHistory] = useState([]);+ const [webhookLogs, setWebhookLogs] = useState([]);+ const [branches, setBranches] = useState([]);const [loading, setLoading] = useState(true);const [deploying, setDeploying] = useState(false);const [showConfigModal, setShowConfigModal] = useState(false);+ const [showWebhookLogs, setShowWebhookLogs] = useState(false);+ const [loadingBranches, setLoadingBranches] = useState(false);const [error, setError] = useState(null);// Config form state@@ -996,6 +1000,44 @@ const DeployTab = ({ appId, appPath }) => {}}+ async function loadBranchesFromUrl(repoUrl) {+ if (!repoUrl) return;+ setLoadingBranches(true);+ try {+ const result = await api.getBranchesFromUrl(repoUrl);+ if (result.success) {+ setBranches(result.branches || []);+ }+ } catch (err) {+ console.error('Failed to load branches:', err);+ } finally {+ setLoadingBranches(false);+ }+ }++ async function loadBranchesFromApp() {+ setLoadingBranches(true);+ try {+ const result = await api.getAppBranches(appId);+ if (result.success) {+ setBranches(result.branches || []);+ }+ } catch (err) {+ console.error('Failed to load branches:', err);+ } finally {+ setLoadingBranches(false);+ }+ }++ async function loadWebhookLogs() {+ try {+ const result = await api.getWebhookLogs(appId, 20);+ setWebhookLogs(result.logs || []);+ } catch (err) {+ console.error('Failed to load webhook logs:', err);+ }+ }+async function handleConfigureDeployment(e) {e.preventDefault();try {@@ -1233,6 +1275,56 @@ const DeployTab = ({ appId, appPath }) => {Copy</button></div>+ <div className="webhook-logs-toggle">+ <button+ className="btn btn-secondary btn-sm"+ onClick={() => {+ setShowWebhookLogs(!showWebhookLogs);+ if (!showWebhookLogs) loadWebhookLogs();+ }}+ >+ {showWebhookLogs ? 'Hide Webhook Logs' : 'Show Webhook Logs'}+ </button>+ </div>+ {showWebhookLogs && (+ <div className="webhook-logs">+ <div className="webhook-logs-header">+ <h4>Recent Webhook Requests</h4>+ <button className="btn btn-secondary btn-sm" onClick={loadWebhookLogs}>+ Refresh+ </button>+ </div>+ {webhookLogs.length === 0 ? (+ <p className="hint">No webhook requests received yet.</p>+ ) : (+ <div className="webhook-logs-list">+ {webhookLogs.map((log, index) => (+ <div key={index} className="webhook-log-item">+ <div className="webhook-log-header">+ <span className={`provider-badge ${log.provider}`}>+ {log.provider}+ </span>+ <span className="webhook-log-time">+ {new Date(log.timestamp).toLocaleString()}+ </span>+ </div>+ <div className="webhook-log-details">+ <span className="webhook-log-size">+ Payload: {log.payload_size} bytes+ </span>+ </div>+ {log.payload_preview && (+ <pre className="webhook-log-preview">+ {log.payload_preview.substring(0, 200)}+ {log.payload_preview.length > 200 && '...'}+ </pre>+ )}+ </div>+ ))}+ </div>+ )}+ </div>+ )}</div></div>@@ -1309,23 +1401,49 @@ const DeployTab = ({ appId, appPath }) => {<div className="modal-body"><div className="form-group"><label>Repository URL *</label>- <input- type="url"- value={configForm.repoUrl}- onChange={(e) => setConfigForm({...configForm, repoUrl: e.target.value})}- placeholder="https://github.com/user/repo.git"- required- />+ <div className="input-with-action">+ <input+ type="url"+ value={configForm.repoUrl}+ onChange={(e) => setConfigForm({...configForm, repoUrl: e.target.value})}+ placeholder="https://github.com/user/repo.git"+ required+ />+ <button+ type="button"+ className="btn btn-secondary btn-sm"+ onClick={() => loadBranchesFromUrl(configForm.repoUrl)}+ disabled={!configForm.repoUrl || loadingBranches}+ >+ {loadingBranches ? 'Loading...' : 'Fetch Branches'}+ </button>+ </div></div><div className="form-group"><label>Branch</label>- <input- type="text"- value={configForm.branch}- onChange={(e) => setConfigForm({...configForm, branch: e.target.value})}- placeholder="main"- />+ {branches.length > 0 ? (+ <select+ value={configForm.branch}+ onChange={(e) => setConfigForm({...configForm, branch: e.target.value})}+ >+ {branches.map(branch => (+ <option key={branch} value={branch}>{branch}</option>+ ))}+ </select>+ ) : (+ <input+ type="text"+ value={configForm.branch}+ onChange={(e) => setConfigForm({...configForm, branch: e.target.value})}+ placeholder="main"+ />+ )}+ <span className="form-help">+ {branches.length > 0+ ? `${branches.length} branches available`+ : 'Click "Fetch Branches" to load available branches'}+ </span></div><div className="form-group">diff --git a/frontend/src/services/api.js b/frontend/src/services/api.jsindex 3c5fefaa..1ab2c026 100644--- a/frontend/src/services/api.js+++ b/frontend/src/services/api.js@@ -1205,6 +1205,23 @@ class ApiService {});}+ async getAppBranches(appId) {+ return this.request(`/deploy/apps/${appId}/branches`);+ }++ async getBranchesFromUrl(repoUrl) {+ return this.request('/deploy/branches', {+ method: 'POST',+ body: { repo_url: repoUrl }+ });+ }++ async getWebhookLogs(appId = null, limit = 50) {+ const params = new URLSearchParams({ limit });+ if (appId) params.append('app_id', appId);+ return this.request(`/deploy/webhook-logs?${params}`);+ }+// ========================================// File Manager endpoints// ========================================diff --git a/frontend/src/styles/components/_deploy.less b/frontend/src/styles/components/_deploy.lessnew file mode 100644index 00000000..9e4b5fec--- /dev/null+++ b/frontend/src/styles/components/_deploy.less@@ -0,0 +1,262 @@+// ============================================+// DEPLOY TAB STYLES+// ============================================++// Deploy Tab Container+.deploy-tab {+ display: flex;+ flex-direction: column;+ gap: @space-6;+}++// Deploy Setup Empty State+.deploy-setup {+ .empty-state {+ text-align: center;+ padding: @space-12 @space-8;+ background: @bg-card;+ border: 1px dashed @border-subtle;+ border-radius: @radius-lg;++ svg {+ color: @text-tertiary;+ margin-bottom: @space-4;+ }++ h3 {+ margin-bottom: @space-2;+ }++ p {+ color: @text-secondary;+ margin-bottom: @space-6;+ max-width: 400px;+ margin-left: auto;+ margin-right: auto;+ }+ }+}++// Deploy Header+.deploy-header {+ margin-bottom: @space-4;+}++.deploy-status-card {+ display: flex;+ justify-content: space-between;+ align-items: center;+ padding: @space-4 @space-6;+ background: @bg-card;+ border: 1px solid @border-subtle;+ border-radius: @radius-lg;+}++.deploy-repo-info {+ display: flex;+ align-items: center;+ gap: @space-3;++ svg {+ color: @text-secondary;+ }++ .repo-url {+ display: block;+ font-weight: @font-weight-medium;+ color: @text-primary;+ }++ .repo-branch {+ display: block;+ font-size: @font-size-sm;+ color: @text-secondary;+ }+}++.deploy-actions {+ display: flex;+ gap: @space-3;+}++// Deploy Grid+.deploy-grid {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));+ gap: @space-6;+}++// Webhook URL+.webhook-url {+ display: flex;+ gap: @space-2;+ align-items: center;+ margin-top: @space-3;+ padding: @space-3;+ background: @bg-hover;+ border-radius: @radius-md;+ overflow: hidden;++ code {+ flex: 1;+ font-family: @font-mono;+ font-size: @font-size-sm;+ color: @text-primary;+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+ }+}++.webhook-logs-toggle {+ margin-top: @space-4;+}++// Webhook Logs+.webhook-logs {+ margin-top: @space-4;+ padding-top: @space-4;+ border-top: 1px solid @border-subtle;+}++.webhook-logs-header {+ display: flex;+ justify-content: space-between;+ align-items: center;+ margin-bottom: @space-3;++ h4 {+ margin: 0;+ font-size: @font-size-sm;+ font-weight: @font-weight-semibold;+ color: @text-secondary;+ }+}++.webhook-logs-list {+ display: flex;+ flex-direction: column;+ gap: @space-3;+ max-height: 400px;+ overflow-y: auto;+}++.webhook-log-item {+ padding: @space-3;+ background: @bg-hover;+ border-radius: @radius-md;+ border: 1px solid @border-subtle;+}++.webhook-log-header {+ display: flex;+ justify-content: space-between;+ align-items: center;+ margin-bottom: @space-2;+}++.provider-badge {+ display: inline-block;+ padding: @space-1 @space-2;+ font-size: @font-size-xs;+ font-weight: @font-weight-medium;+ border-radius: @radius-sm;+ text-transform: capitalize;++ &.github {+ background: fade(#333, 15%);+ color: #333;+ }++ &.gitlab {+ background: fade(#fc6d26, 15%);+ color: #fc6d26;+ }++ &.bitbucket {+ background: fade(#0052cc, 15%);+ color: #0052cc;+ }+}++.webhook-log-time {+ font-size: @font-size-xs;+ color: @text-tertiary;+}++.webhook-log-details {+ margin-bottom: @space-2;+}++.webhook-log-size {+ font-size: @font-size-sm;+ color: @text-secondary;+}++.webhook-log-preview {+ margin: 0;+ padding: @space-2;+ background: @bg-body;+ border-radius: @radius-sm;+ font-family: @font-mono;+ font-size: @font-size-xs;+ color: @text-secondary;+ white-space: pre-wrap;+ word-break: break-all;+ max-height: 100px;+ overflow-y: auto;+}++// Input with action button+.input-with-action {+ display: flex;+ gap: @space-2;++ input {+ flex: 1;+ }++ .btn {+ flex-shrink: 0;+ }+}++// Scripts Grid+.scripts-grid {+ display: grid;+ grid-template-columns: 1fr 1fr;+ gap: @space-4;++ @media (max-width: 768px) {+ grid-template-columns: 1fr;+ }+}++.script-section {+ h4 {+ margin: 0 0 @space-2 0;+ font-size: @font-size-sm;+ color: @text-secondary;+ }+}++.script-code {+ margin: 0;+ padding: @space-3;+ background: @bg-hover;+ border-radius: @radius-md;+ font-family: @font-mono;+ font-size: @font-size-sm;+ color: @text-primary;+ white-space: pre-wrap;+ word-break: break-all;+}++// Card Actions+.card-actions {+ display: flex;+ gap: @space-2;+ margin-top: @space-4;+ padding-top: @space-4;+ border-top: 1px solid @border-subtle;+}diff --git a/frontend/src/styles/main.less b/frontend/src/styles/main.lessindex 9726d4aa..c84ca9b3 100644--- a/frontend/src/styles/main.less+++ b/frontend/src/styles/main.less@@ -44,6 +44,7 @@@import 'components/_two-factor';@import 'components/_notifications';@import 'components/_query-runner';+@import 'components/_deploy';// --------------------------------------------// 5. PAGE-SPECIFIC STYLES