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 /ports/check and /ports/suggest
Juan Denis2f52c87a39dd
diff --git a/backend/app/api/ports.py b/backend/app/api/ports.pynew file mode 100644index 00000000..9fa692af--- /dev/null+++ b/backend/app/api/ports.py@@ -0,0 +1,25 @@+"""Host-port checks for the panel's port inputs. Mounted at ``/api/v1/ports``.++ GET /check?port=<n> — valid / free / privileged, and who holds it+ GET /suggest?start=<n> — the next free port at or above ``start``++Read-only. Developer role, the same as deploying the app that would use it.+"""+from flask import Blueprint, jsonify, request++from app.middleware.rbac import developer_required+from app.services import port_service++ports_bp = Blueprint('ports', __name__)+++@ports_bp.route('/check', methods=['GET'])+@developer_required+def check_port():+ return jsonify(port_service.check_port(request.args.get('port'))), 200+++@ports_bp.route('/suggest', methods=['GET'])+@developer_required+def suggest_port():+ return jsonify({'port': port_service.suggest_port(request.args.get('start', 8000))}), 200diff --git a/backend/app/core_blueprints.py b/backend/app/core_blueprints.pyindex 05b2f2f1..2e815888 100644--- a/backend/app/core_blueprints.py+++ b/backend/app/core_blueprints.py@@ -54,6 +54,7 @@ CORE_BLUEPRINTS: tuple[BlueprintSpec, ...] = (BlueprintSpec('app.api.app_volumes', 'app_volumes_bp', '/api/v1/apps'),BlueprintSpec('app.api.app_attachments', 'app_attachments_bp', '/api/v1/apps'),BlueprintSpec('app.api.app_slots', 'app_slots_bp', '/api/v1/apps'),+ BlueprintSpec('app.api.ports', 'ports_bp', '/api/v1/ports'),BlueprintSpec('app.api.app_volumes','app_volumes_bp',diff --git a/backend/app/services/port_service.py b/backend/app/services/port_service.pynew file mode 100644index 00000000..0253a66f--- /dev/null+++ b/backend/app/services/port_service.py@@ -0,0 +1,67 @@+"""Answer "can I use this host port?" for the panel's port inputs.++The deploy paths already pick and check host ports through+TemplateService (app rows, slot rows, Docker mappings, then a bind test).+This module asks the same sources on behalf of one typed port and adds+*who* holds it, so the UI can say "taken by shop-api" instead of "invalid".+"""+from app.services.template_service import TemplateService++# Ports below this need root to bind and are never handed to an app.+PRIVILEGED_PORT_LIMIT = 1024+++def port_holder(port: int):+ """The app or container holding ``port``, as ``{'kind', 'name', 'id'}``,+ or None when nothing ServerKit knows about holds it."""+ try:+ from app import db+ from app.models import Application+ from app.models.app_slot import AppSlot+ # Unfiltered on purpose, like TemplateService: a soft-deleted app keeps+ # its port so restoring it from the recycle bin cannot collide.+ app = Application.query.filter_by(port=port).first()+ if app is None:+ slot = AppSlot.query.filter_by(host_port=port).first()+ app = db.session.get(Application, slot.application_id) if slot else None+ if app is not None:+ return {'kind': 'app', 'name': app.name, 'id': app.id}+ except Exception:+ pass+ if port in TemplateService._get_docker_used_ports():+ return {'kind': 'container', 'name': None, 'id': None}+ return None+++def check_port(port) -> dict:+ """Validity, availability and holder of one host port."""+ try:+ port = int(port)+ except (TypeError, ValueError):+ return {'port': None, 'valid': False, 'free': False, 'reason': 'not_a_number'}+ if not 1 <= port <= 65535:+ return {'port': port, 'valid': False, 'free': False, 'reason': 'out_of_range'}+ holder = port_holder(port)+ free = holder is None and TemplateService._port_is_free(port)+ reason = None+ if holder is not None:+ reason = 'in_use'+ elif not free:+ reason = 'bound' # something outside ServerKit is listening+ return {+ 'port': port,+ 'valid': True,+ 'free': free,+ 'privileged': port < PRIVILEGED_PORT_LIMIT,+ 'holder': holder,+ 'reason': reason,+ }+++def suggest_port(start: int = 8000) -> int:+ """The next free host port at or above ``start``."""+ try:+ start = max(PRIVILEGED_PORT_LIMIT, min(int(start), 65535))+ except (TypeError, ValueError):+ start = 8000+ return TemplateService._find_available_port(start_port=start)diff --git a/backend/tests/test_core_blueprint_registry.py b/backend/tests/test_core_blueprint_registry.pyindex 30875352..3b4e86e4 100644--- a/backend/tests/test_core_blueprint_registry.py+++ b/backend/tests/test_core_blueprint_registry.py@@ -7,9 +7,9 @@ from pathlib import Pathfrom app.core_blueprints import CORE_BLUEPRINTS-EXPECTED_CORE_BLUEPRINT_COUNT = 115+EXPECTED_CORE_BLUEPRINT_COUNT = 116EXPECTED_MANIFEST_SHA256 = (- '0bca63affd364e925e2599e4915528e7d0bfd895feeb37adef4841963c6d0927'+ '25d28d92ccddddc246d5b2081d84b11f1df10cb662f33c256ebcbe390d2813d5')diff --git a/backend/tests/test_ports_api.py b/backend/tests/test_ports_api.pynew file mode 100644index 00000000..0494e91d--- /dev/null+++ b/backend/tests/test_ports_api.py@@ -0,0 +1,61 @@+"""/api/v1/ports: the check behind the shared PortField input."""+import pytest++from app import db+from app.services import port_service+from app.services.template_service import TemplateService+from tests.factories import make_application++[email protected](autouse=True)+def _no_docker_or_sockets(monkeypatch):+ # Hermetic: no `docker ps`, and every unheld port binds.+ monkeypatch.setattr(TemplateService, '_get_docker_used_ports', classmethod(lambda cls: set()))+ monkeypatch.setattr(TemplateService, '_port_is_free', classmethod(+ lambda cls, port: port not in TemplateService._get_database_used_ports()))+++def test_free_port(client, developer_headers):+ res = client.get('/api/v1/ports/check?port=18080', headers=developer_headers)+ assert res.status_code == 200+ body = res.get_json()+ assert body == {'port': 18080, 'valid': True, 'free': True, 'privileged': False,+ 'holder': None, 'reason': None}+++def test_port_held_by_an_app_names_it(app, client, developer_headers):+ make_application(db, name='shop-api', port=18081)+ body = client.get('/api/v1/ports/check?port=18081', headers=developer_headers).get_json()+ assert body['free'] is False+ assert body['reason'] == 'in_use'+ assert body['holder']['kind'] == 'app'+ assert body['holder']['name'] == 'shop-api'++[email protected]('raw,reason', [('abc', 'not_a_number'), ('0', 'out_of_range'),+ ('70000', 'out_of_range'), (None, 'not_a_number')])+def test_invalid_ports(raw, reason):+ body = port_service.check_port(raw)+ assert body['valid'] is False and body['free'] is False+ assert body['reason'] == reason+++def test_privileged_port_is_flagged():+ assert port_service.check_port(80)['privileged'] is True+++def test_bound_outside_serverkit(monkeypatch):+ monkeypatch.setattr(TemplateService, '_port_is_free', classmethod(lambda cls, port: False))+ body = port_service.check_port(18082)+ assert body['free'] is False and body['holder'] is None and body['reason'] == 'bound'+++def test_suggest_skips_taken_ports(app, client, developer_headers, monkeypatch):+ make_application(db, name='a', port=18090)+ monkeypatch.setattr('socket.socket.bind', lambda self, addr: None)+ body = client.get('/api/v1/ports/suggest?start=18090', headers=developer_headers).get_json()+ assert body['port'] == 18091+++def test_requires_developer(client, viewer_headers):+ assert client.get('/api/v1/ports/check?port=8080', headers=viewer_headers).status_code == 403diff --git a/docs/API_SURFACE.md b/docs/API_SURFACE.mdindex 71c078cd..4009e331 100644--- a/docs/API_SURFACE.md+++ b/docs/API_SURFACE.md@@ -477,6 +477,8 @@ Regenerate (backend/):- `GET /plugins/{plugin_id}/permissions`- `GET /plugins/{plugin_id}/requirements`- `GET /plugins/{slug}/assets/<path:asset_path>`+- `GET /ports/check`+- `GET /ports/suggest`- `GET /processes`- `GET /processes/services`- `GET /processes/services/{service_name}/logs`