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(extensions): per-plugin config store + Configure form (#49)
Juan Denis4ca07fb71c7a
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex f1788388..69683fc6 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -20,6 +20,12 @@ awaiting a stable release:### Added+- **Extensions platform (Phase 7 — per-extension configuration)** — an extension+ that declares a `config_schema` in its manifest now gets a real **Configure**+ form on the Marketplace Installed tab (text/number/boolean/enum/secret fields);+ values persist on the panel and the extension's backend reads them with the new+ `plugins_sdk.config(slug)` accessor. Config values may hold secrets, so they are+ served only by an admin-gated endpoint and never appear in plugin listings.- **Extensions platform (Phase 7 — installed extensions survive panel updates)** —previously a panel update deployed a fresh source tree preserving only `.env`and the database, silently wiping any URL/registry/upload-installed extension'sdiff --git a/backend/app/api/plugins.py b/backend/app/api/plugins.pyindex c7cbab52..00026fe9 100644--- a/backend/app/api/plugins.py+++ b/backend/app/api/plugins.py@@ -463,6 +463,64 @@ def get_manifest_spec():})+@plugins_bp.route('/<int:plugin_id>/config', methods=['GET'])+@jwt_required()+def get_plugin_config(plugin_id):+ """Read a plugin's saved config values + its schema (#49).++ Admin-only: config values may hold secrets (API keys etc.), which is also+ why they are deliberately NOT part of the plugin's to_dict().+ """+ 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 get_plugin+ plugin = get_plugin(plugin_id)+ if not plugin:+ return jsonify({'error': 'Plugin not found'}), 404+ return jsonify({+ 'config': plugin.config,+ 'config_schema': (plugin.manifest or {}).get('config_schema') or {},+ })+++@plugins_bp.route('/<int:plugin_id>/config', methods=['PUT'])+@jwt_required()+def update_plugin_config(plugin_id):+ """Save a plugin's config values (#49). Body: {"config": {...}}.++ The manifest's config_schema is advisory — values are stored as given so a+ plugin can evolve its fields without a panel release. Plugins read them via+ plugins_sdk.config(slug).+ """+ user = get_current_user()+ if not user or not user.is_admin:+ return jsonify({'error': 'Admin access required'}), 403++ from app import db+ from app.services.plugin_service import get_plugin+ plugin = get_plugin(plugin_id)+ if not plugin:+ return jsonify({'error': 'Plugin not found'}), 404++ data = request.get_json(silent=True) or {}+ config = data.get('config')+ if not isinstance(config, dict):+ return jsonify({'error': 'config must be an object'}), 400++ plugin.config = config+ db.session.commit()+ AuditService.log(+ action=AuditLog.ACTION_RESOURCE_UPDATE,+ user_id=user.id,+ target_type='plugin',+ target_id=str(plugin.id),+ details={'event': 'config_update', 'keys': sorted(config.keys())},+ )+ return jsonify({'config': plugin.config})++@plugins_bp.route('/updates', methods=['GET'])@jwt_required()def list_updates():diff --git a/backend/app/models/plugin.py b/backend/app/models/plugin.pyindex 9f04fa14..95d576eb 100644--- a/backend/app/models/plugin.py+++ b/backend/app/models/plugin.py@@ -38,6 +38,12 @@ class InstalledPlugin(db.Model):# Full manifest stored as JSONmanifest_json = db.Column(db.Text)+ # Saved per-plugin config values (#49). The manifest's `config_schema`+ # describes the fields; admins edit values from the Marketplace and the+ # plugin reads them via plugins_sdk.config(slug). May hold secrets — kept+ # out of to_dict; served only by the admin-gated config endpoint.+ config_json = db.Column(db.Text)+# StatusSTATUS_ACTIVE = 'active'STATUS_DISABLED = 'disabled'@@ -63,6 +69,14 @@ class InstalledPlugin(db.Model):def manifest(self, v):self.manifest_json = json.dumps(v)+ @property+ def config(self):+ return json.loads(self.config_json) if self.config_json else {}++ @config.setter+ def config(self, v):+ self.config_json = json.dumps(v or {})+def to_dict(self):manifest = self.manifest or {}return {@@ -92,6 +106,9 @@ class InstalledPlugin(db.Model):'contributions': manifest.get('contributions') or {},'templates': manifest.get('templates') or [],'lifecycle': manifest.get('lifecycle') or {},+ # Schema only — saved VALUES may hold secrets and are served+ # exclusively by the admin-gated /config endpoint.+ 'config_schema': manifest.get('config_schema') or {},'installed_at': self.installed_at.isoformat() if self.installed_at else None,'updated_at': self.updated_at.isoformat() if self.updated_at else None,}diff --git a/backend/app/plugins_sdk/__init__.py b/backend/app/plugins_sdk/__init__.pyindex 40397c80..5e592387 100644--- a/backend/app/plugins_sdk/__init__.py+++ b/backend/app/plugins_sdk/__init__.py@@ -105,6 +105,18 @@ def panel_version():return get_panel_version()+def config(slug):+ """Saved config values for an installed plugin (empty dict if none).++ The manifest's ``config_schema`` documents the fields; admins edit the+ values from Marketplace → Installed → Configure. Read-only here — the+ panel owns writes (PUT /api/v1/plugins/<id>/config).+ """+ from app.models.plugin import InstalledPlugin+ p = InstalledPlugin.query.filter_by(slug=slug).first()+ return dict(p.config or {}) if p else {}++# Capability gate: `require(slug, 'docker')` raises unless the plugin declared# that permission in its manifest. See app/plugins_sdk/permissions.py.require_permission = permissions.require@@ -125,5 +137,6 @@ __all__ = ['permissions','require_permission','panel_version',+ 'config','sockets',]diff --git a/backend/migrations/versions/045_plugin_config.py b/backend/migrations/versions/045_plugin_config.pynew file mode 100644index 00000000..deab2bf4--- /dev/null+++ b/backend/migrations/versions/045_plugin_config.py@@ -0,0 +1,41 @@+"""Per-plugin config store (#49).++Adds:+- installed_plugins.config_json (saved config values; the manifest's+ config_schema describes the fields, plugins read them via+ plugins_sdk.config(slug))++Idempotent: MigrationService runs _fix_missing_columns() + db.create_all() on boot+before Alembic, so guard on the live schema.++Revision ID: 045_plugin_config+Revises: 044_managed_databases+Create Date: 2026-07-02+"""+from alembic import op+import sqlalchemy as sa++revision = '045_plugin_config'+down_revision = '044_managed_databases'+branch_labels = None+depends_on = None+++def upgrade():+ conn = op.get_bind()+ inspector = sa.inspect(conn)+ if 'installed_plugins' not in set(inspector.get_table_names()):+ return+ cols = {c['name'] for c in inspector.get_columns('installed_plugins')}+ if 'config_json' not in cols:+ op.add_column('installed_plugins', sa.Column('config_json', sa.Text, nullable=True))+++def downgrade():+ conn = op.get_bind()+ inspector = sa.inspect(conn)+ if 'installed_plugins' not in set(inspector.get_table_names()):+ return+ cols = {c['name'] for c in inspector.get_columns('installed_plugins')}+ if 'config_json' in cols:+ op.drop_column('installed_plugins', 'config_json')diff --git a/backend/tests/test_plugins_pipeline.py b/backend/tests/test_plugins_pipeline.pyindex 68071a55..7a28ac36 100644--- a/backend/tests/test_plugins_pipeline.py+++ b/backend/tests/test_plugins_pipeline.py@@ -225,6 +225,48 @@ def test_disable_guard_returns_503(app):assert r.get_json()['status'] == 'disabled'+# --------------------------------------------------------------------------- #+# Per-plugin config store (#49)+# --------------------------------------------------------------------------- #++def test_plugin_config_roundtrip_and_sdk(app, client, auth_headers, plugin_dirs):+ """Config saves via the admin API, reads back, and reaches the plugin+ through the plugins_sdk.config(slug) accessor."""+ _write_builtin(plugin_dirs['builtin'])+ plugin = plugin_service.install_builtin_extension('serverkit-demo')++ # Starts empty (schema comes along for the form).+ r = client.get(f'/api/v1/plugins/{plugin.id}/config', headers=auth_headers)+ assert r.status_code == 200+ assert r.get_json()['config'] == {}++ r = client.put(+ f'/api/v1/plugins/{plugin.id}/config', headers=auth_headers,+ json={'config': {'api_key': 'sk-123', 'refresh_seconds': 30, 'enabled': True}},+ )+ assert r.status_code == 200++ r = client.get(f'/api/v1/plugins/{plugin.id}/config', headers=auth_headers)+ assert r.get_json()['config'] == {+ 'api_key': 'sk-123', 'refresh_seconds': 30, 'enabled': True}++ from app import plugins_sdk+ assert plugins_sdk.config('serverkit-demo')['api_key'] == 'sk-123'+ assert plugins_sdk.config('no-such-plugin') == {}++ # Values may hold secrets — they must never leak through to_dict().+ assert 'config' not in plugin.to_dict()+ assert 'config_json' not in plugin.to_dict()+++def test_plugin_config_rejects_non_object(app, client, auth_headers, plugin_dirs):+ _write_builtin(plugin_dirs['builtin'])+ plugin = plugin_service.install_builtin_extension('serverkit-demo')+ r = client.put(f'/api/v1/plugins/{plugin.id}/config', headers=auth_headers,+ json={'config': 'not-a-dict'})+ assert r.status_code == 400++# --------------------------------------------------------------------------- ## Boot repair pass (#48): plugins whose files a panel update wiped# --------------------------------------------------------------------------- #diff --git a/docs/EXTENSIONS.md b/docs/EXTENSIONS.mdindex 7d84db11..9f0425e3 100644--- a/docs/EXTENSIONS.md+++ b/docs/EXTENSIONS.md@@ -294,6 +294,34 @@ on install and **pause automatically when the plugin is disabled**:"schedules": [ { "name": "myext-nightly", "kind": "myext.reindex", "cron": "0 3 * * *" } ]```+## Config (`config_schema`)++Declare a `config_schema` in the manifest and the Marketplace renders a+**Configure** form on the installed plugin (Installed tab). Values persist on+the panel and your backend reads them with `plugins_sdk.config(slug)`:++```jsonc+"config_schema": {+ "api_key": { "type": "string", "secret": true, "description": "…" },+ "refresh_seconds": { "type": "integer", "default": 60 },+ "mode": { "type": "string", "enum": ["fast", "thorough"] },+ "enabled": { "type": "boolean", "default": true }+}+```++- Top-level keys are the field names (a JSON-schema-style `properties` wrapper+ also works). Supported: `string` / `number` / `integer` / `boolean`, `enum`+ (renders a select), `default`, `title`, `description`, and `secret: true`+ (renders a password input).+- Values may hold secrets, so they are **not** part of the plugin's public+ dict — only the admin-gated `GET/PUT /api/v1/plugins/<id>/config` serves+ them, and `plugins_sdk.config()` is read-only.++```python+from app.plugins_sdk import config+key = config('my-extension').get('api_key')+```+## Real-time (Socket.IO)Declare `"socket_entry": "sockets:register"`; the function returnsdiff --git a/frontend/src/pages/Marketplace.jsx b/frontend/src/pages/Marketplace.jsxindex d366ef9a..3c96c955 100644--- a/frontend/src/pages/Marketplace.jsx+++ b/frontend/src/pages/Marketplace.jsx@@ -203,6 +203,8 @@ const Marketplace = () => {const [detailEntry, setDetailEntry] = useState(null);// Plugin pending uninstall — drives the keep-vs-purge data-policy dialog.const [uninstallTarget, setUninstallTarget] = useState(null);+ // Plugin whose config is being edited (#49) — drives the config dialog.+ const [configTarget, setConfigTarget] = useState(null);const loadExtensions = useCallback(async () => {try {@@ -716,6 +718,7 @@ const Marketplace = () => {onToggle={handlePluginToggle}onUpdate={handlePluginUpdate}onUninstall={requestPluginUninstall}+ onConfigure={setConfigTarget}statusVariant={pluginStatusVariant}/>))}@@ -752,6 +755,13 @@ const Marketplace = () => {onConfirm={confirmPluginUninstall}/>)}++ {configTarget && (+ <PluginConfigDialog+ plugin={configTarget}+ onClose={() => setConfigTarget(null)}+ />+ )}</div>);};@@ -1001,9 +1011,12 @@ const InstalledCatalogRow = ({ entry, onUninstall }) => {);};-const PluginRow = ({ plugin, update, installing, onToggle, onUpdate, onUninstall, statusVariant }) => {+const PluginRow = ({ plugin, update, installing, onToggle, onUpdate, onUninstall, onConfigure, statusVariant }) => {const updateAvailable = Boolean(update?.update_available);const compatible = update?.compatible !== false;+ const configurable = plugin.config_schema+ && typeof plugin.config_schema === 'object'+ && Object.keys(plugin.config_schema).length > 0;return (<article className={`installed-item installed-item--plugin card ${plugin.status === 'error' ? 'installed-item--error' : ''}`}>@@ -1040,6 +1053,11 @@ const PluginRow = ({ plugin, update, installing, onToggle, onUpdate, onUninstallUpdate</Button>)}+ {configurable && (+ <Button size="sm" variant="outline" onClick={() => onConfigure(plugin)}>+ Configure+ </Button>+ )}<Buttonsize="sm"variant={plugin.status === 'active' ? 'outline' : 'default'}@@ -1055,6 +1073,112 @@ const PluginRow = ({ plugin, update, installing, onToggle, onUpdate, onUninstall);};+// Config editor for an installed plugin (#49). Fields come from the manifest's+// config_schema (top-level keys, or JSON-schema `properties`); values persist+// via PUT /plugins/<id>/config and the plugin reads them on the backend via+// plugins_sdk.config(slug).+const PluginConfigDialog = ({ plugin, onClose }) => {+ const toast = useToast();+ const [values, setValues] = useState(null);+ const [saving, setSaving] = useState(false);++ const schema = plugin.config_schema || {};+ const fields = schema.properties && typeof schema.properties === 'object'+ ? schema.properties+ : schema;++ useEffect(() => {+ api.getPluginConfig(plugin.id)+ .then((data) => setValues(data.config || {}))+ .catch(() => setValues({}));+ }, [plugin.id]);++ const setField = (key, v) => setValues((prev) => ({ ...prev, [key]: v }));++ const save = async () => {+ setSaving(true);+ try {+ await api.updatePluginConfig(plugin.id, values || {});+ toast.success('Plugin configuration saved');+ onClose();+ } catch (err) {+ toast.error(err.message || 'Failed to save configuration');+ } finally {+ setSaving(false);+ }+ };++ return (+ <Modal+ open+ onClose={onClose}+ title={`Configure ${plugin.display_name}`}+ size="sm"+ footer={+ <>+ <Button variant="ghost" onClick={onClose}>Cancel</Button>+ <Button onClick={save} disabled={saving || values === null}>+ {saving ? 'Saving…' : 'Save'}+ </Button>+ </>+ }+ >+ {values === null ? (+ <p className="text-muted">Loading…</p>+ ) : (+ <div className="plugin-config-form">+ {Object.entries(fields).map(([key, spec]) => {+ const s = spec && typeof spec === 'object' ? spec : {};+ const type = s.type || 'string';+ const isNumber = type === 'number' || type === 'integer';+ const value = values[key] ?? s.default ?? (type === 'boolean' ? false : '');+ return (+ <label key={key} className="plugin-config-form__field">+ <span className="plugin-config-form__label">{s.title || key}</span>+ {type === 'boolean' ? (+ <input+ type="checkbox"+ checked={Boolean(value)}+ onChange={(e) => setField(key, e.target.checked)}+ />+ ) : Array.isArray(s.enum) ? (+ <select+ className="ui-input"+ value={value}+ onChange={(e) => setField(key, e.target.value)}+ >+ {s.enum.map((opt) => (+ <option key={opt} value={opt}>{opt}</option>+ ))}+ </select>+ ) : (+ <input+ className="ui-input"+ type={isNumber ? 'number' : (s.secret ? 'password' : 'text')}+ value={value}+ onChange={(e) => setField(+ key,+ isNumber+ ? (e.target.value === '' ? '' : Number(e.target.value))+ : e.target.value+ )}+ />+ )}+ {s.description && (+ <span className="plugin-config-form__hint text-muted">{s.description}</span>+ )}+ </label>+ );+ })}+ {Object.keys(fields).length === 0 && (+ <p className="text-muted">This plugin declares no configuration fields.</p>+ )}+ </div>+ )}+ </Modal>+ );+};+// Data-policy dialog for plugin uninstall. Keeping data (default) leaves the// extension's tables intact for a later reinstall; purging drops them.const PluginUninstallDialog = ({ plugin, onCancel, onConfirm }) => (diff --git a/frontend/src/services/api/plugins.js b/frontend/src/services/api/plugins.jsindex b1e5abcc..d0e7eedb 100644--- a/frontend/src/services/api/plugins.js+++ b/frontend/src/services/api/plugins.js@@ -75,6 +75,21 @@ export async function installBuiltinExtension(slug) {});}+// Saved config values for an installed plugin (admin):+// { config: {...}, config_schema: {...} }+export async function getPluginConfig(pluginId) {+ return this.request(`/plugins/${pluginId}/config`);+}++// Persist a plugin's config values (admin). The plugin reads them via+// plugins_sdk.config(slug) on the backend.+export async function updatePluginConfig(pluginId, config) {+ return this.request(`/plugins/${pluginId}/config`, {+ method: 'PUT',+ body: JSON.stringify({ config }),+ });+}+// Returns available updates for installed plugins:// { updates: [ { slug, plugin_id, installed_version, available_version,// update_available, compatible, source } ] }diff --git a/frontend/src/styles/pages/_marketplace.scss b/frontend/src/styles/pages/_marketplace.scssindex 50cc761d..d8520952 100644--- a/frontend/src/styles/pages/_marketplace.scss+++ b/frontend/src/styles/pages/_marketplace.scss@@ -915,3 +915,26 @@line-height: $line-height-normal;}}++// Per-plugin config editor (#49) — fields generated from config_schema.+.plugin-config-form {+ display: flex;+ flex-direction: column;+ gap: $space-4;++ &__field {+ display: flex;+ flex-direction: column;+ gap: $space-1;+ }++ &__label {+ font-size: $font-size-sm;+ font-weight: $font-weight-semibold;+ }++ &__hint {+ font-size: $font-size-xs;+ line-height: $line-height-normal;+ }+}