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): settings.section slot + manifest shape lint (#52)

Juan Denis0ec55accbe77
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 41dad14d..b44a4015 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -28,6 +28,13 @@ awaiting a stable release:
### Added
+- **Extensions platform (Phase 7 — settings slot + manifest linting)** — extensions
+ can now contribute sections to the Settings page (a `settings.section` widget
+ slot rendered below the active tab), and `plugin.json` manifests are shape-checked
+ at install time: malformed entry points, socket/model references, jobs, schedules,
+ or contribution entries now fail the install with a message naming each problem
+ instead of being silently dropped at runtime. Authors get the same rules locally
+ via `node scripts/new-extension.mjs --validate <path>`.
- **Extensions platform (Phase 7 — scheduled update checks)** — the panel now
checks the extension registry for updates once a day (a regular scheduled job,
visible under Jobs) and notifies admins through the Notifications Bus when new
diff --git a/backend/app/services/plugin_service.py b/backend/app/services/plugin_service.py
index e67b9332..c4d40f59 100644
--- a/backend/app/services/plugin_service.py
+++ b/backend/app/services/plugin_service.py
@@ -223,8 +223,34 @@ def _find_manifest(zf):
return None, None
+# 'module:attr' references (entry_point, socket_entry, models, lifecycle hooks,
+# job handlers). Module part may be dotted; attr must be a bare identifier.
+_MODULE_REF_RE = re.compile(r'^[A-Za-z_][\w.]*:[A-Za-z_]\w*$')
+
+# Required keys per contribution kind (mirrors GET /plugins/manifest-spec and
+# docs/EXTENSIONS.md — keep the three in sync).
+_REQUIRED_CONTRIB_KEYS = {
+ 'nav': ('id', 'label', 'route'),
+ 'routes': ('path', 'component'),
+ 'tabs': ('group', 'to', 'label'),
+ 'command_palette': ('label', 'path'),
+ 'widgets': ('slot', 'component'),
+ 'layouts': ('id', 'component'),
+}
+
+_KNOWN_CONTRIB_KINDS = set(_REQUIRED_CONTRIB_KEYS) | {'page_titles', 'ai'}
+
+
def _validate_manifest(manifest):
- """Validate required fields in plugin manifest."""
+ """Validate the manifest: required fields plus the SHAPE of every
+ declarative block the platform consumes (#52).
+
+ A malformed block used to be silently skipped at runtime (contribution
+ dropped, socket never registered, job never scheduled) — hard to debug.
+ Now the install fails with a message naming each problem. Unknown
+ contribution kinds only warn, so newer manifests stay installable on
+ older panels (forward compat).
+ """
required = ['name', 'display_name', 'version']
missing = [f for f in required if f not in manifest]
if missing:
@@ -235,6 +261,77 @@ def _validate_manifest(manifest):
if not re.match(r'^[a-zA-Z0-9_-]+$', name):
raise ValueError(f"Plugin name must be alphanumeric/dashes/underscores: {name}")
+ problems = []
+
+ for field in ('entry_point', 'socket_entry', 'models'):
+ val = manifest.get(field)
+ if val and not (isinstance(val, str) and _MODULE_REF_RE.match(val)):
+ problems.append(f"{field} must be a 'module:attr' string (got {val!r})")
+
+ lifecycle = manifest.get('lifecycle')
+ if lifecycle is not None:
+ if not isinstance(lifecycle, dict):
+ problems.append('lifecycle must be an object of phase -> module:func')
+ else:
+ for phase, target in lifecycle.items():
+ if not (isinstance(target, str) and _MODULE_REF_RE.match(target)):
+ problems.append(
+ f"lifecycle.{phase} must be a 'module:func' string (got {target!r})")
+
+ jobs = manifest.get('jobs')
+ if jobs is not None:
+ if not isinstance(jobs, list):
+ problems.append('jobs must be a list of {kind, handler}')
+ else:
+ for i, j in enumerate(jobs):
+ if not (isinstance(j, dict) and j.get('kind')
+ and isinstance(j.get('handler'), str)
+ and _MODULE_REF_RE.match(j['handler'])):
+ problems.append(f"jobs[{i}] must be {{kind, handler: 'module:func'}}")
+
+ schedules = manifest.get('schedules')
+ if schedules is not None:
+ if not isinstance(schedules, list):
+ problems.append('schedules must be a list of {name, kind, cron?|interval_seconds?}')
+ else:
+ for i, s in enumerate(schedules):
+ if not (isinstance(s, dict) and s.get('name') and s.get('kind')):
+ problems.append(f'schedules[{i}] needs name and kind')
+
+ contrib = manifest.get('contributions')
+ if contrib is not None and not isinstance(contrib, dict):
+ problems.append('contributions must be an object')
+ elif isinstance(contrib, dict):
+ for key in contrib:
+ if key not in _KNOWN_CONTRIB_KINDS:
+ logger.warning(
+ f"Manifest for {name}: unknown contribution kind '{key}' (ignored)")
+
+ for kind, req in _REQUIRED_CONTRIB_KEYS.items():
+ entries = contrib.get(kind)
+ if entries is None:
+ continue
+ if not isinstance(entries, list):
+ problems.append(f'contributions.{kind} must be a list')
+ continue
+ for i, entry in enumerate(entries):
+ if not isinstance(entry, dict):
+ problems.append(f'contributions.{kind}[{i}] must be an object')
+ continue
+ missing_keys = [k for k in req if not entry.get(k)]
+ if missing_keys:
+ problems.append(
+ f"contributions.{kind}[{i}] missing {', '.join(missing_keys)}")
+
+ titles = contrib.get('page_titles')
+ if titles is not None and not isinstance(titles, dict):
+ problems.append('contributions.page_titles must be an object of path -> title')
+
+ if problems:
+ raise ValueError(
+ 'Manifest validation failed: ' + '; '.join(problems)
+ + '. See GET /api/v1/plugins/manifest-spec or docs/EXTENSIONS.md.')
+
return True
diff --git a/backend/tests/test_plugins_pipeline.py b/backend/tests/test_plugins_pipeline.py
index 1da5e4fe..87bb61b8 100644
--- a/backend/tests/test_plugins_pipeline.py
+++ b/backend/tests/test_plugins_pipeline.py
@@ -267,6 +267,60 @@ def test_plugin_config_rejects_non_object(app, client, auth_headers, plugin_dirs
assert r.status_code == 400
+# --------------------------------------------------------------------------- #
+# Manifest shape lint (#52)
+# --------------------------------------------------------------------------- #
+
+_LINT_BASE = {'name': 'demo', 'display_name': 'Demo', 'version': '1.0.0'}
+
+
+def test_manifest_lint_rejects_bad_shapes():
+ from app.services.plugin_service import _validate_manifest
+
+ with pytest.raises(ValueError, match='entry_point'):
+ _validate_manifest({**_LINT_BASE, 'entry_point': 'not-a-module-ref'})
+ with pytest.raises(ValueError, match='socket_entry'):
+ _validate_manifest({**_LINT_BASE, 'socket_entry': 'nope nope'})
+ with pytest.raises(ValueError, match=r'jobs\[0\]'):
+ _validate_manifest({**_LINT_BASE, 'jobs': [{'kind': 'x'}]})
+ with pytest.raises(ValueError, match=r'schedules\[0\]'):
+ _validate_manifest({**_LINT_BASE, 'schedules': [{'name': 'n'}]})
+ with pytest.raises(ValueError, match=r'tabs\[0\] missing to, label'):
+ _validate_manifest({**_LINT_BASE,
+ 'contributions': {'tabs': [{'group': 'files'}]}})
+ with pytest.raises(ValueError, match=r'routes\[0\] missing component'):
+ _validate_manifest({**_LINT_BASE,
+ 'contributions': {'routes': [{'path': 'x'}]}})
+ with pytest.raises(ValueError, match='lifecycle.install'):
+ _validate_manifest({**_LINT_BASE, 'lifecycle': {'install': 'no-colon'}})
+
+
+def test_manifest_lint_unknown_contrib_kind_warns_not_fails():
+ """Forward compat: a newer manifest with a contribution kind this panel
+ doesn't know must still install (warn only)."""
+ from app.services.plugin_service import _validate_manifest
+ assert _validate_manifest(
+ {**_LINT_BASE, 'contributions': {'future_kind': [{'x': 1}]}}) is True
+
+
+def test_manifest_lint_accepts_all_shipped_builtins():
+ """Every in-repo builtin manifest passes the lint — keeps the rules and the
+ shipped extensions honest against each other."""
+ from app.services.plugin_service import _validate_manifest
+ tests_dir = os.path.dirname(os.path.abspath(__file__))
+ repo_root = os.path.dirname(os.path.dirname(tests_dir))
+ builtin_root = os.path.join(repo_root, 'builtin-extensions')
+ manifests = []
+ for folder in sorted(os.listdir(builtin_root)):
+ mpath = os.path.join(builtin_root, folder, 'plugin.json')
+ if os.path.isfile(mpath):
+ with open(mpath, encoding='utf-8') as f:
+ manifests.append((folder, json.load(f)))
+ assert manifests, 'no builtin manifests found'
+ for folder, manifest in manifests:
+ assert _validate_manifest(manifest) is True, folder
+
+
# --------------------------------------------------------------------------- #
# Scheduled extension-update check (#50)
# --------------------------------------------------------------------------- #
diff --git a/docs/EXTENSIONS.md b/docs/EXTENSIONS.md
index 9f0425e3..44146c99 100644
--- a/docs/EXTENSIONS.md
+++ b/docs/EXTENSIONS.md
@@ -409,7 +409,10 @@ Proven with `serverkit-git`; automated by the one-shot upgrade auto-install
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
+5. Lint the manifest: `node scripts/new-extension.mjs --validate
+ builtin-extensions/<slug>` — the same shape rules are enforced at install
+ time, so catching a malformed contribution here saves a failed install.
+6. 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
diff --git a/frontend/src/pages/Settings.jsx b/frontend/src/pages/Settings.jsx
index 716ef9e9..61fe2907 100644
--- a/frontend/src/pages/Settings.jsx
+++ b/frontend/src/pages/Settings.jsx
@@ -20,6 +20,7 @@ import IconReferenceTab from '../components/settings/IconReferenceTab';
import AISettingsTab from '../components/settings/AISettingsTab';
import ModulesTab from '../components/settings/ModulesTab';
import AboutTab from '../components/settings/AboutTab';
+import PluginSlot from '../components/PluginSlot';
import { Activity, Code, Database, Layers, Link2, PaintBucket, Sparkles, Settings as SettingsIcon } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { PageTopbar, SegControl } from '@/components/ds';
@@ -314,6 +315,11 @@ const Settings = () => {
{activeTab === 'system' && isAdmin && <SystemTab />}
{activeTab === 'developer' && devMode && isAdmin && <IconReferenceTab />}
{activeTab === 'about' && <AboutTab />}
+ {/* Extension-contributed settings sections (#52): widgets
+ targeting the settings.section slot render below the
+ active tab's content; the tab id comes down as context
+ so a widget can scope itself to specific tabs. */}
+ <PluginSlot name="settings.section" context={{ tab: activeTab }} />
</div>
</div>
</div>
diff --git a/scripts/new-extension.mjs b/scripts/new-extension.mjs
index 571fb58a..7806c52e 100644
--- a/scripts/new-extension.mjs
+++ b/scripts/new-extension.mjs
@@ -3,11 +3,17 @@
* Scaffold a new ServerKit extension (task #40).
*
* node scripts/new-extension.mjs <slug> [--backend] [--builtin]
+ * node scripts/new-extension.mjs --validate <path>
*
* <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
+ * --validate lint an existing plugin.json (or a folder containing one)
+ * against the same shape rules the panel enforces at install
+ * time (#52): module:attr refs, jobs/schedules shapes, required
+ * keys per contribution kind. Exits non-zero on problems;
+ * unknown contribution kinds only warn.
*
* After scaffolding, install it into a dev panel with:
* - builtin: one-click from the Marketplace (Built-in), or
@@ -24,12 +30,153 @@ const __dirname = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(__dirname, '..');
const args = process.argv.slice(2);
+
+// ---------------------------------------------------------------------------
+// --validate mode: lint a manifest with the same rules plugin_service enforces
+// at install. Keep in sync with _validate_manifest + GET /plugins/manifest-spec.
+// ---------------------------------------------------------------------------
+const MODULE_REF_RE = /^[A-Za-z_][\w.]*:[A-Za-z_]\w*$/;
+const REQUIRED_CONTRIB_KEYS = {
+ nav: ['id', 'label', 'route'],
+ routes: ['path', 'component'],
+ tabs: ['group', 'to', 'label'],
+ command_palette: ['label', 'path'],
+ widgets: ['slot', 'component'],
+ layouts: ['id', 'component'],
+};
+const KNOWN_CONTRIB_KINDS = new Set([...Object.keys(REQUIRED_CONTRIB_KEYS), 'page_titles', 'ai']);
+
+function validateManifest(manifest) {
+ const problems = [];
+ const warnings = [];
+
+ for (const field of ['name', 'display_name', 'version']) {
+ if (!manifest[field]) problems.push(`missing required field: ${field}`);
+ }
+ if (manifest.name && !/^[a-zA-Z0-9_-]+$/.test(manifest.name)) {
+ problems.push(`name must be alphanumeric/dashes/underscores: ${manifest.name}`);
+ }
+
+ for (const field of ['entry_point', 'socket_entry', 'models']) {
+ const val = manifest[field];
+ if (val && !(typeof val === 'string' && MODULE_REF_RE.test(val))) {
+ problems.push(`${field} must be a 'module:attr' string (got ${JSON.stringify(val)})`);
+ }
+ }
+
+ const lifecycle = manifest.lifecycle;
+ if (lifecycle != null) {
+ if (typeof lifecycle !== 'object' || Array.isArray(lifecycle)) {
+ problems.push('lifecycle must be an object of phase -> module:func');
+ } else {
+ for (const [phase, target] of Object.entries(lifecycle)) {
+ if (!(typeof target === 'string' && MODULE_REF_RE.test(target))) {
+ problems.push(`lifecycle.${phase} must be a 'module:func' string`);
+ }
+ }
+ }
+ }
+
+ if (manifest.jobs != null) {
+ if (!Array.isArray(manifest.jobs)) {
+ problems.push('jobs must be a list of {kind, handler}');
+ } else {
+ manifest.jobs.forEach((j, i) => {
+ if (!(j && typeof j === 'object' && j.kind
+ && typeof j.handler === 'string' && MODULE_REF_RE.test(j.handler))) {
+ problems.push(`jobs[${i}] must be {kind, handler: 'module:func'}`);
+ }
+ });
+ }
+ }
+
+ if (manifest.schedules != null) {
+ if (!Array.isArray(manifest.schedules)) {
+ problems.push('schedules must be a list of {name, kind, cron?|interval_seconds?}');
+ } else {
+ manifest.schedules.forEach((s, i) => {
+ if (!(s && typeof s === 'object' && s.name && s.kind)) {
+ problems.push(`schedules[${i}] needs name and kind`);
+ }
+ });
+ }
+ }
+
+ const contrib = manifest.contributions;
+ if (contrib != null && (typeof contrib !== 'object' || Array.isArray(contrib))) {
+ problems.push('contributions must be an object');
+ } else if (contrib) {
+ for (const key of Object.keys(contrib)) {
+ if (!KNOWN_CONTRIB_KINDS.has(key)) {
+ warnings.push(`unknown contribution kind '${key}' (ignored by the panel)`);
+ }
+ }
+ for (const [kind, req] of Object.entries(REQUIRED_CONTRIB_KEYS)) {
+ const entries = contrib[kind];
+ if (entries == null) continue;
+ if (!Array.isArray(entries)) {
+ problems.push(`contributions.${kind} must be a list`);
+ continue;
+ }
+ entries.forEach((entry, i) => {
+ if (!entry || typeof entry !== 'object') {
+ problems.push(`contributions.${kind}[${i}] must be an object`);
+ return;
+ }
+ const missing = req.filter((k) => !entry[k]);
+ if (missing.length) {
+ problems.push(`contributions.${kind}[${i}] missing ${missing.join(', ')}`);
+ }
+ });
+ }
+ if (contrib.page_titles != null
+ && (typeof contrib.page_titles !== 'object' || Array.isArray(contrib.page_titles))) {
+ problems.push('contributions.page_titles must be an object of path -> title');
+ }
+ }
+
+ return { problems, warnings };
+}
+
+const validateIdx = args.indexOf('--validate');
+if (validateIdx !== -1) {
+ const target = path.resolve(args[validateIdx + 1] || '.');
+ let manifestPath = target;
+ try {
+ if ((await fs.stat(target)).isDirectory()) {
+ manifestPath = path.join(target, 'plugin.json');
+ }
+ } catch {
+ console.error(`Not found: ${target}`);
+ process.exit(1);
+ }
+
+ let manifest;
+ try {
+ manifest = JSON.parse(await fs.readFile(manifestPath, 'utf8'));
+ } catch (e) {
+ console.error(`Cannot read ${manifestPath}: ${e.message}`);
+ process.exit(1);
+ }
+
+ const { problems, warnings } = validateManifest(manifest);
+ for (const w of warnings) console.warn(` ⚠ ${w}`);
+ if (problems.length) {
+ for (const p of problems) console.error(` ✘ ${p}`);
+ console.error(`\n${problems.length} problem(s) in ${path.relative(process.cwd(), manifestPath)}`);
+ process.exit(1);
+ }
+ console.log(`✔ ${path.relative(process.cwd(), manifestPath)} is a valid ServerKit extension manifest`);
+ process.exit(0);
+}
+
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(' node scripts/new-extension.mjs --validate <path>');
console.error(' <slug> must be alphanumeric/dashes/underscores.');
process.exit(1);
}