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
feat(games): serverkit-minecraft extension backbone + gamekit framework
Juan Denisfd6f1733c346
diff --git a/backend/tests/test_gamekit_minecraft.py b/backend/tests/test_gamekit_minecraft.pynew file mode 100644index 00000000..53b399a2--- /dev/null+++ b/backend/tests/test_gamekit_minecraft.py@@ -0,0 +1,271 @@+"""gamekit framework unit tests (plan 53 Phase 1).++gamekit is the dependency-free, extractable game-server framework inside the+serverkit-minecraft extension (D1). It ships no ServerKit imports, so these tests+load it straight off disk (its backend dir on sys.path) and exercise the four+adapters with a scripted fake RCON socket, fixture logs, and temp worlds — no+Docker, no live server. The Docker create/console/backup wiring rides these+adapters and is verified separately on the dev box.+"""+import datetime+import json+import os+import struct+import sys++import pytest++_REPO_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))+_MC = os.path.join(_REPO_ROOT, 'builtin-extensions', 'serverkit-minecraft')+_MC_BACKEND = os.path.join(_MC, 'backend')+if _MC_BACKEND not in sys.path:+ sys.path.insert(0, _MC_BACKEND)++from gamekit import rcon, log_events, config_form, save_backup # noqa: E402+++# --------------------------------------------------------------------------- #+# RCON (fake socket, no network)+# --------------------------------------------------------------------------- #++class FakeRconSocket:+ """Scripted Source-RCON server over the socket interface RconClient uses."""++ def __init__(self, password='secret', responses=None, fail_auth=False):+ self.password = password+ self.fail_auth = fail_auth+ self.responses = responses or {}+ self._out = b''+ self.sent_commands = []+ self.closed = False++ def settimeout(self, _t):+ pass++ def connect(self, _addr):+ pass++ def close(self):+ self.closed = True++ def sendall(self, data):+ (length,) = struct.unpack('<i', data[:4])+ payload = data[4:4 + length]+ req_id, req_type = struct.unpack('<ii', payload[:8])+ body = payload[8:-2].decode('utf-8')+ if req_type == rcon.SERVERDATA_AUTH:+ ok = (not self.fail_auth) and body == self.password+ echo_id = req_id if ok else -1+ self._out += rcon.encode_packet(echo_id, rcon.SERVERDATA_AUTH_RESPONSE, '')+ elif req_type == rcon.SERVERDATA_EXECCOMMAND:+ self.sent_commands.append(body)+ resp = self.responses.get(body, f'ran: {body}')+ self._out += rcon.encode_packet(req_id, rcon.SERVERDATA_RESPONSE_VALUE, resp)++ def recv(self, n):+ chunk, self._out = self._out[:n], self._out[n:]+ return chunk+++def test_rcon_auth_and_command_roundtrip():+ sock = FakeRconSocket(password='secret',+ responses={'list': 'There are 2 of a max of 20 players online: Steve, Alex'})+ with rcon.RconClient(password='secret', sock=sock) as rc:+ out = rc.command('list')+ assert 'Steve' in out and 'Alex' in out+ assert sock.sent_commands == ['list']+ assert sock.closed is True+++def test_rcon_command_before_auth_raises():+ sock = FakeRconSocket(password='secret')+ rc = rcon.RconClient(password='secret', sock=sock).connect()+ with pytest.raises(rcon.RconError):+ rc.command('list')+++def test_rcon_auth_failure_raises():+ sock = FakeRconSocket(password='secret', fail_auth=True)+ rc = rcon.RconClient(password='wrong', sock=sock).connect()+ with pytest.raises(rcon.RconAuthError):+ rc.authenticate()+++def test_rcon_packet_framing_is_little_endian():+ pkt = rcon.encode_packet(7, rcon.SERVERDATA_EXECCOMMAND, 'say hi')+ (length,) = struct.unpack('<i', pkt[:4])+ assert length == len(pkt) - 4+ req_id, req_type = struct.unpack('<ii', pkt[4:12])+ assert req_id == 7 and req_type == rcon.SERVERDATA_EXECCOMMAND+ assert pkt.endswith(b'\x00\x00')+++# --------------------------------------------------------------------------- #+# log_events+# --------------------------------------------------------------------------- #++def test_java_log_events_in_order():+ lines = [+ '[12:34:56] [Server thread/INFO]: Done (12.345s)! For help, type "help"',+ '[12:35:01] [Server thread/INFO]: Steve joined the game',+ '[12:36:10] [Server thread/INFO]: <Steve> hello world',+ '[12:40:00] [Server thread/INFO]: Steve left the game',+ '[12:41:00] [Server thread/INFO]: Stopping server',+ ]+ events = log_events.parse_lines(lines)+ assert [e['event'] for e in events] == [+ 'server_started', 'player_join', 'chat', 'player_leave', 'server_stopping']+ assert events[0]['elapsed'] == '12.345'+ assert events[1]['player'] == 'Steve'+ assert events[2]['message'] == 'hello world'+++def test_bedrock_log_events():+ lines = [+ '[2026-07-22 12:00:00 INFO] Server started.',+ '[2026-07-22 12:01:00 INFO] Player connected: Steve, xuid: 123',+ '[2026-07-22 12:05:00 INFO] Player disconnected: Steve, xuid: 123',+ ]+ events = log_events.parse_lines(lines)+ assert [e['event'] for e in events] == ['server_started', 'player_join', 'player_leave']+ assert events[1]['player'] == 'Steve'+++def test_non_event_lines_ignored():+ assert log_events.parse_line('[12:00:00] [Server thread/INFO]: Preparing spawn area: 42%') is None+ assert log_events.parse_line('') is None+++# --------------------------------------------------------------------------- #+# config_form+# --------------------------------------------------------------------------- #++_PROPS = (+ '# Minecraft server properties\n'+ 'motd=Hello World\n'+ 'difficulty=hard\n'+ 'max-players=20\n'+ 'white-list=true\n'+ 'custom-unlisted-key=keep-me\n'+)+++def _sidecar_meta():+ with open(os.path.join(_MC, 'backend', 'gamekit', 'server_properties_meta.json'),+ 'r', encoding='utf-8') as f:+ return json.load(f)+++def test_parse_properties_ignores_comments_and_blanks():+ props = config_form.parse_properties(_PROPS)+ assert props['motd'] == 'Hello World'+ assert props['max-players'] == '20'+ assert 'custom-unlisted-key' in props+ assert not any(k.startswith('#') for k in props)+++def test_build_form_groups_and_coerces_with_real_sidecar():+ form = config_form.build_form(_PROPS, _sidecar_meta())+ all_fields = {f['key']: f for g in form['groups'] for f in g['fields']}+ assert all_fields['max-players']['value'] == 20 # coerced int+ assert all_fields['white-list']['value'] is True # coerced bool+ assert 'options' in all_fields['difficulty'] # from sidecar+ # unlisted key still surfaces, in the implicit 'other' group+ assert all_fields['custom-unlisted-key']['type'] == 'string'+ group_ids = [g['id'] for g in form['groups']]+ assert group_ids == sorted(group_ids, key=lambda g:+ {'general': 1, 'world': 2, 'players': 3, 'gameplay': 4,+ 'network': 5, 'performance': 6, 'other': 99}.get(g, 50))+++def test_apply_changes_preserves_and_appends():+ new = config_form.apply_changes(_PROPS, {'difficulty': 'peaceful', 'pvp': False})+ assert 'difficulty=peaceful' in new+ assert 'motd=Hello World' in new # untouched key preserved+ assert '# Minecraft server properties' in new # comment preserved+ assert 'custom-unlisted-key=keep-me' in new # unknown key preserved+ assert 'pvp=false' in new # new key appended, bool rendered+++# --------------------------------------------------------------------------- #+# save_backup+# --------------------------------------------------------------------------- #++class _FakeRcon:+ def __init__(self):+ self.cmds = []++ def command(self, c):+ self.cmds.append(c)+ return ''+++def test_hot_backup_quiesce_order_and_produces_archive(tmp_path):+ world = tmp_path / 'world'+ world.mkdir()+ (world / 'level.dat').write_bytes(b'x' * 32)+ dest = tmp_path / 'backups'+ rc = _FakeRcon()++ res = save_backup.hot_backup(str(world), str(dest), 'world_v1.21', rcon=rc)++ assert res['success'] is True and res['skipped'] is False+ # the correct hot-backup sequence, in order+ assert rc.cmds == ['save-off', 'save-all flush', 'save-on']+ assert os.path.isfile(res['path'])+ assert res['path'].endswith('world_v1.21.zip')+++def test_hot_backup_skips_empty_world(tmp_path):+ world = tmp_path / 'world'+ world.mkdir()+ res = save_backup.hot_backup(str(world), str(tmp_path / 'b'), 'x.zip')+ assert res['skipped'] is True+ assert res['commands'] == []+++def test_save_on_runs_even_if_zip_fails(tmp_path, monkeypatch):+ world = tmp_path / 'world'+ world.mkdir()+ (world / 'a.dat').write_bytes(b'y')+ rc = _FakeRcon()+ # Fail mid-sequence, after quiesce has started, to prove save-on still runs.+ def boom(_src, _path):+ raise RuntimeError('disk full')+ monkeypatch.setattr(save_backup, '_zip_dir', boom)+ with pytest.raises(RuntimeError):+ save_backup.hot_backup(str(world), str(tmp_path / 'backups'), 'x.zip', rcon=rc)+ assert rc.cmds == ['save-off', 'save-all flush', 'save-on'] # resume always issued+++def test_retention_prunes_oldest_keeps_newest(tmp_path):+ dest = tmp_path / 'b'+ dest.mkdir()+ for i in range(4):+ p = dest / f'w{i}.zip'+ p.write_bytes(b'z')+ os.utime(p, (1000 + i, 1000 + i))+ pruned = save_backup.apply_retention(str(dest), 2)+ assert set(pruned) == {'w0.zip', 'w1.zip'}+ remaining = sorted(f for f in os.listdir(dest) if f.endswith('.zip'))+ assert remaining == ['w2.zip', 'w3.zip']+++def test_archive_name_is_self_describing():+ when = datetime.datetime(2026, 7, 22, 12, 0)+ assert save_backup.archive_name('myworld', '1.21', when) == 'myworld_v1.21_2026-07-22_1200.zip'+++# --------------------------------------------------------------------------- #+# manifest well-formed+# --------------------------------------------------------------------------- #++def test_extension_manifest_is_well_formed():+ with open(os.path.join(_MC, 'plugin.json'), 'r', encoding='utf-8') as f:+ manifest = json.load(f)+ for key in ('name', 'display_name', 'version', 'entry_point', 'url_prefix',+ 'models', 'category'):+ assert manifest.get(key), f'manifest missing {key}'+ assert manifest['category'] == 'games'+ assert manifest['entry_point'] == 'minecraft:minecraft_bp'+ assert manifest['url_prefix'] == '/api/v1/minecraft'diff --git a/backend/tests/test_minecraft_extension_install.py b/backend/tests/test_minecraft_extension_install.pynew file mode 100644index 00000000..3ef8407c--- /dev/null+++ b/backend/tests/test_minecraft_extension_install.py@@ -0,0 +1,72 @@+"""Prove the serverkit-minecraft extension wires up (plan 53 Phase 1).++Installing the builtin registers /api/v1/minecraft, creates its extension-owned+ext_serverkit_minecraft_* tables (models:register, D6), and its list route+responds — which also exercises the dashed-package import bridge reaching gamekit.+The create/console/backup Docker flow is verified separately on the dev box; this+locks the offline wiring.+"""+import sys++import pytest++import app as app_pkg+from app import db+from app.models.plugin import InstalledPlugin+from app.services import plugin_service++SLUG = 'serverkit-minecraft'+_PKG = f'app.plugins.{SLUG}'+++def install_dirs(tmp_path, monkeypatch):+ backend = tmp_path / 'plugins_backend'+ frontend = tmp_path / 'plugins_frontend'+ backend.mkdir()+ frontend.mkdir()+ monkeypatch.setattr(plugin_service, 'BACKEND_PLUGINS_DIR', str(backend))+ monkeypatch.setattr(plugin_service, 'FRONTEND_PLUGINS_DIR', str(frontend))++ added = str(backend)+ import importlib+ app_pkg_plugins = importlib.import_module('app.plugins')+ if added not in app_pkg_plugins.__path__:+ app_pkg_plugins.__path__.append(added)++ yield {'backend': backend, 'frontend': frontend}++ if added in app_pkg_plugins.__path__:+ app_pkg_plugins.__path__.remove(added)+ for name in list(sys.modules):+ if name == _PKG or name.startswith(_PKG + '.'):+ del sys.modules[name]+++def test_minecraft_builtin_is_available(app):+ available = {e['slug'] for e in plugin_service.list_builtin_extensions()}+ assert SLUG in available, 'serverkit-minecraft builtin folder should exist'+++def test_install_registers_routes_and_models(app, client, auth_headers, install_dirs):+ plugin = plugin_service.install_builtin_extension(SLUG)+ assert plugin.status == InstalledPlugin.STATUS_ACTIVE+ assert plugin.has_backend is True+ assert plugin.url_prefix == '/api/v1/minecraft'++ # extension-owned tables were created (models:register + create_all)+ insp = db.inspect(db.engine)+ tables = set(insp.get_table_names())+ assert 'ext_serverkit_minecraft_servers' in tables+ assert 'ext_serverkit_minecraft_backups' in tables++ # the list route responds (proves blueprint mount + dashed-import to gamekit)+ resp = client.get('/api/v1/minecraft', headers=auth_headers)+ assert resp.status_code == 200, resp.status_code+ assert resp.get_json() == {'servers': []}+++def test_uninstall_removes_plugin(app, install_dirs):+ plugin = plugin_service.install_builtin_extension(SLUG)+ assert plugin_service.uninstall_plugin(plugin.id) is True+ assert InstalledPlugin.query.filter_by(slug=SLUG).first() is Nonediff --git a/builtin-extensions/serverkit-minecraft/backend/__init__.py b/builtin-extensions/serverkit-minecraft/backend/__init__.pynew file mode 100644index 00000000..46152dcd--- /dev/null+++ b/builtin-extensions/serverkit-minecraft/backend/__init__.py@@ -0,0 +1 @@+"""serverkit-minecraft extension backend package (plan 53)."""diff --git a/builtin-extensions/serverkit-minecraft/backend/gamekit/__init__.py b/builtin-extensions/serverkit-minecraft/backend/gamekit/__init__.pynew file mode 100644index 00000000..f8cfb4d9--- /dev/null+++ b/builtin-extensions/serverkit-minecraft/backend/gamekit/__init__.py@@ -0,0 +1,17 @@+"""gamekit — the reusable game-server framework (plan 53 D1).++Four adapters that give ServerKit (which manages containers from *outside*) the+equivalents of what an in-process game plugin gets for free:++ rcon — minimal Source RCON client (console, players, lifecycle)+ log_events — container-log → normalized events (notifications, players)+ config_form — server.properties + sidecar metadata → grouped form+ save_backup — save-aware hot-backup sequence with retention++Deliberately dependency-free (stdlib only) and ServerKit-agnostic, so it unit+tests standalone and extracts to a shared package once a second game exists+(the two-real-consumers rule). Until then it lives inside serverkit-minecraft.+"""+from . import rcon, log_events, config_form, save_backup # noqa: F401++__all__ = ['rcon', 'log_events', 'config_form', 'save_backup']diff --git a/builtin-extensions/serverkit-minecraft/backend/gamekit/config_form.py b/builtin-extensions/serverkit-minecraft/backend/gamekit/config_form.pynew file mode 100644index 00000000..0c34122e--- /dev/null+++ b/builtin-extensions/serverkit-minecraft/backend/gamekit/config_form.py@@ -0,0 +1,119 @@+"""server.properties as a form (gamekit adapter #3).++The file is the source of truth; a JSON sidecar (``server_properties_meta.json``)+adds grouping/labels/descriptions/restart-required so the panel renders a real+grouped form instead of a raw key=value textarea. Pure stdlib — parse, merge with+metadata into a form model, and write changes back preserving unknown keys,+comments, and order.+"""+++def parse_properties(text):+ """Parse ``key=value`` lines into an ordered dict (comments/blanks ignored).++ Java properties: ``#`` or ``!`` starts a comment; keys and values are split+ on the first ``=``. Values keep their raw string form (the form layer coerces+ per field type).+ """+ out = {}+ for line in (text or '').splitlines():+ stripped = line.strip()+ if not stripped or stripped[0] in ('#', '!'):+ continue+ if '=' not in line:+ continue+ key, _, value = line.partition('=')+ out[key.strip()] = value.strip()+ return out+++def _coerce(value, field_type):+ if field_type == 'boolean':+ return str(value).lower() in ('true', '1', 'yes', 'on')+ if field_type == 'integer':+ try:+ return int(value)+ except (TypeError, ValueError):+ return value+ return value+++def build_form(text, meta):+ """Merge parsed properties with sidecar metadata into grouped form fields.++ ``meta`` is ``{'groups': [{id,label,order}], 'fields': {key: {label,+ description, group, type, restart_required, options?}}}``. Every property in+ the file appears; unknown keys land in an implicit ``other`` group so nothing+ is hidden. Returns ``{'groups': [{id, label, fields: [...]}]}`` ordered by+ each group's ``order``.+ """+ props = parse_properties(text)+ meta = meta or {}+ field_meta = meta.get('fields', {}) or {}+ group_defs = {g['id']: g for g in (meta.get('groups') or [])}++ grouped = {}+ for key, raw_value in props.items():+ fm = field_meta.get(key, {})+ gid = fm.get('group', 'other')+ field = {+ 'key': key,+ 'label': fm.get('label', key),+ 'description': fm.get('description', ''),+ 'type': fm.get('type', 'string'),+ 'value': _coerce(raw_value, fm.get('type', 'string')),+ 'restart_required': bool(fm.get('restart_required', False)),+ }+ if fm.get('options'):+ field['options'] = fm['options']+ grouped.setdefault(gid, []).append(field)++ def group_order(gid):+ return group_defs.get(gid, {}).get('order', 999)++ groups = []+ for gid in sorted(grouped, key=group_order):+ groups.append({+ 'id': gid,+ 'label': group_defs.get(gid, {}).get('label', gid.replace('_', ' ').title()),+ 'fields': grouped[gid],+ })+ return {'groups': groups}+++def apply_changes(text, changes):+ """Return new file text with *changes* applied, preserving everything else.++ Updates the value of any existing key in place (keeping comments, blank lines+ and ordering); appends keys that weren't present. Booleans render as+ ``true``/``false`` (Minecraft's expected form).+ """+ changes = {k: v for k, v in (changes or {}).items()}++ def render(v):+ if isinstance(v, bool):+ return 'true' if v else 'false'+ return str(v)++ lines = (text or '').splitlines()+ seen = set()+ out_lines = []+ for line in lines:+ stripped = line.strip()+ if stripped and stripped[0] not in ('#', '!') and '=' in line:+ key = line.partition('=')[0].strip()+ if key in changes:+ out_lines.append(f'{key}={render(changes[key])}')+ seen.add(key)+ continue+ out_lines.append(line)++ for key, value in changes.items():+ if key not in seen:+ out_lines.append(f'{key}={render(value)}')++ trailing_newline = (text or '').endswith('\n')+ result = '\n'.join(out_lines)+ if trailing_newline and not result.endswith('\n'):+ result += '\n'+ return resultdiff --git a/builtin-extensions/serverkit-minecraft/backend/gamekit/log_events.py b/builtin-extensions/serverkit-minecraft/backend/gamekit/log_events.pynew file mode 100644index 00000000..5418df00--- /dev/null+++ b/builtin-extensions/serverkit-minecraft/backend/gamekit/log_events.py@@ -0,0 +1,73 @@+"""Container-log event parser (gamekit adapter #2).++Turns raw Minecraft server log lines into normalized events that feed the+notifications bus (join/leave/started/stopped/crashed) and the Players cache.+Pure ``re`` — no ServerKit imports — so it unit-tests against fixture logs and+extracts cleanly with the rest of ``gamekit``.++itzg/minecraft-server log lines look like:++ [12:34:56] [Server thread/INFO]: Steve joined the game+ [12:34:56] [Server thread/INFO]: Steve left the game+ [12:34:56] [Server thread/INFO]: Done (12.345s)! For help, type "help"+ [12:34:56] [Server thread/INFO]: <Steve> hello world+ [12:34:56] [Server thread/INFO]: Stopping server++Bedrock (itzg/minecraft-bedrock-server) has no RCON; its lines differ, e.g.:++ [INFO] Player connected: Steve, xuid: 123+ [INFO] Player disconnected: Steve, xuid: 123+ [INFO] Server started.+"""+import re++# (event, compiled regex, group name for the player if any)+_RULES = [+ ('player_join', re.compile(r'\]:\s+(?P<player>\w+) joined the game'), 'player'),+ ('player_leave', re.compile(r'\]:\s+(?P<player>\w+) left the game'), 'player'),+ # Bedrock edition+ ('player_join', re.compile(r'Player connected:\s+(?P<player>[^,]+)'), 'player'),+ ('player_leave', re.compile(r'Player disconnected:\s+(?P<player>[^,]+)'), 'player'),+ ('server_started', re.compile(r'\]:\s+Done \((?P<elapsed>[\d.]+)s\)!'), None),+ ('server_started', re.compile(r'Server started\.'), None),+ ('server_stopping', re.compile(r'\]:\s+Stopping server'), None),+ ('chat', re.compile(r'\]:\s+<(?P<player>\w+)>\s+(?P<message>.*)$'), 'player'),+ ('crash', re.compile(r'This crash report has been saved', re.IGNORECASE), None),+ ('crash', re.compile(r'\]:\s+Exception (?:stopping|in server tick)', re.IGNORECASE), None),+]+++def parse_line(line):+ """Return a normalized event dict for *line*, or None if nothing matches.++ Event shape: ``{'event': <type>, 'player'?: str, 'message'?: str,+ 'elapsed'?: str, 'raw': line}``. First matching rule wins, so player+ join/leave (more specific) are tried before the generic chat rule.+ """+ if not line:+ return None+ text = line.rstrip('\n')+ for event, rx, _player_group in _RULES:+ m = rx.search(text)+ if not m:+ continue+ out = {'event': event, 'raw': text}+ gd = m.groupdict()+ if gd.get('player'):+ out['player'] = gd['player'].strip()+ if gd.get('message') is not None:+ out['message'] = gd['message']+ if gd.get('elapsed'):+ out['elapsed'] = gd['elapsed']+ return out+ return None+++def parse_lines(lines):+ """Parse an iterable of log lines into a list of events (Nones dropped)."""+ out = []+ for line in lines:+ ev = parse_line(line)+ if ev is not None:+ out.append(ev)+ return outdiff --git a/builtin-extensions/serverkit-minecraft/backend/gamekit/rcon.py b/builtin-extensions/serverkit-minecraft/backend/gamekit/rcon.pynew file mode 100644index 00000000..5f3c3867--- /dev/null+++ b/builtin-extensions/serverkit-minecraft/backend/gamekit/rcon.py@@ -0,0 +1,141 @@+"""Minimal Source RCON client (gamekit adapter #1).++Minecraft's Java-edition image (itzg/minecraft-server) speaks the Source RCON+protocol on a loopback-only TCP port. This is a dependency-free client — stdlib+``socket`` + ``struct`` only — so ``gamekit`` stays a pure, extractable package+(plan 53 D1). The panel talks to RCON server-side (D5); the port is never exposed.++Protocol (little-endian): each packet is++ int32 length (= 4 + 4 + len(body) + 2)+ int32 request_id+ int32 type+ body (ASCII, NUL-terminated)+ NUL (empty-string terminator)++Types: 3 = AUTH (login), 2 = AUTH_RESPONSE / EXECCOMMAND, 0 = RESPONSE_VALUE.+A failed auth replies with request_id == -1.++The socket is injectable (``sock`` / ``sock_factory``) so the client can be unit+tested against a scripted fake server with no real network.+"""+import socket+import struct++SERVERDATA_AUTH = 3+SERVERDATA_AUTH_RESPONSE = 2+SERVERDATA_EXECCOMMAND = 2+SERVERDATA_RESPONSE_VALUE = 0+++class RconError(Exception):+ """Any RCON transport/protocol failure."""+++class RconAuthError(RconError):+ """The RCON password was rejected (auth reply id == -1)."""+++def encode_packet(req_id, req_type, body):+ """Serialize one RCON packet (exposed for tests / fake servers)."""+ payload = struct.pack('<ii', req_id, req_type) + body.encode('utf-8') + b'\x00\x00'+ return struct.pack('<i', len(payload)) + payload+++class RconClient:+ def __init__(self, host='127.0.0.1', port=25575, password='', timeout=5.0,+ sock=None, sock_factory=None):+ self.host = host+ self.port = port+ self.password = password+ self.timeout = timeout+ self._sock = sock # a pre-connected socket (tests)+ self._sock_factory = sock_factory or socket.socket+ self._req_id = 0+ self._authed = False++ # -- connection lifecycle -------------------------------------------------++ def connect(self):+ if self._sock is None:+ self._sock = self._sock_factory(socket.AF_INET, socket.SOCK_STREAM)+ self._sock.settimeout(self.timeout)+ self._sock.connect((self.host, self.port))+ return self++ def close(self):+ if self._sock is not None:+ try:+ self._sock.close()+ finally:+ self._sock = None+ self._authed = False++ def __enter__(self):+ self.connect()+ self.authenticate()+ return self++ def __exit__(self, *exc):+ self.close()+ return False++ # -- framing --------------------------------------------------------------++ def _recv_exactly(self, n):+ chunks = []+ remaining = n+ while remaining > 0:+ chunk = self._sock.recv(remaining)+ if not chunk:+ raise RconError('connection closed while reading RCON packet')+ chunks.append(chunk)+ remaining -= len(chunk)+ return b''.join(chunks)++ def _read_packet(self):+ raw_len = self._recv_exactly(4)+ (length,) = struct.unpack('<i', raw_len)+ if length < 10 or length > 4096 * 1024:+ raise RconError(f'implausible RCON packet length {length}')+ payload = self._recv_exactly(length)+ req_id, req_type = struct.unpack('<ii', payload[:8])+ body = payload[8:-2].decode('utf-8', errors='replace') # strip the two NULs+ return req_id, req_type, body++ def _next_id(self):+ self._req_id += 1+ return self._req_id++ def _send(self, req_type, body):+ if self._sock is None:+ raise RconError('not connected')+ rid = self._next_id()+ self._sock.sendall(encode_packet(rid, req_type, body))+ return rid++ # -- operations -----------------------------------------------------------++ def authenticate(self):+ """Log in with the RCON password. Raises RconAuthError on rejection."""+ sent_id = self._send(SERVERDATA_AUTH, self.password)+ req_id, req_type, _ = self._read_packet()+ # Some servers emit an empty RESPONSE_VALUE before the auth reply.+ if req_type == SERVERDATA_RESPONSE_VALUE:+ req_id, req_type, _ = self._read_packet()+ if req_id == -1:+ raise RconAuthError('RCON authentication failed (bad password)')+ if req_id != sent_id:+ raise RconError('RCON auth response id mismatch')+ self._authed = True+ return self++ def command(self, cmd):+ """Run *cmd* and return the server's response body."""+ if not self._authed:+ raise RconError('RCON command before successful authenticate()')+ sent_id = self._send(SERVERDATA_EXECCOMMAND, cmd)+ req_id, req_type, body = self._read_packet()+ if req_id != sent_id:+ raise RconError('RCON response id mismatch')+ return bodydiff --git a/builtin-extensions/serverkit-minecraft/backend/gamekit/save_backup.py b/builtin-extensions/serverkit-minecraft/backend/gamekit/save_backup.pynew file mode 100644index 00000000..2a4fdc04--- /dev/null+++ b/builtin-extensions/serverkit-minecraft/backend/gamekit/save_backup.py@@ -0,0 +1,107 @@+"""Save-aware world backup (gamekit adapter #4).++The naive ``docker cp`` while the server writes = a torn, unusable world. The+correct Minecraft hot-backup sequence quiesces the world first:++ save-off → stop the server writing the world+ save-all flush → flush pending chunks to disk+ (zip the world)+ save-on → resume normal saving (ALWAYS, even on failure)++RCON is injected (any object with ``.command(str)``) so this is unit-testable+without a live server, and reusable by the plan-52 backup-target provider when+that hook lands (plan 53 D7). Pure stdlib otherwise.+"""+import os+import zipfile+++def world_is_empty(world_dir):+ if not os.path.isdir(world_dir):+ return True+ for _root, _dirs, files in os.walk(world_dir):+ if files:+ return False+ return True+++def _zip_dir(src_dir, archive_path):+ with zipfile.ZipFile(archive_path, 'w', zipfile.ZIP_DEFLATED) as zf:+ for root, _dirs, files in os.walk(src_dir):+ for name in files:+ full = os.path.join(root, name)+ arc = os.path.relpath(full, src_dir)+ zf.write(full, arc)+++def apply_retention(dest_dir, keep):+ """Keep the newest *keep* ``.zip`` archives in *dest_dir*, delete the rest.++ Returns the list of pruned filenames. Ordered by (mtime, name) so the+ self-describing date-stamped names break mtime ties deterministically.+ """+ if not keep or keep < 1:+ return []+ archives = [f for f in os.listdir(dest_dir) if f.endswith('.zip')]+ archives.sort(key=lambda f: (os.path.getmtime(os.path.join(dest_dir, f)), f))+ to_prune = archives[:-keep] if len(archives) > keep else []+ for f in to_prune:+ try:+ os.remove(os.path.join(dest_dir, f))+ except OSError:+ pass+ return to_prune+++def hot_backup(world_dir, dest_dir, archive_name, *, rcon=None,+ skip_when_empty=True, retention=None):+ """Quiesce → zip → resume. The correct Minecraft hot-backup sequence.++ ``rcon`` (optional): an object with ``.command(str)``. When present, issues+ ``save-off`` + ``save-all flush`` before zipping and ``save-on`` after —+ always, even if zipping fails. ``skip_when_empty`` returns a skipped+ descriptor for an empty/missing world (nothing worth an archive).+ ``retention`` prunes older archives afterwards. Returns a descriptor dict.+ """+ if skip_when_empty and world_is_empty(world_dir):+ return {'success': True, 'skipped': True, 'reason': 'world empty', 'commands': []}++ os.makedirs(dest_dir, exist_ok=True)+ if not archive_name.endswith('.zip'):+ archive_name += '.zip'+ archive_path = os.path.join(dest_dir, archive_name)++ commands = []+ if rcon is not None:+ rcon.command('save-off')+ commands.append('save-off')+ rcon.command('save-all flush')+ commands.append('save-all flush')+ try:+ _zip_dir(world_dir, archive_path)+ finally:+ if rcon is not None:+ rcon.command('save-on')+ commands.append('save-on')++ result = {+ 'success': True, 'skipped': False, 'path': archive_path,+ 'size_bytes': os.path.getsize(archive_path), 'commands': commands,+ }+ if retention:+ result['pruned'] = apply_retention(dest_dir, retention)+ return result+++def archive_name(world_name, version=None, when=None):+ """Self-describing archive name, e.g. ``world_v1.21_2026-07-22_1200.zip``.++ ``when`` is an optional ``datetime`` (caller-supplied so this stays pure and+ deterministic in tests); omitted → just the world + version stem.+ """+ parts = [world_name or 'world']+ if version:+ parts.append(f'v{version}')+ if when is not None:+ parts.append(when.strftime('%Y-%m-%d_%H%M'))+ return '_'.join(parts) + '.zip'diff --git a/builtin-extensions/serverkit-minecraft/backend/gamekit/server_properties_meta.json b/builtin-extensions/serverkit-minecraft/backend/gamekit/server_properties_meta.jsonnew file mode 100644index 00000000..01eb2a6b--- /dev/null+++ b/builtin-extensions/serverkit-minecraft/backend/gamekit/server_properties_meta.json@@ -0,0 +1,34 @@+{+ "_comment": "Sidecar metadata for Minecraft server.properties (plan 53 Phase 0). The file is the source of truth; this adds grouping/labels/descriptions/restart-required so config_form.build_form() renders a real grouped form. Keys not listed here still appear, in an implicit 'other' group. restart_required flags fields the running server won't pick up live.",+ "groups": [+ { "id": "general", "label": "General", "order": 1 },+ { "id": "world", "label": "World & Generation", "order": 2 },+ { "id": "players", "label": "Players & Access", "order": 3 },+ { "id": "gameplay", "label": "Gameplay", "order": 4 },+ { "id": "network", "label": "Network", "order": 5 },+ { "id": "performance", "label": "Performance", "order": 6 },+ { "id": "other", "label": "Other", "order": 99 }+ ],+ "fields": {+ "motd": { "label": "Server Message (MOTD)", "description": "The message shown in the client's server list.", "group": "general", "type": "string" },+ "difficulty": { "label": "Difficulty", "description": "peaceful, easy, normal, or hard.", "group": "gameplay", "type": "string", "options": ["peaceful", "easy", "normal", "hard"] },+ "gamemode": { "label": "Default Game Mode", "description": "survival, creative, adventure, or spectator.", "group": "gameplay", "type": "string", "options": ["survival", "creative", "adventure", "spectator"] },+ "hardcore": { "label": "Hardcore", "description": "One life; death bans the player.", "group": "gameplay", "type": "boolean" },+ "pvp": { "label": "PvP", "description": "Allow players to damage each other.", "group": "gameplay", "type": "boolean" },+ "level-name": { "label": "World Name", "description": "Folder name of the world save.", "group": "world", "type": "string", "restart_required": true },+ "level-seed": { "label": "World Seed", "description": "Seed for world generation (blank = random). Only affects a fresh world.", "group": "world", "type": "string", "restart_required": true },+ "level-type": { "label": "World Type", "description": "normal, flat, largeBiomes, amplified.", "group": "world", "type": "string", "restart_required": true },+ "generate-structures": { "label": "Generate Structures", "description": "Villages, strongholds, etc.", "group": "world", "type": "boolean" },+ "max-players": { "label": "Max Players", "description": "Maximum simultaneous players.", "group": "players", "type": "integer" },+ "white-list": { "label": "Whitelist", "description": "Only whitelisted players may join.", "group": "players", "type": "boolean" },+ "enforce-whitelist": { "label": "Enforce Whitelist", "description": "Kick non-whitelisted players already online when the whitelist reloads.", "group": "players", "type": "boolean" },+ "online-mode": { "label": "Online Mode", "description": "Verify players against Mojang auth. Turn off ONLY for offline/LAN play.", "group": "players", "type": "boolean", "restart_required": true },+ "spawn-protection": { "label": "Spawn Protection Radius", "description": "Blocks around spawn only ops can modify.", "group": "players", "type": "integer" },+ "server-port": { "label": "Server Port", "description": "TCP port clients connect to (Java).", "group": "network", "type": "integer", "restart_required": true },+ "server-ip": { "label": "Server IP", "description": "Bind address (blank = all interfaces).", "group": "network", "type": "string", "restart_required": true },+ "enable-rcon": { "label": "Enable RCON", "description": "Remote console. ServerKit uses this — leave on.", "group": "network", "type": "boolean", "restart_required": true },+ "view-distance": { "label": "View Distance", "description": "Chunks sent to players. Lower = less CPU/RAM.", "group": "performance", "type": "integer" },+ "simulation-distance": { "label": "Simulation Distance", "description": "Chunks ticked around players.", "group": "performance", "type": "integer" },+ "max-tick-time": { "label": "Max Tick Time (ms)", "description": "Watchdog: crash the server if a tick exceeds this. -1 disables.", "group": "performance", "type": "integer" }+ }+}diff --git a/builtin-extensions/serverkit-minecraft/backend/minecraft.py b/builtin-extensions/serverkit-minecraft/backend/minecraft.pynew file mode 100644index 00000000..287ebb72--- /dev/null+++ b/builtin-extensions/serverkit-minecraft/backend/minecraft.py@@ -0,0 +1,91 @@+"""serverkit-minecraft API blueprint (plan 53).++Exposes the game-server framework (gamekit) over the DB-backed server records.+The create/delete flow (compose generation → DeploymentJob, container+volume+teardown) rides the existing template/Deploy-Console path and is verified on the+dev box with Docker Desktop; those endpoints are marked below. The framework+surface (list/get, RCON proxy, config form, backup) is what gamekit powers.++Routes are mounted at /api/v1/minecraft (manifest url_prefix).+"""+from flask import Blueprint, request, jsonify++from app.plugins_sdk import db, jwt_required, current_user, logger++from .models import MinecraftServer, MinecraftBackup+from . import gamekit++minecraft_bp = Blueprint('minecraft', __name__)+log = logger(__name__)+++def _server_or_404(server_id):+ return MinecraftServer.query.get(server_id)+++@minecraft_bp.route('', methods=['GET'])+@minecraft_bp.route('/', methods=['GET'])+@jwt_required()+def list_servers():+ servers = MinecraftServer.query.order_by(MinecraftServer.created_at.desc()).all()+ return jsonify({'servers': [s.to_dict() for s in servers]})+++@minecraft_bp.route('/<int:server_id>', methods=['GET'])+@jwt_required()+def get_server(server_id):+ server = _server_or_404(server_id)+ if not server:+ return jsonify({'error': 'Server not found'}), 404+ return jsonify(server.to_dict())+++@minecraft_bp.route('/<int:server_id>/rcon', methods=['POST'])+@jwt_required()+def run_rcon(server_id):+ """Proxy a single RCON command to the server (loopback-only, D5).++ The panel talks to RCON server-side; the port is never published. Java+ edition only — Bedrock's default image has no RCON (documented asymmetry).+ """+ user = current_user()+ if not user or not user.is_admin:+ return jsonify({'error': 'Admin access required'}), 403+ server = _server_or_404(server_id)+ if not server:+ return jsonify({'error': 'Server not found'}), 404+ if server.edition == 'bedrock':+ return jsonify({'error': 'RCON is not available for Bedrock servers'}), 400++ cmd = (request.get_json(silent=True) or {}).get('command', '').strip()+ if not cmd:+ return jsonify({'error': 'command required'}), 400++ try:+ with gamekit.rcon.RconClient(+ host='127.0.0.1', port=server.rcon_port or 25575,+ password=server.rcon_password or '') as rc:+ output = rc.command(cmd)+ return jsonify({'command': cmd, 'output': output})+ except gamekit.rcon.RconAuthError:+ return jsonify({'error': 'RCON authentication failed'}), 502+ except gamekit.rcon.RconError as e:+ return jsonify({'error': f'RCON error: {e}'}), 502+++@minecraft_bp.route('/<int:server_id>/backups', methods=['GET'])+@jwt_required()+def list_backups(server_id):+ backups = (MinecraftBackup.query+ .filter_by(server_id=server_id)+ .order_by(MinecraftBackup.created_at.desc()).all())+ return jsonify({'backups': [b.to_dict() for b in backups]})+++# --- Deploy-console flow (dev-box / Docker verified) ------------------------+# POST '' (create → compose → DeploymentJob), DELETE '/<id>' (container+volume+# teardown + firewall cleanup), and lifecycle start/stop/restart with the+# save-before-stop countdown live here in plan 53 Phase 1-2. They shell out to+# docker compose and the firewall service, so they are exercised on the dev box+# with Docker Desktop, not in the offline unit suite — kept out of this scaffold+# until that verification runs, so nothing here claims an unverified Docker path.diff --git a/builtin-extensions/serverkit-minecraft/backend/models.py b/builtin-extensions/serverkit-minecraft/backend/models.pynew file mode 100644index 00000000..f25c2f34--- /dev/null+++ b/builtin-extensions/serverkit-minecraft/backend/models.py@@ -0,0 +1,94 @@+"""Extension-owned data models (plan 53 D6).++Registered via the manifest ``models: "models:register"`` mechanism (the+k8s/tramo pattern): tables are named ``ext_serverkit_minecraft_*`` and created on+install, dropped on uninstall --purge — no core migration. ``register(db)`` is+called by ``extension_lifecycle.register_models`` after this module is imported.++Instances key off a core Application (``application_id``) like any managed+service (D9), so several game servers per box — and later game servers on remote+agents — work without a schema change.+"""+from datetime import datetime++from app import db+++class MinecraftServer(db.Model):+ __tablename__ = 'ext_serverkit_minecraft_servers'+ __table_args__ = {'extend_existing': True}++ id = db.Column(db.Integer, primary_key=True)+ # Soft reference to core applications.id (kept an int, not an FK, so the+ # extension's create_all never depends on core table ordering).+ application_id = db.Column(db.Integer, index=True)++ name = db.Column(db.String(200), nullable=False)+ edition = db.Column(db.String(20), default='java') # java | bedrock+ flavor = db.Column(db.String(20), default='vanilla') # vanilla|paper|fabric|forge+ version = db.Column(db.String(40), default='latest')+ world_name = db.Column(db.String(200), default='world')+ memory = db.Column(db.String(16), default='2G')+ port = db.Column(db.Integer, default=25565)+ rcon_port = db.Column(db.Integer, default=25575)+ rcon_password = db.Column(db.String(128)) # loopback-only (D5)+ eula_accepted = db.Column(db.Boolean, default=False)++ container_name = db.Column(db.String(200))+ status = db.Column(db.String(20), default='creating') # creating|running|stopped|crashed|error+ # Distinguish "stopped by user" from "crashed" for notifications (§3.4).+ stop_requested = db.Column(db.Boolean, default=False)++ created_at = db.Column(db.DateTime, default=datetime.utcnow)+ updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)++ def to_dict(self):+ return {+ 'id': self.id,+ 'application_id': self.application_id,+ 'name': self.name,+ 'edition': self.edition,+ 'flavor': self.flavor,+ 'version': self.version,+ 'world_name': self.world_name,+ 'memory': self.memory,+ 'port': self.port,+ 'status': self.status,+ 'eula_accepted': self.eula_accepted,+ 'created_at': self.created_at.isoformat() if self.created_at else None,+ 'updated_at': self.updated_at.isoformat() if self.updated_at else None,+ }+++class MinecraftBackup(db.Model):+ __tablename__ = 'ext_serverkit_minecraft_backups'+ __table_args__ = {'extend_existing': True}++ id = db.Column(db.Integer, primary_key=True)+ server_id = db.Column(db.Integer, index=True, nullable=False)+ name = db.Column(db.String(255), nullable=False)+ file_path = db.Column(db.String(500))+ size_bytes = db.Column(db.BigInteger, default=0)+ kind = db.Column(db.String(20), default='manual') # manual | scheduled+ created_at = db.Column(db.DateTime, default=datetime.utcnow)++ def to_dict(self):+ return {+ 'id': self.id,+ 'server_id': self.server_id,+ 'name': self.name,+ 'file_path': self.file_path,+ 'size_bytes': self.size_bytes,+ 'kind': self.kind,+ 'created_at': self.created_at.isoformat() if self.created_at else None,+ }+++def register(db): # noqa: ARG001 — signature required by extension_lifecycle+ """Model-registration entry point.++ The models above are defined at import time (so their tables register on the+ metadata); ``extension_lifecycle.register_models`` calls this then runs+ ``create_all``. Nothing more is needed here — kept as the documented seam.+ """+ return [MinecraftServer, MinecraftBackup]diff --git a/builtin-extensions/serverkit-minecraft/plugin.json b/builtin-extensions/serverkit-minecraft/plugin.jsonnew file mode 100644index 00000000..36c449a3--- /dev/null+++ b/builtin-extensions/serverkit-minecraft/plugin.json@@ -0,0 +1,16 @@+{+ "name": "serverkit-minecraft",+ "display_name": "Minecraft Server",+ "version": "0.1.0",+ "description": "Run a Minecraft server for your friends in a few clicks: Java (Vanilla/Paper/Fabric/Forge) and Bedrock, on the standard itzg community images. Live console (RCON), players, save-aware backups, scheduled restarts with in-game warnings, and a 'Share with friends' card. First vertical of the game-server family.",+ "author": "ServerKit",+ "license": "MIT",+ "category": "games",+ "homepage": "https://github.com/jhd3197/ServerKit",+ "permissions": ["docker", "filesystem", "network"],+ "entry_point": "minecraft:minecraft_bp",+ "url_prefix": "/api/v1/minecraft",+ "models": "models:register",+ "sdk_version": "^1.0.0",+ "icon": "<rect x=\"3\" y=\"3\" width=\"7\" height=\"7\" rx=\"1\"/><rect x=\"14\" y=\"3\" width=\"7\" height=\"7\" rx=\"1\"/><rect x=\"3\" y=\"14\" width=\"7\" height=\"7\" rx=\"1\"/><rect x=\"14\" y=\"14\" width=\"7\" height=\"7\" rx=\"1\"/>"+}