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.

Remote Docker remove, normalize API & permissions

Juan Denis313f1a8f6b42
diff --git a/README.md b/README.md
index b58842ae..b2c2ed4c 100644
--- a/README.md
+++ b/README.md
@@ -100,7 +100,7 @@ English | [Español](docs/README.es.md) | [中文版](docs/README.zh-CN.md) | [P
**Agent-Based Architecture** — Go agent with HMAC-SHA256 authentication and real-time WebSocket gateway
-**Fleet Management** — Agent lifecycle control with version rollouts, approval queue, network discovery, and command queue
+**Fleet Management** — Agent inventory, connection status, approval queue, rollouts, discovery, and command queue
**Fleet Monitor** — Cross-server heatmaps, metric comparison charts, alert thresholds, anomaly detection, and capacity forecasting
@@ -108,7 +108,7 @@ English | [Español](docs/README.es.md) | [中文版](docs/README.zh-CN.md) | [P
**Server Templates** — Configuration templates with compliance tracking, drift detection, and auto-remediation
-**Remote Docker** — Manage containers, images, volumes, networks, and Compose projects across all servers
+**Remote Docker** — Agent-backed Docker operations for connected servers; remote app/site deployment is still evolving
**API Key Rotation** — Secure credential rotation with acknowledgment handshake
@@ -280,7 +280,7 @@ See the [Installation Guide](docs/INSTALLATION.md) for step-by-step instructions
- [x] Monitoring & alerts — Metrics, webhooks, uptime tracking
- [x] Security — 2FA, ClamAV, file integrity, Fail2ban, Lynis
- [x] Firewall — UFW/firewalld integration
-- [x] Multi-server management — Go agent, centralized dashboard
+- [x] Multi-server monitoring — Go agent, centralized dashboard
- [x] Git deployment — Webhooks, auto-deploy, rollback, zero-downtime
- [x] Backup & restore — S3, Backblaze B2, scheduled backups
- [x] Email server — Postfix, Dovecot, DKIM/SPF/DMARC, Roundcube
@@ -290,6 +290,7 @@ See the [Installation Guide](docs/INSTALLATION.md) for step-by-step instructions
- [x] Database migrations — Flask-Migrate/Alembic, versioned schema
- [x] Agent fleet management — Version rollouts, approval queue, discovery, command queue
- [x] Cross-server monitoring — Fleet heatmaps, comparison charts, anomaly detection, capacity forecasting
+- [ ] Remote app/site deployment through connected agents
- [x] Agent plugin system — Extensible agent with capabilities, permissions, per-server install
- [x] Server templates & config sync — Drift detection, compliance dashboards, auto-remediation
- [x] Multi-tenancy — Workspaces with quotas, member management, isolation
diff --git a/agent/internal/agent/agent.go b/agent/internal/agent/agent.go
index 3f3fabef..9236bb97 100644
--- a/agent/internal/agent/agent.go
+++ b/agent/internal/agent/agent.go
@@ -138,6 +138,7 @@ func (a *Agent) registerHandlers() {
// Docker network commands
a.handlers[protocol.ActionDockerNetworkList] = a.handleDockerNetworkList
+ a.handlers[protocol.ActionDockerNetworkRemove] = a.handleDockerNetworkRemove
// Docker compose commands
a.handlers[protocol.ActionDockerComposeList] = a.handleDockerComposeList
@@ -775,6 +776,16 @@ func (a *Agent) handleDockerNetworkList(ctx context.Context, params json.RawMess
return a.docker.ListNetworks(ctx)
}
+func (a *Agent) handleDockerNetworkRemove(ctx context.Context, params json.RawMessage) (interface{}, error) {
+ var p struct {
+ ID string `json:"id"`
+ }
+ if err := json.Unmarshal(params, &p); err != nil {
+ return nil, fmt.Errorf("invalid params: %w", err)
+ }
+ return map[string]bool{"success": true}, a.docker.RemoveNetwork(ctx, p.ID)
+}
+
// System command handlers
func (a *Agent) handleSystemMetrics(ctx context.Context, params json.RawMessage) (interface{}, error) {
diff --git a/agent/internal/docker/client.go b/agent/internal/docker/client.go
index beaf28bc..a415798b 100644
--- a/agent/internal/docker/client.go
+++ b/agent/internal/docker/client.go
@@ -413,6 +413,11 @@ func (c *Client) ListNetworks(ctx context.Context) ([]NetworkInfo, error) {
return result, nil
}
+// RemoveNetwork removes a network
+func (c *Client) RemoveNetwork(ctx context.Context, id string) error {
+ return c.cli.NetworkRemove(ctx, id)
+}
+
// GetContainerCount returns the number of containers
func (c *Client) GetContainerCount(ctx context.Context) (total int, running int, err error) {
allContainers, err := c.cli.ContainerList(ctx, types.ContainerListOptions{All: true})
diff --git a/backend/app/api/servers.py b/backend/app/api/servers.py
index b015e40e..533dc000 100644
--- a/backend/app/api/servers.py
+++ b/backend/app/api/servers.py
@@ -22,6 +22,32 @@ from app.middleware.rbac import admin_required, developer_required
servers_bp = Blueprint('servers', __name__)
+def _get_external_base_url():
+ """Return the public origin agents should use when this app sits behind a proxy."""
+ public_url = current_app.config.get('PUBLIC_URL') or os.environ.get('SERVERKIT_PUBLIC_URL')
+ if public_url:
+ return public_url.rstrip('/')
+
+ forwarded_proto = request.headers.get('X-Forwarded-Proto', request.scheme)
+ forwarded_host = request.headers.get('X-Forwarded-Host', request.host)
+
+ scheme = forwarded_proto.split(',')[0].strip() or request.scheme
+ host = forwarded_host.split(',')[0].strip() or request.host
+
+ return f"{scheme}://{host}".rstrip('/')
+
+
+def _get_external_websocket_url():
+ base_url = _get_external_base_url()
+
+ if base_url.startswith('https://'):
+ return f"wss://{base_url[len('https://'):]}/agent"
+ if base_url.startswith('http://'):
+ return f"ws://{base_url[len('http://'):]}/agent"
+
+ return f"{base_url}/agent"
+
+
# ==================== Permission Profiles ====================
PERMISSION_PROFILES = {
@@ -385,10 +411,6 @@ def register_agent():
db.session.commit()
- # Construct WebSocket URL
- ws_scheme = 'wss' if request.is_secure else 'ws'
- ws_url = f"{ws_scheme}://{request.host}/agent"
-
# Security note: api_secret is returned once during registration so the agent
# can store it. The server-side copy is stored encrypted. The registration token
# is already cleared above (single-use), preventing re-registration.
@@ -397,7 +419,7 @@ def register_agent():
'name': server.name,
'api_key': api_key,
'api_secret': api_secret,
- 'websocket_url': ws_url,
+ 'websocket_url': _get_external_websocket_url(),
'server_id': server.id
})
@@ -1056,6 +1078,22 @@ def list_remote_volumes(server_id):
return jsonify(result.get('data', []))
+@servers_bp.route('/<server_id>/docker/volumes/<volume_name>', methods=['DELETE'])
+@jwt_required()
+@developer_required
+def remove_remote_volume(server_id, volume_name):
+ """Remove a volume on a remote server"""
+ user_id = get_jwt_identity()
+ force = request.args.get('force', 'false').lower() == 'true'
+
+ result = RemoteDockerService.remove_volume(server_id, volume_name, force=force, user_id=user_id)
+
+ if not result.get('success'):
+ return jsonify(result), 500
+
+ return jsonify({'message': 'Volume removed'})
+
+
@servers_bp.route('/<server_id>/docker/networks', methods=['GET'])
@jwt_required()
def list_remote_networks(server_id):
@@ -1070,6 +1108,21 @@ def list_remote_networks(server_id):
return jsonify(result.get('data', []))
+@servers_bp.route('/<server_id>/docker/networks/<network_id>', methods=['DELETE'])
+@jwt_required()
+@developer_required
+def remove_remote_network(server_id, network_id):
+ """Remove a network on a remote server"""
+ user_id = get_jwt_identity()
+
+ result = RemoteDockerService.remove_network(server_id, network_id, user_id=user_id)
+
+ if not result.get('success'):
+ return jsonify(result), 500
+
+ return jsonify({'message': 'Network removed'})
+
+
@servers_bp.route('/<server_id>/system/metrics', methods=['GET'])
@jwt_required()
def get_remote_system_metrics(server_id):
@@ -1447,7 +1500,7 @@ def get_install_script_linux():
the ServerKit agent on Linux systems.
Usage:
- curl -fsSL https://your-server/api/servers/install.sh | sudo bash -s -- \\
+ curl -fsSL https://your-server/api/v1/servers/install.sh | sudo bash -s -- \\
--token "YOUR_TOKEN" --server "https://your-server"
"""
script_path = os.path.join(_get_scripts_dir(), 'install.sh')
@@ -1459,7 +1512,7 @@ def get_install_script_linux():
content = f.read()
# Replace placeholders with actual values
- server_url = request.url_root.rstrip('/')
+ server_url = _get_external_base_url()
content = content.replace('https://your-serverkit.com', server_url)
content = content.replace('jhd3197/ServerKit', GITHUB_REPO)
@@ -1482,7 +1535,7 @@ def get_install_script_windows():
the ServerKit agent on Windows systems.
Usage:
- irm https://your-server/api/servers/install.ps1 | iex; \\
+ irm https://your-server/api/v1/servers/install.ps1 | iex; \\
Install-ServerKitAgent -Token "YOUR_TOKEN" -Server "https://your-server"
"""
script_path = os.path.join(_get_scripts_dir(), 'install.ps1')
@@ -1494,7 +1547,7 @@ def get_install_script_windows():
content = f.read()
# Replace placeholders with actual values
- server_url = request.url_root.rstrip('/')
+ server_url = _get_external_base_url()
content = content.replace('https://your-serverkit.com', server_url)
content = content.replace('jhd3197/ServerKit', GITHUB_REPO)
@@ -1514,8 +1567,8 @@ def get_install_instructions(server_id):
"""
Get installation instructions for a specific server.
- Returns the installation commands with the server's registration token
- already embedded.
+ Returns installation commands with the correct API endpoint. Registration
+ tokens are only shown when they are generated, so the UI supplies the token.
"""
server = Server.query.get(server_id)
if not server:
@@ -1535,8 +1588,8 @@ def get_install_instructions(server_id):
}), 400
# Get base URL
- base_url = request.url_root.rstrip('/')
- api_url = f"{base_url}/api/servers"
+ base_url = _get_external_base_url()
+ api_url = f"{base_url}/api/v1/servers"
return jsonify({
'linux': {
diff --git a/backend/app/models/server.py b/backend/app/models/server.py
index 03d827e8..81c3830d 100644
--- a/backend/app/models/server.py
+++ b/backend/app/models/server.py
@@ -54,6 +54,15 @@ class Server(db.Model):
"""Represents a remote server managed by ServerKit"""
__tablename__ = 'servers'
+ DOCKER_READ_ACTIONS = {
+ 'container': {'list', 'inspect', 'logs', 'stats'},
+ 'image': {'list'},
+ 'volume': {'list'},
+ 'network': {'list'},
+ 'compose': {'list', 'ps', 'logs'},
+ }
+ SYSTEM_READ_ACTIONS = {'metrics', 'info', 'processes'}
+
id = db.Column(db.String(36), primary_key=True, default=lambda: str(uuid.uuid4()))
# Basic Info
@@ -251,25 +260,61 @@ class Server(db.Model):
return False
if '*' in self.permissions:
return True
- # Check exact match or wildcard
- scope_parts = scope.split(':')
+
+ candidate_scopes = self._expand_permission_scope(scope)
for perm in self.permissions:
- if perm == scope:
- return True
- # Check wildcard patterns like 'docker:*'
- perm_parts = perm.split(':')
- if len(perm_parts) <= len(scope_parts):
- match = True
- for i, part in enumerate(perm_parts):
- if part == '*':
- break
- if i >= len(scope_parts) or part != scope_parts[i]:
- match = False
- break
- if match:
+ for candidate in candidate_scopes:
+ if self._permission_matches(perm, candidate):
return True
return False
+ @classmethod
+ def _expand_permission_scope(cls, scope):
+ """Add profile and legacy aliases for an agent command scope."""
+ candidate_scopes = {scope}
+ scope_parts = scope.split(':')
+
+ if len(scope_parts) >= 3 and scope_parts[0] == 'docker':
+ resource = scope_parts[1]
+ action = scope_parts[2]
+ read_actions = cls.DOCKER_READ_ACTIONS.get(resource, set())
+
+ if action in read_actions:
+ candidate_scopes.add(f'docker:{resource}:read')
+ candidate_scopes.add('docker:read')
+ else:
+ candidate_scopes.add(f'docker:{resource}:write')
+ candidate_scopes.add('docker:write')
+
+ if len(scope_parts) >= 2 and scope_parts[0] == 'system':
+ action = scope_parts[1]
+ if action in cls.SYSTEM_READ_ACTIONS:
+ candidate_scopes.add(f'system:{action}:read')
+ candidate_scopes.add('system:metrics:read')
+ candidate_scopes.add('system:read')
+
+ return candidate_scopes
+
+ @staticmethod
+ def _permission_matches(permission, scope):
+ """Check exact and wildcard patterns like docker:* or docker:container:*."""
+ if permission == scope:
+ return True
+
+ scope_parts = scope.split(':')
+ perm_parts = permission.split(':')
+
+ if len(perm_parts) > len(scope_parts):
+ return False
+
+ for i, part in enumerate(perm_parts):
+ if part == '*':
+ return True
+ if i >= len(scope_parts) or part != scope_parts[i]:
+ return False
+
+ return True
+
def to_dict(self, include_metrics=False):
result = {
'id': self.id,
diff --git a/backend/app/services/remote_docker_service.py b/backend/app/services/remote_docker_service.py
index 3affcce8..93c24974 100644
--- a/backend/app/services/remote_docker_service.py
+++ b/backend/app/services/remote_docker_service.py
@@ -338,6 +338,24 @@ class RemoteDockerService:
user_id=user_id
)
+ @staticmethod
+ def remove_network(server_id: str, network_id: str, user_id: int = None) -> Dict[str, Any]:
+ """Remove a network on a remote server"""
+ if not server_id or server_id == 'local':
+ from app.services.docker_service import DockerService
+ try:
+ DockerService.remove_network(network_id)
+ return {'success': True}
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
+ return agent_registry.send_command(
+ server_id=server_id,
+ action='docker:network:remove',
+ params={'id': network_id},
+ user_id=user_id
+ )
+
# ==================== System ====================
@staticmethod
diff --git a/backend/tests/test_server_permissions.py b/backend/tests/test_server_permissions.py
new file mode 100644
index 00000000..54444730
--- /dev/null
+++ b/backend/tests/test_server_permissions.py
@@ -0,0 +1,48 @@
+from app.models.server import Server
+
+
+def test_read_profiles_cover_agent_read_actions():
+ server = Server(
+ name='test-server',
+ permissions=[
+ 'docker:container:read',
+ 'docker:image:read',
+ 'docker:volume:read',
+ 'docker:network:read',
+ 'docker:compose:read',
+ 'system:metrics:read',
+ ],
+ )
+
+ assert server.has_permission('docker:container:list')
+ assert server.has_permission('docker:container:inspect')
+ assert server.has_permission('docker:container:logs')
+ assert server.has_permission('docker:image:list')
+ assert server.has_permission('docker:volume:list')
+ assert server.has_permission('docker:network:list')
+ assert server.has_permission('docker:compose:ps')
+ assert server.has_permission('system:metrics')
+ assert server.has_permission('system:info')
+ assert not server.has_permission('docker:container:start')
+ assert not server.has_permission('docker:image:pull')
+
+
+def test_legacy_ui_permissions_still_work_for_existing_servers():
+ server = Server(
+ name='test-server',
+ permissions=['docker:read', 'docker:write', 'system:read'],
+ )
+
+ assert server.has_permission('docker:container:list')
+ assert server.has_permission('docker:container:start')
+ assert server.has_permission('docker:image:pull')
+ assert server.has_permission('system:metrics')
+ assert server.has_permission('system:info')
+
+
+def test_wildcard_permissions_still_match_agent_actions():
+ server = Server(name='test-server', permissions=['docker:container:*'])
+
+ assert server.has_permission('docker:container:list')
+ assert server.has_permission('docker:container:restart')
+ assert not server.has_permission('docker:image:list')
diff --git a/frontend/src/pages/Docker.jsx b/frontend/src/pages/Docker.jsx
index cd7c601a..7c49217b 100644
--- a/frontend/src/pages/Docker.jsx
+++ b/frontend/src/pages/Docker.jsx
@@ -11,6 +11,20 @@ const useServer = () => useContext(ServerContext);
const VALID_TABS = ['containers', 'compose', 'images', 'volumes', 'networks'];
+const unwrapRemoteData = (response) => {
+ if (response?.success && response.data !== undefined) {
+ return response.data;
+ }
+ return response;
+};
+
+const normalizeListResponse = (response, key) => {
+ const data = unwrapRemoteData(response);
+ if (Array.isArray(data)) return data;
+ if (Array.isArray(data?.[key])) return data[key];
+ return [];
+};
+
const Docker = () => {
const [activeTab, setActiveTab] = useTabParam('/docker', VALID_TABS);
const [dockerStatus, setDockerStatus] = useState(null);
@@ -57,7 +71,7 @@ const Docker = () => {
} else {
// For remote servers, check if the agent is online
const serverData = await api.getServer(selectedServer.id);
- if (serverData.server?.status === 'online') {
+ if (serverData.status === 'online' || serverData.server?.status === 'online') {
setDockerStatus({ installed: true, running: true });
loadStats();
} else {
@@ -90,17 +104,20 @@ const Docker = () => {
api.getRemoteNetworks(selectedServer.id)
]);
- // Transform remote response format
- if (containersData.success) containersData = { containers: containersData.data };
- if (imagesData.success) imagesData = { images: imagesData.data };
- if (volumesData.success) volumesData = { volumes: volumesData.data };
- if (networksData.success) networksData = { networks: networksData.data };
}
- const containers = containersData.containers || [];
- const images = imagesData.images || [];
- const volumes = volumesData.volumes || [];
- const networks = networksData.networks || [];
+ const containers = selectedServer.id === 'local'
+ ? containersData.containers || []
+ : normalizeListResponse(containersData, 'containers');
+ const images = selectedServer.id === 'local'
+ ? imagesData.images || []
+ : normalizeListResponse(imagesData, 'images');
+ const volumes = selectedServer.id === 'local'
+ ? volumesData.volumes || []
+ : normalizeListResponse(volumesData, 'volumes');
+ const networks = selectedServer.id === 'local'
+ ? networksData.networks || []
+ : normalizeListResponse(networksData, 'networks');
const running = containers.filter(c => c.state === 'running').length;
@@ -490,7 +507,7 @@ const ContainersTab = ({ onStatsChange }) => {
let data;
if (isRemote) {
const result = await api.getRemoteContainers(serverId, showAll);
- data = result.success ? { containers: result.data || [] } : { containers: [] };
+ data = { containers: normalizeListResponse(result, 'containers') };
} else {
data = await api.getContainers(showAll);
}
@@ -504,7 +521,7 @@ const ContainersTab = ({ onStatsChange }) => {
let statsData;
if (isRemote) {
const result = await api.getRemoteContainerStats(serverId, c.id);
- statsData = result.success ? { stats: result.data } : { stats: null };
+ statsData = { stats: unwrapRemoteData(result) };
} else {
statsData = await api.getContainerStats(c.id);
}
@@ -762,7 +779,7 @@ const ImagesTab = ({ onStatsChange }) => {
let data;
if (isRemote) {
const result = await api.getRemoteImages(serverId);
- data = result.success ? { images: result.data || [] } : { images: [] };
+ data = { images: normalizeListResponse(result, 'images') };
} else {
data = await api.getImages();
}
@@ -891,7 +908,7 @@ const NetworksTab = ({ onStatsChange }) => {
let data;
if (isRemote) {
const result = await api.getRemoteNetworks(serverId);
- data = result.success ? { networks: result.data || [] } : { networks: [] };
+ data = { networks: normalizeListResponse(result, 'networks') };
} else {
data = await api.getNetworks();
}
@@ -908,7 +925,11 @@ const NetworksTab = ({ onStatsChange }) => {
if (!confirmed) return;
try {
- await api.removeNetwork(networkId);
+ if (isRemote) {
+ await api.removeRemoteNetwork(serverId, networkId);
+ } else {
+ await api.removeNetwork(networkId);
+ }
toast.success('Network removed successfully');
loadNetworks();
onStatsChange?.();
@@ -997,7 +1018,7 @@ const VolumesTab = ({ onStatsChange }) => {
let data;
if (isRemote) {
const result = await api.getRemoteVolumes(serverId);
- data = result.success ? { volumes: result.data || [] } : { volumes: [] };
+ data = { volumes: normalizeListResponse(result, 'volumes') };
} else {
data = await api.getVolumes();
}
@@ -1014,7 +1035,11 @@ const VolumesTab = ({ onStatsChange }) => {
if (!confirmed) return;
try {
- await api.removeVolume(volumeName, true);
+ if (isRemote) {
+ await api.removeRemoteVolume(serverId, volumeName, true);
+ } else {
+ await api.removeVolume(volumeName, true);
+ }
toast.success('Volume removed successfully');
loadVolumes();
onStatsChange?.();
@@ -1105,7 +1130,7 @@ const ComposeTab = ({ onStatsChange }) => {
} else {
data = await api.request('/docker/compose/list');
}
- setProjects(Array.isArray(data) ? data : data.projects || []);
+ setProjects(normalizeListResponse(data, 'projects'));
} catch (err) {
console.error('Failed to load compose projects:', err);
setProjects([]);
@@ -1342,7 +1367,10 @@ const ComposeLogsModal = ({ project, onClose }) => {
try {
let containers;
if (isRemote) {
- containers = await api.getRemoteComposePs(serverId, projectPath);
+ containers = normalizeListResponse(
+ await api.getRemoteComposePs(serverId, projectPath),
+ 'containers'
+ );
} else {
const result = await api.composePs(projectPath);
containers = result.containers || result || [];
@@ -1365,7 +1393,7 @@ const ComposeLogsModal = ({ project, onClose }) => {
try {
let data;
if (isRemote) {
- data = await api.remoteComposeLogs(serverId, projectPath, selectedService || null, tail);
+ data = unwrapRemoteData(await api.remoteComposeLogs(serverId, projectPath, selectedService || null, tail));
} else {
data = await api.composeLogs(projectPath, selectedService || null, tail);
}
@@ -1561,7 +1589,7 @@ const ContainerLogsModal = ({ container, onClose }) => {
let data;
if (isRemote) {
const result = await api.getRemoteContainerLogs(serverId, container.id, tail);
- data = result.success ? { logs: result.data?.logs || '' } : { logs: '' };
+ data = unwrapRemoteData(result);
} else {
data = await api.getContainerLogs(container.id, tail);
}
diff --git a/frontend/src/pages/Downloads.jsx b/frontend/src/pages/Downloads.jsx
index dca94cc5..a056fe28 100644
--- a/frontend/src/pages/Downloads.jsx
+++ b/frontend/src/pages/Downloads.jsx
@@ -107,7 +107,7 @@ function Downloads() {
icon: LinuxIcon,
os: 'linux',
archKey: 'amd64',
- command: `curl -fsSL ${getBaseUrl()}/api/servers/install.sh | sudo bash -s -- --token "YOUR_TOKEN" --server "${getBaseUrl()}"`,
+ command: `curl -fsSL ${getBaseUrl()}/api/v1/servers/install.sh | sudo bash -s -- --token "YOUR_TOKEN" --server "${getBaseUrl()}"`,
},
{
id: 'linux-arm64',
@@ -116,7 +116,7 @@ function Downloads() {
icon: LinuxIcon,
os: 'linux',
archKey: 'arm64',
- command: `curl -fsSL ${getBaseUrl()}/api/servers/install.sh | sudo bash -s -- --token "YOUR_TOKEN" --server "${getBaseUrl()}"`,
+ command: `curl -fsSL ${getBaseUrl()}/api/v1/servers/install.sh | sudo bash -s -- --token "YOUR_TOKEN" --server "${getBaseUrl()}"`,
},
{
id: 'windows-amd64',
@@ -125,7 +125,7 @@ function Downloads() {
icon: WindowsIcon,
os: 'windows',
archKey: 'amd64',
- command: `irm ${getBaseUrl()}/api/servers/install.ps1 | iex; Install-ServerKitAgent -Token "YOUR_TOKEN" -Server "${getBaseUrl()}"`,
+ command: `irm ${getBaseUrl()}/api/v1/servers/install.ps1 | iex; Install-ServerKitAgent -Token "YOUR_TOKEN" -Server "${getBaseUrl()}"`,
},
];
@@ -242,7 +242,7 @@ function Downloads() {
<section className="downloads-section">
<h2>Quick Install Commands</h2>
<p className="section-description">
- Use these one-liner commands to download and install the agent. Replace <code>YOUR_TOKEN</code> with your server's registration token.
+ Use these one-liner commands to download and install the agent. Replace <code>YOUR_TOKEN</code> with the server registration token.
</p>
<div className="install-commands">
@@ -314,7 +314,7 @@ function Downloads() {
<div className="step-content">
<h4>Register the Agent</h4>
<p>Run the registration command with your token:</p>
- <pre><code>serverkit-agent register --token "YOUR_TOKEN" --server "{getBaseUrl()}"</code></pre>
+ <pre><code>{`serverkit-agent register --token "YOUR_TOKEN" --server "${getBaseUrl()}"`}</code></pre>
</div>
</div>
<div className="step">
diff --git a/frontend/src/pages/ServerDetail.jsx b/frontend/src/pages/ServerDetail.jsx
index 2ef1843a..673d9595 100644
--- a/frontend/src/pages/ServerDetail.jsx
+++ b/frontend/src/pages/ServerDetail.jsx
@@ -701,7 +701,7 @@ Install-ServerKitAgent -Server "${window.location.origin}" -Token "${token}"` :
<div className="install-script-block">
<div className="install-script-header">
<TerminalIcon />
- <span>Linux / macOS</span>
+ <span>Linux</span>
<button className="btn btn-sm btn-secondary" onClick={() => copyToClipboard(linuxScript)}>
<CopyIcon /> Copy
</button>
@@ -1134,8 +1134,8 @@ Install-ServerKitAgent -Server "${window.location.origin}" -Token "${token}"` :
<div className="install-tab-header">
<TerminalIcon />
<div className="install-tab-title">
- <span>Linux / macOS</span>
- <span className="install-tab-description">Ubuntu, Debian, CentOS, Fedora, Arch, macOS — requires curl and sudo</span>
+ <span>Linux</span>
+ <span className="install-tab-description">Linux server with curl, tar, sudo, and systemd</span>
</div>
<button className="btn btn-sm btn-secondary" onClick={() => copyToClipboard(linuxScript)}>
<CopyIcon /> Copy
@@ -1164,7 +1164,7 @@ Install-ServerKitAgent -Server "${window.location.origin}" -Token "${token}"` :
<ol>
<li>Copy and run the install script on your server</li>
<li>The agent downloads, installs, and registers automatically</li>
- <li>Your server will appear as <strong>"Pending"</strong> until the agent connects, then switch to <strong>"Online"</strong></li>
+ <li>Your server will appear as <strong>Pending</strong> until the agent connects, then switch to <strong>Online</strong></li>
</ol>
<p className="text-muted">
The registration token expires in 24 hours. You can regenerate it from the server settings page.
diff --git a/frontend/src/pages/Servers.jsx b/frontend/src/pages/Servers.jsx
index 685baee5..2ba5b5e6 100644
--- a/frontend/src/pages/Servers.jsx
+++ b/frontend/src/pages/Servers.jsx
@@ -153,7 +153,7 @@ const Servers = () => {
<h3>No servers found</h3>
<p>
{servers.length === 0
- ? 'Add your first server to start managing remote infrastructure.'
+ ? 'Add your first server to connect an agent for monitoring and supported remote Docker actions.'
: 'No servers match your current filters.'}
</p>
{servers.length === 0 && (
@@ -312,7 +312,8 @@ const AddServerModal = ({ groups, onClose, onCreated }) => {
group_id: '',
hostname: '',
ip_address: '',
- permissions: ['docker:read', 'docker:write', 'system:read']
+ permission_profile: 'docker_manager',
+ permissions: []
});
const [registrationData, setRegistrationData] = useState(null);
const [loading, setLoading] = useState(false);
@@ -421,29 +422,12 @@ Install-ServerKitAgent -Server "${window.location.origin}" -Token "${registratio
</div>
<div className="form-group">
- <label>Permissions</label>
- <div className="permissions-grid">
- {[
- { key: 'docker:read', label: 'Docker (Read)' },
- { key: 'docker:write', label: 'Docker (Write)' },
- { key: 'system:read', label: 'System Metrics' },
- { key: 'system:exec', label: 'Remote Execution' }
- ].map(perm => (
- <label key={perm.key} className="permission-checkbox">
- <input
- type="checkbox"
- checked={formData.permissions.includes(perm.key)}
- onChange={(e) => {
- const newPerms = e.target.checked
- ? [...formData.permissions, perm.key]
- : formData.permissions.filter(p => p !== perm.key);
- setFormData(prev => ({ ...prev, permissions: newPerms }));
- }}
- />
- {perm.label}
- </label>
- ))}
- </div>
+ <label>Access Profile</label>
+ <select name="permission_profile" value={formData.permission_profile} onChange={handleChange}>
+ <option value="docker_manager">Docker Manager</option>
+ <option value="docker_readonly">Docker Read-Only</option>
+ <option value="full_access">Full Access</option>
+ </select>
</div>
<div className="modal-actions">
@@ -460,15 +444,15 @@ Install-ServerKitAgent -Server "${window.location.origin}" -Token "${registratio
<div className="success-banner">
<CheckCircleIcon />
<div>
- <strong>Server registered successfully</strong>
+ <strong>Agent token created</strong>
<p className="success-subtitle">Run the install script on your target machine to connect the agent.</p>
</div>
</div>
<div className="install-tabs">
<InstallTab
- title="Linux / macOS"
- description="Ubuntu, Debian, CentOS, Fedora, Arch, macOS — requires curl and sudo"
+ title="Linux"
+ description="Linux server with curl, tar, sudo, and systemd"
icon={<TerminalIcon />}
script={linuxInstallScript}
onCopy={() => copyToClipboard(linuxInstallScript)}
@@ -487,7 +471,7 @@ Install-ServerKitAgent -Server "${window.location.origin}" -Token "${registratio
<ol>
<li>Copy and run the install script on your server</li>
<li>The agent downloads, installs, and registers automatically</li>
- <li>Your server will appear as <strong>"Pending"</strong> until the agent connects, then switch to <strong>"Online"</strong></li>
+ <li>Your server will appear as <strong>Pending</strong> until the agent connects, then switch to <strong>Online</strong></li>
</ol>
<p className="text-muted">
The registration token expires in 24 hours. You can regenerate it from the server details page.
diff --git a/frontend/src/services/api/servers.js b/frontend/src/services/api/servers.js
index 404560f6..c3245cc3 100644
--- a/frontend/src/services/api/servers.js
+++ b/frontend/src/services/api/servers.js
@@ -146,10 +146,22 @@ export async function getRemoteVolumes(serverId) {
return this.request(`/servers/${serverId}/docker/volumes`);
}
+export async function removeRemoteVolume(serverId, volumeName, force = false) {
+ return this.request(`/servers/${serverId}/docker/volumes/${encodeURIComponent(volumeName)}?force=${force}`, {
+ method: 'DELETE'
+ });
+}
+
export async function getRemoteNetworks(serverId) {
return this.request(`/servers/${serverId}/docker/networks`);
}
+export async function removeRemoteNetwork(serverId, networkId) {
+ return this.request(`/servers/${serverId}/docker/networks/${encodeURIComponent(networkId)}`, {
+ method: 'DELETE'
+ });
+}
+
export async function getRemoteSystemMetrics(serverId) {
return this.request(`/servers/${serverId}/system/metrics`);
}
@@ -347,7 +359,7 @@ export async function getAgentVersion() {
export async function getAgentDownloadUrl(os, arch) {
const baseUrl = this.baseUrl.replace('/api/v1', '');
- return `${baseUrl}/api/servers/agent/download/${os}/${arch}`;
+ return `${baseUrl}/api/v1/servers/agent/download/${os}/${arch}`;
}
// Agent Fleet Management endpoints
diff --git a/scripts/install.ps1 b/scripts/install.ps1
index 156a3699..f9bc2660 100644
--- a/scripts/install.ps1
+++ b/scripts/install.ps1
@@ -44,7 +44,8 @@ param(
# Configuration
$InstallDir = "$env:ProgramFiles\ServerKit"
-$ConfigDir = "$env:ProgramData\ServerKit"
+$ConfigDir = "$env:ProgramData\ServerKit\Agent"
+$LogDir = "$env:ProgramData\ServerKit\Agent\logs"
$ServiceName = "ServerKitAgent"
$GitHubRepo = "jhd3197/ServerKit"
$AgentBinary = "serverkit-agent.exe"
@@ -141,11 +142,15 @@ function Install-Agent {
}
function New-ConfigDirectory {
- Write-ColorOutput "Creating configuration directory..." "Info"
+ Write-ColorOutput "Creating configuration and log directories..." "Info"
if (-not (Test-Path $ConfigDir)) {
New-Item -ItemType Directory -Path $ConfigDir -Force | Out-Null
}
+
+ if (-not (Test-Path $LogDir)) {
+ New-Item -ItemType Directory -Path $LogDir -Force | Out-Null
+ }
}
function Register-Agent {
@@ -158,7 +163,8 @@ function Register-Agent {
Write-ColorOutput "Registering agent with ServerKit..." "Info"
$agentPath = Join-Path $InstallDir $AgentBinary
- $arguments = @("register", "--token", $Token, "--server", $Server)
+ $configPath = Join-Path $ConfigDir "config.yaml"
+ $arguments = @("--config", $configPath, "register", "--token", $Token, "--server", $Server)
if ($Name) {
$arguments += @("--name", $Name)
@@ -181,6 +187,7 @@ function Install-WindowsService {
Write-ColorOutput "Installing Windows service..." "Info"
$agentPath = Join-Path $InstallDir $AgentBinary
+ $configPath = Join-Path $ConfigDir "config.yaml"
# Check if service already exists
$existingService = Get-Service -Name $ServiceName -ErrorAction SilentlyContinue
@@ -196,7 +203,7 @@ function Install-WindowsService {
}
# Create the service using sc.exe
- $binPath = "`"$agentPath`" start"
+ $binPath = "`"$agentPath`" --config `"$configPath`" start"
$result = sc.exe create $ServiceName binPath= $binPath start= auto DisplayName= "ServerKit Agent"
if ($LASTEXITCODE -ne 0) {
diff --git a/scripts/install.sh b/scripts/install.sh
index 1c39fc64..80389efb 100644
--- a/scripts/install.sh
+++ b/scripts/install.sh
@@ -24,8 +24,9 @@ NC='\033[0m' # No Color
# Configuration
INSTALL_DIR="/usr/local/bin"
-CONFIG_DIR="/etc/serverkit"
-SERVICE_USER="serverkit"
+CONFIG_DIR="/etc/serverkit-agent"
+LOG_DIR="/var/log/serverkit-agent"
+SERVICE_USER="serverkit-agent"
GITHUB_REPO="jhd3197/ServerKit"
AGENT_BINARY="serverkit-agent"
@@ -217,27 +218,35 @@ create_user() {
}
create_config_dir() {
- log_info "Creating configuration directory..."
- mkdir -p "$CONFIG_DIR"
- chown "$SERVICE_USER:$SERVICE_USER" "$CONFIG_DIR"
- chmod 750 "$CONFIG_DIR"
+ log_info "Creating configuration and log directories..."
+ mkdir -p "$CONFIG_DIR" "$LOG_DIR"
+ chown "$SERVICE_USER:$SERVICE_USER" "$CONFIG_DIR" "$LOG_DIR"
+ chmod 750 "$CONFIG_DIR" "$LOG_DIR"
}
register_agent() {
log_info "Registering agent with ServerKit..."
- REGISTER_CMD="${INSTALL_DIR}/${AGENT_BINARY} register --token \"${TOKEN}\" --server \"${SERVER_URL}\""
+ REGISTER_CMD=(
+ "${INSTALL_DIR}/${AGENT_BINARY}"
+ --config "${CONFIG_DIR}/config.yaml"
+ register
+ --token "${TOKEN}"
+ --server "${SERVER_URL}"
+ )
if [[ -n "$SERVER_NAME" ]]; then
- REGISTER_CMD="${REGISTER_CMD} --name \"${SERVER_NAME}\""
+ REGISTER_CMD+=(--name "${SERVER_NAME}")
fi
- if ! eval "$REGISTER_CMD"; then
+ if ! "${REGISTER_CMD[@]}"; then
log_error "Agent registration failed"
fi
# Fix permissions on config files
- chown -R "$SERVICE_USER:$SERVICE_USER" "$CONFIG_DIR"
+ chown -R "$SERVICE_USER:$SERVICE_USER" "$CONFIG_DIR" "$LOG_DIR"
+ [[ -f "${CONFIG_DIR}/config.yaml" ]] && chmod 600 "${CONFIG_DIR}/config.yaml"
+ [[ -f "${CONFIG_DIR}/agent.key" ]] && chmod 600 "${CONFIG_DIR}/agent.key"
log_success "Agent registered successfully"
}
@@ -261,7 +270,7 @@ Wants=network-online.target
Type=simple
User=${SERVICE_USER}
Group=${SERVICE_USER}
-ExecStart=${INSTALL_DIR}/${AGENT_BINARY} start
+ExecStart=${INSTALL_DIR}/${AGENT_BINARY} --config ${CONFIG_DIR}/config.yaml start
Restart=always
RestartSec=10
StandardOutput=journal
@@ -272,7 +281,7 @@ SyslogIdentifier=serverkit-agent
NoNewPrivileges=true
ProtectSystem=strict
ProtectHome=true
-ReadWritePaths=${CONFIG_DIR}
+ReadWritePaths=${CONFIG_DIR} ${LOG_DIR}
PrivateTmp=true
# Environment
@@ -293,7 +302,7 @@ start_service() {
log_warn "Cannot auto-start without systemd"
echo ""
echo "To start the agent manually:"
- echo " ${INSTALL_DIR}/${AGENT_BINARY} start"
+ echo " ${INSTALL_DIR}/${AGENT_BINARY} --config ${CONFIG_DIR}/config.yaml start"
return
fi