Skip to content

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.

feat(servers): ServerKit-to-ServerKit peering — embedded agent mode

Juan Denisdb3c29179dfb
diff --git a/backend/app/__init__.py b/backend/app/__init__.py
index 6a85da0c..918ffa14 100644
--- a/backend/app/__init__.py
+++ b/backend/app/__init__.py
@@ -125,6 +125,11 @@ def create_app(config_name=None):
from app.api.agent_poll import agent_poll_bp
app.register_blueprint(agent_poll_bp, url_prefix='/api/v1/agent')
+ # ServerKit-to-ServerKit peering: this panel linked to a master panel
+ # (embedded agent mode — no standalone Go agent required).
+ from app.api.linked_panel import linked_panel_bp
+ app.register_blueprint(linked_panel_bp, url_prefix='/api/v1/linked-panel')
+
# Register blueprints - Core
from app.api.apps import apps_bp
from app.api.domains import domains_bp
@@ -696,6 +701,11 @@ def create_app(config_name=None):
BandwidthService.register_jobs()
start_job_system(app, seed=seed_builtin_schedules)
+ # Resume the embedded agent when this panel is linked to a master
+ # ServerKit panel (ServerKit-to-ServerKit peering).
+ from app.services.linked_panel_service import LinkedPanelService
+ LinkedPanelService.start_client_if_linked(app)
+
# Request body size limit
app.config['MAX_CONTENT_LENGTH'] = 100 * 1024 * 1024 # 100MB limit
diff --git a/backend/app/api/linked_panel.py b/backend/app/api/linked_panel.py
new file mode 100644
index 00000000..99ad72ba
--- /dev/null
+++ b/backend/app/api/linked_panel.py
@@ -0,0 +1,45 @@
+"""Linked-panel API — manage this panel's link to a master ServerKit panel."""
+from flask import Blueprint, jsonify, request
+from flask_jwt_extended import jwt_required
+
+from app.middleware.rbac import developer_required
+from app.services.linked_panel_service import LinkedPanelService
+
+linked_panel_bp = Blueprint('linked_panel', __name__)
+
+
+@linked_panel_bp.route('', methods=['GET'])
+@jwt_required()
+def get_status():
+ """Current link status (linked/connected/last_error)."""
+ return jsonify(LinkedPanelService.get_status())
+
+
+@linked_panel_bp.route('', methods=['POST'])
+@jwt_required()
+@developer_required
+def link():
+ """Link this panel to a master ServerKit panel.
+
+ Body: {"master_url": "https://panel-a", "registration_token": "sk_reg_…",
+ "name": "optional display name"}
+ The registration token comes from the master's Servers page (Add Server
+ / regenerate-token) — the same token the Go agent consumes.
+ """
+ data = request.get_json(silent=True) or {}
+ result = LinkedPanelService.link(
+ master_url=data.get('master_url'),
+ registration_token=data.get('registration_token'),
+ name=data.get('name'),
+ )
+ if not result.get('success'):
+ return jsonify(result), 400
+ return jsonify(result)
+
+
+@linked_panel_bp.route('', methods=['DELETE'])
+@jwt_required()
+@developer_required
+def unlink():
+ """Stop the embedded agent and forget the master credentials."""
+ return jsonify(LinkedPanelService.unlink())
diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.py
index 975a9c64..b174965a 100644
--- a/backend/app/models/__init__.py
+++ b/backend/app/models/__init__.py
@@ -12,6 +12,7 @@ from app.models.application_preview import ApplicationPreview, ApplicationPrevie
from app.models.proxy_stack import ProxyStack
from app.models.site_base_domain import SiteBaseDomain
from app.models.deployment_job import DeploymentJob, DeploymentJobLog
+from app.models.linked_panel import LinkedPanelConfig
from app.models.system_settings import SystemSettings
from app.models.audit_log import AuditLog
from app.models.metrics_history import MetricsHistory
diff --git a/backend/app/models/linked_panel.py b/backend/app/models/linked_panel.py
new file mode 100644
index 00000000..383d2379
--- /dev/null
+++ b/backend/app/models/linked_panel.py
@@ -0,0 +1,54 @@
+"""Linked-panel (ServerKit-to-ServerKit) model.
+
+A single-row config that turns THIS panel into a worker of another
+("master") ServerKit panel: instead of installing the standalone Go agent,
+the panel runs an embedded agent client (see
+app/services/linked_panel_agent.py) that speaks the exact same agent
+protocol (HMAC auth + HTTP long-poll transport) to the master.
+
+The master needs zero changes — to it, a linked panel is just another
+agent-backed Server row, with the usual scoped/revocable credentials and
+Managed/Observed trust levels.
+"""
+
+from datetime import datetime
+
+from app import db
+from app.utils.crypto import encrypt_secret, decrypt_secret_safe
+
+
+class LinkedPanelConfig(db.Model):
+ """Credentials + addressing for the master panel this panel links to."""
+
+ __tablename__ = 'linked_panel_config'
+
+ id = db.Column(db.Integer, primary_key=True)
+ master_url = db.Column(db.String(255), nullable=False)
+ # Agent identity minted by the master during registration.
+ agent_id = db.Column(db.String(64), nullable=False)
+ api_key_prefix = db.Column(db.String(24), nullable=False)
+ api_secret_encrypted = db.Column(db.Text, nullable=False)
+ # The Server row id/name the master created for us.
+ remote_server_id = db.Column(db.String(36), nullable=False)
+ remote_server_name = db.Column(db.String(120), nullable=True)
+ enabled = db.Column(db.Boolean, default=True, nullable=False)
+ created_at = db.Column(db.DateTime, default=datetime.utcnow)
+ updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
+
+ def set_api_secret(self, plaintext: str):
+ self.api_secret_encrypted = encrypt_secret(plaintext)
+
+ def get_api_secret(self):
+ return decrypt_secret_safe(self.api_secret_encrypted)
+
+ def to_dict(self):
+ return {
+ 'linked': True,
+ 'enabled': self.enabled,
+ 'master_url': self.master_url,
+ 'agent_id': self.agent_id,
+ 'api_key_prefix': self.api_key_prefix,
+ 'remote_server_id': self.remote_server_id,
+ 'remote_server_name': self.remote_server_name,
+ 'created_at': self.created_at.isoformat() if self.created_at else None,
+ }
diff --git a/backend/app/services/linked_panel_agent.py b/backend/app/services/linked_panel_agent.py
new file mode 100644
index 00000000..d1e5481d
--- /dev/null
+++ b/backend/app/services/linked_panel_agent.py
@@ -0,0 +1,374 @@
+"""Embedded agent client — lets THIS panel act as a worker of a master panel.
+
+Instead of installing the standalone Go agent (serverkit-agent), a linked
+panel runs this client: it registers with the master (one REST call), then
+keeps an HTTP long-poll session to the master's agent gateway
+(/api/v1/agent/connect|poll|result) — the same protocol and HMAC auth the
+Go agent uses. Incoming commands are dispatched to this panel's OWN local
+services (DockerService, filesystem), so the master can deploy apps here
+exactly as if the Go agent were installed.
+
+Transport note: the long-poll fallback intentionally has no streaming
+(live logs / terminal); the master degrades those to "view recent only".
+"""
+import base64
+import hashlib
+import hmac
+import logging
+import os
+import platform
+import secrets
+import socket
+import threading
+import time
+
+import requests
+
+from app import db
+from app.models.linked_panel import LinkedPanelConfig
+
+logger = logging.getLogger(__name__)
+
+# Version reported to the master as User-Agent (ServerKit-Agent/<version>).
+AGENT_VERSION = 'panel-embedded-1.0'
+
+# Root prefixes the master is allowed to write files under. Template
+# installs target <apps_root>/<app-name>/..., matching the local layout.
+DEFAULT_ALLOWED_WRITE_ROOTS = ('/var/serverkit/apps', '/etc/serverkit')
+
+POLL_TIMEOUT_S = 35 # slightly above the master's 25s long-poll
+RECONNECT_DELAY_S = 10
+CONNECT_TIMEOUT_S = 15
+
+_client = None
+
+
+class EmbeddedAgentClient:
+ """Long-poll agent-protocol client bound to one LinkedPanelConfig row."""
+
+ def __init__(self, app):
+ self.app = app
+ self.running = False
+ self.session_token = None
+ self.last_error = None
+ self.connected_at = None
+ self.last_heartbeat_at = None
+ self._thread = None
+ self._send_state = True # ship system_info+capabilities on next poll
+
+ # ------------------------------------------------------------------
+ # Lifecycle
+ # ------------------------------------------------------------------
+ def start(self):
+ if self.running:
+ return
+ self.running = True
+ self._thread = threading.Thread(
+ target=self._run, daemon=True, name='linked-panel-agent')
+ self._thread.start()
+ logger.info('Linked-panel embedded agent started')
+
+ def stop(self):
+ self.running = False
+ token, self.session_token = self.session_token, None
+ if token:
+ try:
+ cfg = self._load_config()
+ if cfg:
+ requests.post(
+ f'{cfg.master_url}/api/v1/agent/disconnect',
+ headers={'X-Session-Token': token},
+ timeout=CONNECT_TIMEOUT_S,
+ )
+ except Exception:
+ pass
+
+ # ------------------------------------------------------------------
+ # Main loop: connect → poll → (reconnect on failure)
+ # ------------------------------------------------------------------
+ def _run(self):
+ while self.running:
+ try:
+ cfg = self._load_config()
+ if not cfg or not cfg.enabled:
+ self.last_error = 'Link disabled or removed'
+ return
+ self._connect(cfg)
+ self._poll_loop(cfg)
+ except Exception as exc: # pragma: no cover - defensive
+ self.last_error = str(exc)
+ logger.warning('Linked-panel agent error: %s', exc)
+ self.session_token = None
+ self.connected_at = None
+ if self.running:
+ time.sleep(RECONNECT_DELAY_S)
+
+ def _load_config(self):
+ with self.app.app_context():
+ cfg = LinkedPanelConfig.query.first()
+ if not cfg:
+ return None
+ # Detach the values we need from the session-bound object.
+ return _ConfigSnapshot(cfg)
+
+ # ------------------------------------------------------------------
+ # Protocol: HMAC auth connect (mirrors agent_poll.connect expectations)
+ # ------------------------------------------------------------------
+ def _connect(self, cfg):
+ timestamp = int(time.time() * 1000)
+ nonce = secrets.token_hex(16)
+ message = f'{cfg.agent_id}:{timestamp}:{nonce}'
+ signature = hmac.new(
+ cfg.api_secret.encode(), message.encode(), hashlib.sha256
+ ).hexdigest()
+ resp = requests.post(
+ f'{cfg.master_url}/api/v1/agent/connect',
+ json={
+ 'agent_id': cfg.agent_id,
+ 'api_key_prefix': cfg.api_key_prefix,
+ 'signature': signature,
+ 'timestamp': timestamp,
+ 'nonce': nonce,
+ },
+ headers={'User-Agent': f'ServerKit-Agent/{AGENT_VERSION}'},
+ timeout=CONNECT_TIMEOUT_S,
+ )
+ if resp.status_code != 200:
+ raise RuntimeError(
+ f'connect failed ({resp.status_code}): {resp.text[:200]}')
+ data = resp.json()
+ if not data.get('success'):
+ raise RuntimeError(f"connect rejected: {data.get('error')}")
+ self.session_token = data['session_token']
+ self.connected_at = time.time()
+ self.last_error = None
+ self._send_state = True
+ logger.info('Linked-panel agent connected to %s', cfg.master_url)
+
+ def _poll_loop(self, cfg):
+ while self.running:
+ body = {'metrics': collect_metrics()}
+ if self._send_state:
+ body['system_info'] = collect_system_info()
+ body['capabilities'] = {
+ 'capabilities': {
+ 'docker': True,
+ 'compose': True,
+ 'files': True,
+ 'metrics': True,
+ },
+ 'platform': 'linux' if os.name == 'posix' else os.name,
+ }
+ resp = requests.post(
+ f'{cfg.master_url}/api/v1/agent/poll',
+ json=body,
+ headers={'X-Session-Token': self.session_token},
+ timeout=POLL_TIMEOUT_S,
+ )
+ if resp.status_code == 401:
+ raise RuntimeError('session expired — reconnecting')
+ resp.raise_for_status()
+ self._send_state = False
+ self.last_heartbeat_at = time.time()
+ for command in (resp.json().get('commands') or []):
+ # Long-running commands (compose build) must not block the
+ # heartbeat loop — dispatch each on its own thread.
+ threading.Thread(
+ target=self._dispatch,
+ args=(cfg, command),
+ daemon=True,
+ name=f'linked-panel-cmd-{command.get("id", "?")[:8]}',
+ ).start()
+
+ # ------------------------------------------------------------------
+ # Command dispatch → this panel's own local services
+ # ------------------------------------------------------------------
+ def _dispatch(self, cfg, command):
+ command_id = command.get('id')
+ action = command.get('action')
+ params = command.get('params') or {}
+ started = time.time()
+ try:
+ handler = ACTION_HANDLERS.get(action)
+ if not handler:
+ raise RuntimeError(f'Unsupported action: {action}')
+ data = handler(params)
+ result = {
+ 'command_id': command_id,
+ 'success': True,
+ 'data': data,
+ 'error': None,
+ 'duration': time.time() - started,
+ }
+ except Exception as exc:
+ logger.warning('Linked-panel command %s (%s) failed: %s',
+ command_id, action, exc)
+ result = {
+ 'command_id': command_id,
+ 'success': False,
+ 'data': None,
+ 'error': str(exc),
+ 'duration': time.time() - started,
+ }
+ try:
+ requests.post(
+ f'{cfg.master_url}/api/v1/agent/result',
+ json=result,
+ headers={'X-Session-Token': self.session_token},
+ timeout=CONNECT_TIMEOUT_S,
+ )
+ except Exception as exc: # pragma: no cover - defensive
+ logger.warning('Linked-panel result post failed: %s', exc)
+
+
+class _ConfigSnapshot:
+ """Plain-data copy of a LinkedPanelConfig row (detached from the session)."""
+
+ def __init__(self, cfg: LinkedPanelConfig):
+ self.master_url = cfg.master_url.rstrip('/')
+ self.agent_id = cfg.agent_id
+ self.api_key_prefix = cfg.api_key_prefix
+ self.api_secret = cfg.get_api_secret()
+ self.enabled = cfg.enabled
+
+
+# ---------------------------------------------------------------------------
+# Command handlers (agent action → local execution)
+# ---------------------------------------------------------------------------
+
+def _allowed_write_roots():
+ raw = os.environ.get('LINKED_PANEL_ALLOWED_WRITE_ROOTS', '')
+ roots = tuple(r.strip() for r in raw.split(',') if r.strip())
+ return roots or DEFAULT_ALLOWED_WRITE_ROOTS
+
+
+def handle_file_write(params):
+ path = params.get('path') or ''
+ if not os.path.isabs(path):
+ raise RuntimeError(f'file:write requires an absolute path, got {path!r}')
+ real = os.path.realpath(path)
+ if not any(real == os.path.realpath(root)
+ or real.startswith(os.path.realpath(root) + os.sep)
+ for root in _allowed_write_roots()):
+ raise RuntimeError(f'file:write path outside allowed roots: {path}')
+ content = base64.b64decode(params.get('content') or b'').decode('utf-8')
+ mode = int(params.get('mode', 0o644))
+ if params.get('create_dirs', True):
+ os.makedirs(os.path.dirname(real), exist_ok=True)
+ with open(real, 'w') as handle:
+ handle.write(content)
+ os.chmod(real, mode)
+ return {'path': real, 'size': len(content)}
+
+
+def handle_compose_up(params):
+ from app.services.docker_service import DockerService
+ project_path = params.get('project_path')
+ if not project_path:
+ raise RuntimeError('docker:compose:up requires project_path')
+ result = DockerService.compose_up(
+ project_path,
+ detach=bool(params.get('detach', True)),
+ build=bool(params.get('build', False)),
+ )
+ if not result.get('success'):
+ raise RuntimeError(result.get('error') or 'docker compose up failed')
+ return result
+
+
+def handle_compose_ps(params):
+ from app.services.docker_service import DockerService
+ project_path = params.get('project_path')
+ if not project_path:
+ raise RuntimeError('docker:compose:ps requires project_path')
+ return DockerService.compose_ps(project_path)
+
+
+def handle_compose_logs(params):
+ from app.services.docker_service import DockerService
+ project_path = params.get('project_path')
+ if not project_path:
+ raise RuntimeError('docker:compose:logs requires project_path')
+ result = DockerService.compose_logs(
+ project_path,
+ service=params.get('service') or None,
+ tail=int(params.get('tail', 100)),
+ )
+ if not result.get('success'):
+ raise RuntimeError(result.get('error') or 'docker compose logs failed')
+ return result
+
+
+def handle_system_info(_params):
+ return collect_system_info()
+
+
+def handle_system_metrics(_params):
+ return collect_metrics()
+
+
+ACTION_HANDLERS = {
+ 'file:write': handle_file_write,
+ 'docker:compose:up': handle_compose_up,
+ 'docker:compose:ps': handle_compose_ps,
+ 'docker:compose:logs': handle_compose_logs,
+ 'system:info': handle_system_info,
+ 'system:metrics': handle_system_metrics,
+}
+
+
+# ---------------------------------------------------------------------------
+# Host telemetry
+# ---------------------------------------------------------------------------
+
+def collect_system_info():
+ import psutil
+ return {
+ 'hostname': socket.gethostname(),
+ 'os': 'linux' if os.name == 'posix' else os.name,
+ 'platform': platform.system().lower(),
+ 'platform_version': platform.release(),
+ 'architecture': platform.machine(),
+ 'cpu_cores': psutil.cpu_count(),
+ 'total_memory': psutil.virtual_memory().total,
+ 'total_disk': psutil.disk_usage('/').total,
+ }
+
+
+def collect_metrics():
+ import psutil
+ return {
+ 'cpu_percent': psutil.cpu_percent(interval=None),
+ 'memory_percent': psutil.virtual_memory().percent,
+ 'memory_used': psutil.virtual_memory().used,
+ 'disk_percent': psutil.disk_usage('/').percent,
+ 'disk_used': psutil.disk_usage('/').used,
+ }
+
+
+# ---------------------------------------------------------------------------
+# Singleton management (mirrors the job-consumer pattern)
+# ---------------------------------------------------------------------------
+
+def get_client():
+ return _client
+
+
+def start_embedded_agent(app):
+ """Start the embedded agent if this panel is linked. Skipped under testing."""
+ global _client
+ if _client is not None:
+ return _client
+ if app.config.get('ENV') == 'testing' or app.config.get('TESTING'):
+ return None
+ client = EmbeddedAgentClient(app)
+ client.start()
+ _client = client
+ return client
+
+
+def stop_embedded_agent():
+ global _client
+ if _client is not None:
+ _client.stop()
+ _client = None
diff --git a/backend/app/services/linked_panel_service.py b/backend/app/services/linked_panel_service.py
new file mode 100644
index 00000000..f93734d5
--- /dev/null
+++ b/backend/app/services/linked_panel_service.py
@@ -0,0 +1,130 @@
+"""Linked-panel management: link/unlink/status for ServerKit-to-ServerKit peering.
+
+Linking = register this panel as an agent on the master (single REST call
+with the master's registration token), persist the returned credentials,
+and start the embedded agent client (app/services/linked_panel_agent.py).
+"""
+import logging
+from datetime import datetime
+from typing import Dict
+
+import requests
+
+from app import db
+from app.models.linked_panel import LinkedPanelConfig
+from app.services import linked_panel_agent
+from app.services.linked_panel_agent import AGENT_VERSION, collect_system_info
+
+logger = logging.getLogger(__name__)
+
+REGISTER_TIMEOUT_S = 20
+
+
+class LinkedPanelService:
+ """Manages this panel's link to a master ServerKit panel."""
+
+ @classmethod
+ def get_status(cls) -> Dict:
+ cfg = LinkedPanelConfig.query.first()
+ if not cfg:
+ return {'linked': False}
+ status = cfg.to_dict()
+ client = linked_panel_agent.get_client()
+ status['connected'] = bool(client and client.session_token)
+ status['last_error'] = client.last_error if client else None
+ status['connected_at'] = (
+ datetime.utcfromtimestamp(client.connected_at).isoformat()
+ if client and client.connected_at else None
+ )
+ status['last_heartbeat_at'] = (
+ datetime.utcfromtimestamp(client.last_heartbeat_at).isoformat()
+ if client and client.last_heartbeat_at else None
+ )
+ return status
+
+ @classmethod
+ def link(cls, master_url: str, registration_token: str, name: str = None) -> Dict:
+ """Register with the master and start the embedded agent.
+
+ The token comes from the master's Servers page (Add Server /
+ regenerate-token) — the same ``sk_reg_…`` token the Go agent's
+ install script consumes.
+ """
+ master_url = (master_url or '').strip().rstrip('/')
+ registration_token = (registration_token or '').strip()
+ if not master_url.startswith(('http://', 'https://')):
+ return {'success': False, 'error': 'master_url must start with http:// or https://'}
+ if not registration_token:
+ return {'success': False, 'error': 'registration_token is required'}
+
+ if LinkedPanelConfig.query.first():
+ return {'success': False, 'error': 'This panel is already linked — unlink first'}
+
+ # One-shot registration on the master: exchanges the single-use
+ # token for scoped agent credentials (same endpoint the Go agent
+ # install script calls).
+ try:
+ resp = requests.post(
+ f'{master_url}/api/v1/servers/register',
+ json={
+ 'token': registration_token,
+ 'name': name,
+ 'system_info': collect_system_info(),
+ 'agent_version': AGENT_VERSION,
+ },
+ timeout=REGISTER_TIMEOUT_S,
+ )
+ except requests.RequestException as exc:
+ return {'success': False, 'error': f'Cannot reach master panel: {exc}'}
+
+ if resp.status_code != 200:
+ try:
+ error = resp.json().get('error')
+ except ValueError:
+ error = resp.text[:200]
+ return {'success': False,
+ 'error': f'Master rejected registration ({resp.status_code}): {error}'}
+
+ data = resp.json()
+ required = ('agent_id', 'api_key', 'api_secret', 'server_id')
+ if not all(data.get(k) for k in required):
+ return {'success': False, 'error': f'Unexpected registration response: {data!r}'}
+
+ cfg = LinkedPanelConfig(
+ master_url=master_url,
+ agent_id=data['agent_id'],
+ api_key_prefix=data['api_key'][:12],
+ remote_server_id=data['server_id'],
+ remote_server_name=data.get('name'),
+ enabled=True,
+ )
+ cfg.set_api_secret(data['api_secret'])
+ db.session.add(cfg)
+ db.session.commit()
+
+ # (Re)start the embedded agent against the fresh credentials.
+ linked_panel_agent.stop_embedded_agent()
+ from flask import current_app
+ linked_panel_agent.start_embedded_agent(current_app._get_current_object())
+
+ logger.info('Linked to master panel %s as server %s',
+ master_url, cfg.remote_server_id)
+ return {'success': True, 'status': cls.get_status()}
+
+ @classmethod
+ def unlink(cls) -> Dict:
+ linked_panel_agent.stop_embedded_agent()
+ cfg = LinkedPanelConfig.query.first()
+ if cfg:
+ db.session.delete(cfg)
+ db.session.commit()
+ return {'success': True}
+
+ @classmethod
+ def start_client_if_linked(cls, app):
+ """App-startup hook: resume the embedded agent for a persisted link."""
+ try:
+ if LinkedPanelConfig.query.first():
+ linked_panel_agent.start_embedded_agent(app)
+ except Exception as exc: # never block boot on the link
+ logger.warning('Could not resume linked-panel agent: %s', exc)
diff --git a/backend/migrations/versions/077_linked_panel.py b/backend/migrations/versions/077_linked_panel.py
new file mode 100644
index 00000000..460ca1ae
--- /dev/null
+++ b/backend/migrations/versions/077_linked_panel.py
@@ -0,0 +1,46 @@
+"""Linked-panel config table (ServerKit-to-ServerKit peering).
+
+Single-row table holding the agent credentials this panel uses when it is
+linked to a "master" ServerKit panel as a worker (embedded agent mode).
+
+Idempotent: guards on table presence like other migrations here.
+
+Revision ID: 077_linked_panel
+Revises: 076_deployment_job_logs_sqlite_id
+Create Date: 2026-07-22
+"""
+from alembic import op
+import sqlalchemy as sa
+
+revision = '077_linked_panel'
+down_revision = '076_deployment_job_logs_sqlite_id'
+branch_labels = None
+depends_on = None
+
+
+def upgrade():
+ conn = op.get_bind()
+ inspector = sa.inspect(conn)
+ if 'linked_panel_config' in set(inspector.get_table_names()):
+ return
+ op.create_table(
+ 'linked_panel_config',
+ sa.Column('id', sa.Integer(), nullable=False),
+ sa.Column('master_url', sa.String(length=255), nullable=False),
+ sa.Column('agent_id', sa.String(length=64), nullable=False),
+ sa.Column('api_key_prefix', sa.String(length=24), nullable=False),
+ sa.Column('api_secret_encrypted', sa.Text(), nullable=False),
+ sa.Column('remote_server_id', sa.String(length=36), nullable=False),
+ sa.Column('remote_server_name', sa.String(length=120), nullable=True),
+ sa.Column('enabled', sa.Boolean(), nullable=False, server_default=sa.true()),
+ sa.Column('created_at', sa.DateTime(), nullable=True),
+ sa.Column('updated_at', sa.DateTime(), nullable=True),
+ sa.PrimaryKeyConstraint('id'),
+ )
+
+
+def downgrade():
+ conn = op.get_bind()
+ inspector = sa.inspect(conn)
+ if 'linked_panel_config' in set(inspector.get_table_names()):
+ op.drop_table('linked_panel_config')
diff --git a/backend/tests/test_linked_panel.py b/backend/tests/test_linked_panel.py
new file mode 100644
index 00000000..51e384c0
--- /dev/null
+++ b/backend/tests/test_linked_panel.py
@@ -0,0 +1,231 @@
+"""Linked-panel (ServerKit-to-ServerKit peering) tests.
+
+Covers the link/unlink service flow (registration driver), the HMAC auth
+payload the embedded agent presents to the master, and the command-dispatch
+shim that maps agent actions onto this panel's local services.
+"""
+import base64
+import hashlib
+import hmac
+import os
+import stat
+import time
+
+import pytest
+
+from app import db
+from app.models.linked_panel import LinkedPanelConfig
+from app.services import linked_panel_agent as agent
+from app.services.linked_panel_service import LinkedPanelService
+
+
+REGISTER_PAYLOAD = {
+ 'agent_id': 'agent-123',
+ 'name': 'worker-b',
+ 'api_key': 'sk_abcdef1234567890',
+ 'api_secret': 'super-secret',
+ 'websocket_url': 'wss://master/agent',
+ 'server_id': 'srv-456',
+}
+
+
+class _FakeResponse:
+ def __init__(self, status_code=200, payload=None, text=''):
+ self.status_code = status_code
+ self._payload = payload or {}
+ self.text = text
+
+ def json(self):
+ return self._payload
+
+
[email protected](autouse=True)
+def _no_client_thread(monkeypatch):
+ """Never spawn the real embedded-agent thread from the service layer."""
+ monkeypatch.setattr(agent, 'start_embedded_agent', lambda app: None)
+ monkeypatch.setattr(agent, 'stop_embedded_agent', lambda: None)
+
+
+# ---------------------------------------------------------------------------
+# link() / unlink()
+# ---------------------------------------------------------------------------
+
+def test_link_success_persists_credentials(app, monkeypatch):
+ calls = {}
+
+ def fake_post(url, json=None, timeout=None, headers=None):
+ calls['url'] = url
+ calls['json'] = json
+ return _FakeResponse(200, REGISTER_PAYLOAD)
+
+ monkeypatch.setattr(agent.requests, 'post', fake_post)
+ monkeypatch.setattr('app.services.linked_panel_service.requests.post', fake_post)
+
+ with app.app_context():
+ result = LinkedPanelService.link('https://master.example/', 'sk_reg_token')
+
+ assert result['success'] is True
+ assert calls['url'] == 'https://master.example/api/v1/servers/register'
+ assert calls['json']['token'] == 'sk_reg_token'
+ assert calls['json']['system_info']['hostname']
+
+ cfg = LinkedPanelConfig.query.first()
+ assert cfg is not None
+ assert cfg.master_url == 'https://master.example' # trailing / stripped
+ assert cfg.agent_id == 'agent-123'
+ assert cfg.api_key_prefix == 'sk_abcdef123'[:12]
+ assert cfg.remote_server_id == 'srv-456'
+ # Secret stored encrypted, retrievable in plaintext.
+ assert cfg.api_secret_encrypted != 'super-secret'
+ assert cfg.get_api_secret() == 'super-secret'
+
+ status = LinkedPanelService.get_status()
+ assert status['linked'] is True
+ assert status['connected'] is False # client thread mocked out
+
+
+def test_link_rejects_bad_url(app):
+ with app.app_context():
+ result = LinkedPanelService.link('master.example', 'sk_reg_token')
+ assert result['success'] is False
+ assert 'http' in result['error']
+
+
+def test_link_master_rejection_surfaces_error(app, monkeypatch):
+ monkeypatch.setattr(
+ 'app.services.linked_panel_service.requests.post',
+ lambda *a, **k: _FakeResponse(401, {'error': 'Invalid or expired registration token'}),
+ )
+ with app.app_context():
+ result = LinkedPanelService.link('https://master.example', 'bad-token')
+ assert result['success'] is False
+ assert 'Invalid or expired registration token' in result['error']
+ assert LinkedPanelConfig.query.first() is None
+
+
+def test_link_twice_refused(app, monkeypatch):
+ monkeypatch.setattr(
+ 'app.services.linked_panel_service.requests.post',
+ lambda *a, **k: _FakeResponse(200, REGISTER_PAYLOAD),
+ )
+ with app.app_context():
+ assert LinkedPanelService.link('https://m.example', 'tok')['success']
+ second = LinkedPanelService.link('https://m.example', 'tok')
+ assert second['success'] is False
+ assert 'already linked' in second['error']
+
+
+def test_unlink_clears_config(app, monkeypatch):
+ monkeypatch.setattr(
+ 'app.services.linked_panel_service.requests.post',
+ lambda *a, **k: _FakeResponse(200, REGISTER_PAYLOAD),
+ )
+ with app.app_context():
+ LinkedPanelService.link('https://m.example', 'tok')
+ assert LinkedPanelService.unlink()['success'] is True
+ assert LinkedPanelConfig.query.first() is None
+ assert LinkedPanelService.get_status() == {'linked': False}
+
+
+# ---------------------------------------------------------------------------
+# API endpoints
+# ---------------------------------------------------------------------------
+
+def test_api_status_unlinked(client, auth_headers):
+ resp = client.get('/api/v1/linked-panel', headers=auth_headers)
+ assert resp.status_code == 200
+ assert resp.get_json() == {'linked': False}
+
+
+def test_api_requires_auth(client):
+ assert client.get('/api/v1/linked-panel').status_code in (401, 422)
+
+
+# ---------------------------------------------------------------------------
+# HMAC auth payload (must match agent_registry.verify_agent_auth)
+# ---------------------------------------------------------------------------
+
+def test_hmac_signature_matches_master_verification():
+ agent_id, secret = 'agent-123', 'super-secret'
+ timestamp = int(time.time() * 1000)
+ nonce = 'abc123'
+ # Client side (what linked_panel_agent._connect builds).
+ message = f'{agent_id}:{timestamp}:{nonce}'
+ signature = hmac.new(secret.encode(), message.encode(), hashlib.sha256).hexdigest()
+ # Master side (agent_registry.verify_agent_auth) reconstructs identically.
+ expected = hmac.new(secret.encode(), message.encode(), hashlib.sha256).hexdigest()
+ assert hmac.compare_digest(signature, expected)
+
+
+# ---------------------------------------------------------------------------
+# Command dispatch shim
+# ---------------------------------------------------------------------------
+
+def test_file_write_happy_path(tmp_path, monkeypatch):
+ monkeypatch.setenv('LINKED_PANEL_ALLOWED_WRITE_ROOTS', str(tmp_path))
+ target = tmp_path / 'app' / 'docker-compose.yml'
+ data = agent.handle_file_write({
+ 'path': str(target),
+ 'content': base64.b64encode(b'services: {}').decode(),
+ 'mode': 0o640,
+ 'create_dirs': True,
+ })
+ assert data['path'] == os.path.realpath(str(target))
+ assert target.read_text() == 'services: {}'
+ if os.name == 'posix': # Windows ignores POSIX permission bits
+ assert stat.S_IMODE(target.stat().st_mode) == 0o640
+
+
+def test_file_write_rejects_relative_path():
+ with pytest.raises(RuntimeError, match='absolute'):
+ agent.handle_file_write({'path': 'Dockerfile', 'content': ''})
+
+
+def test_file_write_rejects_outside_allowed_roots(tmp_path, monkeypatch):
+ monkeypatch.setenv('LINKED_PANEL_ALLOWED_WRITE_ROOTS', str(tmp_path / 'allowed'))
+ with pytest.raises(RuntimeError, match='outside allowed roots'):
+ agent.handle_file_write({
+ 'path': str(tmp_path / 'evil' / 'x.yml'),
+ 'content': base64.b64encode(b'x').decode(),
+ })
+
+
+def test_compose_up_maps_params_and_raises_on_failure(monkeypatch):
+ seen = {}
+
+ class FakeDocker:
+ @staticmethod
+ def compose_up(project_path, detach=True, build=False):
+ seen.update(path=project_path, detach=detach, build=build)
+ return {'success': True, 'output': 'ok'}
+
+ monkeypatch.setattr(
+ 'app.services.docker_service.DockerService', FakeDocker)
+ data = agent.handle_compose_up(
+ {'project_path': '/var/serverkit/apps/x', 'detach': True, 'build': True})
+ assert data['success'] is True
+ assert seen == {'path': '/var/serverkit/apps/x', 'detach': True, 'build': True}
+
+ class FailingDocker(FakeDocker):
+ @staticmethod
+ def compose_up(project_path, detach=True, build=False):
+ return {'success': False, 'error': 'build exploded'}
+
+ monkeypatch.setattr(
+ 'app.services.docker_service.DockerService', FailingDocker)
+ with pytest.raises(RuntimeError, match='build exploded'):
+ agent.handle_compose_up({'project_path': '/x'})
+
+
+def test_unknown_action_reported_via_dispatch(monkeypatch):
+ posted = {}
+ monkeypatch.setattr(agent.requests, 'post',
+ lambda url, json=None, headers=None, timeout=None:
+ posted.update(json=json) or _FakeResponse(200, {'ok': True}))
+ cfg = type('C', (), {'master_url': 'https://m.example'})()
+ client = agent.EmbeddedAgentClient(app=None)
+ client.session_token = 'tok'
+ client._dispatch(cfg, {'id': 'cmd1', 'action': 'nuke:everything', 'params': {}})
+ assert posted['json']['command_id'] == 'cmd1'
+ assert posted['json']['success'] is False
+ assert 'Unsupported action' in posted['json']['error']
diff --git a/frontend/src/components/servers/LinkedPanelCard.jsx b/frontend/src/components/servers/LinkedPanelCard.jsx
new file mode 100644
index 00000000..e6cee4e0
--- /dev/null
+++ b/frontend/src/components/servers/LinkedPanelCard.jsx
@@ -0,0 +1,180 @@
+import { useEffect, useState } from 'react';
+import { Link2, Unlink } from 'lucide-react';
+import api from '../../services/api';
+import { useToast } from '../../contexts/ToastContext';
+import { ConfirmDialog } from '../ConfirmDialog';
+import StatusBadge from '../StatusBadge';
+import { InfoList, InfoItem } from '../InfoList';
+import { Button } from '@/components/ui/button';
+import { Input } from '@/components/ui/input';
+
+const POLL_INTERVAL = 5000;
+
+function formatTimestamp(iso) {
+ if (!iso) return '—';
+ const date = new Date(iso);
+ return Number.isNaN(date.getTime()) ? '—' : date.toLocaleString();
+}
+
+// "Linked Panel" — the inverse of Add Server: link THIS panel to a master
+// ServerKit so the master can deploy apps here as if the Go agent were
+// installed. Polls the link status while visible so the connection badge
+// flips to Connected live.
+const LinkedPanelCard = () => {
+ const toast = useToast();
+ const [status, setStatus] = useState(null); // null = still loading
+ const [masterUrl, setMasterUrl] = useState('');
+ const [token, setToken] = useState('');
+ const [name, setName] = useState('');
+ const [submitting, setSubmitting] = useState(false);
+ const [linkError, setLinkError] = useState('');
+ const [unlinkOpen, setUnlinkOpen] = useState(false);
+
+ async function loadStatus({ silent = false } = {}) {
+ try {
+ const data = await api.getLinkedPanel();
+ setStatus(data);
+ } catch (err) {
+ if (!silent) toast.error(err?.data?.error || err.message || 'Failed to load linked panel status');
+ }
+ }
+
+ useEffect(() => {
+ loadStatus();
+ const interval = setInterval(() => loadStatus({ silent: true }), POLL_INTERVAL);
+ return () => clearInterval(interval);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
+
+ async function handleLink(e) {
+ e.preventDefault();
+ setLinkError('');
+ setSubmitting(true);
+ try {
+ const result = await api.linkPanel({
+ master_url: masterUrl.trim(),
+ registration_token: token.trim(),
+ name: name.trim() || undefined,
+ });
+ toast.success('Panel linked to master');
+ setStatus(result.status || { linked: true, master_url: masterUrl.trim() });
+ setToken('');
+ } catch (err) {
+ setLinkError(err?.data?.error || err.message || 'Failed to link panel');
+ } finally {
+ setSubmitting(false);
+ }
+ }
+
+ async function handleUnlink() {
+ try {
+ await api.unlinkPanel();
+ toast.success('Panel unlinked');
+ setUnlinkOpen(false);
+ setStatus({ linked: false });
+ } catch (err) {
+ toast.error(err?.data?.error || err.message || 'Failed to unlink panel');
+ }
+ }
+
+ const linked = Boolean(status?.linked);
+
+ return (
+ <section className="linked-panel-card">
+ <div className="linked-panel-card__header">
+ <Link2 size={16} />
+ <div>
+ <h3>Linked Panel</h3>
+ <p className="text-muted">
+ Link this panel to a master ServerKit so it can manage this server — no separate agent install needed.
+ </p>
+ </div>
+ {linked && (
+ <StatusBadge status={status.connected ? 'connected' : 'disconnected'} />
+ )}
+ </div>
+
+ {status === null ? (
+ <p className="text-muted">Loading link status…</p>
+ ) : !linked ? (
+ <form className="linked-panel-card__form" onSubmit={handleLink}>
+ <p className="text-muted">
+ Generate a registration token on the master: Servers → Add Server / regenerate token.
+ </p>
+ {linkError && <div className="alert alert-danger">{linkError}</div>}
+ <div className="form-group">
+ <label>Master URL *</label>
+ <Input
+ type="url"
+ value={masterUrl}
+ onChange={(e) => setMasterUrl(e.target.value)}
+ placeholder="https://panel.example.com"
+ required
+ />
+ </div>
+ <div className="form-group">
+ <label>Registration token *</label>
+ <Input
+ type="password"
+ value={token}
+ onChange={(e) => setToken(e.target.value)}
+ placeholder="Token generated on the master"
+ required
+ />
+ </div>
+ <div className="form-group">
+ <label>Display name</label>
+ <Input
+ type="text"
+ value={name}
+ onChange={(e) => setName(e.target.value)}
+ placeholder="Optional — how this server appears on the master"
+ />
+ </div>
+ <div className="linked-panel-card__actions">
+ <Button type="submit" disabled={submitting}>
+ <Link2 size={14} /> {submitting ? 'Linking…' : 'Link panel'}
+ </Button>
+ </div>
+ </form>
+ ) : (
+ <div className="linked-panel-card__status">
+ <InfoList>
+ <InfoItem label="Master" value={status.master_url} mono />
+ <InfoItem
+ label="Remote server"
+ value={status.remote_server_name
+ ? `${status.remote_server_name}${status.remote_server_id ? ` (#${status.remote_server_id})` : ''}`
+ : (status.remote_server_id ? `#${status.remote_server_id}` : '—')}
+ />
+ <InfoItem label="Agent ID" value={status.agent_id} mono />
+ <InfoItem label="Linked since" value={formatTimestamp(status.created_at)} />
+ <InfoItem label="Last heartbeat" value={formatTimestamp(status.last_heartbeat_at)} />
+ </InfoList>
+ {status.last_error && (
+ <div className="alert alert-danger">
+ <strong>Connection error:</strong> {status.last_error}
+ </div>
+ )}
+ <div className="linked-panel-card__actions">
+ <Button type="button" variant="destructive" onClick={() => setUnlinkOpen(true)}>
+ <Unlink size={14} /> Unlink
+ </Button>
+ </div>
+ </div>
+ )}
+
+ <ConfirmDialog
+ isOpen={unlinkOpen}
+ title="Unlink from master panel?"
+ message={`This server will stop being manageable by ${status?.master_url || 'the master panel'}. The link credentials are removed from this panel.`}
+ confirmText="Unlink"
+ variant="danger"
+ onConfirm={handleUnlink}
+ onCancel={() => setUnlinkOpen(false)}
+ />
+ </section>
+ );
+};
+
+export default LinkedPanelCard;
diff --git a/frontend/src/pages/Servers.jsx b/frontend/src/pages/Servers.jsx
index a1fdc8d3..65392625 100644
--- a/frontend/src/pages/Servers.jsx
+++ b/frontend/src/pages/Servers.jsx
@@ -19,6 +19,7 @@ import Modal from '@/components/Modal';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { DataTable } from '@/components/ds';
+import LinkedPanelCard from '../components/servers/LinkedPanelCard';
const Servers = () => {
const [servers, setServers] = useState([]);
@@ -439,6 +440,8 @@ const Servers = () => {
/>
</div>
)}
+
+ <LinkedPanelCard />
</main>
</div>
diff --git a/frontend/src/services/api/servers.js b/frontend/src/services/api/servers.js
index da1368ca..dfe4f8e0 100644
--- a/frontend/src/services/api/servers.js
+++ b/frontend/src/services/api/servers.js
@@ -1035,3 +1035,19 @@ export async function deleteCloudSnapshot(id) {
export async function getCloudCosts() {
return this.request('/cloud/costs');
}
+
+// Linked Panel — this panel linked to a MASTER ServerKit as a worker
+// (embedded agent mode: the master manages this server without a separate
+// Go agent install).
+export async function getLinkedPanel() {
+ return this.request('/linked-panel');
+}
+
+export async function linkPanel(data) {
+ // data: { master_url, registration_token, name? }
+ return this.request('/linked-panel', { method: 'POST', body: data });
+}
+
+export async function unlinkPanel() {
+ return this.request('/linked-panel', { method: 'DELETE' });
+}
diff --git a/frontend/src/styles/pages/_servers.scss b/frontend/src/styles/pages/_servers.scss
index 97d8b584..d92e5ca4 100644
--- a/frontend/src/styles/pages/_servers.scss
+++ b/frontend/src/styles/pages/_servers.scss
@@ -4291,3 +4291,70 @@
}
}
}
+
+// ============================================
+// LINKED PANEL CARD — link this panel to a master ServerKit (embedded agent)
+// ============================================
+.linked-panel-card {
+ flex-shrink: 0;
+ display: flex;
+ flex-direction: column;
+ gap: $space-3;
+ padding: $space-4;
+ background: $bg-card;
+ border: 1px solid $border-default;
+ border-radius: $radius-lg;
+
+ &__header {
+ display: flex;
+ align-items: flex-start;
+ gap: $space-3;
+
+ > svg {
+ color: $accent-primary;
+ flex-shrink: 0;
+ margin-top: 2px;
+ }
+
+ > div {
+ flex: 1;
+ min-width: 0;
+ }
+
+ h3 {
+ margin: 0;
+ font-size: $font-size-base;
+ font-weight: $font-weight-semibold;
+ color: $text-primary;
+ }
+
+ p {
+ margin: $space-1 0 0;
+ font-size: $font-size-sm;
+ }
+ }
+
+ &__form {
+ display: flex;
+ flex-direction: column;
+ gap: $space-3;
+ max-width: 480px;
+
+ > p {
+ margin: 0;
+ font-size: $font-size-sm;
+ }
+ }
+
+ &__status {
+ display: flex;
+ flex-direction: column;
+ gap: $space-3;
+ }
+
+ &__actions {
+ display: flex;
+ justify-content: flex-end;
+ gap: $space-2;
+ }
+}