Skip to content

ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.

feat(extensions): Phase 2 backend — remote registry, checksum install, updates

Juan Denis6f5f2b10470a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 94267ed8..d3207483 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -20,6 +20,16 @@ awaiting a stable release:
### Added
+- **Extensions platform (Phase 2 — remote registry & updates)** — the Marketplace
+ Browse tab can now show extensions from a curated remote **registry** (a single
+ `index.json`), merged in and labeled "Registry", with no per-panel seeding. The
+ fetch is offline-tolerant (last-good cache → a bundled fallback index) and
+ cached. Installing from the registry is **checksum-verified** — the downloaded
+ zip's sha256 must match the index before extraction, or the install hard-fails.
+ Panel-version gates (`min_panel_version`/`max_panel_version`) block installs a
+ panel is too old to run. Installed extensions listed in the registry now get an
+ "Update available" badge and a one-click **Update**. Format + publishing guide in
+ [`docs/EXTENSIONS_REGISTRY.md`](docs/EXTENSIONS_REGISTRY.md).
- **Extensions platform (Phase 1 — seed the marketplace)** — the Marketplace is
now genuinely populated. **GPU Monitor** and **Workflow Builder** became bundled
builtin extensions (`serverkit-gpu`, `serverkit-workflows`) — same route, but
diff --git a/backend/app/api/marketplace.py b/backend/app/api/marketplace.py
index b237bacc..21871362 100644
--- a/backend/app/api/marketplace.py
+++ b/backend/app/api/marketplace.py
@@ -29,6 +29,47 @@ def get_categories():
return jsonify({'categories': MarketplaceService.get_categories()})
+@marketplace_bp.route('/registry', methods=['GET'])
+@jwt_required()
+def list_registry():
+ """Return the remote-registry extensions (with live install state), for the
+ Browse merge. Read-only; offline-tolerant (falls back to a bundled index)."""
+ from app.services import registry_service
+ return jsonify({
+ 'extensions': registry_service.list_catalog(),
+ 'source': registry_service.registry_source_label(),
+ })
+
+
+@marketplace_bp.route('/registry/<slug>/install', methods=['POST'])
+@jwt_required()
+def install_registry(slug):
+ """Install a registry extension by slug. Checksum-verified (the entry's
+ sha256, when present, must match before extraction)."""
+ user = get_current_user()
+ if not user or not user.is_admin:
+ return jsonify({'error': 'Admin access required'}), 403
+
+ from app.services.plugin_service import install_registry_extension
+ try:
+ plugin = install_registry_extension(slug, user_id=user.id)
+ AuditService.log(
+ action=AuditLog.ACTION_RESOURCE_CREATE,
+ user_id=user.id,
+ target_type='plugin',
+ target_id=plugin.id,
+ details={'name': plugin.name, 'version': plugin.version, 'source': 'registry'},
+ )
+ return jsonify(plugin.to_dict()), 201
+ except ValueError as e:
+ return jsonify({'error': str(e)}), 400
+ except Exception:
+ import logging, uuid
+ ref = uuid.uuid4().hex[:8]
+ logging.getLogger(__name__).exception('Registry install failed (ref=%s)', ref)
+ return jsonify({'error': 'Installation failed. Check server logs.', 'ref': ref}), 500
+
+
@marketplace_bp.route('/<int:ext_id>', methods=['GET'])
@jwt_required()
def get_extension(ext_id):
diff --git a/backend/app/api/plugins.py b/backend/app/api/plugins.py
index cc79dbe4..e62c43bc 100644
--- a/backend/app/api/plugins.py
+++ b/backend/app/api/plugins.py
@@ -410,6 +410,46 @@ def get_manifest_spec():
})
+@plugins_bp.route('/updates', methods=['GET'])
+@jwt_required()
+def list_updates():
+ """List installed plugins that have a newer version in the registry.
+
+ Each entry: {slug, plugin_id, installed_version, available_version,
+ update_available, compatible, source}.
+ """
+ from app.services.plugin_service import check_for_updates
+ return jsonify({'updates': check_for_updates()})
+
+
+@plugins_bp.route('/<int:plugin_id>/update', methods=['POST'])
+@jwt_required()
+def update_plugin_route(plugin_id):
+ """Update an installed plugin to the registry version (reinstall in place)."""
+ user = get_current_user()
+ if not user or not user.is_admin:
+ return jsonify({'error': 'Admin access required'}), 403
+
+ from app.services.plugin_service import update_plugin
+ try:
+ plugin = update_plugin(plugin_id, user_id=user.id)
+ AuditService.log(
+ action=AuditLog.ACTION_RESOURCE_UPDATE,
+ user_id=user.id,
+ target_type='plugin',
+ target_id=plugin.id,
+ details={'name': plugin.name, 'version': plugin.version, 'source': 'registry-update'},
+ )
+ return jsonify(plugin.to_dict())
+ except ValueError as e:
+ return jsonify({'error': str(e)}), 400
+ except Exception:
+ import logging, uuid
+ ref = uuid.uuid4().hex[:8]
+ logging.getLogger(__name__).exception('Plugin update failed (ref=%s)', ref)
+ return jsonify({'error': 'Update failed. Check server logs.', 'ref': ref}), 500
+
+
@plugins_bp.route('/contributions', methods=['GET'])
@jwt_required()
def get_contributions():
diff --git a/backend/app/data/registry_index.json b/backend/app/data/registry_index.json
new file mode 100644
index 00000000..8b76c630
--- /dev/null
+++ b/backend/app/data/registry_index.json
@@ -0,0 +1,24 @@
+{
+ "schema_version": 1,
+ "updated": "2026-07-01",
+ "note": "Bundled fallback copy of the ServerKit extension registry index. The live index is fetched from SERVERKIT_REGISTRY_URL when configured; this file is used offline and in tests. Curated via PR in the serverkit-extensions repo.",
+ "extensions": [
+ {
+ "slug": "serverkit-gui",
+ "display_name": "ServerKit Agent GUI",
+ "description": "Agent-powered desktop view for managed servers. Streams live screenshots when available, with a synthetic desktop fallback for headless hosts.",
+ "version": "0.1.0",
+ "category": "monitoring",
+ "author": "Juan Denis",
+ "first_party": false,
+ "permissions": ["agent.command:gui:screenshot", "agent.command:gui:capabilities"],
+ "min_panel_version": "1.7.0",
+ "max_panel_version": null,
+ "source": "https://github.com/jhd3197/serverkit-gui",
+ "sha256": null,
+ "homepage": "https://github.com/jhd3197/serverkit-gui",
+ "icon": "<rect x=\"2\" y=\"3\" width=\"20\" height=\"14\" rx=\"2\"/><line x1=\"8\" y1=\"21\" x2=\"16\" y2=\"21\"/><line x1=\"12\" y1=\"17\" x2=\"12\" y2=\"21\"/>",
+ "screenshots": []
+ }
+ ]
+}
diff --git a/backend/app/services/plugin_service.py b/backend/app/services/plugin_service.py
index 0a20dffd..4a93bd60 100644
--- a/backend/app/services/plugin_service.py
+++ b/backend/app/services/plugin_service.py
@@ -232,12 +232,15 @@ def _update_plugin_metadata(plugin, manifest):
plugin.category = manifest.get('category', 'utility')
-def install_from_url(url, user_id=None):
+def install_from_url(url, user_id=None, expected_sha256=None, force=False):
"""Download and install a plugin from a URL.
Args:
url: GitHub repo URL, release URL, or direct zip URL
user_id: ID of the user performing the install
+ expected_sha256: if given, the downloaded zip must match this digest
+ before extraction — a mismatch is a hard failure (no partial install)
+ force: allow reinstalling over an already-active plugin (used by updates)
Returns:
InstalledPlugin instance
@@ -247,8 +250,18 @@ def install_from_url(url, user_id=None):
except Exception as e:
raise ValueError(f'Failed to download plugin: {e}')
+ if expected_sha256:
+ import hashlib
+ digest = hashlib.sha256(buf.getvalue()).hexdigest()
+ if digest.lower() != str(expected_sha256).lower():
+ raise ValueError(
+ f'Checksum mismatch — refusing to install. '
+ f'Expected sha256 {expected_sha256}, got {digest}.'
+ )
+ buf.seek(0)
+
return _install_from_buffer(
- buf, source_url=url, source_type='url', user_id=user_id,
+ buf, source_url=url, source_type='url', user_id=user_id, force=force,
)
@@ -333,11 +346,14 @@ def install_from_zip(zip_bytes, user_id=None, source_name=None):
)
-def _install_from_buffer(buf, source_url, source_type, user_id=None):
+def _install_from_buffer(buf, source_url, source_type, user_id=None, force=False):
"""Shared install pipeline: takes a seekable BytesIO containing a zip,
extracts it into the panel's plugin dirs, and registers / hot-loads
the resulting blueprint. All public install_* helpers funnel here so
behavior matches across URL / local / upload sources.
+
+ `force=True` allows reinstalling over an active plugin (the update path);
+ normal installs still refuse to clobber an active install.
"""
_ensure_dirs()
@@ -359,7 +375,7 @@ def _install_from_buffer(buf, source_url, source_type, user_id=None):
# Check if already installed
existing = InstalledPlugin.query.filter_by(slug=slug).first()
- if existing and existing.status in ('active', 'installing'):
+ if existing and existing.status in ('active', 'installing') and not force:
raise ValueError(f"Plugin '{slug}' is already installed (v{existing.version}). Uninstall first to reinstall.")
# Create DB record early so we can track errors
@@ -947,3 +963,82 @@ def install_builtin_extension(slug, user_id=None):
return install_from_path(entry['path'], user_id=user_id)
raise ValueError(f"No builtin extension with slug '{slug}'")
+
+
+def _assert_panel_compatible(entry):
+ """Raise if the panel version is outside an entry's min/max_panel_version."""
+ from app.utils.version import version_satisfies, get_panel_version
+ panel = get_panel_version()
+ minv = entry.get('min_panel_version')
+ maxv = entry.get('max_panel_version')
+ if not version_satisfies(panel, minv, maxv):
+ raise ValueError(
+ f"{entry.get('display_name') or entry.get('slug')} "
+ f"v{entry.get('version')} needs panel "
+ f"{minv or '*'}–{maxv or '*'} (this panel is {panel})."
+ )
+
+
+def install_registry_extension(slug, user_id=None):
+ """Install an extension listed in the remote registry (checksum-verified)."""
+ from app.services import registry_service
+ entry = registry_service.get_entry(slug)
+ if not entry:
+ raise ValueError(f"No registry extension with slug '{slug}'")
+ _assert_panel_compatible(entry)
+ source = (entry.get('source') or '').strip()
+ if not source:
+ raise ValueError(f"Registry entry '{slug}' has no source URL.")
+ return install_from_url(
+ source, user_id=user_id, expected_sha256=entry.get('sha256'),
+ )
+
+
+def check_for_updates():
+ """Compare installed plugins to the registry; return update candidates.
+
+ Update v1 is registry-driven: a plugin whose slug is in the registry with a
+ higher version than installed is flagged. Panel-version compatibility is
+ surfaced so the UI can gray out an update the panel can't run yet.
+ """
+ from app.services import registry_service
+ from app.utils.version import compare_versions, version_satisfies, get_panel_version
+ panel = get_panel_version()
+ out = []
+ for p in InstalledPlugin.query.all():
+ entry = registry_service.get_entry(p.slug)
+ if not entry:
+ continue
+ available = entry.get('version')
+ out.append({
+ 'slug': p.slug,
+ 'plugin_id': p.id,
+ 'installed_version': p.version,
+ 'available_version': available,
+ 'update_available': compare_versions(available, p.version) > 0,
+ 'compatible': version_satisfies(
+ panel, entry.get('min_panel_version'), entry.get('max_panel_version')
+ ),
+ 'source': entry.get('source'),
+ })
+ return out
+
+
+def update_plugin(plugin_id, user_id=None):
+ """Update an installed plugin to the registry's version (reinstall in place)."""
+ from app.services import registry_service
+ plugin = InstalledPlugin.query.get(plugin_id)
+ if not plugin:
+ raise ValueError('Plugin not found')
+ entry = registry_service.get_entry(plugin.slug)
+ if not entry:
+ raise ValueError(
+ f"No registry entry for '{plugin.slug}' — cannot update from the registry."
+ )
+ _assert_panel_compatible(entry)
+ source = (entry.get('source') or '').strip()
+ if not source:
+ raise ValueError('Registry entry has no source URL.')
+ return install_from_url(
+ source, user_id=user_id, expected_sha256=entry.get('sha256'), force=True,
+ )
diff --git a/backend/app/services/registry_service.py b/backend/app/services/registry_service.py
new file mode 100644
index 00000000..07f57696
--- /dev/null
+++ b/backend/app/services/registry_service.py
@@ -0,0 +1,162 @@
+"""Remote extension registry (Phase 2).
+
+The registry is a single curated `index.json` (hosted in a `serverkit-extensions`
+repo, submitted via PR). It lists third-party + first-party extensions that aren't
+bundled with the panel, so the Marketplace Browse tab has real content without any
+DB seeding.
+
+Design rules:
+ - Read-only discovery. NOTHING here ever auto-installs; installs are explicit.
+ - Offline-tolerant. A failed/absent fetch falls back to the last good cache, then
+ to a bundled copy (app/data/registry_index.json) — the Marketplace never blanks.
+ - Configurable. SERVERKIT_REGISTRY_URL points at the live index; unset ⇒ bundled.
+"""
+import json
+import logging
+import os
+import time
+
+import requests
+
+from app.models.plugin import InstalledPlugin
+
+logger = logging.getLogger(__name__)
+
+_BUNDLED_INDEX = os.path.join(
+ os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'data', 'registry_index.json'
+)
+
+REGISTRY_URL = os.environ.get('SERVERKIT_REGISTRY_URL', '').strip()
+try:
+ _TTL = int(os.environ.get('SERVERKIT_REGISTRY_TTL', '3600'))
+except ValueError:
+ _TTL = 3600
+
+# Module-level cache: last successfully-parsed entry list + when we fetched it.
+_cache = {'ts': 0.0, 'entries': None, 'source': None}
+
+# Fields we surface for a registry entry, with defaults.
+_FIELDS = {
+ 'slug': '',
+ 'display_name': '',
+ 'description': '',
+ 'version': '0.0.0',
+ 'category': 'utility',
+ 'author': '',
+ 'first_party': False,
+ 'permissions': [],
+ 'min_panel_version': None,
+ 'max_panel_version': None,
+ 'source': '',
+ 'sha256': None,
+ 'homepage': '',
+ 'icon': None,
+ 'screenshots': [],
+}
+
+
+def _normalize(raw):
+ if not isinstance(raw, dict) or not raw.get('slug'):
+ return None
+ out = {}
+ for key, default in _FIELDS.items():
+ out[key] = raw.get(key, default)
+ if not isinstance(out['permissions'], list):
+ out['permissions'] = []
+ if not isinstance(out['screenshots'], list):
+ out['screenshots'] = []
+ return out
+
+
+def _read_index_payload(payload):
+ exts = payload.get('extensions') if isinstance(payload, dict) else None
+ if not isinstance(exts, list):
+ return []
+ return [e for e in (_normalize(x) for x in exts) if e]
+
+
+def _load_bundled():
+ try:
+ with open(_BUNDLED_INDEX, 'r', encoding='utf-8') as f:
+ return _read_index_payload(json.load(f))
+ except Exception as e:
+ logger.warning(f'Could not read bundled registry index: {e}')
+ return []
+
+
+def _fetch_remote():
+ if not REGISTRY_URL:
+ return None
+ resp = requests.get(REGISTRY_URL, timeout=15, headers={
+ 'Accept': 'application/json',
+ 'User-Agent': 'ServerKit-Registry/1.0',
+ })
+ resp.raise_for_status()
+ return _read_index_payload(resp.json())
+
+
+def refresh(force=False):
+ """Return the registry entries, refreshing from the remote index when the
+ cache is stale. Never raises — falls back to cache, then bundled copy."""
+ now = time.time()
+ if not force and _cache['entries'] is not None and (now - _cache['ts']) < _TTL:
+ return _cache['entries']
+
+ entries = None
+ source = None
+ try:
+ entries = _fetch_remote()
+ if entries is not None:
+ source = 'remote'
+ except Exception as e:
+ logger.warning(f'Registry fetch failed ({REGISTRY_URL}): {e}')
+
+ if entries is None:
+ # Keep the last good remote cache if we have one; else bundled.
+ if _cache['entries'] is not None:
+ return _cache['entries']
+ entries = _load_bundled()
+ source = 'bundled'
+
+ _cache['entries'] = entries
+ _cache['ts'] = now
+ _cache['source'] = source
+ return entries
+
+
+def list_extensions():
+ return refresh()
+
+
+def get_entry(slug):
+ for e in refresh():
+ if e['slug'] == slug:
+ return e
+ return None
+
+
+def _install_state(slug):
+ p = InstalledPlugin.query.filter_by(slug=slug).first()
+ if not p:
+ return {'installed': False, 'status': 'not_installed', 'installed_version': None}
+ return {
+ 'installed': True,
+ 'status': p.status,
+ 'installed_version': p.version,
+ }
+
+
+def to_catalog_dict(entry):
+ """Registry entry + live install state, for the Marketplace Browse merge."""
+ d = dict(entry)
+ d.update(_install_state(entry['slug']))
+ d['source_kind'] = 'registry'
+ return d
+
+
+def list_catalog():
+ return [to_catalog_dict(e) for e in refresh()]
+
+
+def registry_source_label():
+ return _cache.get('source')
diff --git a/backend/app/utils/version.py b/backend/app/utils/version.py
new file mode 100644
index 00000000..d23af1ef
--- /dev/null
+++ b/backend/app/utils/version.py
@@ -0,0 +1,87 @@
+"""Panel version helpers.
+
+Single source for "what version is this panel" plus semver-ish comparison used by
+extension compatibility gates (min_panel_version / max_panel_version) and the
+update flow. The version string lives in the repo-root VERSION file.
+"""
+import os
+import logging
+
+logger = logging.getLogger(__name__)
+
+_cached_version = None
+
+
+def get_panel_version():
+ """Return the panel version from the VERSION file, or '0.0.0' if unknown.
+
+ Cached after first read (the file doesn't change while the process runs).
+ """
+ global _cached_version
+ if _cached_version is not None:
+ return _cached_version
+
+ here = os.path.dirname(os.path.abspath(__file__)) # backend/app/utils
+ backend_root = os.path.dirname(os.path.dirname(here)) # backend/
+ candidates = [
+ '/opt/serverkit/VERSION',
+ os.path.join(backend_root, '..', 'VERSION'),
+ os.path.join(backend_root, 'VERSION'),
+ ]
+ version = '0.0.0'
+ for path in candidates:
+ try:
+ if os.path.exists(path):
+ with open(path, 'r', encoding='utf-8') as f:
+ version = f.read().strip() or version
+ break
+ except Exception:
+ pass
+ _cached_version = version
+ return version
+
+
+def _parse(v):
+ """Best-effort parse into a comparable object. Uses packaging when possible,
+ falling back to a tuple of leading integer components."""
+ if not v:
+ return None
+ try:
+ from packaging.version import Version
+ return Version(str(v))
+ except Exception:
+ parts = []
+ for chunk in str(v).split('.'):
+ num = ''.join(ch for ch in chunk if ch.isdigit())
+ parts.append(int(num) if num else 0)
+ return tuple(parts) if parts else None
+
+
+def compare_versions(a, b):
+ """Return -1/0/1 for a<b / a==b / a>b. Unparseable values sort as equal."""
+ pa, pb = _parse(a), _parse(b)
+ if pa is None or pb is None:
+ return 0
+ try:
+ if pa < pb:
+ return -1
+ if pa > pb:
+ return 1
+ return 0
+ except TypeError:
+ return 0
+
+
+def version_satisfies(current, min_version=None, max_version=None):
+ """True if `current` is within [min_version, max_version] (inclusive).
+
+ Missing bounds are open. Unparseable bounds are ignored (fail open) so a
+ malformed manifest never hard-blocks an install for the wrong reason.
+ """
+ if min_version and _parse(min_version) is not None:
+ if compare_versions(current, min_version) < 0:
+ return False
+ if max_version and _parse(max_version) is not None:
+ if compare_versions(current, max_version) > 0:
+ return False
+ return True
diff --git a/backend/tests/test_registry.py b/backend/tests/test_registry.py
new file mode 100644
index 00000000..a7f7da44
--- /dev/null
+++ b/backend/tests/test_registry.py
@@ -0,0 +1,153 @@
+"""Registry fetch/cache, checksum-verified install, version gates, update flow."""
+import hashlib
+import io
+import json
+import zipfile
+
+import pytest
+
+from app import db
+from app.models.plugin import InstalledPlugin
+from app.services import plugin_service, registry_service
+from app.utils import version as version_util
+
+
[email protected](autouse=True)
+def _reset_registry_cache():
+ registry_service._cache.update({'ts': 0.0, 'entries': None, 'source': None})
+ yield
+ registry_service._cache.update({'ts': 0.0, 'entries': None, 'source': None})
+
+
+def plugin_dirs(tmp_path, monkeypatch):
+ backend = tmp_path / 'b'
+ frontend = tmp_path / 'f'
+ for d in (backend, frontend):
+ d.mkdir()
+ monkeypatch.setattr(plugin_service, 'BACKEND_PLUGINS_DIR', str(backend))
+ monkeypatch.setattr(plugin_service, 'FRONTEND_PLUGINS_DIR', str(frontend))
+ return {'backend': backend, 'frontend': frontend}
+
+
+def _make_plugin_zip(slug='regext', version='2.0.0'):
+ """A minimal, valid backend-less plugin zip (frontend-only)."""
+ manifest = {
+ 'name': slug, 'display_name': 'Registry Ext', 'version': version,
+ 'category': 'utility',
+ 'contributions': {'nav': [{'id': slug, 'label': 'Reg', 'route': '/reg'}]},
+ }
+ buf = io.BytesIO()
+ with zipfile.ZipFile(buf, 'w') as zf:
+ zf.writestr('plugin.json', json.dumps(manifest))
+ zf.writestr('frontend/index.jsx', 'export function P(){return null;}\n')
+ return buf.getvalue()
+
+
+# --------------------------------------------------------------------------- #
+# Registry fetch / cache (offline-tolerant → bundled fallback)
+# --------------------------------------------------------------------------- #
+
+def test_bundled_registry_lists_serverkit_gui(app):
+ # No SERVERKIT_REGISTRY_URL in tests → bundled index is used.
+ entries = registry_service.list_extensions()
+ slugs = {e['slug'] for e in entries}
+ assert 'serverkit-gui' in slugs
+ assert registry_service.registry_source_label() == 'bundled'
+
+
+def test_registry_catalog_carries_install_state(app):
+ catalog = registry_service.list_catalog()
+ gui = next(e for e in catalog if e['slug'] == 'serverkit-gui')
+ assert gui['installed'] is False
+ assert gui['status'] == 'not_installed'
+ assert gui['source_kind'] == 'registry'
+
+
+def test_registry_endpoint(app, client, auth_headers):
+ resp = client.get('/api/v1/marketplace/registry', headers=auth_headers)
+ assert resp.status_code == 200
+ data = resp.get_json()
+ assert any(e['slug'] == 'serverkit-gui' for e in data['extensions'])
+
+
+# --------------------------------------------------------------------------- #
+# Version helpers + compat gates
+# --------------------------------------------------------------------------- #
+
+def test_version_helpers():
+ assert version_util.compare_versions('2.0.0', '1.9.9') == 1
+ assert version_util.compare_versions('1.0.0', '1.0.0') == 0
+ assert version_util.version_satisfies('1.7.5', min_version='1.7.0') is True
+ assert version_util.version_satisfies('1.6.0', min_version='1.7.0') is False
+ assert version_util.version_satisfies('2.5.0', max_version='2.0.0') is False
+
+
+def test_registry_install_blocked_by_min_panel_version(app, plugin_dirs, monkeypatch):
+ monkeypatch.setattr(registry_service, '_cache', {
+ 'ts': 9e18, 'source': 'test',
+ 'entries': [registry_service._normalize({
+ 'slug': 'future-ext', 'display_name': 'Future', 'version': '1.0.0',
+ 'source': 'https://example.com/x.zip', 'min_panel_version': '999.0.0',
+ })],
+ })
+ with pytest.raises(ValueError, match='needs panel'):
+ plugin_service.install_registry_extension('future-ext')
+
+
+# --------------------------------------------------------------------------- #
+# Checksum-verified install
+# --------------------------------------------------------------------------- #
+
+def test_checksum_mismatch_rejected(app, plugin_dirs, monkeypatch):
+ zip_bytes = _make_plugin_zip()
+ monkeypatch.setattr(plugin_service, '_download_zip', lambda url: io.BytesIO(zip_bytes))
+
+ with pytest.raises(ValueError, match='Checksum mismatch'):
+ plugin_service.install_from_url('https://x/y.zip', expected_sha256='deadbeef')
+
+ # Nothing was installed.
+ assert InstalledPlugin.query.filter_by(slug='regext').first() is None
+
+
+def test_checksum_match_installs(app, plugin_dirs, monkeypatch):
+ zip_bytes = _make_plugin_zip()
+ digest = hashlib.sha256(zip_bytes).hexdigest()
+ monkeypatch.setattr(plugin_service, '_download_zip', lambda url: io.BytesIO(zip_bytes))
+
+ plugin = plugin_service.install_from_url('https://x/y.zip', expected_sha256=digest)
+ assert plugin.status == InstalledPlugin.STATUS_ACTIVE
+ assert plugin.version == '2.0.0'
+
+
+# --------------------------------------------------------------------------- #
+# Update flow
+# --------------------------------------------------------------------------- #
+
+def test_update_flow(app, plugin_dirs, monkeypatch):
+ # Install v1.0.0 first.
+ v1 = _make_plugin_zip(slug='regext', version='1.0.0')
+ monkeypatch.setattr(plugin_service, '_download_zip', lambda url: io.BytesIO(v1))
+ plugin = plugin_service.install_from_url('https://x/regext.zip')
+ assert plugin.version == '1.0.0'
+
+ # Registry advertises v2.0.0 for the same slug.
+ monkeypatch.setattr(registry_service, '_cache', {
+ 'ts': 9e18, 'source': 'test',
+ 'entries': [registry_service._normalize({
+ 'slug': 'regext', 'display_name': 'Registry Ext', 'version': '2.0.0',
+ 'source': 'https://x/regext.zip', 'min_panel_version': '0.0.1',
+ })],
+ })
+
+ updates = {u['slug']: u for u in plugin_service.check_for_updates()}
+ assert updates['regext']['update_available'] is True
+ assert updates['regext']['available_version'] == '2.0.0'
+ assert updates['regext']['compatible'] is True
+
+ # Serve v2 bytes and run the update (reinstall over active → force).
+ v2 = _make_plugin_zip(slug='regext', version='2.0.0')
+ monkeypatch.setattr(plugin_service, '_download_zip', lambda url: io.BytesIO(v2))
+ updated = plugin_service.update_plugin(plugin.id)
+ assert updated.version == '2.0.0'
+ assert InstalledPlugin.query.filter_by(slug='regext').count() == 1
diff --git a/docs/EXTENSIONS.md b/docs/EXTENSIONS.md
index 9cdee29f..ef827245 100644
--- a/docs/EXTENSIONS.md
+++ b/docs/EXTENSIONS.md
@@ -277,7 +277,7 @@ Tools are namespaced `<slug>__<name>`, RBAC-gated per tool, and write tools
| GitHub / release / zip URL | Paste a URL | `POST /api/v1/plugins/install` |
| Uploaded zip | Upload (≤ 50 MB) | `POST /api/v1/plugins/install-upload` |
| Local path (dev) | Panel-host path | `POST /api/v1/plugins/install-local` |
-| Registry | Curated index (checksum-verified) | via Marketplace Browse |
+| Registry | Curated index (checksum-verified) — see [EXTENSIONS_REGISTRY.md](EXTENSIONS_REGISTRY.md) | via Marketplace Browse |
All sources funnel through one install pipeline (`_install_from_buffer`) so
behavior is identical. Zip-slip is rejected (absolute paths, `..`, escaping
diff --git a/docs/EXTENSIONS_REGISTRY.md b/docs/EXTENSIONS_REGISTRY.md
new file mode 100644
index 00000000..36bb552c
--- /dev/null
+++ b/docs/EXTENSIONS_REGISTRY.md
@@ -0,0 +1,104 @@
+# Extension Registry & Publishing
+
+The **registry** is how third-party (and non-bundled first-party) extensions
+become browsable in the Marketplace without any per-panel seeding. It is a single
+curated `index.json`; panels fetch it, merge its entries into Browse labeled
+"Registry", and install from it with checksum verification.
+
+This document is the format spec (task #16) and the publisher guide (task #21).
+
+---
+
+## How a panel consumes the registry
+
+- The panel fetches the index from `SERVERKIT_REGISTRY_URL` (env var). When unset,
+ or when the fetch fails (offline), it falls back to the **last good cache**, then
+ to a **bundled copy** shipped at `backend/app/data/registry_index.json`. The
+ Marketplace never blanks.
+- Results are cached in-memory for `SERVERKIT_REGISTRY_TTL` seconds (default 3600).
+- Discovery is **read-only** — nothing in the registry is ever auto-installed.
+- Installing a registry entry downloads its `source`, verifies `sha256` (when
+ present) before extraction, and checks the panel version against
+ `min_panel_version` / `max_panel_version`.
+
+Relevant endpoints:
+
+| Endpoint | Purpose |
+|---|---|
+| `GET /api/v1/marketplace/registry` | list registry entries + live install state |
+| `POST /api/v1/marketplace/registry/<slug>/install` | checksum-verified install (admin) |
+| `GET /api/v1/plugins/updates` | installed plugins with a newer registry version |
+| `POST /api/v1/plugins/<id>/update` | update a plugin to the registry version (admin) |
+
+---
+
+## `index.json` format (schema_version 1)
+
+```jsonc
+{
+ "schema_version": 1,
+ "updated": "2026-07-01",
+ "extensions": [
+ {
+ "slug": "serverkit-gui", // required — matches the manifest name
+ "display_name": "ServerKit Agent GUI", // required
+ "description": "…",
+ "version": "0.1.0", // required — the published version
+ "category": "monitoring", // ai|monitoring|security|deployment|integration|ui|utility
+ "author": "Juan Denis",
+ "first_party": false, // true only for ServerKit-authored entries
+ "permissions": ["network"], // declared host permissions (honesty is reviewed)
+ "min_panel_version": "1.7.0", // optional compat gate (inclusive)
+ "max_panel_version": null, // optional
+ "source": "https://github.com/owner/repo", // repo URL (latest release), release URL, or direct .zip
+ "sha256": "…", // sha256 of the release zip — STRONGLY recommended
+ "homepage": "https://…",
+ "icon": "<svg-inner-markup/>", // rendered on the detail view
+ "screenshots": ["https://…/1.png"] // rendered on the detail view
+ }
+ ]
+}
+```
+
+Notes:
+- `source` accepts the same forms as a URL install: a GitHub repo URL (resolves the
+ latest release asset), a release-tag URL, or a direct `.zip` URL.
+- `sha256` is the digest of the exact zip `source` resolves to. When present it is
+ **enforced** — a mismatch is a hard failure with no partial install. Omit only
+ while prototyping.
+- `min_panel_version`/`max_panel_version` are compared against the panel's
+ `VERSION`. An incompatible entry can be listed but not installed/updated.
+
+---
+
+## Publishing an extension
+
+1. **Structure the repo** per [`docs/EXTENSIONS.md`](EXTENSIONS.md): a `plugin.json`
+ at the archive root, plus `backend/` and/or `frontend/`. Remember the production
+ frontend constraint — a third-party extension that ships a frontend won't render
+ on a prebuilt panel until the Phase 3 delivery mechanism lands, so ship
+ backend-only (or a `bare`/custom-layout escape hatch) for now.
+
+2. **Cut a release.** Tag a version and attach a plugin `.zip` as a release asset
+ (the installer prefers a `.zip` asset over the source zipball). Record the
+ asset's `sha256`:
+ ```bash
+ sha256sum my-extension-0.1.0.zip
+ ```
+
+3. **Submit the index PR.** Open a PR against the `serverkit-extensions` repo adding
+ (or bumping) your entry in `index.json`. Bumping `version` is what surfaces the
+ "Update available" badge on installed panels.
+
+### Review checklist (what a maintainer verifies)
+
+- **Permissions honesty** — declared `permissions` match what the code actually
+ uses (`docker|filesystem|shell|network|db`, or `agent.command:*`). Over-broad or
+ undeclared permissions are rejected. Enforcement (Phase 3 #25) makes an
+ undeclared capability raise at runtime — declare accurately.
+- **Checksum** — `sha256` present and matches the release asset.
+- **License** — a real OSS license (`license` field + a LICENSE in the repo).
+- **Compat** — `min_panel_version` reflects the oldest panel actually tested.
+- **Brand-neutral** — no competitor names in the name/description (project policy).
+
+Free/OSS project: there are **no paid extensions, quotas, or billing** — ever.