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): Phase 0 hygiene — author guide, sync gate, truth pass, tests
Juan Denis74c5e0a88559
diff --git a/.github/workflows/extensions-ci.yml b/.github/workflows/extensions-ci.ymlnew file mode 100644index 00000000..6ae5e700--- /dev/null+++ b/.github/workflows/extensions-ci.yml@@ -0,0 +1,36 @@+name: Extensions CI++# Guards the builtin-extension platform. The pre-bundled plugin frontends under+# frontend/src/plugins/<slug>/ are build artifacts of builtin-extensions/<slug>/+# frontend/ (decision D5 in docs/plans/12_EXTENSIONS_PLATFORM_PLAN.md). They used+# to be hand-duplicated and silently drifted; this job fails the build if the+# artifact no longer matches its source, so the two can never diverge unnoticed.++on:+ push:+ branches: [dev, main]+ paths:+ - 'builtin-extensions/**'+ - 'frontend/src/plugins/**'+ - 'scripts/sync-builtin-frontends.mjs'+ - '.github/workflows/extensions-ci.yml'+ pull_request:+ branches: [dev, main]+ paths:+ - 'builtin-extensions/**'+ - 'frontend/src/plugins/**'+ - 'scripts/sync-builtin-frontends.mjs'+ - '.github/workflows/extensions-ci.yml'+ workflow_call:++jobs:+ builtin-frontend-drift:+ name: builtin frontend drift check+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@v4+ - uses: actions/setup-node@v4+ with:+ node-version: '20'+ - name: Check builtin-extension frontends are in sync+ run: node scripts/sync-builtin-frontends.mjs --checkdiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 581d47e5..f6923399 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -20,6 +20,18 @@ awaiting a stable release:### Added+- **Extensions platform (Phase 0 — hygiene)** — groundwork for the small-core ++ marketplace direction. A single **extension author guide**+ ([`docs/EXTENSIONS.md`](docs/EXTENSIONS.md)) documents the manifest schema,+ contribution envelope, lifecycle hooks, backend SDK, install sources, and the+ production frontend-delivery constraint. Builtin-extension frontends are now+ mechanically kept in sync with their source+ (`scripts/sync-builtin-frontends.mjs` + an `Extensions CI` drift gate) instead+ of hand-duplicated. The Marketplace labels bundled entries honestly ("Built-in"+ rather than "Local mapping/Entries"). First automated coverage for the plugin+ install pipeline (builtin install, contributions envelope, disable→503 guard,+ reinstall metadata refresh, zip-slip rejection).+- **Managed databases** — the databases ServerKit provisions are now tracked asfirst-class resources (beside the existing live explorer): durable rows forbackups and connection strings. A managed database backs a `BackupPolicy` by adiff --git a/backend/tests/test_plugins_pipeline.py b/backend/tests/test_plugins_pipeline.pynew file mode 100644index 00000000..f0673e60--- /dev/null+++ b/backend/tests/test_plugins_pipeline.py@@ -0,0 +1,212 @@+"""Baseline coverage for the plugin/extension install pipeline.++These behaviors already existed (builtin install, the contributions envelope,+the disable→503 guard, reinstall metadata refresh, zip-slip rejection) but were+untested. Phase 0 of docs/plans/12_EXTENSIONS_PLATFORM_PLAN.md locks them in+before later phases build on them.+"""+import json+import os++import pytest++from app import db+from app.models.plugin import InstalledPlugin+from app.services import plugin_service+++# --------------------------------------------------------------------------- #+# Fixtures+# --------------------------------------------------------------------------- #++def plugin_dirs(tmp_path, monkeypatch):+ """Redirect the plugin service's on-disk targets into a temp tree so tests+ never touch the real repo's backend/app/plugins or frontend/src/plugins."""+ backend = tmp_path / 'backend_plugins'+ frontend = tmp_path / 'frontend_plugins'+ builtin = tmp_path / 'builtin_extensions'+ backend.mkdir()+ frontend.mkdir()+ builtin.mkdir()+ monkeypatch.setattr(plugin_service, 'BACKEND_PLUGINS_DIR', str(backend))+ monkeypatch.setattr(plugin_service, 'FRONTEND_PLUGINS_DIR', str(frontend))+ monkeypatch.setattr(plugin_service, 'BUILTIN_EXTENSIONS_DIR', str(builtin))+ return {'backend': backend, 'frontend': frontend, 'builtin': builtin}+++def _write_builtin(builtin_dir, slug='serverkit-demo', version='1.0.0',+ display_name='Demo Extension'):+ """Create a minimal frontend-only builtin extension on disk."""+ folder = builtin_dir / slug+ (folder / 'frontend').mkdir(parents=True)+ manifest = {+ 'name': slug,+ 'display_name': display_name,+ 'version': version,+ 'description': 'A demo builtin extension.',+ 'author': 'ServerKit',+ 'category': 'utility',+ 'permissions': ['filesystem'],+ 'contributions': {+ 'nav': [{'id': 'demo', 'label': 'Demo', 'route': '/demo',+ 'category': 'system', 'icon': '<circle cx="12" cy="12" r="8"/>'}],+ 'routes': [{'path': 'demo', 'component': 'DemoPage'}],+ 'page_titles': {'/demo': 'Demo'},+ 'command_palette': [{'label': 'Demo', 'path': '/demo',+ 'category': 'Pages', 'keywords': 'demo'}],+ },+ }+ (folder / 'plugin.json').write_text(json.dumps(manifest), encoding='utf-8')+ (folder / 'frontend' / 'index.jsx').write_text(+ 'export function DemoPage() { return null; }\n', encoding='utf-8')+ return folder, manifest+++# --------------------------------------------------------------------------- #+# Zip-slip defense+# --------------------------------------------------------------------------- #+[email protected]('evil', [+ '../../etc/passwd',+ 'a/../../b',+ '..\\..\\windows\\system32',+ 'C:\\Windows\\system32', # drive-qualified absolute path+])+def test_safe_extract_path_rejects_traversal(tmp_path, evil):+ with pytest.raises(ValueError):+ plugin_service._safe_extract_path(str(tmp_path), evil)+++def test_safe_extract_path_allows_normal(tmp_path):+ out = plugin_service._safe_extract_path(str(tmp_path), 'sub/dir/file.py')+ assert out.startswith(str(tmp_path))+++def test_safe_extract_path_neutralizes_leading_slash(tmp_path):+ # A rooted POSIX path is not an error — the leading slash is stripped so+ # the entry lands *inside* the destination rather than at the filesystem+ # root. The guarantee is containment, not rejection.+ out = plugin_service._safe_extract_path(str(tmp_path), '/etc/cron.d/x')+ assert out.startswith(str(tmp_path))+ assert out.endswith(os.path.join('etc', 'cron.d', 'x'))+++# --------------------------------------------------------------------------- #+# Builtin install + reinstall metadata refresh+# --------------------------------------------------------------------------- #++def test_install_builtin_creates_active_plugin(app, plugin_dirs):+ _write_builtin(plugin_dirs['builtin'])++ listed = plugin_service.list_builtin_extensions()+ assert len(listed) == 1+ assert listed[0]['slug'] == 'serverkit-demo'+ assert listed[0]['status'] == 'not_installed'++ plugin = plugin_service.install_builtin_extension('serverkit-demo')+ assert plugin.status == InstalledPlugin.STATUS_ACTIVE+ assert plugin.has_frontend is True+ assert plugin.has_backend is False+ # Contributions survive the round-trip through the manifest.+ assert plugin.manifest['contributions']['nav'][0]['route'] == '/demo'++ # The pre-bundled frontend was written into the (temp) plugins dir.+ assert (plugin_dirs['frontend'] / 'serverkit-demo' / 'index.jsx').exists()+++def test_reinstall_refreshes_metadata(app, plugin_dirs):+ folder, manifest = _write_builtin(plugin_dirs['builtin'])+ plugin_service.install_builtin_extension('serverkit-demo')++ # An active plugin can't be reinstalled directly — disable it first.+ existing = InstalledPlugin.query.filter_by(slug='serverkit-demo').first()+ plugin_service.disable_plugin(existing.id)++ # Bump the manifest and reinstall.+ manifest['version'] = '2.0.0'+ manifest['display_name'] = 'Demo Extension v2'+ (folder / 'plugin.json').write_text(json.dumps(manifest), encoding='utf-8')++ plugin = plugin_service.install_builtin_extension('serverkit-demo')+ assert plugin.version == '2.0.0'+ assert plugin.display_name == 'Demo Extension v2'+ assert plugin.status == InstalledPlugin.STATUS_ACTIVE+ # Still a single row — reinstall updates in place.+ assert InstalledPlugin.query.filter_by(slug='serverkit-demo').count() == 1+++def test_reinstall_active_plugin_is_rejected(app, plugin_dirs):+ _write_builtin(plugin_dirs['builtin'])+ plugin_service.install_builtin_extension('serverkit-demo')+ with pytest.raises(ValueError, match='already installed'):+ plugin_service.install_builtin_extension('serverkit-demo')+++# --------------------------------------------------------------------------- #+# Contributions endpoint envelope+# --------------------------------------------------------------------------- #++def test_contributions_endpoint_envelope(app, client, auth_headers, plugin_dirs):+ _write_builtin(plugin_dirs['builtin'])+ plugin_service.install_builtin_extension('serverkit-demo')++ resp = client.get('/api/v1/plugins/contributions', headers=auth_headers)+ assert resp.status_code == 200+ data = resp.get_json()++ # The envelope always carries every key.+ for key in ('nav', 'routes', 'page_titles', 'command_palette', 'widgets',+ 'layouts', 'ai'):+ assert key in data++ # Contributions are tagged with the source plugin slug.+ assert any(n.get('plugin') == 'serverkit-demo' and n.get('route') == '/demo'+ for n in data['nav'])+ assert any(r.get('plugin') == 'serverkit-demo' and r.get('component') == 'DemoPage'+ for r in data['routes'])+ assert data['page_titles'].get('/demo') == 'Demo'+++def test_disabled_plugin_drops_from_contributions(app, client, auth_headers, plugin_dirs):+ _write_builtin(plugin_dirs['builtin'])+ plugin = plugin_service.install_builtin_extension('serverkit-demo')++ plugin_service.disable_plugin(plugin.id)+ resp = client.get('/api/v1/plugins/contributions', headers=auth_headers)+ assert resp.status_code == 200+ assert not any(n.get('plugin') == 'serverkit-demo' for n in resp.get_json()['nav'])+++# --------------------------------------------------------------------------- #+# Disable guard: a disabled plugin's routes return 503+# --------------------------------------------------------------------------- #++def test_disable_guard_returns_503(app):+ from flask import Blueprint, jsonify++ p = InstalledPlugin(+ name='guard-test', display_name='Guard Test', slug='guard-test',+ version='1.0.0', status=InstalledPlugin.STATUS_ACTIVE, has_backend=True,+ )+ p.manifest = {}+ db.session.add(p)+ db.session.commit()++ bp = Blueprint('guard_test_bp', __name__)++ @bp.route('/ping')+ def ping():+ return jsonify({'ok': True})++ plugin_service._attach_status_guard(bp, 'guard-test')+ app.register_blueprint(bp, url_prefix='/api/v1/guard-test')++ c = app.test_client()+ assert c.get('/api/v1/guard-test/ping').status_code == 200++ p.status = InstalledPlugin.STATUS_DISABLED+ db.session.commit()+ r = c.get('/api/v1/guard-test/ping')+ assert r.status_code == 503+ assert r.get_json()['status'] == 'disabled'diff --git a/docs/EXTENSIONS.md b/docs/EXTENSIONS.mdnew file mode 100644index 00000000..9cdee29f--- /dev/null+++ b/docs/EXTENSIONS.md@@ -0,0 +1,317 @@+# Extension Author Guide++ServerKit is a small core of primitives plus optional **extensions** installed+from the Marketplace. This document is the honest, single reference for building+one: the manifest schema, the contribution envelope, lifecycle hooks, the backend+SDK, install sources, and — importantly — the constraints you will hit in+production.++> If you only remember one thing: **an extension's frontend must be compiled into+> the panel's Vite bundle to render.** For builtin (in-repo) extensions we handle+> this by pre-bundling (see [The production frontend constraint](#the-production-frontend-constraint)).+> A third-party extension that ships only a backend works everywhere today; one+> that ships a frontend needs the delivery mechanism tracked in Phase 3 of the+> platform plan.++---++## Anatomy of an extension++An extension is a folder (zipped for distribution) with this layout:++```+my-extension/+ plugin.json # manifest — the only required file+ backend/ # optional: Flask blueprint + services + lifecycle hooks+ blueprint.py+ lifecycle.py+ frontend/ # optional: React components exposed to the host UI+ index.jsx # entry module — named exports referenced by contributions+ styles/+ my-extension.scss+```++- `backend/` is extracted to `backend/app/plugins/<slug>/` on the panel host and+ its blueprint is hot-loaded (no restart needed for install).+- `frontend/` is extracted to `frontend/src/plugins/<slug>/`. For builtin+ extensions this directory is **checked in** (a build artifact — see below).+- Either half is optional. A pure-frontend extension (like `serverkit-git`, whose+ backend API stays in core) declares only `contributions`; a pure-backend+ extension declares an `entry_point` and no frontend.++---++## `plugin.json` manifest++```jsonc+{+ "name": "serverkit-git", // required — slug: ^[a-zA-Z0-9_-]+$+ "display_name": "Git Server", // required+ "version": "1.0.0", // required — semver recommended+ "description": "…",+ "author": "ServerKit",+ "homepage": "https://…",+ "repository": "https://…",+ "license": "MIT",+ "category": "deployment", // ai|monitoring|security|deployment|integration|ui|utility+ "icon": "<svg…>", // optional — rendered on the marketplace detail view+ "screenshots": ["https://…/1.png"], // optional — rendered on the detail view++ "permissions": ["docker", "filesystem"], // docker|filesystem|shell|network|db+ "min_panel_version": "1.7.0", // optional compat gate (enforced at install)+ "max_panel_version": "2.0.0", // optional++ "entry_point": "blueprint:git_bp", // backend: module:bp_var under app.plugins.<slug>+ "url_prefix": "/api/v1/git", // defaults to /api/v1/<slug>++ "templates": ["gitea"], // app-template ids to install alongside+ "lifecycle": { // module:func hooks under app.plugins.<slug>+ "install": "lifecycle:on_install",+ "uninstall": "lifecycle:on_uninstall",+ "upgrade": "lifecycle:on_upgrade"+ },++ "models": ["models:register"], // optional — plugin-owned tables (see Data models)+ "config_schema": { … }, // optional — rendered as a settings form++ "contributions": { … } // UI contributions — see below+}+```++The authoritative, machine-readable contract is served at+`GET /api/v1/plugins/manifest-spec` and mirrors what `plugin_service.py` actually+consumes — keep them in sync when extending the schema.++---++## The `contributions` envelope++Everything an extension adds to the host UI is declared here. Each entry is+tagged at runtime with its source `plugin` slug so the frontend can resolve+`component` strings against the right module.++```jsonc+"contributions": {+ "nav": [+ { "id": "git", "label": "Git", "route": "/git",+ "category": "infrastructure", "icon": "<circle …/>",+ "requiresCondition": "gpuAvailable" } // optional runtime gate+ ],+ "routes": [+ { "path": "git", "component": "GitExtensionPage" },+ { "path": "git/:tab", "component": "GitExtensionPage", "layout": "padded" }+ ],+ "page_titles": { "/git": "Git Repositories" },+ "command_palette": [+ { "label": "Git", "path": "/git", "category": "Pages", "keywords": "repos deploy" }+ ],+ "widgets": [ { "slot": "dashboard.top", "component": "GitStatusWidget" } ],+ "layouts": [ { "id": "my-fullscreen", "component": "MyLayout" } ],+ "ai": {+ "suggested_prompts": [ { "route": "/git", "label": "…", "prompt": "…" } ],+ "tool_renderers": [ { "tool": "git__list_branches", "component": "BranchList" } ]+ }+}+```++| Kind | Shape | Notes |+|---|---|---|+| `nav` | `{id,label,route,category,icon,requiresCondition?}` | `icon` is raw inner-SVG markup. `category`: overview/infrastructure/operations/system. Merged into the sidebar; deduped by `id`. |+| `routes` | `{path,component,layout?}` | `component` = a named export of the plugin's `index.{js,jsx}`. `layout`: `padded` (default) / `full` / `bare` / a custom layout id. |+| `page_titles` | `{ "/path": "Title" }` | Sets `document.title`. |+| `command_palette` | `{label,path,category,keywords}` | `category` defaults to `Extensions`. |+| `widgets` | `{slot,component}` | Slots: `global` (renders inside DashboardLayout), plus the enrich-core slots (`dashboard.top`, `service.detail.tab`, `domain.drawer.panel`). |+| `layouts` | `{id,component}` | Custom wrappers; the component must render `<Outlet/>`. Built-in ids `padded`/`full`/`bare` are reserved. |+| `ai` | `{suggested_prompts,tool_renderers}` | See [AI](#extending-the-ai-assistant). |++### Route layouts++- `padded` (default) — inside `DashboardLayout`, normal padding.+- `full` — inside `DashboardLayout`, no padding (like `/files`, `/docker`).+- `bare` — **outside** `DashboardLayout` (no sidebar), under the auth guard —+ fullscreen authenticated pages.+- `<custom-id>` — wrapped in a `layouts`-contributed component.++---++## The production frontend constraint++`frontend/src/plugins/contributions.js` discovers plugin UI modules at **build+time** via `import.meta.glob('../plugins/*/index.{js,jsx}')`. Two consequences you+must design around:++1. **Builtin (in-repo) extensions work in production** because their frontend+ halves are checked into `frontend/src/plugins/<slug>/` and compiled into every+ shipped bundle. "Install" just flips the runtime contribution envelope on.+2. **A third-party extension that ships a frontend does *not* render on a+ production panel** (the panel serves a pre-built bundle; `plugin_service` copies+ files but nothing rebuilds Vite). Its **backend half loads fine.** Until the+ Phase 3 frontend-delivery mechanism lands, third-party extensions should be+ backend-only, or use a `bare`/custom layout escape hatch.++### D5 — builtin frontends are pre-bundled (single source of truth)++For an in-repo extension, `builtin-extensions/<slug>/frontend/` is the **source of+truth**; `frontend/src/plugins/<slug>/` is a **generated artifact**. Never edit the+artifact by hand. Regenerate it with:++```bash+node scripts/sync-builtin-frontends.mjs # source → artifact+node scripts/sync-builtin-frontends.mjs --check # CI drift gate (fails on drift)+```++The `Extensions CI` workflow runs `--check` on every change to+`builtin-extensions/**` or `frontend/src/plugins/**`, so the two can never+silently diverge.++---++## Backend SDK (`app.plugins_sdk`)++Depend on the SDK, not on host internals — as long as this surface is stable,+core refactors won't break you.++```python+from flask import Blueprint, request, jsonify+from app.plugins_sdk import (+ db, jwt_required, current_user, audit, logger,+ ai, queue, notify, jobs,+)++my_bp = Blueprint('my_ext', __name__)+log = logger(__name__)++@my_bp.route('/things', methods=['GET'])+@jwt_required()+def list_things():+ user = current_user()+ return jsonify({'ok': True})+```++| Name | What it is |+|---|---|+| `db` | SQLAlchemy handle (`db.session`, `db.Model`). |+| `jwt_required`, `get_jwt`, `get_jwt_identity` | Flask-JWT-Extended re-exports. |+| `current_user()` | Resolves the JWT identity to a `User` row (or `None`). |+| `audit(action, target_type, …)` | Write an audit-log entry. |+| `logger(name)` | Module-scoped logger. |+| `ai` | Extend the core assistant (tools, context, prompts). |+| `queue` | Queue Bus SDK (publish/consume). |+| `notify` | Notifications SDK (`notify.send(event, to, data)`). |+| `jobs` | Jobs SDK (schedule/enqueue background work). |++Errors follow the core convention: `return jsonify({'error': 'message'}), status`.++### Blueprint registration & the disable guard++`entry_point` (`module:bp_var`) is imported from `app.plugins.<slug>.<module>` and+registered at `url_prefix`. A `before_request` guard is attached automatically:+when the plugin's DB status isn't `active`, its routes return **503** — so+disabling an extension actually stops serving it, even though Flask can't+unregister a blueprint from a running app.++Keep the same `/api/v1/<feature>` prefix when a feature moves from core into an+extension (decision D9) so existing agents/scripts/UI keep working.++---++## Lifecycle hooks++Declared under `lifecycle`; resolved as `module:func` under `app.plugins.<slug>`.+Each hook receives the `InstalledPlugin` row as its single positional arg.++- `install` — runs **after** files are extracted (e.g. seed default rows).+- `upgrade` — runs when installing a version different from the installed one.+- `uninstall` — runs **before** files are removed. Receives whether the caller+ requested a data purge (see [Data policy](#data-models--policy)).++Hook failures are logged and swallowed — hooks are convenience, not correctness.++---++## Data models & policy++Raw `db` access works, but for tables you own, declare a `models` entry point so+the platform can create/upgrade/clean them up:++```python+# app/plugins/<slug>/models.py+def register(ctx):+ """Return SQLAlchemy model classes owned by this extension.+ Table names are prefixed ext_<slug>_ automatically."""+ ...+```++- 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.++---++## Extending the AI assistant++The assistant is core (decision D7) — you never rebuild it, you extend it. Declare+an `ai` block and ship `app/plugins/<slug>/ai.py`:++```python+from app.plugins_sdk import ai++def register(reg): # reg is a PluginToolBinder+ @reg.tool(rbac_feature="git", rbac_level="read")+ def list_branches(repo: str) -> list:+ """List branches in a repo. Args: repo: repository slug."""+ from app.services.git_service import GitService+ return GitService.list_branches(repo)+```++Tools are namespaced `<slug>__<name>`, RBAC-gated per tool, and write tools+(`is_write=True`) always route through confirmation.++---++## Install sources++| Source | How | Endpoint |+|---|---|---|+| Builtin (in-repo) | One-click from the Marketplace | `POST /api/v1/plugins/builtin/<slug>/install` |+| GitHub / release / zip URL | Paste a URL | `POST /api/v1/plugins/install` |+| Uploaded zip | Upload (≤ 50 MB) | `POST /api/v1/plugins/install-upload` |+| Local path (dev) | Panel-host path | `POST /api/v1/plugins/install-local` |+| Registry | Curated index (checksum-verified) | via Marketplace Browse |++All sources funnel through one install pipeline (`_install_from_buffer`) so+behavior is identical. Zip-slip is rejected (absolute paths, `..`, escaping+entries). Python `requirements.txt` is **not** installed unless the operator sets+`SERVERKIT_ALLOW_PLUGIN_PIP=1` (installing runs pip with the backend's+privileges).++### Docker note++A dockerized backend only sees `/app`, not the host's `frontend/` tree. To install+an extension that ships a frontend on such a panel, bind-mount the host's+`frontend/src/plugins` into the container and set+`SERVERKIT_FRONTEND_PLUGINS_DIR`, or run the backend natively for development.++---++## Converting a core page into a builtin extension (recipe)++Proven with `serverkit-git`; automated by the one-shot upgrade auto-install+(so existing users never lose a page). Steps:++1. Create `builtin-extensions/<slug>/plugin.json` with the `contributions`+ (nav / routes / page_titles / command_palette) that reproduce the page.+2. Create `builtin-extensions/<slug>/frontend/index.jsx` — usually a thin+ re-export of the existing host page while the backend API stays in core:+ ```jsx+ import GpuMonitor from '../../pages/GpuMonitor';+ export function GpuMonitorPage() { return <GpuMonitor />; }+ ```+3. Remove the hardcoded entries from `App.jsx` (import + `<Route>` + `PAGE_TITLES`),+ `sidebarItems.js` (or the group `*Tabs.jsx`), and `CommandPalette.jsx`.+4. Pre-bundle: `node scripts/sync-builtin-frontends.mjs`.+5. The backend API stays core for now (two-speed extraction, decision D2). Full+ backend extraction happens only after the Phase 3 primitives exist.++Existing panels auto-install converted builtins once on upgrade (a marker in+settings) so nothing disappears; fresh installs see them in the Marketplace.diff --git a/frontend/src/pages/Marketplace.jsx b/frontend/src/pages/Marketplace.jsxindex 1ef883b1..50200ba2 100644--- a/frontend/src/pages/Marketplace.jsx+++ b/frontend/src/pages/Marketplace.jsx@@ -97,15 +97,15 @@ const getLocalCatalogEntry = (builtin) => {return {key: `local:${builtin.slug}`,source: 'local',- sourceLabel: 'Local mapping',- sourceDetail: 'Mapped in local registry',+ sourceLabel: 'Built-in',+ sourceDetail: 'Bundled with ServerKit',installKey: builtin.slug,displayName: manifest.display_name || builtin.slug,- description: manifest.description || 'Local extension package.',+ description: manifest.description || 'Bundled extension.',category: manifest.category || 'utility',version: manifest.version || '0.0.0',author: manifest.author,- extensionType: 'local',+ extensionType: 'built-in',installed: Boolean(builtin.installed),status: builtin.status,};@@ -294,7 +294,7 @@ const Marketplace = () => {<div className="sk-tabgroup__inner marketplace-page"><StatStrip ariaLabel="Marketplace summary"><Stat label="Catalog" value={availableCount} />- <Stat label="Local Entries" value={builtins.length} />+ <Stat label="Built-in" value={builtins.length} /><Stat label="Installed" value={installedCatalogCount} /><Statlabel="Active Plugins"@@ -442,8 +442,8 @@ const Marketplace = () => {</div><div className="marketplace-runtime"><RuntimeRow label="Published installs" value={formatCount(totalDownloads)} />- <RuntimeRow label="Local mappings" value={builtins.length} />- <RuntimeRow label="Installed local" value={`${installedBuiltinCount}/${builtins.length}`} />+ <RuntimeRow label="Built-in" value={builtins.length} />+ <RuntimeRow label="Built-in installed" value={`${installedBuiltinCount}/${builtins.length}`} /><RuntimeRow label="Active plugins" value={`${activePluginCount}/${plugins.length}`} /><RuntimeRowlabel="Plugin issues"@@ -667,7 +667,7 @@ const CatalogExtensionCard = ({ entry, installing, onInstall, statusVariant }) ={entry.author && <span>by {entry.author}</span>}{entry.extensionType && (<Badge variant="secondary">- {isLocal ? 'local db' : entry.extensionType}+ {isLocal ? 'built-in' : entry.extensionType}</Badge>)}</div>diff --git a/frontend/src/plugins/contributions.js b/frontend/src/plugins/contributions.jsindex a718ec23..fcfd19bb 100644--- a/frontend/src/plugins/contributions.js+++ b/frontend/src/plugins/contributions.js@@ -81,61 +81,12 @@ const EMPTY = {ai: { suggested_prompts: [], tool_renderers: [] },};-const GIT_PLUGIN_SLUG = 'serverkit-git';-const GIT_ICON = '<circle cx="18" cy="18" r="3"/><circle cx="6" cy="6" r="3"/><path d="M6 21V9a9 9 0 0 0 9 9"/>';-+// Merge a raw contribution envelope onto the empty shape so every+// consumer sees the full set of keys. Extension-specific values (nav,+// routes, titles, palette entries) now come entirely from each plugin's+// manifest — there are no host-side compatibility rewrites here.function normalizeContributions(value) {- const out = { ...EMPTY, ...(value || {}) };- const hasGitPlugin = [- ...(out.nav || []),- ...(out.routes || []),- ...(out.command_palette || []),- ].some((item) => item?.plugin === GIT_PLUGIN_SLUG);-- if (!hasGitPlugin) return out;-- const oldGitNav = (out.nav || []).find((item) => item?.plugin === GIT_PLUGIN_SLUG);-- // Compatibility for the initial Git extension experiment, which- // contributed /git-ext while the host still owned /git. The extension- // is now the canonical Git surface.- return {- ...out,- nav: [- ...(out.nav || []).filter((item) => item?.plugin !== GIT_PLUGIN_SLUG),- {- ...oldGitNav,- plugin: GIT_PLUGIN_SLUG,- id: 'git',- label: 'Git',- route: '/git',- category: oldGitNav?.category || 'infrastructure',- icon: oldGitNav?.icon || GIT_ICON,- },- ],- routes: [- ...(out.routes || []).filter((item) => item?.plugin !== GIT_PLUGIN_SLUG),- { plugin: GIT_PLUGIN_SLUG, path: 'git', component: 'GitExtensionPage' },- { plugin: GIT_PLUGIN_SLUG, path: 'git/:tab', component: 'GitExtensionPage' },- ],- page_titles: {- ...(Object.fromEntries(- Object.entries(out.page_titles || {})- .filter(([path]) => path !== '/git-ext')- )),- '/git': 'Git Repositories',- },- command_palette: [- ...(out.command_palette || []).filter((item) => item?.plugin !== GIT_PLUGIN_SLUG),- {- plugin: GIT_PLUGIN_SLUG,- label: 'Git',- path: '/git',- category: 'Pages',- keywords: 'git repos deploy extension plugin',- },- ],- };+ return { ...EMPTY, ...(value || {}) };}function tagItems(items, slug) {diff --git a/scripts/sync-builtin-frontends.mjs b/scripts/sync-builtin-frontends.mjsnew file mode 100644index 00000000..33e091d1--- /dev/null+++ b/scripts/sync-builtin-frontends.mjs@@ -0,0 +1,158 @@+#!/usr/bin/env node+/**+ * Sync builtin-extension frontends into the pre-bundled plugin tree.+ *+ * Decision D5 / task #3 of docs/plans/12_EXTENSIONS_PLATFORM_PLAN.md:+ *+ * `builtin-extensions/<slug>/frontend/` is the SINGLE SOURCE OF TRUTH for a+ * builtin extension's UI. `frontend/src/plugins/<slug>/` is a *build artifact*+ * of it — checked in only so Vite's build-time `import.meta.glob` can compile+ * the extension into every shipped bundle (the production frontend-delivery+ * constraint documented in the plan §1.3).+ *+ * Historically the two copies were hand-maintained and silently drifted. This+ * script makes the relationship mechanical:+ *+ * - `node scripts/sync-builtin-frontends.mjs` → copy source → artifact+ * - `node scripts/sync-builtin-frontends.mjs --check` → fail (exit 1) on drift+ *+ * Only builtin extensions that actually ship a `frontend/` dir are managed.+ * Other entries under frontend/src/plugins/ (e.g. serverkit-gui, whose source+ * lives in a sibling repo, and the shared sdk/ + loader files) are left alone.+ */+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 BUILTIN_DIR = path.join(ROOT, 'builtin-extensions');+const PLUGINS_DIR = path.join(ROOT, 'frontend', 'src', 'plugins');++const CHECK = process.argv.includes('--check');++async function exists(p) {+ try { await fs.access(p); return true; } catch { return false; }+}++async function readJson(p) {+ return JSON.parse(await fs.readFile(p, 'utf8'));+}++// Canonical on-disk form of a manifest: 2-space indent + trailing newline.+// Normalizing here means the source manifest's own formatting is irrelevant —+// the check compares semantic content, not whitespace.+function canonicalManifest(manifest) {+ return JSON.stringify(manifest, null, 2) + '\n';+}++// Recursively collect relative file paths under `dir` (posix separators).+async function walk(dir, base = dir) {+ const out = [];+ let entries;+ try {+ entries = await fs.readdir(dir, { withFileTypes: true });+ } catch {+ return out;+ }+ for (const e of entries.sort((a, b) => a.name.localeCompare(b.name))) {+ const full = path.join(dir, e.name);+ if (e.isDirectory()) {+ out.push(...await walk(full, base));+ } else if (e.isFile()) {+ out.push(path.relative(base, full).split(path.sep).join('/'));+ }+ }+ return out;+}++// Build the expected file map { relPath: Buffer } for a managed slug.+async function expectedFiles(builtinSlugDir, manifest) {+ const map = new Map();+ const frontendSrc = path.join(builtinSlugDir, 'frontend');+ for (const rel of await walk(frontendSrc)) {+ map.set(rel, await fs.readFile(path.join(frontendSrc, rel)));+ }+ // The pre-bundled copy also carries the manifest so contributions.js can+ // read it at build time (import.meta.glob of plugin.json).+ map.set('plugin.json', Buffer.from(canonicalManifest(manifest), 'utf8'));+ return map;+}++async function main() {+ if (!(await exists(BUILTIN_DIR))) {+ console.error(`No builtin-extensions dir at ${BUILTIN_DIR}`);+ process.exit(CHECK ? 1 : 0);+ }++ const folders = (await fs.readdir(BUILTIN_DIR, { withFileTypes: true }))+ .filter((e) => e.isDirectory())+ .map((e) => e.name)+ .sort();++ const drift = [];+ let managed = 0;++ for (const folder of folders) {+ const slugDir = path.join(BUILTIN_DIR, folder);+ const manifestPath = path.join(slugDir, 'plugin.json');+ const frontendSrc = path.join(slugDir, 'frontend');++ // Only builtins that ship a frontend are managed here.+ if (!(await exists(manifestPath)) || !(await exists(frontendSrc))) continue;++ const manifest = await readJson(manifestPath);+ const slug = manifest.name || folder;+ const target = path.join(PLUGINS_DIR, slug);+ managed += 1;++ const expected = await expectedFiles(slugDir, manifest);++ if (CHECK) {+ const actualRel = new Set(await walk(target));+ for (const [rel, buf] of expected) {+ const cur = path.join(target, rel);+ if (!(await exists(cur))) {+ drift.push(`missing ${slug}/${rel}`);+ continue;+ }+ const got = await fs.readFile(cur);+ if (!got.equals(buf)) drift.push(`differs ${slug}/${rel}`);+ actualRel.delete(rel);+ }+ for (const rel of actualRel) drift.push(`extra ${slug}/${rel}`);+ } else {+ // Write mode: mirror source → artifact, pruning stale files.+ const actualRel = new Set(await walk(target));+ for (const [rel, buf] of expected) {+ const cur = path.join(target, rel);+ await fs.mkdir(path.dirname(cur), { recursive: true });+ await fs.writeFile(cur, buf);+ actualRel.delete(rel);+ }+ for (const rel of actualRel) {+ await fs.rm(path.join(target, rel));+ }+ console.log(`synced ${slug} (${expected.size} files)`);+ }+ }++ if (CHECK) {+ if (drift.length) {+ console.error('Builtin-extension frontend drift detected:\n');+ for (const d of drift) console.error(` ${d}`);+ console.error(+ '\nThe pre-bundled copy under frontend/src/plugins/ is out of sync '+ + 'with its source under builtin-extensions/<slug>/frontend/.\n'+ + 'Run: node scripts/sync-builtin-frontends.mjs and commit the result.'+ );+ process.exit(1);+ }+ console.log(`Builtin-extension frontends in sync (${managed} managed).`);+ }+}++main().catch((e) => {+ console.error(e);+ process.exit(1);+});