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 3 — platform primitives (models, jobs, sockets, perms)

Juan Deniscdcfba5980e7
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d3207483..678aff11 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -20,6 +20,19 @@ awaiting a stable release:
### Added
+- **Extensions platform (Phase 3 — platform primitives)** — the machinery that
+ makes extensions first-class and safe. Extensions can now own **data models**
+ (manifest `models` → `ext_<slug>_*` tables, created on install, dropped on
+ purge), **background jobs & schedules** (wired into the Jobs system, and paused
+ automatically when the extension is disabled), and a **real-time Socket.IO
+ namespace** (`/ext/<slug>`, status-guarded). Declared **permissions** are now a
+ consent step and enforced by an SDK capability gate (`require_permission`).
+ **Panel-version compatibility** (`min_panel_version`/`max_panel_version`) is
+ enforced at install and update. Uninstall offers **keep-data vs purge**. New
+ generic **contribution slots** (`dashboard.top`, `service.detail.tab`,
+ `domain.drawer.panel`) let extensions enrich core surfaces, not just add pages.
+ The frontend-delivery decision is recorded in
+ [`docs/adr/0001-extension-frontend-delivery.md`](docs/adr/0001-extension-frontend-delivery.md).
- **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
diff --git a/backend/app/api/plugins.py b/backend/app/api/plugins.py
index e62c43bc..18e48e19 100644
--- a/backend/app/api/plugins.py
+++ b/backend/app/api/plugins.py
@@ -217,15 +217,22 @@ def uninstall_plugin(plugin_id):
if not plugin:
return jsonify({'error': 'Plugin not found'}), 404
+ # Keep-data by default; purge drops the plugin's ext_<slug>_ tables. Accept
+ # ?purge=true or a JSON body {"purge": true}.
+ purge = str(request.args.get('purge', '')).lower() in ('1', 'true', 'yes')
+ if not purge:
+ body = request.get_json(silent=True) or {}
+ purge = bool(body.get('purge'))
+
plugin_name = plugin.name
- uninstall_plugin(plugin_id)
+ uninstall_plugin(plugin_id, purge=purge)
AuditService.log(
action=AuditLog.ACTION_RESOURCE_DELETE,
user_id=user.id,
target_type='plugin',
target_id=plugin_id,
- details={'name': plugin_name}
+ details={'name': plugin_name, 'purge': purge}
)
return jsonify({'message': f'Plugin {plugin_name} uninstalled. Restart to fully unload backend routes.'})
@@ -328,6 +335,35 @@ def install_builtin(slug):
}), 500
+@plugins_bp.route('/<slug>/assets/<path:asset_path>', methods=['GET'])
+@jwt_required()
+def plugin_asset(slug, asset_path):
+ """Serve a file from an installed plugin's frontend directory.
+
+ Foundation for the future remote-frontend delivery mechanism (ADR 0001):
+ a panel can serve a plugin's prebuilt/static assets. Path-traversal safe via
+ send_from_directory. Only active plugins' assets are served.
+ """
+ import re
+ from flask import send_from_directory
+ if not re.match(r'^[a-zA-Z0-9_-]+$', slug or ''):
+ return jsonify({'error': 'Invalid slug'}), 400
+
+ from app.services.plugin_service import get_plugin_by_slug, FRONTEND_PLUGINS_DIR
+ import os
+ plugin = get_plugin_by_slug(slug)
+ if not plugin or plugin.status != 'active':
+ return jsonify({'error': 'Plugin not active'}), 404
+
+ base = os.path.join(FRONTEND_PLUGINS_DIR, slug)
+ if not os.path.isdir(base):
+ return jsonify({'error': 'No assets for this plugin'}), 404
+ try:
+ return send_from_directory(base, asset_path)
+ except Exception:
+ return jsonify({'error': 'Asset not found'}), 404
+
+
@plugins_bp.route('/manifest-spec', methods=['GET'])
@jwt_required()
def get_manifest_spec():
@@ -361,13 +397,28 @@ def get_manifest_spec():
'frontend_entry': {'type': 'string',
'description': 'Optional path within the frontend bundle (informational).'},
'permissions': {'type': 'array', 'items': {'type': 'string'},
- 'description': 'Declared host permissions (docker, shell, filesystem, network, db). Informational; surfaced to admins on install.'},
+ 'description': 'Declared host capabilities (docker, shell, filesystem, network, db) or agent.command:<action>. Surfaced as a consent step on install and enforced by the SDK capability gate (require_permission).'},
+ 'min_panel_version': {'type': 'string',
+ 'description': 'Lowest compatible panel version (inclusive). Enforced at install/update.'},
+ 'max_panel_version': {'type': 'string',
+ 'description': 'Highest compatible panel version (inclusive). Optional.'},
'templates': {'type': 'array',
'description': 'App-template ids to install on plugin install. String or {id, app_name?, variables?}.'},
+ 'models': {'type': 'string',
+ 'description': "module:func — returns/defines the plugin's SQLAlchemy models (tables named ext_<slug>_*). Tables are created on install; dropped on uninstall --purge."},
+ 'jobs': {'type': 'array',
+ 'description': 'Background job handlers: [{kind, handler}] where handler is module:func.'},
+ 'schedules': {'type': 'array',
+ 'description': 'Recurring jobs: [{name, kind, cron?|interval_seconds?, payload?}]. Paused automatically when the plugin is disabled.'},
+ 'socket_entry': {'type': 'string',
+ 'description': "module:func returning {event: handler}. Registers a status-guarded Socket.IO namespace at /ext/<slug>."},
+ 'config_schema': {'type': 'object',
+ 'description': 'JSON-schema-ish object rendered as a settings form on the installed-extension detail.'},
'lifecycle': {'type': 'object',
'properties': {
'install': {'type': 'string', 'description': "module:func — runs after install."},
- 'uninstall': {'type': 'string', 'description': "module:func — runs before uninstall."},
+ 'upgrade': {'type': 'string', 'description': "module:func — runs when installing a different version."},
+ 'uninstall': {'type': 'string', 'description': "module:func(plugin, purge=bool) — runs before uninstall."},
}},
'contributions': {
'type': 'object',
diff --git a/backend/app/plugins_sdk/__init__.py b/backend/app/plugins_sdk/__init__.py
index e82aa5c7..40397c80 100644
--- a/backend/app/plugins_sdk/__init__.py
+++ b/backend/app/plugins_sdk/__init__.py
@@ -88,6 +88,8 @@ def audit(action, target_type, target_id=None, details=None, user_id=None):
# tools/context against the core assistant (see plugins_sdk/ai.py). Imported
# lazily-safe: ai.py only depends on the AI tool registry, not on a running app.
from app.plugins_sdk import ai
+from app.plugins_sdk import permissions
+from app.plugins_sdk import sockets
from app.queue_bus.sdk import QueueBusSdk
from app.notifications.sdk import NotifySdk
from app.jobs.sdk import JobsSdk
@@ -96,6 +98,17 @@ queue = QueueBusSdk()
notify = NotifySdk()
jobs = JobsSdk()
+
+def panel_version():
+ """The panel's version string (for compat checks inside a plugin)."""
+ from app.utils.version import get_panel_version
+ return get_panel_version()
+
+
+# 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
+
__all__ = [
'db',
'jwt',
@@ -109,4 +122,8 @@ __all__ = [
'queue',
'notify',
'jobs',
+ 'permissions',
+ 'require_permission',
+ 'panel_version',
+ 'sockets',
]
diff --git a/backend/app/plugins_sdk/permissions.py b/backend/app/plugins_sdk/permissions.py
new file mode 100644
index 00000000..21c050df
--- /dev/null
+++ b/backend/app/plugins_sdk/permissions.py
@@ -0,0 +1,66 @@
+"""Extension permission model + capability gate (#25).
+
+A manifest's declared ``permissions`` become enforceable capability checks. A
+plugin calls ``require(slug, capability)`` (or the SDK re-export
+``require_permission``) before doing something privileged; if the plugin did not
+declare that permission, it raises ``PermissionDenied``.
+
+This is **in-process, declaration-based** enforcement. Combined with install-time
+consent (the install dialog surfaces requested permissions from the manifest) and
+the curated registry, it's the accepted risk posture (decision D6). It does NOT
+sandbox a plugin that reaches for a raw host import without going through the gate
+— true out-of-process isolation is deliberately out of scope (plan #42). The gate
+makes honest plugins verifiable and gives the host a single choke point to tighten
+later.
+"""
+import logging
+
+logger = logging.getLogger(__name__)
+
+# Canonical host capabilities a manifest may request. Agent-command permissions
+# use the namespaced form ``agent.command:<action>`` and are matched verbatim.
+KNOWN_PERMISSIONS = {'docker', 'filesystem', 'shell', 'network', 'db'}
+
+
+class PermissionDenied(PermissionError):
+ """Raised when a plugin uses a capability it did not declare."""
+
+
+def declared_permissions(slug):
+ """The set of permissions the installed plugin `slug` declared (empty if the
+ plugin is unknown)."""
+ from app.models.plugin import InstalledPlugin
+ p = InstalledPlugin.query.filter_by(slug=slug).first()
+ if not p:
+ return set()
+ perms = (p.manifest or {}).get('permissions') or []
+ if not isinstance(perms, list):
+ return set()
+ return {str(x) for x in perms}
+
+
+def has(slug, capability):
+ """True if plugin `slug` declared `capability`."""
+ return capability in declared_permissions(slug)
+
+
+def require(slug, capability):
+ """Assert plugin `slug` declared `capability`, else raise PermissionDenied."""
+ if not has(slug, capability):
+ raise PermissionDenied(
+ f"Plugin '{slug}' has not declared the '{capability}' permission. "
+ f"Add it to the plugin.json \"permissions\" array."
+ )
+ return True
+
+
+def unknown_permissions(permissions):
+ """Return declared permissions that aren't recognized host capabilities
+ (agent-command permissions are always accepted). Useful for review/consent UI."""
+ out = []
+ for p in permissions or []:
+ p = str(p)
+ if p in KNOWN_PERMISSIONS or p.startswith('agent.command:'):
+ continue
+ out.append(p)
+ return out
diff --git a/backend/app/plugins_sdk/sockets.py b/backend/app/plugins_sdk/sockets.py
new file mode 100644
index 00000000..f77bd476
--- /dev/null
+++ b/backend/app/plugins_sdk/sockets.py
@@ -0,0 +1,89 @@
+"""Socket.IO extension point for plugins (#26).
+
+A plugin can own a real-time namespace at ``/ext/<slug>``, guarded by plugin
+status exactly like the HTTP blueprint guard: when the plugin isn't active, new
+connections to its namespace are refused. This lets real-time features (log tails,
+live streams, the serverkit-gui screenshot case) be plugins.
+
+Manifest surface::
+
+ "socket_entry": "sockets:register" # app.plugins.<slug>.sockets:register
+
+The referenced function returns a mapping of event name → handler::
+
+ def register():
+ def on_connect():
+ ...
+ def on_subscribe(data):
+ ...
+ return {"connect": on_connect, "subscribe": on_subscribe}
+
+Each handler is wrapped so it only runs while the plugin is active; a ``connect``
+to a disabled plugin's namespace is disconnected immediately.
+"""
+import functools
+import logging
+
+logger = logging.getLogger(__name__)
+
+
+def _guard(slug, fn):
+ @functools.wraps(fn)
+ def wrapper(*args, **kwargs):
+ from app.models.plugin import InstalledPlugin
+ p = InstalledPlugin.query.filter_by(slug=slug).first()
+ if not p or p.status != InstalledPlugin.STATUS_ACTIVE:
+ try:
+ from flask_socketio import disconnect
+ disconnect()
+ except Exception:
+ pass
+ return None
+ return fn(*args, **kwargs)
+ return wrapper
+
+
+def register_namespace(slug, handlers):
+ """Register ``handlers`` (event → fn) on the plugin's ``/ext/<slug>``
+ namespace, each status-guarded. Best-effort; returns the namespace string or
+ None if Socket.IO isn't available (e.g. a worker without it)."""
+ if not handlers or not isinstance(handlers, dict):
+ return None
+ try:
+ from app import get_socketio
+ io = get_socketio()
+ except Exception:
+ io = None
+ if io is None:
+ logger.info(f'Socket.IO not available; skipping namespace for {slug}')
+ return None
+
+ namespace = f'/ext/{slug}'
+ for event, fn in handlers.items():
+ if not callable(fn):
+ continue
+ try:
+ io.on_event(event, _guard(slug, fn), namespace=namespace)
+ except Exception as e:
+ logger.warning(f"Socket handler '{event}' for {slug} failed to register: {e}")
+ logger.info(f'Registered Socket.IO namespace {namespace} for {slug}')
+ return namespace
+
+
+def register_from_manifest(plugin, manifest):
+ """Resolve a plugin's ``socket_entry`` and register the namespace it returns."""
+ target = (manifest or {}).get('socket_entry')
+ if not target or ':' not in str(target):
+ return None
+ import importlib
+ module_name, func_name = str(target).split(':', 1)
+ try:
+ mod = importlib.import_module(f'app.plugins.{plugin.slug}.{module_name}')
+ fn = getattr(mod, func_name, None)
+ if not callable(fn):
+ return None
+ handlers = fn()
+ except Exception as e:
+ logger.warning(f'socket_entry for {plugin.slug} failed: {e}')
+ return None
+ return register_namespace(plugin.slug, handlers)
diff --git a/backend/app/services/extension_lifecycle.py b/backend/app/services/extension_lifecycle.py
new file mode 100644
index 00000000..d59e4257
--- /dev/null
+++ b/backend/app/services/extension_lifecycle.py
@@ -0,0 +1,167 @@
+"""Extension runtime lifecycle: data models + declarative jobs.
+
+Beyond hot-loading a blueprint, an extension can own database tables and
+background jobs declared in its manifest. This module creates/tears those down in
+lockstep with install / uninstall / enable / disable so a plugin no longer just
+gets raw ``db`` and prays, and a disabled plugin's scheduled work actually pauses
+(status-guard parity for background jobs).
+
+Manifest surface:
+
+ "models": "models:register", # app.plugins.<slug>.models:register(db)
+ "jobs": [ # background job handlers
+ {"kind": "myext.reindex", "handler": "jobs:reindex"}
+ ],
+ "schedules": [ # recurring jobs
+ {"name": "myext-nightly", "kind": "myext.reindex", "cron": "0 3 * * *"}
+ ]
+
+Data-model tables SHOULD be named ``ext_<slug>_*`` (dashes → underscores); purge
+on uninstall drops exactly those.
+"""
+import importlib
+import logging
+
+logger = logging.getLogger(__name__)
+
+
+def _table_prefix(slug):
+ return f"ext_{slug.replace('-', '_')}_"
+
+
+def _import_target(slug, target):
+ """Resolve a ``module:func`` target under app.plugins.<slug>."""
+ if not target or ':' not in str(target):
+ return None
+ module_name, func_name = str(target).split(':', 1)
+ mod = importlib.import_module(f'app.plugins.{slug}.{module_name}')
+ return getattr(mod, func_name, None)
+
+
+# --------------------------------------------------------------------------- #
+# Data models (#24)
+# --------------------------------------------------------------------------- #
+
+def register_models(plugin, manifest):
+ """Import the plugin's model module (registering its SQLAlchemy tables on the
+ metadata as a side effect) and create any missing tables. Best-effort."""
+ target = (manifest or {}).get('models')
+ if not target:
+ return
+ from app import db
+ try:
+ fn = _import_target(plugin.slug, target)
+ if callable(fn):
+ fn(db)
+ except Exception as e:
+ logger.warning(f'Model registration failed for {plugin.slug}: {e}')
+ return
+ try:
+ db.create_all()
+ logger.info(f'Ensured data-model tables for extension {plugin.slug}')
+ except Exception as e:
+ logger.warning(f'create_all after {plugin.slug} model register failed: {e}')
+
+
+def purge_models(plugin):
+ """Drop the plugin's ``ext_<slug>_*`` tables. Called on uninstall --purge."""
+ from app import db
+ from sqlalchemy import inspect, text
+ prefix = _table_prefix(plugin.slug)
+ try:
+ tables = inspect(db.engine).get_table_names()
+ except Exception as e:
+ logger.warning(f'Could not inspect tables to purge {plugin.slug}: {e}')
+ return 0
+ dropped = 0
+ for table in tables:
+ if table.startswith(prefix):
+ try:
+ db.session.execute(text(f'DROP TABLE IF EXISTS "{table}"'))
+ dropped += 1
+ except Exception as e:
+ logger.warning(f'Failed dropping {table}: {e}')
+ if dropped:
+ db.session.commit()
+ logger.info(f'Purged {dropped} table(s) for extension {plugin.slug}')
+ return dropped
+
+
+# --------------------------------------------------------------------------- #
+# Declarative jobs (#29)
+# --------------------------------------------------------------------------- #
+
+def _schedule_names(manifest):
+ return [s.get('name') for s in (manifest or {}).get('schedules') or []
+ if isinstance(s, dict) and s.get('name')]
+
+
+def register_jobs(plugin, manifest):
+ """Register the plugin's job handlers and (enabled) schedules."""
+ from app.jobs.sdk import JobsSdk
+ sdk = JobsSdk()
+
+ for job in (manifest or {}).get('jobs') or []:
+ if not isinstance(job, dict):
+ continue
+ kind = job.get('kind')
+ handler_ref = job.get('handler')
+ if not kind or not handler_ref:
+ continue
+ try:
+ handler = _import_target(plugin.slug, handler_ref)
+ if callable(handler):
+ sdk.register(kind, handler, replace=True)
+ except Exception as e:
+ logger.warning(f'Job handler {handler_ref} for {plugin.slug} failed: {e}')
+
+ for sched in (manifest or {}).get('schedules') or []:
+ if not isinstance(sched, dict) or not sched.get('name') or not sched.get('kind'):
+ continue
+ try:
+ sdk.schedule(
+ sched['name'], sched['kind'],
+ interval_seconds=sched.get('interval_seconds'),
+ cron=sched.get('cron'),
+ payload=sched.get('payload'),
+ )
+ except Exception as e:
+ logger.warning(f"Schedule {sched.get('name')} for {plugin.slug} failed: {e}")
+
+
+def _set_schedules_enabled(manifest, enabled):
+ from app.jobs.service import ScheduledJobService
+ from app.jobs.models import ScheduledJob
+ names = set(_schedule_names(manifest))
+ if not names:
+ return
+ for row in ScheduledJob.query.filter(ScheduledJob.name.in_(names)).all():
+ try:
+ ScheduledJobService.set_enabled(row.id, enabled)
+ except Exception as e:
+ logger.warning(f'Could not toggle schedule {row.name}: {e}')
+
+
+def pause_jobs(plugin, manifest):
+ """Disable a plugin's scheduled jobs (called on plugin disable)."""
+ _set_schedules_enabled(manifest, False)
+
+
+def resume_jobs(plugin, manifest):
+ """Re-enable a plugin's scheduled jobs (called on plugin enable)."""
+ _set_schedules_enabled(manifest, True)
+
+
+def remove_jobs(plugin, manifest):
+ """Delete a plugin's scheduled-job rows (called on uninstall)."""
+ from app import db
+ from app.jobs.models import ScheduledJob
+ names = set(_schedule_names(manifest))
+ if not names:
+ return
+ try:
+ ScheduledJob.query.filter(ScheduledJob.name.in_(names)).delete(
+ synchronize_session=False)
+ db.session.commit()
+ except Exception as e:
+ logger.warning(f'Could not remove schedules for {plugin.slug}: {e}')
diff --git a/backend/app/services/plugin_service.py b/backend/app/services/plugin_service.py
index 4a93bd60..113702be 100644
--- a/backend/app/services/plugin_service.py
+++ b/backend/app/services/plugin_service.py
@@ -191,6 +191,24 @@ def _validate_manifest(manifest):
return True
+def _assert_manifest_panel_compatible(manifest):
+ """Enforce a manifest's min/max_panel_version at install (#28), for every
+ install source (URL/upload/local/builtin), not just the registry. A manifest
+ without bounds installs anywhere."""
+ from app.utils.version import version_satisfies, get_panel_version
+ minv = manifest.get('min_panel_version')
+ maxv = manifest.get('max_panel_version')
+ if not (minv or maxv):
+ return
+ panel = get_panel_version()
+ if not version_satisfies(panel, minv, maxv):
+ raise ValueError(
+ f"{manifest.get('display_name') or manifest.get('name')} "
+ f"v{manifest.get('version')} needs panel {minv or '*'}–{maxv or '*'} "
+ f"(this panel is {panel})."
+ )
+
+
def _safe_extract_path(dest_root, rel_path):
"""Resolve `rel_path` under `dest_root` and assert it stays inside.
@@ -370,6 +388,7 @@ def _install_from_buffer(buf, source_url, source_type, user_id=None, force=False
manifest = json.loads(zf.read(manifest_path))
_validate_manifest(manifest)
+ _assert_manifest_panel_compatible(manifest)
slug = manifest['name']
@@ -378,6 +397,10 @@ def _install_from_buffer(buf, source_url, source_type, user_id=None, force=False
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.")
+ # Remember the version we're replacing so we can run lifecycle.upgrade when
+ # it actually changes (reinstall/update over an existing row).
+ previous_version = existing.version if existing else None
+
# Create DB record early so we can track errors
if existing:
plugin = existing
@@ -531,11 +554,31 @@ def _install_from_buffer(buf, source_url, source_type, user_id=None, force=False
# not roll back the plugin install.
template_results = _install_template_dependencies(plugin, manifest)
+ # Register plugin-owned data models (create ext_<slug>_ tables) and
+ # declarative jobs/schedules before the install hook runs, so the hook
+ # can seed rows into those tables. Best-effort (never fail the install).
+ if has_backend:
+ try:
+ from app.services import extension_lifecycle
+ extension_lifecycle.register_models(plugin, manifest)
+ extension_lifecycle.register_jobs(plugin, manifest)
+ except Exception as e:
+ logger.warning(f'Extension lifecycle setup failed for {slug}: {e}')
+ try:
+ from app.plugins_sdk import sockets as _ext_sockets
+ _ext_sockets.register_from_manifest(plugin, manifest)
+ except Exception as e:
+ logger.warning(f'Extension socket setup failed for {slug}: {e}')
+
# Run plugin's lifecycle.install hook if declared. Failure here is
# also non-fatal — the plugin is installed; the hook is for
# convenience setup (e.g. creating default rows).
_run_lifecycle_hook(plugin, manifest, 'install')
+ # If this was an in-place version change, run the upgrade hook too.
+ if previous_version and previous_version != manifest['version']:
+ _run_lifecycle_hook(plugin, manifest, 'upgrade')
+
# If the plugin declares an "ai" block, register its tools/context with
# the core assistant now so installing it teaches the assistant new
# abilities without a restart. Best effort.
@@ -701,6 +744,19 @@ def load_all_plugins(app):
_attach_status_guard(bp, plugin.slug)
app.register_blueprint(bp, url_prefix=plugin.url_prefix)
logger.info(f'Loaded plugin: {plugin.display_name} v{plugin.version} at {plugin.url_prefix}')
+
+ # Re-establish the plugin's data models, jobs, and socket
+ # namespace on boot (install-time registration doesn't survive
+ # a restart).
+ manifest = plugin.manifest or {}
+ try:
+ from app.services import extension_lifecycle
+ extension_lifecycle.register_models(plugin, manifest)
+ extension_lifecycle.register_jobs(plugin, manifest)
+ from app.plugins_sdk import sockets as _ext_sockets
+ _ext_sockets.register_from_manifest(plugin, manifest)
+ except Exception as e:
+ logger.warning(f'Extension runtime setup for {plugin.slug}: {e}')
except Exception as e:
logger.error(f'Failed to load plugin {plugin.slug}: {e}')
plugin.status = InstalledPlugin.STATUS_ERROR
@@ -708,8 +764,12 @@ def load_all_plugins(app):
db.session.commit()
-def uninstall_plugin(plugin_id):
- """Uninstall a plugin by removing its files and DB record."""
+def uninstall_plugin(plugin_id, purge=False):
+ """Uninstall a plugin by removing its files and DB record.
+
+ `purge=True` also drops the plugin's ``ext_<slug>_`` data tables (keep-data
+ is the default, mirroring the installer's --purge/--keep-data semantics).
+ """
plugin = InstalledPlugin.query.get(plugin_id)
if not plugin:
return False
@@ -718,8 +778,18 @@ def uninstall_plugin(plugin_id):
manifest = plugin.manifest or {}
# Run lifecycle.uninstall hook *before* we delete the files (the hook
- # may need to read its own files). Best effort — never block teardown.
- _run_lifecycle_hook(plugin, manifest, 'uninstall')
+ # may need to read its own files). It's told whether the caller asked to
+ # purge data. Best effort — never block teardown.
+ _run_lifecycle_hook(plugin, manifest, 'uninstall', purge=purge)
+
+ # Tear down declarative schedules, and (only on purge) the data tables.
+ try:
+ from app.services import extension_lifecycle
+ extension_lifecycle.remove_jobs(plugin, manifest)
+ if purge:
+ extension_lifecycle.purge_models(plugin)
+ except Exception as e:
+ logger.warning(f'Extension lifecycle teardown for {slug}: {e}')
# Drop any AI tools/context this plugin contributed to the assistant.
_unregister_plugin_ai(slug)
@@ -754,6 +824,12 @@ def enable_plugin(plugin_id):
db.session.commit()
_regenerate_frontend_manifest()
_refresh_plugin_ai(plugin)
+ # Resume the plugin's scheduled jobs (status-guard parity for background work).
+ try:
+ from app.services import extension_lifecycle
+ extension_lifecycle.resume_jobs(plugin, plugin.manifest or {})
+ except Exception as e:
+ logger.warning(f'Could not resume jobs for {plugin.slug}: {e}')
return plugin
@@ -766,6 +842,12 @@ def disable_plugin(plugin_id):
db.session.commit()
_regenerate_frontend_manifest()
_unregister_plugin_ai(plugin.slug)
+ # Pause the plugin's scheduled jobs so a disabled plugin does no background work.
+ try:
+ from app.services import extension_lifecycle
+ extension_lifecycle.pause_jobs(plugin, plugin.manifest or {})
+ except Exception as e:
+ logger.warning(f'Could not pause jobs for {plugin.slug}: {e}')
return plugin
@@ -790,16 +872,19 @@ def _unregister_plugin_ai(slug):
logger.warning(f'AI tool unregister failed for plugin {slug}', exc_info=True)
-def _run_lifecycle_hook(plugin, manifest, phase):
+def _run_lifecycle_hook(plugin, manifest, phase, **kwargs):
"""Execute a plugin's lifecycle hook.
Manifest format:
- "lifecycle": { "install": "module:func", "uninstall": "module:func" }
-
- The module path is resolved under ``app.plugins.<slug>``. The hook
- receives the InstalledPlugin row as its single positional arg. Return
- value is ignored. Failure is logged and swallowed — lifecycle hooks
- are convenience, not correctness.
+ "lifecycle": { "install": "module:func", "upgrade": "module:func",
+ "uninstall": "module:func" }
+
+ The module path is resolved under ``app.plugins.<slug>``. The hook receives
+ the InstalledPlugin row as its single positional arg; the uninstall hook may
+ additionally accept ``purge`` (whether the caller asked to drop data). Hooks
+ written as ``func(plugin)`` still work — extra kwargs are only passed when the
+ signature accepts them. Return value is ignored; failure is logged and
+ swallowed — lifecycle hooks are convenience, not correctness.
"""
lifecycle = (manifest or {}).get('lifecycle') or {}
target = lifecycle.get(phase)
@@ -811,6 +896,7 @@ def _run_lifecycle_hook(plugin, manifest, phase):
try:
import importlib
+ import inspect
mod = importlib.import_module(full_module)
func = getattr(mod, func_name, None)
if not callable(func):
@@ -818,7 +904,20 @@ def _run_lifecycle_hook(plugin, manifest, phase):
f'Lifecycle {phase} hook {target} for {plugin.slug} is not callable'
)
return
- func(plugin)
+ # Only forward kwargs the hook actually declares (keeps func(plugin) valid).
+ if kwargs:
+ try:
+ params = inspect.signature(func).parameters
+ accepts_kwargs = any(
+ p.kind == inspect.Parameter.VAR_KEYWORD for p in params.values()
+ )
+ passable = {k: v for k, v in kwargs.items()
+ if accepts_kwargs or k in params}
+ except (TypeError, ValueError):
+ passable = {}
+ func(plugin, **passable)
+ else:
+ func(plugin)
logger.info(f'Ran lifecycle.{phase} hook for {plugin.slug}')
except Exception as e:
logger.warning(f'Lifecycle {phase} hook for {plugin.slug} failed: {e}')
diff --git a/backend/tests/test_extension_platform.py b/backend/tests/test_extension_platform.py
new file mode 100644
index 00000000..1c7a60c9
--- /dev/null
+++ b/backend/tests/test_extension_platform.py
@@ -0,0 +1,240 @@
+"""Phase 3 platform primitives: version gates, permissions, data models,
+declarative jobs, socket extension point, and data-purge on uninstall.
+
+Backend plugin code normally lives at app/plugins/<slug>/ on disk and is imported
+by name. To exercise the importlib-driven hooks without writing packages into the
+repo, we inject synthetic modules into sys.modules under the expected names.
+"""
+import io
+import json
+import sys
+import types
+import zipfile
+
+import pytest
+
+from app import db
+from app.models.plugin import InstalledPlugin
+from app.services import plugin_service, extension_lifecycle
+from app.plugins_sdk import permissions, sockets as sdk_sockets
+import app.plugins_sdk as sdk
+
+
+SLUG = 'testext'
+
+
+# A plugin-owned model, defined once against the real db so it registers on the
+# shared metadata a single time (extend_existing keeps re-imports harmless).
+class _ExtThing(db.Model):
+ __tablename__ = 'ext_testext_thing'
+ __table_args__ = {'extend_existing': True}
+ id = db.Column(db.Integer, primary_key=True)
+ label = db.Column(db.String(40))
+
+
+_job_calls = []
+
+
+def _inject_plugin_modules():
+ """Register synthetic app.plugins.testext.{models,jobs,sockets} modules."""
+ pkg = types.ModuleType(f'app.plugins.{SLUG}')
+ pkg.__path__ = []
+ sys.modules[f'app.plugins.{SLUG}'] = pkg
+
+ models_mod = types.ModuleType(f'app.plugins.{SLUG}.models')
+ models_mod.register = lambda _db: [_ExtThing]
+ sys.modules[f'app.plugins.{SLUG}.models'] = models_mod
+
+ jobs_mod = types.ModuleType(f'app.plugins.{SLUG}.jobs')
+ jobs_mod.reindex = lambda job: _job_calls.append(job)
+ sys.modules[f'app.plugins.{SLUG}.jobs'] = jobs_mod
+
+ sockets_mod = types.ModuleType(f'app.plugins.{SLUG}.sockets')
+
+ def _register():
+ def on_connect():
+ return 'connected'
+ def on_ping(data):
+ return {'pong': data}
+ return {'connect': on_connect, 'ping': on_ping}
+ sockets_mod.register = _register
+ sys.modules[f'app.plugins.{SLUG}.sockets'] = sockets_mod
+
+
+def injected_plugin():
+ _inject_plugin_modules()
+ yield
+ for name in list(sys.modules):
+ if name == f'app.plugins.{SLUG}' or name.startswith(f'app.plugins.{SLUG}.'):
+ del sys.modules[name]
+ _job_calls.clear()
+
+
+def _plugin_row(manifest):
+ p = InstalledPlugin(
+ name=SLUG, display_name='Test Ext', slug=SLUG, version='1.0.0',
+ status=InstalledPlugin.STATUS_ACTIVE, has_backend=True,
+ )
+ p.manifest = manifest
+ db.session.add(p)
+ db.session.commit()
+ return p
+
+
+# --------------------------------------------------------------------------- #
+# #28 — version compat gate at install (all sources)
+# --------------------------------------------------------------------------- #
+
+def test_min_panel_version_blocks_install(app):
+ manifest = {'name': 'toonew', 'display_name': 'Too New', 'version': '1.0.0',
+ 'min_panel_version': '999.0.0'}
+ with pytest.raises(ValueError, match='needs panel'):
+ plugin_service._assert_manifest_panel_compatible(manifest)
+
+
+def test_no_bounds_installs_anywhere(app):
+ # Missing bounds → no exception.
+ plugin_service._assert_manifest_panel_compatible(
+ {'name': 'x', 'display_name': 'X', 'version': '1.0.0'})
+
+
+def test_sdk_exposes_panel_version(app):
+ v = sdk.panel_version()
+ assert isinstance(v, str) and v
+
+
+# --------------------------------------------------------------------------- #
+# #25 — permission enforcement
+# --------------------------------------------------------------------------- #
+
+def test_permission_gate(app):
+ _plugin_row({'permissions': ['docker', 'network']})
+ assert permissions.has(SLUG, 'docker') is True
+ assert permissions.has(SLUG, 'shell') is False
+ assert permissions.require(SLUG, 'docker') is True
+ with pytest.raises(permissions.PermissionDenied):
+ permissions.require(SLUG, 'shell')
+ # SDK re-export points at the same gate.
+ with pytest.raises(permissions.PermissionDenied):
+ sdk.require_permission(SLUG, 'filesystem')
+
+
+def test_unknown_permissions_flagged():
+ assert permissions.unknown_permissions(['docker', 'bogus', 'agent.command:x']) == ['bogus']
+
+
+# --------------------------------------------------------------------------- #
+# #24 — plugin data models + purge
+# --------------------------------------------------------------------------- #
+
+def test_register_and_purge_models(app, injected_plugin):
+ from sqlalchemy import inspect
+ p = _plugin_row({'models': 'models:register'})
+
+ extension_lifecycle.register_models(p, p.manifest)
+ assert 'ext_testext_thing' in inspect(db.engine).get_table_names()
+
+ dropped = extension_lifecycle.purge_models(p)
+ assert dropped >= 1
+ assert 'ext_testext_thing' not in inspect(db.engine).get_table_names()
+
+
+# --------------------------------------------------------------------------- #
+# #29 — declarative jobs (register / pause / resume / remove)
+# --------------------------------------------------------------------------- #
+
+def test_declarative_jobs_lifecycle(app, injected_plugin):
+ from app.jobs import registry
+ from app.jobs.models import ScheduledJob
+
+ manifest = {
+ 'jobs': [{'kind': 'testext.reindex', 'handler': 'jobs:reindex'}],
+ 'schedules': [{'name': 'testext-nightly', 'kind': 'testext.reindex',
+ 'interval_seconds': 3600}],
+ }
+ p = _plugin_row(manifest)
+
+ extension_lifecycle.register_jobs(p, manifest)
+ assert registry.get('testext.reindex') is not None
+ sched = ScheduledJob.query.filter_by(name='testext-nightly').first()
+ assert sched is not None and sched.enabled is True
+
+ extension_lifecycle.pause_jobs(p, manifest)
+ assert ScheduledJob.query.filter_by(name='testext-nightly').first().enabled is False
+
+ extension_lifecycle.resume_jobs(p, manifest)
+ assert ScheduledJob.query.filter_by(name='testext-nightly').first().enabled is True
+
+ extension_lifecycle.remove_jobs(p, manifest)
+ assert ScheduledJob.query.filter_by(name='testext-nightly').first() is None
+
+
+def test_disable_enable_pauses_jobs(app, injected_plugin):
+ from app.jobs.models import ScheduledJob
+ manifest = {
+ 'schedules': [{'name': 'testext-nightly', 'kind': 'testext.reindex',
+ 'interval_seconds': 3600}],
+ }
+ p = _plugin_row(manifest)
+ extension_lifecycle.register_jobs(p, manifest)
+
+ plugin_service.disable_plugin(p.id)
+ assert ScheduledJob.query.filter_by(name='testext-nightly').first().enabled is False
+ plugin_service.enable_plugin(p.id)
+ assert ScheduledJob.query.filter_by(name='testext-nightly').first().enabled is True
+
+
+# --------------------------------------------------------------------------- #
+# #26 — Socket.IO extension point
+# --------------------------------------------------------------------------- #
+
+class _FakeIO:
+ def __init__(self):
+ self.registered = []
+ def on_event(self, event, handler, namespace=None):
+ self.registered.append((event, namespace, handler))
+
+
+def test_socket_namespace_registration(app, injected_plugin, monkeypatch):
+ fake = _FakeIO()
+ monkeypatch.setattr('app.get_socketio', lambda: fake, raising=False)
+ import app as app_pkg
+ monkeypatch.setattr(app_pkg, 'get_socketio', lambda: fake)
+
+ p = _plugin_row({'socket_entry': 'sockets:register'})
+ ns = sdk_sockets.register_from_manifest(p, p.manifest)
+
+ assert ns == f'/ext/{SLUG}'
+ events = {e for e, _ns, _h in fake.registered}
+ assert events == {'connect', 'ping'}
+ assert all(_ns == f'/ext/{SLUG}' for _e, _ns, _h in fake.registered)
+
+
+# --------------------------------------------------------------------------- #
+# #30 — uninstall purge vs keep-data
+# --------------------------------------------------------------------------- #
+
+def test_uninstall_purge_drops_tables(app, injected_plugin, tmp_path, monkeypatch):
+ from sqlalchemy import inspect
+ monkeypatch.setattr(plugin_service, 'BACKEND_PLUGINS_DIR', str(tmp_path / 'b'))
+ monkeypatch.setattr(plugin_service, 'FRONTEND_PLUGINS_DIR', str(tmp_path / 'f'))
+
+ p = _plugin_row({'models': 'models:register'})
+ extension_lifecycle.register_models(p, p.manifest)
+ assert 'ext_testext_thing' in inspect(db.engine).get_table_names()
+
+ plugin_service.uninstall_plugin(p.id, purge=True)
+ assert 'ext_testext_thing' not in inspect(db.engine).get_table_names()
+
+
+def test_uninstall_keep_data_leaves_tables(app, injected_plugin, tmp_path, monkeypatch):
+ from sqlalchemy import inspect
+ monkeypatch.setattr(plugin_service, 'BACKEND_PLUGINS_DIR', str(tmp_path / 'b'))
+ monkeypatch.setattr(plugin_service, 'FRONTEND_PLUGINS_DIR', str(tmp_path / 'f'))
+
+ p = _plugin_row({'models': 'models:register'})
+ extension_lifecycle.register_models(p, p.manifest)
+
+ plugin_service.uninstall_plugin(p.id, purge=False)
+ assert 'ext_testext_thing' in inspect(db.engine).get_table_names()
diff --git a/docs/EXTENSIONS.md b/docs/EXTENSIONS.md
index ef827245..77ab7f34 100644
--- a/docs/EXTENSIONS.md
+++ b/docs/EXTENSIONS.md
@@ -199,6 +199,9 @@ def list_things():
| `queue` | Queue Bus SDK (publish/consume). |
| `notify` | Notifications SDK (`notify.send(event, to, data)`). |
| `jobs` | Jobs SDK (schedule/enqueue background work). |
+| `sockets` | Register a status-guarded Socket.IO namespace (`/ext/<slug>`). |
+| `require_permission(slug, cap)` | Capability gate — raises `PermissionDenied` if `cap` isn't declared in `permissions`. |
+| `panel_version()` | The panel's version string (for in-plugin compat checks). |
Errors follow the core convention: `return jsonify({'error': 'message'}), status`.
@@ -244,7 +247,41 @@ def register(ctx):
- Install creates the tables; the `upgrade` hook runs on version change.
- Uninstall offers **keep-data** vs **purge** (mirrors the installer's `--purge`
- semantics); the choice is passed to the `uninstall` hook.
+ semantics); the choice is passed to the `uninstall` hook (`func(plugin, purge=...)`)
+ and, on purge, drops the `ext_<slug>_*` tables.
+
+## Background jobs & schedules
+
+Declare handlers and recurring jobs in the manifest; they wire into the Jobs SDK
+on install and **pause automatically when the plugin is disabled**:
+
+```jsonc
+"jobs": [ { "kind": "myext.reindex", "handler": "jobs:reindex" } ],
+"schedules": [ { "name": "myext-nightly", "kind": "myext.reindex", "cron": "0 3 * * *" } ]
+```
+
+## Real-time (Socket.IO)
+
+Declare `"socket_entry": "sockets:register"`; the function returns
+`{event: handler}` and the panel registers them on `/ext/<slug>`, status-guarded
+(a disabled plugin's namespace refuses new connections):
+
+```python
+# app/plugins/<slug>/sockets.py
+def register():
+ def on_connect(): ...
+ def on_subscribe(data): ...
+ return {"connect": on_connect, "subscribe": on_subscribe}
+```
+
+## Permissions & compatibility
+
+- `permissions` is a consent step on install and is **enforced** by the SDK gate:
+ `require_permission(slug, "docker")` raises unless `docker` is declared. (This is
+ in-process, declaration-based enforcement — see ADR 0001 / plan #42 for the
+ sandboxing posture.)
+- `min_panel_version` / `max_panel_version` are enforced at install **and** update
+ for every source (URL/upload/local/builtin/registry).
---
diff --git a/docs/adr/0001-extension-frontend-delivery.md b/docs/adr/0001-extension-frontend-delivery.md
new file mode 100644
index 00000000..70d820f0
--- /dev/null
+++ b/docs/adr/0001-extension-frontend-delivery.md
@@ -0,0 +1,68 @@
+# ADR 0001 — Production frontend delivery for extensions
+
+**Status:** Accepted (2026-07-01) · Task #22 of the Extensions Platform plan
+**Context:** the §1.3 constraint — the load-bearing blocker for third-party UI.
+
+## Problem
+
+`frontend/src/plugins/contributions.js` discovers plugin UI at **build time** via
+`import.meta.glob('../plugins/*/index.{js,jsx}')`. A production panel ships a
+**prebuilt** Vite bundle (Docker image / `frontend/dist`). Installing a plugin
+copies files onto disk but nothing rebuilds the bundle, so:
+
+- **Builtin (in-repo) extensions** render in production, because their frontend is
+ checked into `frontend/src/plugins/<slug>/` and compiled into every build.
+- **Third-party extensions that ship a frontend do NOT render** on a prebuilt panel.
+ Their **backend halves load fine** (blueprints are hot-loaded at runtime).
+
+## Options considered
+
+**(a) Per-plugin prebuilt ESM bundle.** Plugin repos ship a built `dist/` ESM
+module; the panel serves it and `import()`s it at runtime, with React and shared
+libs provided as externals via an import map. *Pro:* real third-party UI with no
+panel rebuild. *Con:* version-skew risk (React/singleton duplication), a public
+module contract to keep stable, build tooling every plugin author must adopt, and
+a meaningfully larger runtime loader. High effort, real fragility.
+
+**(b) Iframe / `bare`-layout escape hatch.** A plugin renders a fullscreen page
+the panel embeds. *Pro:* total isolation, no shared-dep problem. *Con:* not a
+first-class contribution (no nav integration, no shared theme/components), clunky.
+Fine as an escape hatch, not the default.
+
+**(c) Backend-only third parties + builtin-only frontends (the current reality).**
+Third-party extensions ship backend blueprints (which work everywhere today);
+any first-class UI ships as an in-repo builtin, pre-bundled per D5. *Pro:* zero new
+machinery, zero version-skew risk, already proven (`serverkit-git`, `serverkit-gui`).
+*Con:* a third party can't ship arbitrary bundled UI without a panel release.
+
+## Decision
+
+**Ship (c) as the supported posture now; keep (b) as an escape hatch; treat (a) as
+the documented future direction, not yet built.** This matches the plan's own risk
+mitigation (§Risks) and decision D5, and unblocks Phases 4–5 (extraction of *core*
+verticals into *builtin* extensions), which never needed (a) in the first place.
+
+Concretely, what we guarantee today:
+
+1. **Builtin frontends are the first-class UI path** — pre-bundled, single source of
+ truth enforced by `scripts/sync-builtin-frontends.mjs` + the Extensions CI drift
+ gate. Every extracted core vertical (Email, WordPress, Tier-1 pages) uses this.
+2. **Third-party backend extensions are fully supported** — hot-loaded blueprints,
+ status guard, permissions, data models, jobs, sockets (Phase 3 primitives).
+3. **Graceful degradation, never a white-screen** — when a contributed `component`
+ or custom `layout` can't be resolved from the compiled bundle, the route/widget
+ is **skipped and warned** (already implemented in `ExtensionRoutes.jsx` /
+ `contributions.js` / `PluginLoader.jsx`), so a plugin whose frontend isn't in the
+ bundle degrades to "backend works, UI absent" rather than crashing the SPA.
+4. **A plugin-asset serving route exists** (`GET /api/v1/plugins/<slug>/assets/...`)
+ as the foundation for (a): a panel can serve a plugin's static/prebuilt files.
+ The dynamic-`import()` loader + import-map externals are deliberately **out of
+ scope** until a third party needs bundled UI badly enough to justify the skew risk.
+
+## Consequences
+
+- Phases 4–5 proceed now (builtin extraction is unaffected by this blocker).
+- The registry's near-term third-party entries are **backend-only or builtin**
+ (e.g. `serverkit-gui` is backend + a widget whose code is pre-bundled).
+- Revisiting (a) is a self-contained follow-up: implement the loader + externals on
+ top of the already-shipped asset-serving route and graceful-skip guarantee.
diff --git a/docs/adr/0002-third-party-sandboxing.md b/docs/adr/0002-third-party-sandboxing.md
new file mode 100644
index 00000000..21422947
--- /dev/null
+++ b/docs/adr/0002-third-party-sandboxing.md
@@ -0,0 +1,60 @@
+# ADR 0002 — Third-party extension sandboxing (research note)
+
+**Status:** Research note (not scheduled) · Task #42 of the Extensions Platform plan
+**TL;DR:** in-process execution + declared-permission gate + curated registry is
+the accepted risk posture. Out-of-process sandboxing is documented here as the
+escalation path if third-party volume ever demands it — not built now.
+
+## Current posture (what we actually ship)
+
+A plugin's backend runs **in-process**: its blueprint is imported and registered
+into the panel's Flask app, with the panel's privileges. Safety today comes from:
+
+- **Curated registry** — entries are PR-reviewed (permissions honesty, checksum,
+ license). No open publish.
+- **Checksum-verified install** — the downloaded zip must match the index `sha256`.
+- **Declared-permission gate** — `require_permission(slug, cap)` raises for
+ undeclared capabilities (ADR context: this is *declaration-based*, not a syscall
+ jail — an in-process plugin that bypasses the SDK and imports a host module
+ directly is not stopped).
+- **Gated pip** — `SERVERKIT_ALLOW_PLUGIN_PIP` is off by default, so a plugin's
+ Python deps aren't installed (and setup.py can't run) without operator opt-in.
+- **Status guard** — disabled ⇒ HTTP 503 + socket disconnect + paused jobs.
+
+This is appropriate for first-party + a small, curated third-party set. It is
+**not** a security boundary against a malicious in-process plugin.
+
+## When to escalate
+
+Escalate to real isolation when any of these become true: an open/self-serve
+registry, untrusted publishers at volume, or multi-tenant panels where one
+operator's plugin must not reach another's data.
+
+## Options for out-of-process execution
+
+1. **Subprocess + RPC.** Run each plugin's backend in its own process (own venv),
+ exposing a JSON-RPC/HTTP surface the panel proxies. *Pro:* real process boundary,
+ per-plugin dependency isolation, crash containment. *Con:* IPC latency, a stable
+ RPC contract to maintain, lifecycle/health management, harder access to shared
+ `db`/services (must go through a mediated API).
+
+2. **Container-per-plugin.** Each plugin runs in its own container; the panel talks
+ to it over the network. *Pro:* strongest isolation, resource limits (cgroups),
+ reuses the Docker layer ServerKit already manages. *Con:* heaviest; startup cost;
+ the panel already assumes single-worker in-memory agent state — orchestrating
+ plugin containers adds real complexity.
+
+3. **In-process capability confinement (Python).** RestrictedPython / import hooks /
+ audit hooks to block undeclared imports and syscalls. *Pro:* no IPC. *Con:*
+ CPython sandboxing is famously leaky; not a real boundary. Rejected as a security
+ control (fine only as a lint/nudge).
+
+## Recommendation
+
+Keep the current posture. If escalation is triggered, prefer **(1) subprocess + RPC**
+as the first step (smaller blast radius than containers, isolates deps), reserving
+**(2) container-per-plugin** for genuinely hostile multi-tenant scenarios. Either way
+the SDK is the seam: because plugins depend on `app.plugins_sdk` rather than host
+internals, the SDK can become the RPC client without changing plugin code.
+
+Out of scope for the current plan; revisit when the registry opens up.
diff --git a/frontend/src/components/PluginSlot.jsx b/frontend/src/components/PluginSlot.jsx
new file mode 100644
index 00000000..76c6a000
--- /dev/null
+++ b/frontend/src/components/PluginSlot.jsx
@@ -0,0 +1,41 @@
+/**
+ * PluginSlot - Renders installed plugin widgets contributed to a named slot.
+ *
+ * Extensions declare slotted widgets in their manifest:
+ * "contributions": { "widgets": [{ "slot": "dashboard.top",
+ * "component": "MyWidget" }] }
+ *
+ * Mount a slot at any host render point with
+ * <PluginSlot name="dashboard.top" />
+ * and every widget whose `slot` matches renders there. Resolution mirrors
+ * PluginLoader (build-time module discovery + optional Provider wrap); an
+ * unresolved component is skipped rather than crashing the host.
+ *
+ * The optional `context` object is passed as a prop to each rendered widget so
+ * a mount point can hand down page-scoped data (e.g. the current domain or
+ * service id). Renders nothing when no widget targets the slot.
+ */
+import { useContributions, resolveComponent, getPluginModule } from '../plugins/contributions';
+
+const PluginSlot = ({ name, context }) => {
+ const { widgets } = useContributions();
+
+ const rendered = (widgets || [])
+ .filter((w) => w && w.slot === name)
+ .map((w, i) => {
+ const Component = resolveComponent(w.plugin, w.component);
+ if (!Component) return null; // unresolved → skip, never crash the host
+ const mod = getPluginModule(w.plugin);
+ const Provider = (mod && mod.Provider) || null;
+ const node = <Component key={`${w.plugin}:${w.component}:${i}`} context={context} />;
+ return Provider
+ ? <Provider key={`provider:${w.plugin}:${i}`}>{node}</Provider>
+ : node;
+ })
+ .filter(Boolean);
+
+ if (rendered.length === 0) return null;
+ return <>{rendered}</>;
+};
+
+export default PluginSlot;
diff --git a/frontend/src/pages/Dashboard.jsx b/frontend/src/pages/Dashboard.jsx
index 6fb863bc..571d69df 100644
--- a/frontend/src/pages/Dashboard.jsx
+++ b/frontend/src/pages/Dashboard.jsx
@@ -17,6 +17,7 @@ import { Popover, PopoverTrigger, PopoverContent } from '@/components/ui/popover
import { MetricCard, Pill, Feed, FeedItem } from '@/components/ds';
import { formatRelativeTime } from '@/utils/time';
import EmptyState from '../components/EmptyState';
+import PluginSlot from '../components/PluginSlot';
// Map an audit action verb to a tinted icon + semantic tone token.
// Falls back to a neutral history icon for unrecognised actions.
@@ -377,6 +378,9 @@ const Dashboard = () => {
</div>
</div>
+ {/* Extension slot: widgets contributed to the top of the dashboard */}
+ <PluginSlot name="dashboard.top" />
+
{/* Grid Container */}
<div className="grid-container">
{widgets.filter(w => w.visible).map(w => {
diff --git a/frontend/src/pages/Domains.jsx b/frontend/src/pages/Domains.jsx
index 9afbf4d6..8a0ca14b 100644
--- a/frontend/src/pages/Domains.jsx
+++ b/frontend/src/pages/Domains.jsx
@@ -21,6 +21,7 @@ import { useTopbarActions } from '@/hooks/useTopbarActions';
import RegistrarPortfolio from '../components/domains/RegistrarPortfolio';
import { ProviderBrandIcon } from '../components/icons/ProviderBrands';
import DomainDnsPanel from '../components/domains/DomainDnsPanel';
+import PluginSlot from '../components/PluginSlot';
import { formatExpiry } from '../utils/expiry';
const Domains = () => {
@@ -539,6 +540,9 @@ const Domains = () => {
</Button>
</div>
)}
+
+ {/* Extension slot: panels contributed to the domain drawer */}
+ <PluginSlot name="domain.drawer.panel" context={{ domain: drawerDomain }} />
</div>
)}
</Drawer>
diff --git a/frontend/src/pages/Marketplace.jsx b/frontend/src/pages/Marketplace.jsx
index 5e2164b1..d366ef9a 100644
--- a/frontend/src/pages/Marketplace.jsx
+++ b/frontend/src/pages/Marketplace.jsx
@@ -96,6 +96,8 @@ const getPublishedCatalogEntry = (extension, installed) => ({
firstParty: isFirstParty(extension.author, extension),
icon: extension.icon || null,
screenshots: Array.isArray(extension.screenshots) ? extension.screenshots : [],
+ permissions: Array.isArray(extension.permissions) ? extension.permissions : [],
+ configSchema: extension.config_schema && typeof extension.config_schema === 'object' ? extension.config_schema : null,
extensionType: extension.extension_type,
installed,
rating: extension.rating,
@@ -126,6 +128,8 @@ const getRegistryCatalogEntry = (entry) => ({
firstParty: isFirstParty(entry.author, entry),
icon: entry.icon || null,
screenshots: Array.isArray(entry.screenshots) ? entry.screenshots : [],
+ permissions: Array.isArray(entry.permissions) ? entry.permissions : [],
+ configSchema: entry.config_schema && typeof entry.config_schema === 'object' ? entry.config_schema : null,
extensionType: 'registry',
installed: Boolean(entry.installed),
status: entry.status,
@@ -156,6 +160,8 @@ const getLocalCatalogEntry = (builtin) => {
firstParty: isFirstParty(manifest.author, manifest),
icon: manifest.icon || null,
screenshots: Array.isArray(manifest.screenshots) ? manifest.screenshots : [],
+ permissions: Array.isArray(manifest.permissions) ? manifest.permissions : [],
+ configSchema: manifest.config_schema && typeof manifest.config_schema === 'object' ? manifest.config_schema : null,
extensionType: 'built-in',
installed: Boolean(builtin.installed),
status: builtin.status,
@@ -195,6 +201,8 @@ const Marketplace = () => {
const [installSource, setInstallSource] = useState('url');
const [installing, setInstalling] = useState(false);
const [detailEntry, setDetailEntry] = useState(null);
+ // Plugin pending uninstall — drives the keep-vs-purge data-policy dialog.
+ const [uninstallTarget, setUninstallTarget] = useState(null);
const loadExtensions = useCallback(async () => {
try {
@@ -303,10 +311,17 @@ const Marketplace = () => {
}
};
- const handlePluginUninstall = async (pluginId) => {
+ // Open the data-policy dialog instead of uninstalling immediately, so the
+ // operator can choose to keep or purge the extension's tables.
+ const requestPluginUninstall = (plugin) => setUninstallTarget(plugin);
+
+ const confirmPluginUninstall = async (purge) => {
+ const plugin = uninstallTarget;
+ setUninstallTarget(null);
+ if (!plugin) return;
try {
- await api.uninstallPlugin(pluginId);
- toast.success('Plugin uninstalled');
+ await api.uninstallPlugin(plugin.id, purge);
+ toast.success(purge ? 'Plugin uninstalled; data purged' : 'Plugin uninstalled; data kept');
loadExtensions();
} catch (err) { toast.error(err.message); }
};
@@ -700,7 +715,7 @@ const Marketplace = () => {
installing={installing}
onToggle={handlePluginToggle}
onUpdate={handlePluginUpdate}
- onUninstall={handlePluginUninstall}
+ onUninstall={requestPluginUninstall}
statusVariant={pluginStatusVariant}
/>
))}
@@ -729,6 +744,14 @@ const Marketplace = () => {
}}
/>
)}
+
+ {uninstallTarget && (
+ <PluginUninstallDialog
+ plugin={uninstallTarget}
+ onCancel={() => setUninstallTarget(null)}
+ onConfirm={confirmPluginUninstall}
+ />
+ )}
</div>
);
};
@@ -844,6 +867,10 @@ const ExtensionDetailModal = ({ entry, installing, statusVariant, onClose, onIns
const isPublished = entry.source === 'published';
const iconSvg = entry.icon ? sanitizeSvgInner(entry.icon) : '';
const screenshots = entry.screenshots || [];
+ const permissions = Array.isArray(entry.permissions) ? entry.permissions : [];
+ const configKeys = entry.configSchema && typeof entry.configSchema === 'object'
+ ? Object.keys(entry.configSchema)
+ : [];
const installedLabel = !isPublished && entry.status && entry.status !== 'active'
? titleCase(entry.status)
: 'Installed';
@@ -884,6 +911,28 @@ const ExtensionDetailModal = ({ entry, installing, statusVariant, onClose, onIns
<p className="extension-detail__desc">{entry.description}</p>
+ {permissions.length > 0 && (
+ <div className="extension-detail__consent">
+ <p className="extension-detail__section-label">This extension requests:</p>
+ <div className="extension-detail__chips">
+ {permissions.map((permission) => (
+ <Badge key={permission} variant="outline">{permission}</Badge>
+ ))}
+ </div>
+ </div>
+ )}
+
+ {configKeys.length > 0 && (
+ <div className="extension-detail__config">
+ <p className="extension-detail__section-label">Configuration</p>
+ <ul className="extension-detail__config-list">
+ {configKeys.map((key) => (
+ <li key={key}><code>{key}</code></li>
+ ))}
+ </ul>
+ </div>
+ )}
+
{screenshots.length > 0 && (
<div className="extension-detail__gallery" aria-label="Screenshots">
{screenshots.map((src, index) => (
@@ -998,7 +1047,7 @@ const PluginRow = ({ plugin, update, installing, onToggle, onUpdate, onUninstall
>
{plugin.status === 'active' ? 'Disable' : 'Enable'}
</Button>
- <Button size="sm" variant="destructive" onClick={() => onUninstall(plugin.id)}>
+ <Button size="sm" variant="destructive" onClick={() => onUninstall(plugin)}>
Uninstall
</Button>
</div>
@@ -1006,6 +1055,33 @@ const PluginRow = ({ plugin, update, installing, onToggle, onUpdate, onUninstall
);
};
+// 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 }) => (
+ <Modal
+ open
+ onClose={onCancel}
+ title={`Uninstall ${plugin.display_name}?`}
+ size="sm"
+ footer={
+ <>
+ <Button variant="ghost" onClick={onCancel}>Cancel</Button>
+ <Button variant="outline" onClick={() => onConfirm(false)}>Keep data</Button>
+ <Button variant="destructive" onClick={() => onConfirm(true)}>Purge data</Button>
+ </>
+ }
+ >
+ <div className="plugin-uninstall-dialog">
+ <p>Removing this extension stops its routes and UI contributions.</p>
+ <p className="text-muted">
+ <strong>Keep data</strong> leaves the extension&apos;s database tables intact so you can
+ reinstall later. <strong>Purge data</strong> permanently drops the extension&apos;s tables
+ and cannot be undone.
+ </p>
+ </div>
+ </Modal>
+);
+
const PluginInstallInput = ({
description,
placeholder,
diff --git a/frontend/src/pages/ServiceDetail.jsx b/frontend/src/pages/ServiceDetail.jsx
index 74a148ea..b116e7f7 100644
--- a/frontend/src/pages/ServiceDetail.jsx
+++ b/frontend/src/pages/ServiceDetail.jsx
@@ -21,6 +21,7 @@ import OverviewTab from '../components/service-detail/OverviewTab';
// imported by SettingsTab rather than rendered as top-level tabs here.
import PreviewList from '../components/previews/PreviewList';
import EmptyState from '../components/EmptyState';
+import PluginSlot from '../components/PluginSlot';
import { Layers, FileArchive, RotateCcw, LayoutDashboard, History, ScrollText, Variable, Terminal, Activity, Package, Server, SquareTerminal, Settings, Eye } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Pill, ServiceTile, PageTopbar } from '@/components/ds';
@@ -558,6 +559,9 @@ const ServiceDetail = () => {
/>
)}
</div>
+
+ {/* Extension slot: widgets contributed to the service detail page */}
+ <PluginSlot name="service.detail.tab" context={{ serviceId: service.id }} />
</div>
</div>
);
diff --git a/frontend/src/services/api/plugins.js b/frontend/src/services/api/plugins.js
index 20088d97..b1e5abcc 100644
--- a/frontend/src/services/api/plugins.js
+++ b/frontend/src/services/api/plugins.js
@@ -32,8 +32,12 @@ export async function installPluginFromZip(file) {
});
}
-export async function uninstallPlugin(pluginId) {
- return this.request(`/plugins/${pluginId}`, {
+// Uninstall a plugin. When `purge` is true the backend also drops the
+// extension's own database tables (?purge=true); otherwise data is kept so the
+// extension can be reinstalled later.
+export async function uninstallPlugin(pluginId, purge = false) {
+ const query = purge ? '?purge=true' : '';
+ return this.request(`/plugins/${pluginId}${query}`, {
method: 'DELETE',
});
}
diff --git a/frontend/src/styles/pages/_marketplace.scss b/frontend/src/styles/pages/_marketplace.scss
index 97489861..50cc761d 100644
--- a/frontend/src/styles/pages/_marketplace.scss
+++ b/frontend/src/styles/pages/_marketplace.scss
@@ -868,4 +868,50 @@
padding-top: $space-4;
border-top: 1px solid $border-subtle;
}
+
+ &__section-label {
+ margin: 0 0 $space-2;
+ color: $text-tertiary;
+ font-size: $font-size-sm;
+ font-weight: $font-weight-medium;
+ }
+
+ &__consent,
+ &__config {
+ display: flex;
+ flex-direction: column;
+ gap: $space-2;
+ }
+
+ &__chips {
+ display: flex;
+ flex-wrap: wrap;
+ gap: $space-2;
+ }
+
+ &__config-list {
+ display: flex;
+ flex-wrap: wrap;
+ gap: $space-2;
+ margin: 0;
+ padding: 0;
+ list-style: none;
+
+ code {
+ font-size: $font-size-sm;
+ color: $text-secondary;
+ }
+ }
+}
+
+// Keep-vs-purge data policy dialog on plugin uninstall.
+.plugin-uninstall-dialog {
+ display: flex;
+ flex-direction: column;
+ gap: $space-3;
+
+ p {
+ margin: 0;
+ line-height: $line-height-normal;
+ }
}
diff --git a/scripts/new-extension.mjs b/scripts/new-extension.mjs
new file mode 100644
index 00000000..571fb58a
--- /dev/null
+++ b/scripts/new-extension.mjs
@@ -0,0 +1,148 @@
+#!/usr/bin/env node
+/**
+ * Scaffold a new ServerKit extension (task #40).
+ *
+ * node scripts/new-extension.mjs <slug> [--backend] [--builtin]
+ *
+ * <slug> kebab-case extension name, e.g. serverkit-uptime-badge
+ * --backend also scaffold a backend/ blueprint + lifecycle skeleton
+ * --builtin scaffold under builtin-extensions/<slug>/ (in-repo, pre-bundled)
+ * instead of a standalone ./<slug>/ folder for a third-party repo
+ *
+ * After scaffolding, install it into a dev panel with:
+ * - builtin: one-click from the Marketplace (Built-in), or
+ * POST /api/v1/plugins/builtin/<slug>/install
+ * - standalone: POST /api/v1/plugins/install-local { "path": "<abs path>" }
+ *
+ * See docs/EXTENSIONS.md for the full authoring guide.
+ */
+import { promises as fs } from 'fs';
+import path from 'path';
+import { fileURLToPath } from 'url';
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
+const ROOT = path.resolve(__dirname, '..');
+
+const args = process.argv.slice(2);
+const slug = args.find((a) => !a.startsWith('--'));
+const withBackend = args.includes('--backend');
+const asBuiltin = args.includes('--builtin');
+
+if (!slug || !/^[a-zA-Z0-9_-]+$/.test(slug)) {
+ console.error('Usage: node scripts/new-extension.mjs <slug> [--backend] [--builtin]');
+ console.error(' <slug> must be alphanumeric/dashes/underscores.');
+ process.exit(1);
+}
+
+const componentName = slug
+ .split(/[-_]/)
+ .map((p) => p.charAt(0).toUpperCase() + p.slice(1))
+ .join('') + 'Page';
+
+const baseDir = asBuiltin
+ ? path.join(ROOT, 'builtin-extensions', slug)
+ : path.join(ROOT, slug);
+
+const manifest = {
+ name: slug,
+ display_name: slug.replace(/[-_]/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase()),
+ version: '0.1.0',
+ description: 'A ServerKit extension.',
+ author: '',
+ license: 'MIT',
+ category: 'utility',
+ permissions: [],
+ min_panel_version: null,
+ contributions: {
+ nav: [{
+ id: slug,
+ label: slug.replace(/[-_]/g, ' '),
+ route: `/${slug}`,
+ category: 'system',
+ icon: '<circle cx="12" cy="12" r="9"/><path d="M12 8v8M8 12h8"/>',
+ }],
+ routes: [{ path: slug, component: componentName }],
+ page_titles: { [`/${slug}`]: slug },
+ command_palette: [{ label: slug, path: `/${slug}`, category: 'Pages', keywords: slug }],
+ },
+};
+
+if (withBackend) {
+ manifest.entry_point = 'blueprint:ext_bp';
+ manifest.url_prefix = `/api/v1/${slug}`;
+ manifest.lifecycle = { install: 'lifecycle:on_install', uninstall: 'lifecycle:on_uninstall' };
+}
+
+const frontendIndex = `// ${manifest.display_name} — extension UI entry.
+// Exports named components referenced by contributions.routes[].component.
+export function ${componentName}() {
+ return (
+ <div className="sk-tabgroup__inner">
+ <h1>${manifest.display_name}</h1>
+ <p>Replace this with your extension UI.</p>
+ </div>
+ );
+}
+`;
+
+const backendBlueprint = `"""${manifest.display_name} backend blueprint."""
+from flask import Blueprint, jsonify
+from app.plugins_sdk import jwt_required, current_user, logger
+
+ext_bp = Blueprint('${slug.replace(/-/g, '_')}', __name__)
+log = logger(__name__)
+
+
+@ext_bp.route('/ping', methods=['GET'])
+@jwt_required()
+def ping():
+ return jsonify({'ok': True, 'plugin': '${slug}'})
+`;
+
+const backendLifecycle = `"""Lifecycle hooks for ${manifest.display_name}."""
+from app.plugins_sdk import logger
+
+log = logger(__name__)
+
+
+def on_install(plugin):
+ log.info('Installing ${slug}')
+
+
+def on_uninstall(plugin, purge=False):
+ log.info('Uninstalling ${slug} (purge=%s)', purge)
+`;
+
+async function writeFile(rel, content) {
+ const full = path.join(baseDir, rel);
+ await fs.mkdir(path.dirname(full), { recursive: true });
+ await fs.writeFile(full, content);
+ console.log(` created ${path.relative(ROOT, full)}`);
+}
+
+async function main() {
+ try {
+ await fs.access(baseDir);
+ console.error(`Refusing to overwrite existing directory: ${baseDir}`);
+ process.exit(1);
+ } catch { /* doesn't exist — good */ }
+
+ console.log(`Scaffolding ${asBuiltin ? 'builtin ' : ''}extension "${slug}"…`);
+ await writeFile('plugin.json', JSON.stringify(manifest, null, 2) + '\n');
+ await writeFile('frontend/index.jsx', frontendIndex);
+ if (withBackend) {
+ await writeFile('backend/blueprint.py', backendBlueprint);
+ await writeFile('backend/lifecycle.py', backendLifecycle);
+ }
+
+ console.log('\nDone.');
+ if (asBuiltin) {
+ console.log('Pre-bundle the frontend: node scripts/sync-builtin-frontends.mjs');
+ console.log('Then install it from the Marketplace (Built-in).');
+ } else {
+ console.log(`Install into a dev panel: POST /api/v1/plugins/install-local { "path": "${baseDir}" }`);
+ }
+ console.log('Guide: docs/EXTENSIONS.md');
+}
+
+main().catch((e) => { console.error(e); process.exit(1); });