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(plugins): GitHub-native install with preview + permissions consent
Juan Denisbd6b8eff3330
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex d9ec6632..39c2fb4b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -20,6 +20,16 @@ awaiting a stable release:### Added+- **Install extensions straight from GitHub, with a preview + consent step** —+ the manual-install URL flow is now two-step: paste a repo (`owner/repo`,+ `owner/repo@tag`, a release URL, or a direct `.zip`), **Preview** resolves and+ reads the extension, then a consent card shows its version, declared+ permissions, panel-version compatibility, and warnings (no release found,+ slug already installed, version-gate mismatch) before you install. The install+ is pinned to the exact previewed bytes via sha256. A new+ `POST /api/v1/plugins/preview` endpoint powers it. Set the optional+ `SERVERKIT_GITHUB_TOKEN` to lift GitHub's anonymous rate limit and install+ from private repos (the token is only ever sent to GitHub, never logged).- **Public extension index (registry v2)** — the extension registry schema gainsoptional `logo`, `repo`, and `bundled` fields (additive; v1 entries stayvalid). The Marketplace now surfaces extension logos (shown first in the artdiff --git a/backend/app/api/plugins.py b/backend/app/api/plugins.pyindex 00026fe9..183cfc29 100644--- a/backend/app/api/plugins.py+++ b/backend/app/api/plugins.py@@ -66,9 +66,13 @@ def install_plugin():if not url:return jsonify({'error': 'url cannot be empty'}), 400+ # Optional checksum continuity: the preview step returns the resolved URL ++ # sha256; passing them here pins the install to the exact previewed bytes.+ expected_sha256 = (data.get('sha256') or None)+from app.services.plugin_service import install_from_urltry:- plugin = install_from_url(url, user_id=user.id)+ plugin = install_from_url(url, user_id=user.id, expected_sha256=expected_sha256)AuditService.log(action=AuditLog.ACTION_RESOURCE_CREATE,user_id=user.id,@@ -95,6 +99,44 @@ def install_plugin():}), 500+@plugins_bp.route('/preview', methods=['POST'])+@jwt_required()+def preview_plugin():+ """Preview a GitHub/zip extension WITHOUT installing it.++ Body: { "url": "owner/repo" | "owner/repo@tag" | "https://github.com/..." | ".zip URL" }++ Resolves the source, downloads it, reads plugin.json, and returns the+ metadata a user consents to (slug, version, permissions, panel-version gate)+ plus the resolved download URL, its sha256, and any warnings — so the UI can+ show a consent card before the install re-downloads the exact same bytes.+ """+ user = get_current_user()+ if not user or not user.is_admin:+ return jsonify({'error': 'Admin access required'}), 403++ data = request.get_json() or {}+ url = (data.get('url') or '').strip()+ if not url:+ return jsonify({'error': 'url required'}), 400++ from app.services.plugin_service import preview_from_url+ try:+ return jsonify(preview_from_url(url))+ except ValueError as e:+ # GitHubResolveError is a ValueError subclass — its message is already+ # user-actionable (rate limit / 404 / private / no plugin.json).+ return jsonify({'error': str(e)}), 400+ except Exception:+ import logging, uuid+ ref = uuid.uuid4().hex[:8]+ logging.getLogger(__name__).exception('Plugin preview failed (ref=%s)', ref)+ return jsonify({+ 'error': 'Preview failed. Check server logs.',+ 'ref': ref,+ }), 500++@plugins_bp.route('/install-local', methods=['POST'])@jwt_required()def install_plugin_local():diff --git a/backend/app/services/plugin_service.py b/backend/app/services/plugin_service.pyindex d97fc62e..781953d7 100644--- a/backend/app/services/plugin_service.py+++ b/backend/app/services/plugin_service.py@@ -147,13 +147,59 @@ def _ensure_dirs():_ensure_backend_dir()-def _resolve_github_url(url):+def _github_token():+ """Optional GitHub token (SERVERKIT_GITHUB_TOKEN). Lifts the 60/hr anonymous+ rate limit and enables private-repo installs. Never logged or echoed back."""+ return (os.environ.get('SERVERKIT_GITHUB_TOKEN') or '').strip()+++def _is_github_host(url):+ """True for github.com / api.github.com / codeload.github.com URLs — the only+ hosts the token is ever attached to (never leak it to third-party mirrors)."""+ return bool(re.match(r'^https?://(?:[a-z0-9-]+\.)?github\.com/', url or '', re.I))+++def _github_api_headers(accept='application/vnd.github+json'):+ headers = {'Accept': accept, 'User-Agent': 'ServerKit-Plugin-Installer/1.0'}+ token = _github_token()+ if token:+ headers['Authorization'] = f'Bearer {token}'+ return headers+++class GitHubResolveError(ValueError):+ """Actionable failure resolving a GitHub URL (rate limit, 404, private)."""+++def _normalize_source_url(url):+ """Accept `owner/repo` and `owner/repo@tag` shorthand, normalizing to a+ github.com URL. Full URLs and direct .zip links pass through unchanged."""+ if not url:+ return url+ u = url.strip()+ if u.startswith('http://') or u.startswith('https://') or u.endswith('.zip'):+ return u+ m = re.match(r'^([A-Za-z0-9_.-]+)/([A-Za-z0-9_.-]+?)(?:@(.+))?$', u)+ if not m:+ return u+ owner, repo, tag = m.groups()+ if tag:+ return f'https://github.com/{owner}/{repo}/releases/tag/{tag}'+ return f'https://github.com/{owner}/{repo}'+++def _resolve_github_url(url, strict=False):"""Convert a GitHub repo URL to the latest release zip download URL.Handles:- https://github.com/user/repo -> latest release zip- https://github.com/user/repo/releases/tag/v1.0.0 -> that release zip- Direct zip URLs pass through unchanged++ When ``strict`` is False (installs) any API hiccup silently falls back to the+ default-branch/tag zipball. When ``strict`` is True (preview) failures raise+ :class:`GitHubResolveError` with an actionable message, and a+ ``.used_zipball_fallback`` flag records whether no release asset was found."""if url.endswith('.zip'):return url@@ -176,7 +222,9 @@ def _resolve_github_url(url):api_url = f'https://api.github.com/repos/{owner}/{repo}/releases/latest'try:- resp = requests.get(api_url, timeout=15, headers={'Accept': 'application/vnd.github+json'})+ resp = requests.get(api_url, timeout=15, headers=_github_api_headers())+ if strict:+ _raise_for_github_status(resp, owner, repo)resp.raise_for_status()release = resp.json()@@ -185,24 +233,76 @@ def _resolve_github_url(url):if asset['name'].endswith('.zip'):return asset['browser_download_url']- # Fallback to source zipball- return release.get('zipball_url', url)+ # No .zip asset — fall back to source zipball (default branch of the tag).+ zipball = release.get('zipball_url') or (+ f'https://api.github.com/repos/{owner}/{repo}/zipball/{tag}' if tag+ else f'https://api.github.com/repos/{owner}/{repo}/zipball')+ _mark_zipball_fallback(zipball)+ return zipball+ except GitHubResolveError:+ raiseexcept Exception as e:logger.warning(f'Could not resolve GitHub release URL: {e}')- # Fallback: try the zipball endpoint directly- if tag:- return f'https://api.github.com/repos/{owner}/{repo}/zipball/{tag}'- return f'https://api.github.com/repos/{owner}/{repo}/zipball'+ # Fallback: try the zipball endpoint directly (no release published).+ zipball = (f'https://api.github.com/repos/{owner}/{repo}/zipball/{tag}' if tag+ else f'https://api.github.com/repos/{owner}/{repo}/zipball')+ _mark_zipball_fallback(zipball)+ return zipball+++# Records the most recent resolution's zipball fallback so the preview flow can+# warn "no release found (installing the default-branch zipball)". Only read+# immediately after a _resolve_github_url call.+_LAST_RESOLUTION = {'zipball_fallback': False}+++def _mark_zipball_fallback(_url):+ _LAST_RESOLUTION['zipball_fallback'] = True+++def _raise_for_github_status(resp, owner, repo):+ """Turn a GitHub API error response into an actionable GitHubResolveError."""+ if resp.status_code == 200:+ _LAST_RESOLUTION['zipball_fallback'] = False+ return+ if resp.status_code == 403 and resp.headers.get('X-RateLimit-Remaining') == '0':+ reset = resp.headers.get('X-RateLimit-Reset')+ mins = ''+ try:+ import time as _t+ if reset:+ mins = f' (try again in ~{max(1, round((int(reset) - _t.time()) / 60))} min)'+ except Exception:+ pass+ raise GitHubResolveError(+ f'GitHub API rate limit reached{mins}. Set SERVERKIT_GITHUB_TOKEN '+ f'to raise the limit and enable private-repo installs.')+ if resp.status_code == 404:+ raise GitHubResolveError(+ f'Repository or release not found for {owner}/{repo}. Check the URL, '+ f'or set SERVERKIT_GITHUB_TOKEN if the repository is private.')+ raise GitHubResolveError(+ f'GitHub API returned HTTP {resp.status_code} for {owner}/{repo}.')def _download_zip(url):"""Download a zip file from URL and return bytes."""resolved = _resolve_github_url(url)+ return _download_resolved(resolved)+++def _download_resolved(resolved):+ """Download an already-resolved zip URL and return a BytesIO buffer."""logger.info(f'Downloading plugin from: {resolved}')- resp = requests.get(resolved, timeout=120, stream=True, headers={+ headers = {'Accept': 'application/octet-stream','User-Agent': 'ServerKit-Plugin-Installer/1.0',- })+ }+ # Attach the token only for GitHub hosts (private assets / rate limit).+ token = _github_token()+ if token and _is_github_host(resolved):+ headers['Authorization'] = f'Bearer {token}'+ resp = requests.get(resolved, timeout=120, stream=True, headers=headers)resp.raise_for_status()buf = io.BytesIO()@@ -414,6 +514,7 @@ def install_from_url(url, user_id=None, expected_sha256=None, force=False,Returns:InstalledPlugin instance"""+ url = _normalize_source_url(url)try:buf = _download_zip(url)except Exception as e:@@ -436,6 +537,96 @@ def install_from_url(url, user_id=None, expected_sha256=None, force=False,)+def _read_manifest_from_buffer(buf):+ """Read and JSON-parse plugin.json from a plugin zip buffer, handling the+ GitHub zipball directory nesting. Raises ValueError with an actionable+ message when the archive is not a valid plugin package."""+ try:+ zf = zipfile.ZipFile(buf)+ except zipfile.BadZipFile:+ raise ValueError('The downloaded file is not a valid zip archive.')+ manifest_path, _prefix = _find_manifest(zf)+ if not manifest_path:+ raise ValueError(+ 'No plugin.json found at the archive root. A ServerKit extension '+ 'needs plugin.json at the top level (see the layout in '+ 'docs/EXTENSIONS.md).')+ try:+ with zf.open(manifest_path) as f:+ return json.loads(f.read().decode('utf-8'))+ except Exception as e:+ raise ValueError(f'plugin.json could not be parsed: {e}')+++def preview_from_url(url):+ """Resolve + download a GitHub/zip source and read its manifest WITHOUT+ installing. Returns the metadata a user needs to consent to the install:+ slug, display_name, version, description, permissions, panel-version gate,+ the resolved download URL, its sha256, and any warnings.++ Stateless by design — the subsequent install re-downloads (extension zips+ are small) and pins the previewed sha256 so the installed bytes are+ byte-identical to the previewed bytes.+ """+ from app.utils.version import version_satisfies, get_panel_version+ import hashlib++ normalized = _normalize_source_url(url)+ _LAST_RESOLUTION['zipball_fallback'] = False+ resolved = _resolve_github_url(normalized, strict=True)++ try:+ buf = _download_resolved(resolved)+ except GitHubResolveError:+ raise+ except Exception as e:+ raise ValueError(f'Failed to download the extension: {e}')++ digest = hashlib.sha256(buf.getvalue()).hexdigest()+ buf.seek(0)+ manifest = _read_manifest_from_buffer(buf)++ # Validate shape early so preview surfaces manifest problems too.+ _validate_manifest(manifest)++ slug = manifest['name']+ minv = manifest.get('min_panel_version')+ maxv = manifest.get('max_panel_version')++ warnings = []+ if _LAST_RESOLUTION.get('zipball_fallback'):+ warnings.append(+ 'No release asset found — installing the default-branch source '+ 'archive. Publish a release with a plugin .zip asset for '+ 'reproducible, checksum-pinned installs.')+ if (minv or maxv):+ panel = get_panel_version()+ if not version_satisfies(panel, minv, maxv):+ warnings.append(+ f'This extension targets panel {minv or "*"}-{maxv or "*"}, '+ f'but this panel is {panel}. Install will be blocked.')+ if InstalledPlugin.query.filter_by(slug=slug).first():+ warnings.append(+ f'An extension with the slug "{slug}" is already installed. '+ f'Installing will reinstall/overwrite it.')++ return {+ 'slug': slug,+ 'display_name': manifest.get('display_name') or slug,+ 'version': manifest.get('version'),+ 'description': manifest.get('description', ''),+ 'author': manifest.get('author', ''),+ 'homepage': manifest.get('homepage', ''),+ 'permissions': manifest.get('permissions', []) if isinstance(+ manifest.get('permissions'), list) else [],+ 'min_panel_version': minv,+ 'max_panel_version': maxv,+ 'resolved_url': resolved,+ 'sha256': digest,+ 'warnings': warnings,+ }++def install_from_path(path, user_id=None, force=False, hot_load=True,source_type=None):"""Install a plugin from a local directory on the panel host.diff --git a/backend/tests/test_plugin_preview.py b/backend/tests/test_plugin_preview.pynew file mode 100644index 00000000..decb0eb4--- /dev/null+++ b/backend/tests/test_plugin_preview.py@@ -0,0 +1,200 @@+"""GitHub-native install: shorthand normalization, preview endpoint,+token header injection, and preview -> install checksum continuity."""+import hashlib+import io+import json+import zipfile++import pytest++from app.models.plugin import InstalledPlugin+from app.services import plugin_service+++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_zip(slug='prevext', version='1.0.0', permissions=None,+ min_panel_version=None, with_manifest=True):+ manifest = {+ 'name': slug, 'display_name': 'Preview Ext', 'version': version,+ 'category': 'utility', 'description': 'A preview extension.',+ 'author': 'Tester',+ 'contributions': {'nav': [{'id': slug, 'label': 'Prev', 'route': '/prev'}]},+ }+ if permissions is not None:+ manifest['permissions'] = permissions+ if min_panel_version is not None:+ manifest['min_panel_version'] = min_panel_version+ buf = io.BytesIO()+ with zipfile.ZipFile(buf, 'w') as zf:+ if with_manifest:+ zf.writestr('plugin.json', json.dumps(manifest))+ zf.writestr('frontend/index.jsx', 'export function P(){return null;}\n')+ return buf.getvalue()+++# --------------------------------------------------------------------------- #+# Shorthand normalization+# --------------------------------------------------------------------------- #+[email protected]('raw, expected', [+ ('jhd3197/serverkit-gui', 'https://github.com/jhd3197/serverkit-gui'),+ ('jhd3197/[email protected]',+ 'https://github.com/jhd3197/serverkit-gui/releases/tag/v1.2.0'),+ ('https://github.com/jhd3197/serverkit-gui',+ 'https://github.com/jhd3197/serverkit-gui'),+ ('https://example.com/x.zip', 'https://example.com/x.zip'),+])+def test_normalize_source_url_shorthand(raw, expected):+ assert plugin_service._normalize_source_url(raw) == expected+++# --------------------------------------------------------------------------- #+# Preview endpoint / service+# --------------------------------------------------------------------------- #++def _patch_resolve(monkeypatch, zip_bytes, resolved='https://x/prevext.zip',+ zipball_fallback=False):+ def fake_resolve(url, strict=False):+ plugin_service._LAST_RESOLUTION['zipball_fallback'] = zipball_fallback+ return resolved+ monkeypatch.setattr(plugin_service, '_resolve_github_url', fake_resolve)+ monkeypatch.setattr(plugin_service, '_download_resolved',+ lambda r: io.BytesIO(zip_bytes))+++def test_preview_happy_path(app, monkeypatch):+ zip_bytes = _make_zip(permissions=['network', 'docker'])+ _patch_resolve(monkeypatch, zip_bytes)++ result = plugin_service.preview_from_url('owner/prevext')+ assert result['slug'] == 'prevext'+ assert result['version'] == '1.0.0'+ assert result['permissions'] == ['network', 'docker']+ assert result['resolved_url'] == 'https://x/prevext.zip'+ assert result['sha256'] == hashlib.sha256(zip_bytes).hexdigest()+ assert result['warnings'] == []+++def test_preview_warns_on_zipball_fallback(app, monkeypatch):+ zip_bytes = _make_zip()+ _patch_resolve(monkeypatch, zip_bytes, zipball_fallback=True)+ result = plugin_service.preview_from_url('owner/prevext')+ assert any('release asset' in w.lower() or 'default-branch' in w.lower()+ for w in result['warnings'])+++def test_preview_warns_on_panel_gate(app, monkeypatch):+ zip_bytes = _make_zip(min_panel_version='999.0.0')+ _patch_resolve(monkeypatch, zip_bytes)+ result = plugin_service.preview_from_url('owner/prevext')+ assert any('999.0.0' in w for w in result['warnings'])+++def test_preview_warns_on_slug_collision(app, plugin_dirs, monkeypatch):+ # Install prevext first.+ zip_bytes = _make_zip()+ monkeypatch.setattr(plugin_service, '_download_zip', lambda url: io.BytesIO(zip_bytes))+ plugin_service.install_from_url('https://x/prevext.zip')+ assert InstalledPlugin.query.filter_by(slug='prevext').first() is not None++ _patch_resolve(monkeypatch, zip_bytes)+ result = plugin_service.preview_from_url('owner/prevext')+ assert any('already installed' in w.lower() for w in result['warnings'])+++def test_preview_no_manifest_is_actionable(app, monkeypatch):+ zip_bytes = _make_zip(with_manifest=False)+ _patch_resolve(monkeypatch, zip_bytes)+ with pytest.raises(ValueError, match='plugin.json'):+ plugin_service.preview_from_url('owner/prevext')+++def test_preview_endpoint(app, client, auth_headers, monkeypatch):+ zip_bytes = _make_zip(permissions=['network'])+ _patch_resolve(monkeypatch, zip_bytes)+ resp = client.post('/api/v1/plugins/preview',+ json={'url': 'owner/prevext'}, headers=auth_headers)+ assert resp.status_code == 200+ data = resp.get_json()+ assert data['slug'] == 'prevext'+ assert data['permissions'] == ['network']+++# --------------------------------------------------------------------------- #+# preview -> install checksum continuity+# --------------------------------------------------------------------------- #++def test_preview_install_checksum_continuity(app, plugin_dirs, monkeypatch):+ zip_bytes = _make_zip()+ _patch_resolve(monkeypatch, zip_bytes)+ preview = plugin_service.preview_from_url('owner/prevext')++ # Install with the previewed resolved_url + sha256 → byte-identical, succeeds.+ monkeypatch.setattr(plugin_service, '_download_zip', lambda url: io.BytesIO(zip_bytes))+ plugin = plugin_service.install_from_url(+ preview['resolved_url'], expected_sha256=preview['sha256'])+ assert plugin.status == InstalledPlugin.STATUS_ACTIVE+ assert plugin.version == '1.0.0'+++def test_preview_install_tamper_rejected(app, plugin_dirs, monkeypatch):+ zip_bytes = _make_zip()+ _patch_resolve(monkeypatch, zip_bytes)+ preview = plugin_service.preview_from_url('owner/prevext')++ # Serve DIFFERENT bytes at install time; the pinned sha256 must reject them.+ tampered = _make_zip(version='9.9.9')+ monkeypatch.setattr(plugin_service, '_download_zip', lambda url: io.BytesIO(tampered))+ with pytest.raises(ValueError, match='Checksum mismatch'):+ plugin_service.install_from_url(+ preview['resolved_url'], expected_sha256=preview['sha256'])+ assert InstalledPlugin.query.filter_by(slug='prevext').first() is None+++# --------------------------------------------------------------------------- #+# GitHub token header injection (never leaked to non-GitHub hosts)+# --------------------------------------------------------------------------- #++def test_github_api_headers_include_token_when_set(monkeypatch):+ monkeypatch.setenv('SERVERKIT_GITHUB_TOKEN', 'ghp_secret')+ headers = plugin_service._github_api_headers()+ assert headers['Authorization'] == 'Bearer ghp_secret'+++def test_github_api_headers_omit_token_when_unset(monkeypatch):+ monkeypatch.delenv('SERVERKIT_GITHUB_TOKEN', raising=False)+ assert 'Authorization' not in plugin_service._github_api_headers()+++def test_download_token_only_for_github_hosts(monkeypatch):+ monkeypatch.setenv('SERVERKIT_GITHUB_TOKEN', 'ghp_secret')+ captured = {}++ class FakeResp:+ status_code = 200+ def raise_for_status(self): pass+ def iter_content(self, chunk_size=8192): return [b'zipbytes']++ def fake_get(url, **kwargs):+ captured[url] = kwargs.get('headers', {})+ return FakeResp()++ monkeypatch.setattr(plugin_service.requests, 'get', fake_get)++ plugin_service._download_resolved('https://github.com/o/r/releases/download/v1/x.zip')+ plugin_service._download_resolved('https://evil.example.com/x.zip')++ gh_headers = captured['https://github.com/o/r/releases/download/v1/x.zip']+ other_headers = captured['https://evil.example.com/x.zip']+ assert gh_headers.get('Authorization') == 'Bearer ghp_secret'+ assert 'Authorization' not in other_headers # never leak the token off-GitHubdiff --git a/docs/EXTENSIONS_REGISTRY.md b/docs/EXTENSIONS_REGISTRY.mdindex c61892f8..3516ecd3 100644--- a/docs/EXTENSIONS_REGISTRY.md+++ b/docs/EXTENSIONS_REGISTRY.md@@ -23,6 +23,15 @@ This document is the format spec (task #16) and the publisher guide (task #21).- Installing a registry entry downloads its `source`, verifies `sha256` (whenpresent) before extraction, and checks the panel version against`min_panel_version` / `max_panel_version`.+- **Installing straight from GitHub** (Marketplace → *Install manually* → URL)+ works with a repo URL, a release URL, a direct `.zip`, or `owner/repo` /+ `owner/repo@tag` shorthand. The panel first **previews** the extension —+ resolving the download, reading `plugin.json`, and showing the version,+ declared permissions, panel-version compatibility, and any warnings — then+ installs the *exact previewed bytes* (checksum-pinned). Set the optional+ **`SERVERKIT_GITHUB_TOKEN`** env var to lift GitHub's 60/hr anonymous API+ rate limit and enable private-repo installs; the token is attached only to+ GitHub hosts and is never logged or returned by the API.Relevant endpoints:diff --git a/frontend/src/components/marketplace/ManualInstallModal.jsx b/frontend/src/components/marketplace/ManualInstallModal.jsxindex eae6ea07..28b6b186 100644--- a/frontend/src/components/marketplace/ManualInstallModal.jsx+++ b/frontend/src/components/marketplace/ManualInstallModal.jsx@@ -1,10 +1,19 @@import { useState } from 'react';-import { DownloadCloud, FileArchive, FolderOpen, Globe2, PlugZap } from 'lucide-react';+import {+ DownloadCloud,+ FileArchive,+ FolderOpen,+ Globe2,+ PlugZap,+ Search,+ ShieldAlert,+} from 'lucide-react';import api from '../../services/api';import { useToast } from '../../contexts/ToastContext';import Modal from '@/components/Modal';import { Button } from '@/components/ui/button';import { Input } from '@/components/ui/input';+import { Badge } from '@/components/ui/badge';const INSTALL_SOURCES = [{ id: 'url', label: 'URL', icon: Globe2 },@@ -20,6 +29,9 @@ const SourceInput = ({onInstall,disabled,installDisabled,+ actionLabel = 'Install',+ ActionIcon = DownloadCloud,+ busyLabel = 'Installing...',}) => (<div className="plugin-install-source"><p className="text-muted">{description}</p>@@ -32,15 +44,86 @@ const SourceInput = ({disabled={disabled}/><Button onClick={onInstall} disabled={installDisabled}>- <DownloadCloud aria-hidden="true" />- {disabled ? 'Installing...' : 'Install'}+ <ActionIcon aria-hidden="true" />+ {disabled ? busyLabel : actionLabel}</Button></div></div>);+// The consent card shown after a GitHub/zip URL is resolved but before install.+// Presents what will be installed and what it wants — the same permissions+// presentation as the registry detail modal — so the install is never blind.+const PreviewConsent = ({ preview, installing, onInstall, onCancel }) => {+ const permissions = Array.isArray(preview.permissions) ? preview.permissions : [];+ const warnings = Array.isArray(preview.warnings) ? preview.warnings : [];+ const compat = preview.min_panel_version || preview.max_panel_version+ ? `Panel ${preview.min_panel_version || '*'}–${preview.max_panel_version || '*'}`+ : null;++ return (+ <div className="plugin-install-consent">+ <div className="plugin-install-consent__head">+ <div>+ <h4>{preview.display_name}</h4>+ <div className="plugin-install-consent__meta">+ <span>v{preview.version}</span>+ <code>{preview.slug}</code>+ {preview.author && <span>by {preview.author}</span>}+ {compat && <span>{compat}</span>}+ </div>+ </div>+ <Badge variant="warning" className="plugin-install-consent__badge">+ <ShieldAlert aria-hidden="true" />+ GitHub · unverified+ </Badge>+ </div>++ {preview.description && (+ <p className="plugin-install-consent__desc">{preview.description}</p>+ )}++ <div className="plugin-install-consent__section">+ <p className="plugin-install-consent__label">This extension requests:</p>+ {permissions.length > 0 ? (+ <div className="plugin-install-consent__chips">+ {permissions.map((permission) => (+ <Badge key={permission} variant="outline">{permission}</Badge>+ ))}+ </div>+ ) : (+ <p className="text-muted">No host permissions declared.</p>+ )}+ </div>++ {warnings.length > 0 && (+ <ul className="plugin-install-consent__warnings">+ {warnings.map((warning) => (+ <li key={warning}>+ <ShieldAlert aria-hidden="true" />+ {warning}+ </li>+ ))}+ </ul>+ )}++ <div className="plugin-install-consent__actions">+ <Button variant="secondary" onClick={onCancel} disabled={installing}>+ Back+ </Button>+ <Button onClick={onInstall} disabled={installing}>+ <DownloadCloud aria-hidden="true" />+ {installing ? 'Installing...' : 'Install'}+ </Button>+ </div>+ </div>+ );+};+// Manual extension install (URL / host folder / zip upload). An occasional// operator action, so it lives in a modal off the topbar rather than a tab.+// The URL path is two-step: resolve → consent card → install, so what lands is+// previewed (and checksum-pinned) before it touches the panel.const ManualInstallModal = ({ defaultSource = 'url', onClose, onInstalled }) => {const toast = useToast();const [installSource, setInstallSource] = useState(defaultSource);@@ -48,13 +131,49 @@ const ManualInstallModal = ({ defaultSource = 'url', onClose, onInstalled }) =>const [pluginPath, setPluginPath] = useState('');const [pluginFile, setPluginFile] = useState(null);const [installing, setInstalling] = useState(false);+ const [previewing, setPreviewing] = useState(false);+ const [preview, setPreview] = useState(null);++ const switchSource = (id) => {+ setInstallSource(id);+ setPreview(null);+ };++ const handleUrlChange = (value) => {+ setPluginUrl(value);+ if (preview) setPreview(null);+ };++ const handlePreview = async () => {+ if (!pluginUrl.trim()) return;+ setPreviewing(true);+ try {+ const result = await api.previewPlugin(pluginUrl.trim());+ setPreview(result);+ } catch (err) {+ toast.error(err.message || 'Could not resolve that extension');+ } finally {+ setPreviewing(false);+ }+ };++ const handleInstallFromPreview = async () => {+ setInstalling(true);+ try {+ // Pin the install to the exact previewed bytes (resolved URL + sha256).+ const result = await api.installPlugin(preview.resolved_url, preview.sha256);+ toast.success(`Extension "${result.display_name}" installed. Restart backend to activate routes.`);+ onInstalled();+ } catch (err) {+ toast.error(err.message || 'Extension installation failed');+ } finally {+ setInstalling(false);+ }+ };const handleInstall = async () => {let action;- if (installSource === 'url') {- if (!pluginUrl.trim()) return;- action = () => api.installPlugin(pluginUrl.trim());- } else if (installSource === 'path') {+ if (installSource === 'path') {if (!pluginPath.trim()) return;action = () => api.installPluginFromPath(pluginPath.trim());} else if (installSource === 'upload') {@@ -99,7 +218,7 @@ const ManualInstallModal = ({ defaultSource = 'url', onClose, onInstalled }) =>type="button"aria-selected={installSource === source.id}className={`plugin-install-tab ${installSource === source.id ? 'plugin-install-tab--active' : ''}`}- onClick={() => setInstallSource(source.id)}+ onClick={() => switchSource(source.id)}><SourceIcon aria-hidden="true" />{source.label}@@ -108,15 +227,27 @@ const ManualInstallModal = ({ defaultSource = 'url', onClose, onInstalled }) =>})}</div>- {installSource === 'url' && (+ {installSource === 'url' && !preview && (<SourceInput- description="Paste a GitHub repo URL, release URL, or direct zip link."- placeholder="https://github.com/user/serverkit-plugin"+ description="Paste a GitHub repo (owner/repo or owner/repo@tag), a release URL, or a direct zip link. You'll preview what installs before it lands."+ placeholder="owner/serverkit-plugin"value={pluginUrl}- onChange={setPluginUrl}- onInstall={handleInstall}- disabled={installing}- installDisabled={installing || !pluginUrl.trim()}+ onChange={handleUrlChange}+ onInstall={handlePreview}+ disabled={previewing}+ installDisabled={previewing || !pluginUrl.trim()}+ actionLabel="Preview"+ ActionIcon={Search}+ busyLabel="Resolving..."+ />+ )}++ {installSource === 'url' && preview && (+ <PreviewConsent+ preview={preview}+ installing={installing}+ onInstall={handleInstallFromPreview}+ onCancel={() => setPreview(null)}/>)}diff --git a/frontend/src/services/api/plugins.js b/frontend/src/services/api/plugins.jsindex edbb8928..57579b67 100644--- a/frontend/src/services/api/plugins.js+++ b/frontend/src/services/api/plugins.js@@ -9,13 +9,25 @@ export async function getPlugin(pluginId) {return this.request(`/plugins/${pluginId}`);}-export async function installPlugin(url) {- return this.request('/plugins/install', {+// Preview a GitHub/zip extension without installing. Returns the manifest+// metadata (slug, version, permissions, panel gate), the resolved download URL,+// its sha256, and any warnings — used to render the consent card.+export async function previewPlugin(url) {+ return this.request('/plugins/preview', {method: 'POST',body: JSON.stringify({ url }),});}+// Install a plugin from a URL. Pass `sha256` (from previewPlugin) to pin the+// install to the exact previewed bytes.+export async function installPlugin(url, sha256 = null) {+ return this.request('/plugins/install', {+ method: 'POST',+ body: JSON.stringify(sha256 ? { url, sha256 } : { url }),+ });+}+export async function installPluginFromPath(path) {return this.request('/plugins/install-local', {method: 'POST',diff --git a/frontend/src/styles/pages/_marketplace.scss b/frontend/src/styles/pages/_marketplace.scssindex c6f51d91..52f172a6 100644--- a/frontend/src/styles/pages/_marketplace.scss+++ b/frontend/src/styles/pages/_marketplace.scss@@ -687,6 +687,104 @@font-size: $font-size-sm;}+// Two-step GitHub install: consent card shown after resolve, before install.+.plugin-install-consent {+ display: flex;+ flex-direction: column;+ gap: $space-4;+ padding: $space-4;+ border: 1px solid $border-color;+ border-radius: $radius-lg;+ background: $bg-elevated;++ &__head {+ display: flex;+ align-items: flex-start;+ justify-content: space-between;+ gap: $space-3;++ h4 {+ margin: 0 0 $space-1;+ font-size: $font-size-lg;+ }+ }++ &__meta {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: $space-3;+ color: $text-tertiary;+ font-size: $font-size-sm;++ code {+ font-family: $font-mono;+ }+ }++ &__badge {+ display: inline-flex;+ align-items: center;+ gap: $space-1;+ white-space: nowrap;++ svg {+ width: 13px;+ height: 13px;+ }+ }++ &__desc {+ margin: 0;+ color: $text-secondary;+ font-size: $font-size-sm;+ line-height: $line-height-normal;+ }++ &__label {+ margin: 0 0 $space-2;+ font-size: $font-size-sm;+ font-weight: $font-weight-medium;+ color: $text-secondary;+ }++ &__chips {+ display: flex;+ flex-wrap: wrap;+ gap: $space-2;+ }++ &__warnings {+ margin: 0;+ padding: 0;+ list-style: none;+ display: flex;+ flex-direction: column;+ gap: $space-2;++ li {+ display: flex;+ align-items: flex-start;+ gap: $space-2;+ font-size: $font-size-sm;+ color: $warning;++ svg {+ flex-shrink: 0;+ width: 15px;+ height: 15px;+ margin-top: 2px;+ }+ }+ }++ &__actions {+ display: flex;+ justify-content: flex-end;+ gap: $space-3;+ }+}+// Keep-vs-purge data policy dialog on plugin uninstall..plugin-uninstall-dialog {display: flex;