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.

refactor(extensions): extract serverkit-minecraft to its own repo

Juan Denise280a446c17e
diff --git a/builtin-extensions/serverkit-minecraft/backend/__init__.py b/builtin-extensions/serverkit-minecraft/backend/__init__.py
deleted file mode 100644
index 46152dcd..00000000
--- a/builtin-extensions/serverkit-minecraft/backend/__init__.py
+++ /dev/null
@@ -1 +0,0 @@
-"""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__.py
deleted file mode 100644
index f8cfb4d9..00000000
--- a/builtin-extensions/serverkit-minecraft/backend/gamekit/__init__.py
+++ /dev/null
@@ -1,17 +0,0 @@
-"""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.py
deleted file mode 100644
index 0c34122e..00000000
--- a/builtin-extensions/serverkit-minecraft/backend/gamekit/config_form.py
+++ /dev/null
@@ -1,119 +0,0 @@
-"""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 result
diff --git a/builtin-extensions/serverkit-minecraft/backend/gamekit/log_events.py b/builtin-extensions/serverkit-minecraft/backend/gamekit/log_events.py
deleted file mode 100644
index 5418df00..00000000
--- a/builtin-extensions/serverkit-minecraft/backend/gamekit/log_events.py
+++ /dev/null
@@ -1,73 +0,0 @@
-"""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 out
diff --git a/builtin-extensions/serverkit-minecraft/backend/gamekit/rcon.py b/builtin-extensions/serverkit-minecraft/backend/gamekit/rcon.py
deleted file mode 100644
index 5f3c3867..00000000
--- a/builtin-extensions/serverkit-minecraft/backend/gamekit/rcon.py
+++ /dev/null
@@ -1,141 +0,0 @@
-"""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 body
diff --git a/builtin-extensions/serverkit-minecraft/backend/gamekit/save_backup.py b/builtin-extensions/serverkit-minecraft/backend/gamekit/save_backup.py
deleted file mode 100644
index 2a4fdc04..00000000
--- a/builtin-extensions/serverkit-minecraft/backend/gamekit/save_backup.py
+++ /dev/null
@@ -1,107 +0,0 @@
-"""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.json
deleted file mode 100644
index 01eb2a6b..00000000
--- a/builtin-extensions/serverkit-minecraft/backend/gamekit/server_properties_meta.json
+++ /dev/null
@@ -1,34 +0,0 @@
-{
- "_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.py
deleted file mode 100644
index 287ebb72..00000000
--- a/builtin-extensions/serverkit-minecraft/backend/minecraft.py
+++ /dev/null
@@ -1,91 +0,0 @@
-"""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.py
deleted file mode 100644
index eb23d9f3..00000000
--- a/builtin-extensions/serverkit-minecraft/backend/models.py
+++ /dev/null
@@ -1,94 +0,0 @@
-"""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)
-
- 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, 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.json
deleted file mode 100644
index 36c449a3..00000000
--- a/builtin-extensions/serverkit-minecraft/plugin.json
+++ /dev/null
@@ -1,16 +0,0 @@
-{
- "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\"/>"
-}