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(themes): backend model, API, and registry pipeline (plan 60 Phase 2-3)

Juan Denisc20a9f14f2e1
diff --git a/backend/app/__init__.py b/backend/app/__init__.py
index 918ffa14..3ca897bd 100644
--- a/backend/app/__init__.py
+++ b/backend/app/__init__.py
@@ -463,6 +463,10 @@ def create_app(config_name=None):
from app.api.marketplace import marketplace_bp
app.register_blueprint(marketplace_bp, url_prefix='/api/v1/marketplace')
+ # Register blueprints - Themes (plan 60)
+ from app.api.themes import themes_bp
+ app.register_blueprint(themes_bp, url_prefix='/api/v1/themes')
+
# Register blueprints - Plugins
from app.api.plugins import plugins_bp
app.register_blueprint(plugins_bp, url_prefix='/api/v1/plugins')
diff --git a/backend/app/api/themes.py b/backend/app/api/themes.py
new file mode 100644
index 00000000..5e4f6337
--- /dev/null
+++ b/backend/app/api/themes.py
@@ -0,0 +1,194 @@
+"""Themes API (plan 60) — /api/v1/themes.
+
+A theme is data, not code: a validated map of CSS custom-property tokens. This
+blueprint lists themes (bundled seeds + installed), imports a pasted/uploaded
+theme.json, sets the panel-wide default, and exposes an UNAUTHENTICATED
+`GET /public/active` so the login/setup screens can paint themselves with the
+panel default before anyone signs in.
+
+Registry browse/install routes are added in Phase 3.
+"""
+import json
+import logging
+
+from flask import Blueprint, jsonify, request
+from flask_jwt_extended import jwt_required, get_jwt_identity
+
+from app.models.user import User
+from app.services import theme_service
+from app.services.audit_service import AuditService
+from app.models.audit_log import AuditLog
+
+logger = logging.getLogger(__name__)
+
+themes_bp = Blueprint('themes', __name__)
+
+
+def _current_user():
+ return User.query.get(get_jwt_identity())
+
+
+def _require_admin():
+ user = _current_user()
+ if not user or not user.is_admin:
+ return None, (jsonify({'error': 'Admin access required'}), 403)
+ return user, None
+
+
+@themes_bp.route('/installed', methods=['GET'])
+@jwt_required()
+def list_installed():
+ """All selectable themes (bundled seeds + installed) plus the panel default.
+ Any authenticated user may read this — themes are per-user cosmetic."""
+ return jsonify({
+ 'themes': theme_service.list_all(),
+ 'default': theme_service.get_default_slug(),
+ })
+
+
+@themes_bp.route('/<slug>', methods=['GET'])
+@jwt_required()
+def get_theme(slug):
+ theme = theme_service.get_theme(slug)
+ if not theme:
+ return jsonify({'error': 'Theme not found'}), 404
+ return jsonify(theme)
+
+
+@themes_bp.route('/import', methods=['POST'])
+@jwt_required()
+def import_theme():
+ """Import a theme from a pasted JSON body or an uploaded theme.json (admin).
+
+ Accepts either a raw theme object as the JSON body, an object wrapped as
+ ``{"theme": {...}}``, or a multipart upload under ``file``. The token
+ whitelist + value validators run server-side before anything is stored.
+ """
+ user, err = _require_admin()
+ if err:
+ return err
+
+ raw = None
+ upload = request.files.get('file')
+ if upload is not None:
+ try:
+ raw = json.loads(upload.read().decode('utf-8'))
+ except Exception:
+ return jsonify({'error': 'Uploaded file is not valid JSON'}), 400
+ else:
+ body = request.get_json(silent=True)
+ if isinstance(body, dict) and isinstance(body.get('theme'), dict):
+ raw = body['theme']
+ else:
+ raw = body
+ if not isinstance(raw, dict):
+ return jsonify({'error': 'No theme provided'}), 400
+
+ source = 'studio' if request.args.get('source') == 'studio' else 'import'
+ theme, verr = theme_service.import_theme(raw, source=source)
+ if verr:
+ return jsonify({'error': verr}), 400
+
+ AuditService.log(
+ action=AuditLog.ACTION_RESOURCE_CREATE,
+ user_id=user.id,
+ target_type='theme',
+ target_id=theme['slug'],
+ details={'name': theme['name'], 'source': source},
+ )
+ return jsonify(theme), 201
+
+
+@themes_bp.route('/<slug>', methods=['DELETE'])
+@jwt_required()
+def delete_theme(slug):
+ """Uninstall an installed theme (admin). Bundled seeds cannot be removed."""
+ user, err = _require_admin()
+ if err:
+ return err
+ ok, derr = theme_service.delete_theme(slug)
+ if not ok:
+ code = 404 if derr == 'Theme not found' else 400
+ return jsonify({'error': derr}), code
+ AuditService.log(
+ action=AuditLog.ACTION_RESOURCE_DELETE,
+ user_id=user.id,
+ target_type='theme',
+ target_id=slug,
+ details={'slug': slug},
+ )
+ return jsonify({'success': True}), 200
+
+
+@themes_bp.route('/default', methods=['GET'])
+@jwt_required()
+def get_default():
+ return jsonify({'default': theme_service.get_default_slug()})
+
+
+@themes_bp.route('/default', methods=['POST'])
+@jwt_required()
+def set_default():
+ """Set the panel-wide default theme (admin) — what login/setup and new
+ users get before picking their own."""
+ user, err = _require_admin()
+ if err:
+ return err
+ body = request.get_json(silent=True) or {}
+ slug = body.get('slug')
+ if not isinstance(slug, str) or not slug:
+ return jsonify({'error': 'Missing slug'}), 400
+ ok, derr = theme_service.set_default_slug(slug)
+ if not ok:
+ return jsonify({'error': derr}), 400
+ AuditService.log(
+ action=AuditLog.ACTION_SETTINGS_UPDATE,
+ user_id=user.id,
+ target_type='theme',
+ target_id=slug,
+ details={'default_theme': slug},
+ )
+ return jsonify({'default': slug}), 200
+
+
+@themes_bp.route('/registry', methods=['GET'])
+@jwt_required()
+def list_registry():
+ """Remote-registry themes (with live install state), for the Browse gallery.
+ Read-only; offline-tolerant (falls back to the bundled index)."""
+ from app.services import theme_registry_service
+ return jsonify({
+ 'themes': theme_registry_service.list_catalog(),
+ 'source': theme_registry_service.registry_source_label(),
+ })
+
+
+@themes_bp.route('/registry/<slug>/install', methods=['POST'])
+@jwt_required()
+def install_registry(slug):
+ """Install a theme from the registry by slug (admin). Fetches the theme.json,
+ validates it server-side, and stores it — no zips, no checksums."""
+ user, err = _require_admin()
+ if err:
+ return err
+ from app.services import theme_registry_service
+ theme, ierr = theme_registry_service.install(slug)
+ if ierr:
+ code = 404 if 'not found' in ierr.lower() else 400
+ return jsonify({'error': ierr}), code
+ AuditService.log(
+ action=AuditLog.ACTION_RESOURCE_CREATE,
+ user_id=user.id,
+ target_type='theme',
+ target_id=theme['slug'],
+ details={'name': theme['name'], 'source': 'registry'},
+ )
+ return jsonify(theme), 201
+
+
+@themes_bp.route('/public/active', methods=['GET'])
+def public_active():
+ """UNAUTHENTICATED — the panel-default theme's tokens for the login/setup
+ screens. Extends the existing pre-auth branding channel; returns only
+ cosmetic token data, never anything sensitive."""
+ return jsonify(theme_service.get_public_active())
diff --git a/backend/app/data/themes/default.json b/backend/app/data/themes/default.json
new file mode 100644
index 00000000..e534983d
--- /dev/null
+++ b/backend/app/data/themes/default.json
@@ -0,0 +1,82 @@
+{
+ "schema_version": 1,
+ "slug": "default",
+ "name": "ServerKit",
+ "author": "serverkit",
+ "version": "1.0.0",
+ "description": "The stock ServerKit look — deep slate surfaces with a periwinkle accent.",
+ "base": "dark",
+ "builtin": true,
+ "tokens": {
+ "dark": {
+ "--bg-body": "#0a0b0e",
+ "--bg-sidebar": "#0d0f15",
+ "--surface": "#101218",
+ "--surface-2": "#161922",
+ "--surface-3": "#1c2029",
+ "--surface-hover": "#1a1e27",
+ "--border": "#23272f",
+ "--border-soft": "#191c23",
+ "--border-strong": "#2c313b",
+ "--text": "#e9ebf0",
+ "--text-dim": "#9aa1af",
+ "--text-faint": "#646b7a",
+ "--text-ghost": "#444b58",
+ "--green": "#3ddc97",
+ "--green-bg": "rgba(61,220,151,0.12)",
+ "--amber": "#f5b945",
+ "--amber-bg": "rgba(245,185,69,0.12)",
+ "--red": "#fb6f6f",
+ "--red-bg": "rgba(251,111,111,0.12)",
+ "--cyan": "#49c7f0",
+ "--cyan-bg": "rgba(73,199,240,0.12)",
+ "--violet": "#b07bf5",
+ "--violet-bg": "rgba(176,123,245,0.12)",
+ "--radius": "10px",
+ "--radius-sm": "7px",
+ "--radius-lg": "14px",
+ "--scrollbar-track": "#101218",
+ "--scrollbar-thumb": "#2a2f3a",
+ "--scrollbar-thumb-hover": "#363c49",
+ "--bg-code": "#0d1017",
+ "--text-code": "#e2e8f0",
+ "--grid-color": "rgba(255,255,255,0.02)"
+ },
+ "light": {
+ "--bg-body": "#f6f7fb",
+ "--bg-sidebar": "#f1f3f9",
+ "--surface": "#ffffff",
+ "--surface-2": "#f6f7fb",
+ "--surface-3": "#eef1f7",
+ "--surface-hover": "#eef1f7",
+ "--border": "#e2e6ef",
+ "--border-soft": "#eef1f7",
+ "--border-strong": "#cdd3e0",
+ "--text": "#161a23",
+ "--text-dim": "#515a6b",
+ "--text-faint": "#79818f",
+ "--text-ghost": "#a6adba",
+ "--green": "#3ddc97",
+ "--green-bg": "rgba(61,220,151,0.12)",
+ "--amber": "#f5b945",
+ "--amber-bg": "rgba(245,185,69,0.12)",
+ "--red": "#fb6f6f",
+ "--red-bg": "rgba(251,111,111,0.12)",
+ "--cyan": "#49c7f0",
+ "--cyan-bg": "rgba(73,199,240,0.12)",
+ "--violet": "#b07bf5",
+ "--violet-bg": "rgba(176,123,245,0.12)",
+ "--radius": "10px",
+ "--radius-sm": "7px",
+ "--radius-lg": "14px",
+ "--scrollbar-track": "#f1f3f9",
+ "--scrollbar-thumb": "#cdd3e0",
+ "--scrollbar-thumb-hover": "#aab2c2",
+ "--bg-code": "#f1f3f9",
+ "--text-code": "#334155",
+ "--grid-color": "rgba(109,124,255,0.06)"
+ }
+ },
+ "accent": "#6d7cff",
+ "preview": ["#0a0b0e", "#101218", "#6d7cff", "#e9ebf0"]
+}
diff --git a/backend/app/data/themes/gruvbox.json b/backend/app/data/themes/gruvbox.json
new file mode 100644
index 00000000..bbcf0290
--- /dev/null
+++ b/backend/app/data/themes/gruvbox.json
@@ -0,0 +1,46 @@
+{
+ "schema_version": 1,
+ "slug": "gruvbox",
+ "name": "Gruvbox",
+ "author": "serverkit",
+ "version": "1.0.0",
+ "description": "A warm retro terminal palette with earthy browns and an orange accent.",
+ "base": "dark",
+ "builtin": true,
+ "tokens": {
+ "dark": {
+ "--bg-body": "#1d2021",
+ "--bg-sidebar": "#1b1e1f",
+ "--surface": "#282828",
+ "--surface-2": "#3c3836",
+ "--surface-3": "#504945",
+ "--surface-hover": "#32302f",
+ "--border": "#504945",
+ "--border-soft": "#3c3836",
+ "--border-strong": "#665c54",
+ "--text": "#ebdbb2",
+ "--text-dim": "#d5c4a1",
+ "--text-faint": "#a89984",
+ "--text-ghost": "#7c6f64",
+ "--green": "#b8bb26",
+ "--green-bg": "rgba(184,187,38,0.14)",
+ "--amber": "#fabd2f",
+ "--amber-bg": "rgba(250,189,47,0.14)",
+ "--red": "#fb4934",
+ "--red-bg": "rgba(251,73,52,0.14)",
+ "--cyan": "#83a598",
+ "--cyan-bg": "rgba(131,165,152,0.14)",
+ "--violet": "#d3869b",
+ "--violet-bg": "rgba(211,134,155,0.14)",
+ "--scrollbar-track": "#282828",
+ "--scrollbar-thumb": "#504945",
+ "--scrollbar-thumb-hover": "#665c54",
+ "--bg-code": "#1d2021",
+ "--text-code": "#ebdbb2",
+ "--grid-color": "rgba(235,219,178,0.03)",
+ "--mono": "\"IBM Plex Mono\", ui-monospace, \"SF Mono\", Menlo, monospace"
+ }
+ },
+ "accent": "#fe8019",
+ "preview": ["#1d2021", "#282828", "#fe8019", "#ebdbb2"]
+}
diff --git a/backend/app/data/themes/high-contrast.json b/backend/app/data/themes/high-contrast.json
new file mode 100644
index 00000000..8f049bbc
--- /dev/null
+++ b/backend/app/data/themes/high-contrast.json
@@ -0,0 +1,76 @@
+{
+ "schema_version": 1,
+ "slug": "high-contrast",
+ "name": "High Contrast",
+ "author": "serverkit",
+ "version": "1.0.0",
+ "description": "A maximum-contrast theme tuned for accessibility, in dark and light.",
+ "base": "dark",
+ "builtin": true,
+ "tokens": {
+ "dark": {
+ "--bg-body": "#000000",
+ "--bg-sidebar": "#000000",
+ "--surface": "#0a0a0a",
+ "--surface-2": "#141414",
+ "--surface-3": "#1f1f1f",
+ "--surface-hover": "#1a1a1a",
+ "--border": "#ffffff",
+ "--border-soft": "#808080",
+ "--border-strong": "#ffffff",
+ "--text": "#ffffff",
+ "--text-dim": "#e0e0e0",
+ "--text-faint": "#b0b0b0",
+ "--text-ghost": "#808080",
+ "--green": "#00ff66",
+ "--green-bg": "rgba(0,255,102,0.18)",
+ "--amber": "#ffcc00",
+ "--amber-bg": "rgba(255,204,0,0.18)",
+ "--red": "#ff3333",
+ "--red-bg": "rgba(255,51,51,0.18)",
+ "--cyan": "#00ffff",
+ "--cyan-bg": "rgba(0,255,255,0.18)",
+ "--violet": "#cc66ff",
+ "--violet-bg": "rgba(204,102,255,0.18)",
+ "--scrollbar-track": "#000000",
+ "--scrollbar-thumb": "#808080",
+ "--scrollbar-thumb-hover": "#ffffff",
+ "--bg-code": "#000000",
+ "--text-code": "#ffffff",
+ "--grid-color": "rgba(255,255,255,0.06)"
+ },
+ "light": {
+ "--bg-body": "#ffffff",
+ "--bg-sidebar": "#ffffff",
+ "--surface": "#ffffff",
+ "--surface-2": "#f2f2f2",
+ "--surface-3": "#e6e6e6",
+ "--surface-hover": "#ededed",
+ "--border": "#000000",
+ "--border-soft": "#444444",
+ "--border-strong": "#000000",
+ "--text": "#000000",
+ "--text-dim": "#1a1a1a",
+ "--text-faint": "#333333",
+ "--text-ghost": "#555555",
+ "--green": "#007a1f",
+ "--green-bg": "rgba(0,122,31,0.14)",
+ "--amber": "#8a5a00",
+ "--amber-bg": "rgba(138,90,0,0.14)",
+ "--red": "#cc0000",
+ "--red-bg": "rgba(204,0,0,0.14)",
+ "--cyan": "#005f73",
+ "--cyan-bg": "rgba(0,95,115,0.14)",
+ "--violet": "#6a1b9a",
+ "--violet-bg": "rgba(106,27,154,0.14)",
+ "--scrollbar-track": "#ffffff",
+ "--scrollbar-thumb": "#444444",
+ "--scrollbar-thumb-hover": "#000000",
+ "--bg-code": "#f2f2f2",
+ "--text-code": "#000000",
+ "--grid-color": "rgba(0,0,0,0.08)"
+ }
+ },
+ "accent": "#00d0ff",
+ "preview": ["#000000", "#0a0a0a", "#00d0ff", "#ffffff"]
+}
diff --git a/backend/app/data/themes/nord-deep.json b/backend/app/data/themes/nord-deep.json
new file mode 100644
index 00000000..a12b49fa
--- /dev/null
+++ b/backend/app/data/themes/nord-deep.json
@@ -0,0 +1,45 @@
+{
+ "schema_version": 1,
+ "slug": "nord-deep",
+ "name": "Nord Deep",
+ "author": "serverkit",
+ "version": "1.0.0",
+ "description": "A deep arctic dark theme with cool blue surfaces and frosty accents.",
+ "base": "dark",
+ "builtin": true,
+ "tokens": {
+ "dark": {
+ "--bg-body": "#242933",
+ "--bg-sidebar": "#20242d",
+ "--surface": "#2e3440",
+ "--surface-2": "#3b4252",
+ "--surface-3": "#434c5e",
+ "--surface-hover": "#3b4252",
+ "--border": "#4c566a",
+ "--border-soft": "#3b4252",
+ "--border-strong": "#5b667c",
+ "--text": "#eceff4",
+ "--text-dim": "#d8dee9",
+ "--text-faint": "#9aa5b8",
+ "--text-ghost": "#6b7488",
+ "--green": "#a3be8c",
+ "--green-bg": "rgba(163,190,140,0.14)",
+ "--amber": "#ebcb8b",
+ "--amber-bg": "rgba(235,203,139,0.14)",
+ "--red": "#bf616a",
+ "--red-bg": "rgba(191,97,106,0.14)",
+ "--cyan": "#88c0d0",
+ "--cyan-bg": "rgba(136,192,208,0.14)",
+ "--violet": "#b48ead",
+ "--violet-bg": "rgba(180,142,173,0.14)",
+ "--scrollbar-track": "#2e3440",
+ "--scrollbar-thumb": "#434c5e",
+ "--scrollbar-thumb-hover": "#4c566a",
+ "--bg-code": "#272c36",
+ "--text-code": "#d8dee9",
+ "--grid-color": "rgba(216,222,233,0.03)"
+ }
+ },
+ "accent": "#88c0d0",
+ "preview": ["#242933", "#2e3440", "#88c0d0", "#eceff4"]
+}
diff --git a/backend/app/data/themes/paper.json b/backend/app/data/themes/paper.json
new file mode 100644
index 00000000..110cbe9b
--- /dev/null
+++ b/backend/app/data/themes/paper.json
@@ -0,0 +1,45 @@
+{
+ "schema_version": 1,
+ "slug": "paper",
+ "name": "Paper",
+ "author": "serverkit",
+ "version": "1.0.0",
+ "description": "A clean, bright light theme with crisp white surfaces and a blue accent.",
+ "base": "light",
+ "builtin": true,
+ "tokens": {
+ "light": {
+ "--bg-body": "#fbfbfd",
+ "--bg-sidebar": "#f4f5f8",
+ "--surface": "#ffffff",
+ "--surface-2": "#f7f8fa",
+ "--surface-3": "#eef0f4",
+ "--surface-hover": "#f0f2f6",
+ "--border": "#e4e7ee",
+ "--border-soft": "#eef0f4",
+ "--border-strong": "#cfd4de",
+ "--text": "#1a1d24",
+ "--text-dim": "#545b68",
+ "--text-faint": "#808896",
+ "--text-ghost": "#aab0bd",
+ "--green": "#16a34a",
+ "--green-bg": "rgba(22,163,74,0.10)",
+ "--amber": "#d97706",
+ "--amber-bg": "rgba(217,119,6,0.10)",
+ "--red": "#dc2626",
+ "--red-bg": "rgba(220,38,38,0.10)",
+ "--cyan": "#0891b2",
+ "--cyan-bg": "rgba(8,145,178,0.10)",
+ "--violet": "#7c3aed",
+ "--violet-bg": "rgba(124,58,237,0.10)",
+ "--scrollbar-track": "#f4f5f8",
+ "--scrollbar-thumb": "#cfd4de",
+ "--scrollbar-thumb-hover": "#b3bac6",
+ "--bg-code": "#f4f5f8",
+ "--text-code": "#24303f",
+ "--grid-color": "rgba(37,99,235,0.05)"
+ }
+ },
+ "accent": "#2563eb",
+ "preview": ["#fbfbfd", "#ffffff", "#2563eb", "#1a1d24"]
+}
diff --git a/backend/app/data/themes/phosphor.json b/backend/app/data/themes/phosphor.json
new file mode 100644
index 00000000..09a728ad
--- /dev/null
+++ b/backend/app/data/themes/phosphor.json
@@ -0,0 +1,46 @@
+{
+ "schema_version": 1,
+ "slug": "phosphor",
+ "name": "Phosphor",
+ "author": "serverkit",
+ "version": "1.0.0",
+ "description": "A near-black OLED theme with glowing terminal-green text.",
+ "base": "dark",
+ "builtin": true,
+ "tokens": {
+ "dark": {
+ "--bg-body": "#000000",
+ "--bg-sidebar": "#030503",
+ "--surface": "#0a0f0a",
+ "--surface-2": "#0f150f",
+ "--surface-3": "#142014",
+ "--surface-hover": "#111a11",
+ "--border": "#1a241a",
+ "--border-soft": "#101810",
+ "--border-strong": "#294029",
+ "--text": "#c8f7c8",
+ "--text-dim": "#7fcf7f",
+ "--text-faint": "#4f8f4f",
+ "--text-ghost": "#2f5f2f",
+ "--green": "#33ff66",
+ "--green-bg": "rgba(51,255,102,0.12)",
+ "--amber": "#ffcc33",
+ "--amber-bg": "rgba(255,204,51,0.12)",
+ "--red": "#ff5555",
+ "--red-bg": "rgba(255,85,85,0.12)",
+ "--cyan": "#33ffff",
+ "--cyan-bg": "rgba(51,255,255,0.12)",
+ "--violet": "#cc99ff",
+ "--violet-bg": "rgba(204,153,255,0.12)",
+ "--scrollbar-track": "#050805",
+ "--scrollbar-thumb": "#1a301a",
+ "--scrollbar-thumb-hover": "#294029",
+ "--bg-code": "#000000",
+ "--text-code": "#33ff66",
+ "--grid-color": "rgba(51,255,102,0.04)",
+ "--mono": "\"IBM Plex Mono\", ui-monospace, \"SF Mono\", Menlo, monospace"
+ }
+ },
+ "accent": "#33ff66",
+ "preview": ["#000000", "#0a0f0a", "#33ff66", "#c8f7c8"]
+}
diff --git a/backend/app/data/themes_index.json b/backend/app/data/themes_index.json
new file mode 100644
index 00000000..5993ef2a
--- /dev/null
+++ b/backend/app/data/themes_index.json
@@ -0,0 +1,95 @@
+{
+ "schema_version": 1,
+ "themes": [
+ {
+ "slug": "default",
+ "name": "ServerKit",
+ "author": "serverkit",
+ "version": "1.0.0",
+ "description": "The stock ServerKit look — deep slate surfaces with a periwinkle accent.",
+ "base": "dark",
+ "preview": [
+ "#0a0b0e",
+ "#101218",
+ "#6d7cff",
+ "#e9ebf0"
+ ],
+ "bundled": true
+ },
+ {
+ "slug": "gruvbox",
+ "name": "Gruvbox",
+ "author": "serverkit",
+ "version": "1.0.0",
+ "description": "A warm retro terminal palette with earthy browns and an orange accent.",
+ "base": "dark",
+ "preview": [
+ "#1d2021",
+ "#282828",
+ "#fe8019",
+ "#ebdbb2"
+ ],
+ "bundled": true
+ },
+ {
+ "slug": "high-contrast",
+ "name": "High Contrast",
+ "author": "serverkit",
+ "version": "1.0.0",
+ "description": "A maximum-contrast theme tuned for accessibility, in dark and light.",
+ "base": "dark",
+ "preview": [
+ "#000000",
+ "#0a0a0a",
+ "#00d0ff",
+ "#ffffff"
+ ],
+ "bundled": true
+ },
+ {
+ "slug": "nord-deep",
+ "name": "Nord Deep",
+ "author": "serverkit",
+ "version": "1.0.0",
+ "description": "A deep arctic dark theme with cool blue surfaces and frosty accents.",
+ "base": "dark",
+ "preview": [
+ "#242933",
+ "#2e3440",
+ "#88c0d0",
+ "#eceff4"
+ ],
+ "bundled": true
+ },
+ {
+ "slug": "paper",
+ "name": "Paper",
+ "author": "serverkit",
+ "version": "1.0.0",
+ "description": "A clean, bright light theme with crisp white surfaces and a blue accent.",
+ "base": "light",
+ "preview": [
+ "#fbfbfd",
+ "#ffffff",
+ "#2563eb",
+ "#1a1d24"
+ ],
+ "bundled": true
+ },
+ {
+ "slug": "phosphor",
+ "name": "Phosphor",
+ "author": "serverkit",
+ "version": "1.0.0",
+ "description": "A near-black OLED theme with glowing terminal-green text.",
+ "base": "dark",
+ "preview": [
+ "#000000",
+ "#0a0f0a",
+ "#33ff66",
+ "#c8f7c8"
+ ],
+ "bundled": true
+ }
+ ]
+}
diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.py
index b174965a..66507dca 100644
--- a/backend/app/models/__init__.py
+++ b/backend/app/models/__init__.py
@@ -79,6 +79,7 @@ from app.models.cron_run import CronRun
from app.models.fleet_doctor_result import FleetDoctorResult
from app.models.server_survey import ServerSurvey
from app.models.dns_cutover_snapshot import DnsCutoverSnapshot
+from app.models.theme import Theme
__all__ = [
'User', 'Application', 'Domain', 'EnvironmentVariable', 'EnvironmentVariableHistory',
@@ -129,4 +130,5 @@ __all__ = [
'FleetDoctorResult',
'ServerSurvey',
'DnsCutoverSnapshot',
+ 'Theme',
]
diff --git a/backend/app/models/theme.py b/backend/app/models/theme.py
new file mode 100644
index 00000000..034e4615
--- /dev/null
+++ b/backend/app/models/theme.py
@@ -0,0 +1,56 @@
+"""Theme model (plan 60).
+
+A theme is DATA, not code: a validated map of CSS custom-property tokens plus
+gallery metadata. Installed themes (imported, studio-authored, or pulled from
+the registry) live here; the always-present bundled seed themes ship as JSON
+under ``app/data/themes/`` and are merged in by ``theme_service`` — they are not
+rows unless an admin explicitly imports one.
+
+No zips, no sha256, no permissions: reviewing a theme is reading a diff of color
+values, so themes deliberately bypass the whole extension trust machinery.
+"""
+from datetime import datetime
+
+from app import db
+
+
+class Theme(db.Model):
+ __tablename__ = 'themes'
+
+ id = db.Column(db.Integer, primary_key=True)
+ slug = db.Column(db.String(64), nullable=False, unique=True, index=True)
+ name = db.Column(db.String(120), nullable=False)
+ author = db.Column(db.String(120), nullable=True, default='')
+ version = db.Column(db.String(32), nullable=True, default='1.0.0')
+ description = db.Column(db.Text, nullable=True, default='')
+ # 'dark' | 'light' — which mode this theme is primarily a skin of.
+ base = db.Column(db.String(8), nullable=False, default='dark')
+ # { "dark": {token: value, …}, "light": {…} } — already sanitised.
+ tokens = db.Column(db.JSON, nullable=False, default=dict)
+ # Optional single accent hex; ThemeContext derives the ramp.
+ accent = db.Column(db.String(32), nullable=True)
+ # 4 gallery swatches.
+ preview = db.Column(db.JSON, nullable=True, default=list)
+ # Where it came from: 'registry' | 'import' | 'studio' | 'bundled'.
+ source = db.Column(db.String(16), nullable=False, default='import')
+ created_at = db.Column(db.DateTime, default=datetime.utcnow)
+ updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
+
+ def to_dict(self):
+ return {
+ 'schema_version': 1,
+ 'slug': self.slug,
+ 'name': self.name,
+ 'author': self.author or '',
+ 'version': self.version or '1.0.0',
+ 'description': self.description or '',
+ 'base': self.base or 'dark',
+ 'tokens': self.tokens or {},
+ 'accent': self.accent,
+ 'preview': self.preview or [],
+ 'source': self.source,
+ 'builtin': False,
+ 'installed': True,
+ 'created_at': self.created_at.isoformat() if self.created_at else None,
+ 'updated_at': self.updated_at.isoformat() if self.updated_at else None,
+ }
diff --git a/backend/app/services/theme_registry_service.py b/backend/app/services/theme_registry_service.py
new file mode 100644
index 00000000..fb761f8b
--- /dev/null
+++ b/backend/app/services/theme_registry_service.py
@@ -0,0 +1,200 @@
+"""Remote theme registry (plan 60, Phase 3).
+
+Mirrors the extension registry_service pattern, minus the trust machinery: a
+theme is data, not code, so there are no zips, no sha256, no permissions — the
+registry is a curated ``index.json`` (in the ``serverkit-themes`` repo, submitted
+via PR, published on merge) and installing is fetching + validating + storing a
+color map.
+
+Design rules (same as the extension registry):
+ - Read-only discovery. Nothing here auto-installs; installs are explicit.
+ - Offline-tolerant. A failed fetch falls back to the last good cache, then to
+ the bundled index (``app/data/themes_index.json``) — the gallery never blanks.
+ - Configurable. ``SERVERKIT_THEMES_REGISTRY_URL`` points at the live index.
+ Unset ⇒ the public registry; set-but-EMPTY ⇒ disabled (bundled only — also
+ how the test suite stays offline).
+"""
+import json
+import logging
+import os
+import time
+from urllib.parse import urljoin
+
+import requests
+
+from app.models.theme import Theme
+from app.services import theme_service
+
+logger = logging.getLogger(__name__)
+
+_BUNDLED_INDEX = os.path.join(
+ os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'data', 'themes_index.json'
+)
+
+# The curated public index. Default goes through serverkit.ai, which proxies the
+# raw-GitHub index (operator-gated route). Until that route ships, operators can
+# point SERVERKIT_THEMES_REGISTRY_URL at the raw index:
+# https://raw.githubusercontent.com/jhd3197/serverkit-themes/main/index.json
+DEFAULT_REGISTRY_URL = 'https://serverkit.ai/themes/index.json'
+
+_FIELDS = {
+ 'slug': '',
+ 'name': '',
+ 'author': '',
+ 'version': '1.0.0',
+ 'description': '',
+ 'base': 'dark',
+ 'accent': None,
+ 'preview': [],
+ 'modes': [],
+ 'theme': '', # relative path to the full theme.json
+ 'image': None,
+}
+
+
+def _registry_url():
+ value = os.environ.get('SERVERKIT_THEMES_REGISTRY_URL')
+ if value is None:
+ return DEFAULT_REGISTRY_URL
+ return value.strip()
+
+
+try:
+ _TTL = int(os.environ.get('SERVERKIT_THEMES_REGISTRY_TTL', '3600'))
+except ValueError:
+ _TTL = 3600
+
+_cache = {'ts': 0.0, 'entries': None, 'source': None, 'base_url': None}
+
+
+def _resolve_url(path, base_url):
+ if not path or not isinstance(path, str):
+ return path
+ if path.startswith('http://') or path.startswith('https://'):
+ return path
+ return urljoin(base_url, path) if base_url else path
+
+
+def _normalize(raw, base_url=None):
+ if not isinstance(raw, dict) or not raw.get('slug'):
+ return None
+ out = {k: raw.get(k, d) for k, d in _FIELDS.items()}
+ if not isinstance(out['preview'], list):
+ out['preview'] = []
+ if not isinstance(out['modes'], list):
+ out['modes'] = []
+ out['image'] = _resolve_url(out['image'], base_url)
+ # Keep the resolved absolute URL to the full theme.json for install.
+ out['_theme_url'] = _resolve_url(out['theme'], base_url)
+ return out
+
+
+def _read_index_payload(payload, base_url=None):
+ themes = payload.get('themes') if isinstance(payload, dict) else None
+ if not isinstance(themes, list):
+ return []
+ return [t for t in (_normalize(x, base_url) for x in themes) if t]
+
+
+def _load_bundled():
+ try:
+ with open(_BUNDLED_INDEX, 'r', encoding='utf-8') as f:
+ return _read_index_payload(json.load(f), base_url=None)
+ except Exception as e:
+ logger.warning('Could not read bundled themes index: %s', e)
+ return []
+
+
+def _fetch_remote():
+ url = _registry_url()
+ if not url:
+ return None, None
+ resp = requests.get(url, timeout=15, headers={
+ 'Accept': 'application/json',
+ 'User-Agent': 'ServerKit-Themes/1.0',
+ })
+ resp.raise_for_status()
+ return _read_index_payload(resp.json(), base_url=url), url
+
+
+def refresh(force=False):
+ """Return registry entries, refreshing when the cache is stale. Never
+ raises — falls back to last-good cache, then the bundled index."""
+ now = time.time()
+ if not force and _cache['entries'] is not None and (now - _cache['ts']) < _TTL:
+ return _cache['entries']
+
+ entries = None
+ source = None
+ base_url = None
+ try:
+ entries, base_url = _fetch_remote()
+ if entries is not None:
+ source = 'remote'
+ except Exception as e:
+ logger.warning('Theme registry fetch failed (%s): %s', _registry_url(), e)
+
+ if entries is None:
+ if _cache['entries'] is not None:
+ return _cache['entries']
+ entries = _load_bundled()
+ source = 'bundled'
+
+ _cache.update({'entries': entries, 'ts': now, 'source': source, 'base_url': base_url})
+ return entries
+
+
+def _installed_slugs():
+ return {row.slug for row in Theme.query.with_entities(Theme.slug).all()}
+
+
+def list_catalog():
+ """Registry entries + live install state, for the Browse gallery. Bundled
+ seed slugs are dropped — those already show as always-present gallery cards,
+ so a registry entry for them would duplicate."""
+ installed = _installed_slugs()
+ bundled = {t['slug'] for t in theme_service.list_bundled()}
+ out = []
+ for e in refresh():
+ if e['slug'] in bundled:
+ continue
+ d = {k: e[k] for k in _FIELDS if k != 'theme'}
+ d['installed'] = e['slug'] in installed
+ out.append(d)
+ return out
+
+
+def get_entry(slug):
+ for e in refresh():
+ if e['slug'] == slug:
+ return e
+ return None
+
+
+def registry_source_label():
+ return _cache.get('source')
+
+
+def install(slug):
+ """Fetch a registry theme's full theme.json, validate it, and store it.
+ Returns ``(theme_dict, error)``."""
+ entry = get_entry(slug)
+ if entry is None:
+ return None, 'Theme not found in the registry'
+ theme_url = entry.get('_theme_url')
+ if not theme_url:
+ return None, 'Registry entry has no theme file'
+ try:
+ resp = requests.get(theme_url, timeout=15, headers={
+ 'Accept': 'application/json',
+ 'User-Agent': 'ServerKit-Themes/1.0',
+ })
+ resp.raise_for_status()
+ raw = resp.json()
+ except Exception as e:
+ logger.warning('Fetching theme %s failed (%s): %s', slug, theme_url, e)
+ return None, 'Could not download the theme from the registry'
+ # The registry index and the theme file must agree on the slug.
+ if isinstance(raw, dict) and raw.get('slug') and raw['slug'] != slug:
+ return None, 'Registry theme slug mismatch'
+ return theme_service.import_theme(raw, source='registry')
diff --git a/backend/app/services/theme_service.py b/backend/app/services/theme_service.py
new file mode 100644
index 00000000..615cece2
--- /dev/null
+++ b/backend/app/services/theme_service.py
@@ -0,0 +1,183 @@
+"""Theme service (plan 60).
+
+Business logic for the themes platform: load the bundled seed themes, list /
+import / delete installed themes, resolve the panel-default theme (for pre-auth
+login/setup screens), and validate every incoming theme through the shared token
+whitelist before it touches the DB.
+
+A theme is data, not code — installing one is just storing a validated JSON blob
+of color tokens. No filesystem writes, no restart, works identically on a
+prebuilt panel.
+"""
+import json
+import logging
+import os
+
+from app import db
+from app.models.theme import Theme
+from app.services import theme_tokens
+from app.services.settings_service import SettingsService
+
+logger = logging.getLogger(__name__)
+
+# Bundled seed themes ship as JSON alongside the code (synced from the frontend
+# authoring source via frontend/scripts/sync-bundled-themes.mjs).
+_THEMES_DIR = os.path.join(
+ os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'data', 'themes'
+)
+
+# The slug that means "stock look / no skin". Always present, never a DB row.
+DEFAULT_THEME_SLUG = 'default'
+
+# Setting key holding the panel-wide default theme slug (what login/setup and
+# brand-new users get before they pick their own).
+_DEFAULT_SETTING_KEY = 'default_theme'
+
+
+def _load_bundled_file(path):
+ try:
+ with open(path, 'r', encoding='utf-8') as f:
+ theme, err = theme_tokens.validate_theme(json.load(f))
+ if err:
+ logger.warning('Bundled theme %s invalid: %s', path, err)
+ return None
+ theme['source'] = 'bundled'
+ theme['builtin'] = True
+ theme['installed'] = True
+ return theme
+ except Exception as e: # pragma: no cover - defensive
+ logger.warning('Could not read bundled theme %s: %s', path, e)
+ return None
+
+
+def list_bundled():
+ """The always-present seed themes, validated. 'default' sorts first."""
+ out = []
+ try:
+ files = sorted(f for f in os.listdir(_THEMES_DIR) if f.endswith('.json'))
+ except FileNotFoundError:
+ return []
+ for fname in files:
+ theme = _load_bundled_file(os.path.join(_THEMES_DIR, fname))
+ if theme:
+ out.append(theme)
+ out.sort(key=lambda t: (t['slug'] != DEFAULT_THEME_SLUG, t['name'].lower()))
+ return out
+
+
+def _bundled_map():
+ return {t['slug']: t for t in list_bundled()}
+
+
+def list_installed():
+ """Installed (DB) themes as dicts."""
+ return [t.to_dict() for t in Theme.query.order_by(Theme.name.asc()).all()]
+
+
+def list_all():
+ """Bundled seeds + installed themes, de-duplicated by slug (an installed
+ theme with a bundled slug shadows the seed)."""
+ by_slug = {t['slug']: t for t in list_bundled()}
+ for t in list_installed():
+ by_slug[t['slug']] = t
+ themes = list(by_slug.values())
+ themes.sort(key=lambda t: (t['slug'] != DEFAULT_THEME_SLUG, (t.get('name') or t['slug']).lower()))
+ return themes
+
+
+def get_theme(slug):
+ """Resolve a theme by slug: installed row first, then bundled seed."""
+ row = Theme.query.filter_by(slug=slug).first()
+ if row:
+ return row.to_dict()
+ return _bundled_map().get(slug)
+
+
+def import_theme(raw, source='import'):
+ """Validate a raw theme dict and upsert it as an installed theme.
+
+ Returns ``(theme_dict, error)``. ``source`` is one of theme_tokens
+ VALID_SOURCES ('import' | 'studio' | 'registry').
+ """
+ theme, err = theme_tokens.validate_theme(raw)
+ if err:
+ return None, err
+ if source not in theme_tokens.VALID_SOURCES:
+ source = 'import'
+ if theme['slug'] == DEFAULT_THEME_SLUG:
+ return None, "'default' is reserved for the stock theme"
+
+ row = Theme.query.filter_by(slug=theme['slug']).first()
+ if row is None:
+ row = Theme(slug=theme['slug'])
+ db.session.add(row)
+ row.name = theme['name']
+ row.author = theme['author']
+ row.version = theme['version']
+ row.description = theme['description']
+ row.base = theme['base']
+ row.tokens = theme['tokens']
+ row.accent = theme['accent']
+ row.preview = theme['preview']
+ row.source = source
+ db.session.commit()
+ return row.to_dict(), None
+
+
+def delete_theme(slug):
+ """Uninstall an installed theme. Bundled seeds cannot be deleted. If the
+ deleted theme was the panel default, revert the default to the stock look.
+ Returns ``(ok, error)``."""
+ if slug == DEFAULT_THEME_SLUG:
+ return False, 'The default theme cannot be removed'
+ row = Theme.query.filter_by(slug=slug).first()
+ if row is None:
+ # A bundled seed (not a DB row) can't be uninstalled — it ships with the
+ # panel. Distinguish that from a genuinely unknown slug so the API can
+ # return 400 (can't) vs 404 (nonexistent).
+ if slug in _bundled_map():
+ return False, 'Bundled themes cannot be removed'
+ return False, 'Theme not found'
+ db.session.delete(row)
+ if get_default_slug() == slug:
+ set_default_slug(DEFAULT_THEME_SLUG)
+ db.session.commit()
+ return True, None
+
+
+def get_default_slug():
+ """The panel-wide default theme slug."""
+ return SettingsService.get(_DEFAULT_SETTING_KEY, DEFAULT_THEME_SLUG) or DEFAULT_THEME_SLUG
+
+
+def set_default_slug(slug):
+ """Set the panel-wide default theme slug. Returns ``(ok, error)``.
+
+ The default must resolve to a known theme (bundled or installed); 'default'
+ (stock) is always valid."""
+ if slug != DEFAULT_THEME_SLUG and get_theme(slug) is None:
+ return False, 'Unknown theme'
+ SettingsService.set(_DEFAULT_SETTING_KEY, slug)
+ return True, None
+
+
+def get_public_active():
+ """The panel-default theme for the pre-auth login/setup screens.
+
+ Unauthenticated-safe: returns just what the screen needs to paint itself —
+ the slug plus the resolved token maps and accent. For the stock look it
+ returns ``{slug: 'default'}`` with no tokens (the screen uses the shipped
+ stylesheet)."""
+ slug = get_default_slug()
+ if slug == DEFAULT_THEME_SLUG:
+ return {'slug': DEFAULT_THEME_SLUG, 'base': 'dark', 'tokens': {}, 'accent': None}
+ theme = get_theme(slug)
+ if not theme:
+ return {'slug': DEFAULT_THEME_SLUG, 'base': 'dark', 'tokens': {}, 'accent': None}
+ return {
+ 'slug': theme['slug'],
+ 'name': theme.get('name'),
+ 'base': theme.get('base', 'dark'),
+ 'tokens': theme.get('tokens', {}),
+ 'accent': theme.get('accent'),
+ }
diff --git a/backend/app/services/theme_tokens.py b/backend/app/services/theme_tokens.py
new file mode 100644
index 00000000..06998279
--- /dev/null
+++ b/backend/app/services/theme_tokens.py
@@ -0,0 +1,201 @@
+"""Canonical theme token whitelist + alias table + validators (server side).
+
+A ServerKit theme is DATA, not code (plan 60): a map of canonical CSS
+custom-property names to values. This module is the backend source of truth for
+the same three things the panel enforces client-side in
+``frontend/src/data/themeTokens.js`` — KEEP THE TWO IN SYNC:
+
+ - which token names a theme may set (the whitelist),
+ - how canonical names expand to the legacy ``--bg-*/--text-*/--border-*``
+ aliases the stylesheet still reads, and
+ - what a token's value may look like (the validators).
+
+The backend runs this on ``POST /import`` and on registry install so a malicious
+or malformed theme never reaches the DB — the client validation is a
+convenience, this is the gate.
+"""
+import re
+
+# Canonical writable tokens, grouped. Authors write these ~37 names; the alias
+# table fans each out to the legacy names. Accent tokens are intentionally
+# excluded — they are derived at runtime from a theme's single ``accent`` field.
+TOKEN_GROUPS = {
+ 'surfaces': ['--bg-body', '--bg-sidebar', '--surface', '--surface-2', '--surface-3', '--surface-hover'],
+ 'borders': ['--border', '--border-soft', '--border-strong'],
+ 'text': ['--text', '--text-dim', '--text-faint', '--text-ghost'],
+ 'semantic': ['--green', '--green-bg', '--amber', '--amber-bg', '--red', '--red-bg', '--cyan', '--cyan-bg', '--violet', '--violet-bg'],
+ 'radius': ['--radius', '--radius-sm', '--radius-lg'],
+ 'fonts': ['--sans', '--mono'],
+ 'shadows': ['--shadow-sm', '--shadow-md', '--shadow-lg'],
+ 'scrollbar': ['--scrollbar-track', '--scrollbar-thumb', '--scrollbar-thumb-hover'],
+ 'code': ['--bg-code', '--text-code'],
+ 'chrome': ['--grid-color'],
+}
+
+_GROUP_TYPE = {
+ 'surfaces': 'color',
+ 'borders': 'color',
+ 'text': 'color',
+ 'semantic': 'color',
+ 'radius': 'length',
+ 'fonts': 'font',
+ 'shadows': 'shadow',
+ 'scrollbar': 'color',
+ 'code': 'color',
+ 'chrome': 'color',
+}
+
+CANONICAL_TOKENS = [t for group in TOKEN_GROUPS.values() for t in group]
+
+TOKEN_TYPE = {t: _GROUP_TYPE[g] for g, tokens in TOKEN_GROUPS.items() for t in tokens}
+
+# Canonical name -> legacy names that must receive the same value.
+ALIAS_MAP = {
+ '--surface': ['--bg-card'],
+ '--surface-2': ['--bg-elevated', '--bg-secondary'],
+ '--surface-3': ['--bg-tertiary'],
+ '--surface-hover': ['--bg-hover'],
+ '--border': ['--border-default'],
+ '--border-soft': ['--border-subtle'],
+ '--border-strong': ['--border-active', '--border-hover'],
+ '--text': ['--text-primary'],
+ '--text-dim': ['--text-secondary'],
+ '--text-faint': ['--text-tertiary'],
+}
+
+VALID_BASES = ('dark', 'light')
+VALID_SOURCES = ('registry', 'import', 'studio', 'bundled')
+
+# --------------------------------------------
+# Value validation
+# --------------------------------------------
+_FORBIDDEN = re.compile(r'url\(|expression\(|javascript:|@import|[@;{}<>]|/\*', re.IGNORECASE)
+_HEX = re.compile(r'^#([0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$')
+_FUNC_COLOR = re.compile(r'^(rgb|rgba|hsl|hsla)\(\s*[0-9.,%\s/]+\)$', re.IGNORECASE)
+_NAMED_COLOR = re.compile(r'^[a-zA-Z]{3,24}$')
+_LENGTH = re.compile(r'^-?(?:0|\d*\.?\d+)(px|rem|em|%|vh|vw)?$')
+_FONT_STACK = re.compile(r'^[a-zA-Z0-9 ,"\'-]{1,200}$')
+_SHADOW = re.compile(r'^[0-9a-zA-Z.,%()#\s/-]{1,200}$')
+
+
+def _is_color(v):
+ return bool(_HEX.match(v) or _FUNC_COLOR.match(v) or _NAMED_COLOR.match(v))
+
+
+_VALIDATORS = {
+ 'color': _is_color,
+ 'length': lambda v: bool(_LENGTH.match(v)),
+ 'font': lambda v: bool(_FONT_STACK.match(v)),
+ 'shadow': lambda v: v == 'none' or bool(_SHADOW.match(v)),
+}
+
+
+def validate_token_value(token, value):
+ """Return the trimmed value if ``token`` is whitelisted and ``value`` passes
+ its type check (and has no forbidden substring), else ``None``."""
+ ttype = TOKEN_TYPE.get(token)
+ if not ttype:
+ return None
+ if not isinstance(value, str):
+ return None
+ v = value.strip()
+ if not v or len(v) > 200:
+ return None
+ if _FORBIDDEN.search(v):
+ return None
+ return v if _VALIDATORS[ttype](v) else None
+
+
+def sanitize_tokens(raw):
+ """Drop unknown / invalid entries, returning only whitelisted, validated
+ canonical tokens. Unknown keys degrade gracefully (forward-compat)."""
+ out = {}
+ if not isinstance(raw, dict):
+ return out
+ for token, value in raw.items():
+ clean = validate_token_value(token, value)
+ if clean is not None:
+ out[token] = clean
+ return out
+
+
+def expand_aliases(clean_tokens):
+ """Expand a validated canonical map to include legacy aliases."""
+ out = dict(clean_tokens)
+ for token, value in clean_tokens.items():
+ for alias in ALIAS_MAP.get(token, []):
+ if alias not in clean_tokens:
+ out[alias] = value
+ return out
+
+
+_SLUG_RE = re.compile(r'^[a-z0-9]+(?:-[a-z0-9]+)*$')
+
+
+def validate_theme(raw):
+ """Validate and normalise a raw theme dict (from import / registry / studio).
+
+ Returns ``(theme, error)``: on success ``theme`` is a cleaned dict with a
+ sanitised ``tokens`` map (invalid/unknown tokens dropped) and ``error`` is
+ ``None``; on failure ``theme`` is ``None`` and ``error`` is a message.
+ """
+ if not isinstance(raw, dict):
+ return None, 'Theme must be a JSON object'
+ if raw.get('schema_version') not in (1, '1', None):
+ return None, 'Unsupported schema_version (expected 1)'
+
+ slug = raw.get('slug')
+ if not isinstance(slug, str) or not _SLUG_RE.match(slug):
+ return None, 'Invalid or missing slug (kebab-case, lowercase alphanumerics)'
+
+ name = raw.get('name')
+ if not isinstance(name, str) or not name.strip():
+ return None, 'Missing theme name'
+
+ base = raw.get('base', 'dark')
+ if base not in VALID_BASES:
+ return None, "base must be 'dark' or 'light'"
+
+ raw_tokens = raw.get('tokens')
+ if not isinstance(raw_tokens, dict):
+ return None, 'Missing tokens object'
+
+ tokens = {}
+ for mode in ('dark', 'light'):
+ if isinstance(raw_tokens.get(mode), dict):
+ cleaned = sanitize_tokens(raw_tokens[mode])
+ if cleaned:
+ tokens[mode] = cleaned
+ if not tokens:
+ return None, 'Theme defines no valid tokens'
+
+ accent = raw.get('accent')
+ if accent is not None and validate_token_value('--surface', accent) is None:
+ # accent is a plain color; reuse the color validator via a color token.
+ accent = None
+
+ preview = raw.get('preview')
+ if not (isinstance(preview, list) and len(preview) == 4
+ and all(isinstance(c, str) for c in preview)):
+ # Derive a reasonable preview from the tokens if absent/malformed.
+ primary = tokens.get('dark') or tokens.get('light') or {}
+ preview = [
+ primary.get('--bg-body', '#101218'),
+ primary.get('--surface', '#161922'),
+ accent or '#6d7cff',
+ primary.get('--text', '#e9ebf0'),
+ ]
+
+ theme = {
+ 'schema_version': 1,
+ 'slug': slug,
+ 'name': name.strip(),
+ 'author': raw.get('author') if isinstance(raw.get('author'), str) else '',
+ 'version': raw.get('version') if isinstance(raw.get('version'), str) else '1.0.0',
+ 'description': raw.get('description') if isinstance(raw.get('description'), str) else '',
+ 'base': base,
+ 'tokens': tokens,
+ 'accent': accent,
+ 'preview': preview[:4],
+ }
+ return theme, None
diff --git a/backend/migrations/versions/078_themes.py b/backend/migrations/versions/078_themes.py
new file mode 100644
index 00000000..cb2bd43a
--- /dev/null
+++ b/backend/migrations/versions/078_themes.py
@@ -0,0 +1,55 @@
+"""Themes table (plan 60 — community themes platform).
+
+Installed themes (imported, studio-authored, or pulled from the registry). A
+theme is a validated map of CSS custom-property tokens — data, not code — so
+the table is deliberately simple: no zips, no checksums, no permissions. The
+bundled seed themes ship as JSON and are not rows unless explicitly imported.
+
+Idempotent: guards on table presence like the other migrations here.
+
+Revision ID: 078_themes
+Revises: 077_linked_panel
+Create Date: 2026-07-22
+"""
+from alembic import op
+import sqlalchemy as sa
+
+revision = '078_themes'
+down_revision = '077_linked_panel'
+branch_labels = None
+depends_on = None
+
+
+def upgrade():
+ conn = op.get_bind()
+ inspector = sa.inspect(conn)
+ if 'themes' in set(inspector.get_table_names()):
+ return
+ op.create_table(
+ 'themes',
+ sa.Column('id', sa.Integer(), nullable=False),
+ sa.Column('slug', sa.String(length=64), nullable=False),
+ sa.Column('name', sa.String(length=120), nullable=False),
+ sa.Column('author', sa.String(length=120), nullable=True),
+ sa.Column('version', sa.String(length=32), nullable=True),
+ sa.Column('description', sa.Text(), nullable=True),
+ sa.Column('base', sa.String(length=8), nullable=False, server_default='dark'),
+ sa.Column('tokens', sa.JSON(), nullable=False),
+ sa.Column('accent', sa.String(length=32), nullable=True),
+ sa.Column('preview', sa.JSON(), nullable=True),
+ sa.Column('source', sa.String(length=16), nullable=False, server_default='import'),
+ sa.Column('created_at', sa.DateTime(), nullable=True),
+ sa.Column('updated_at', sa.DateTime(), nullable=True),
+ sa.PrimaryKeyConstraint('id'),
+ sa.UniqueConstraint('slug'),
+ )
+ op.create_index('ix_themes_slug', 'themes', ['slug'], unique=True)
+
+
+def downgrade():
+ conn = op.get_bind()
+ inspector = sa.inspect(conn)
+ if 'themes' not in set(inspector.get_table_names()):
+ return
+ op.drop_index('ix_themes_slug', table_name='themes')
+ op.drop_table('themes')
diff --git a/backend/tests/test_theme_registry.py b/backend/tests/test_theme_registry.py
new file mode 100644
index 00000000..be22abb1
--- /dev/null
+++ b/backend/tests/test_theme_registry.py
@@ -0,0 +1,123 @@
+"""Theme registry tests (plan 60, Phase 3).
+
+Proves the panel-side registry pipeline: offline-tolerant fallback to the
+bundled index, the admin-gated install, and a mocked end-to-end install flow
+(fetch index → fetch theme.json → validate → store).
+"""
+import pytest
+
+from app.services import theme_registry_service
+
+
[email protected](autouse=True)
+def _reset_registry_cache():
+ """The registry cache is module-level; clear it around each test."""
+ theme_registry_service._cache.update(
+ {'ts': 0.0, 'entries': None, 'source': None, 'base_url': None}
+ )
+ yield
+ theme_registry_service._cache.update(
+ {'ts': 0.0, 'entries': None, 'source': None, 'base_url': None}
+ )
+
+
+class _FakeResp:
+ def __init__(self, payload):
+ self._payload = payload
+
+ def raise_for_status(self):
+ return None
+
+ def json(self):
+ return self._payload
+
+
+FAKE_INDEX = {
+ 'schema_version': 1,
+ 'themes': [{
+ 'slug': 'aurora',
+ 'name': 'Aurora',
+ 'base': 'dark',
+ 'description': 'Test registry theme',
+ 'preview': ['#111111', '#222222', '#88c0d0', '#eeeeee'],
+ 'modes': ['dark'],
+ 'theme': 'themes/aurora/theme.json',
+ }],
+}
+
+FAKE_THEME = {
+ 'schema_version': 1,
+ 'slug': 'aurora',
+ 'name': 'Aurora',
+ 'base': 'dark',
+ 'tokens': {'dark': {'--surface': '#123456', '--text': '#ffffff'}},
+ 'accent': '#88c0d0',
+ 'preview': ['#111111', '#222222', '#88c0d0', '#eeeeee'],
+}
+
+
+def _mock_requests(monkeypatch):
+ def fake_get(url, *a, **k):
+ if url.endswith('/theme.json'):
+ return _FakeResp(FAKE_THEME)
+ return _FakeResp(FAKE_INDEX)
+ monkeypatch.setattr(theme_registry_service.requests, 'get', fake_get)
+ monkeypatch.setenv('SERVERKIT_THEMES_REGISTRY_URL', 'https://fake.local/index.json')
+
+
+def test_registry_offline_falls_back_to_bundled(client, auth_headers, monkeypatch):
+ """A disabled/unreachable registry serves the bundled index, and bundled
+ seed slugs are excluded from the browse catalogue (they already show)."""
+ monkeypatch.setenv('SERVERKIT_THEMES_REGISTRY_URL', '') # disabled → bundled
+ resp = client.get('/api/v1/themes/registry', headers=auth_headers)
+ assert resp.status_code == 200
+ data = resp.get_json()
+ assert data['source'] == 'bundled'
+ slugs = {t['slug'] for t in data['themes']}
+ assert 'nord-deep' not in slugs and 'default' not in slugs
+
+
+def test_registry_lists_remote_theme(client, auth_headers, monkeypatch):
+ _mock_requests(monkeypatch)
+ resp = client.get('/api/v1/themes/registry', headers=auth_headers)
+ assert resp.status_code == 200
+ themes = resp.get_json()['themes']
+ aurora = next((t for t in themes if t['slug'] == 'aurora'), None)
+ assert aurora is not None
+ assert aurora['installed'] is False
+
+
+def test_registry_install_flow(client, auth_headers, monkeypatch):
+ _mock_requests(monkeypatch)
+ resp = client.post('/api/v1/themes/registry/aurora/install', headers=auth_headers)
+ assert resp.status_code == 201, resp.get_json()
+ stored = resp.get_json()
+ assert stored['slug'] == 'aurora'
+ assert stored['source'] == 'registry'
+ assert stored['tokens']['dark']['--surface'] == '#123456'
+
+ installed = client.get('/api/v1/themes/installed', headers=auth_headers).get_json()
+ assert 'aurora' in {t['slug'] for t in installed['themes']}
+
+
+def test_registry_install_unknown_slug_404(client, auth_headers, monkeypatch):
+ _mock_requests(monkeypatch)
+ resp = client.post('/api/v1/themes/registry/does-not-exist/install', headers=auth_headers)
+ assert resp.status_code == 404
+
+
+def test_registry_install_requires_admin(client, app, monkeypatch):
+ from app import db
+ from app.models import User
+ from flask_jwt_extended import create_access_token
+ from werkzeug.security import generate_password_hash
+ _mock_requests(monkeypatch)
+ with app.app_context():
+ u = User(email='[email protected]', username='d2',
+ password_hash=generate_password_hash('x'),
+ role=User.ROLE_DEVELOPER, is_active=True)
+ db.session.add(u)
+ db.session.commit()
+ headers = {'Authorization': f'Bearer {create_access_token(identity=u.id)}'}
+ resp = client.post('/api/v1/themes/registry/aurora/install', headers=headers)
+ assert resp.status_code == 403
diff --git a/backend/tests/test_themes.py b/backend/tests/test_themes.py
new file mode 100644
index 00000000..b956c717
--- /dev/null
+++ b/backend/tests/test_themes.py
@@ -0,0 +1,144 @@
+"""Themes platform tests (plan 60).
+
+Proves the backend gate: server-side token validation on import, the admin
+gate, bundled-seed listing, panel-default selection, and the UNAUTHENTICATED
+pre-auth GET /public/active channel.
+"""
+
+
+def _dev_headers(app):
+ """A non-admin (developer) user's auth headers."""
+ from app import db
+ from app.models import User
+ from flask_jwt_extended import create_access_token
+ from werkzeug.security import generate_password_hash
+ with app.app_context():
+ u = User(
+ email='[email protected]', username='devuser',
+ password_hash=generate_password_hash('x'),
+ role=User.ROLE_DEVELOPER, is_active=True,
+ )
+ db.session.add(u)
+ db.session.commit()
+ token = create_access_token(identity=u.id)
+ return {'Authorization': f'Bearer {token}'}
+
+
+VALID_THEME = {
+ 'schema_version': 1,
+ 'slug': 'test-theme',
+ 'name': 'Test Theme',
+ 'author': 'tester',
+ 'base': 'dark',
+ 'tokens': {'dark': {'--surface': '#123456', '--text': '#ffffff', '--radius': '12px'}},
+ 'accent': '#88c0d0',
+ 'preview': ['#111111', '#222222', '#333333', '#444444'],
+}
+
+
+def test_public_active_is_unauthenticated_and_defaults_to_stock(client):
+ """The pre-auth channel needs no token and returns the stock look by default."""
+ resp = client.get('/api/v1/themes/public/active')
+ assert resp.status_code == 200
+ data = resp.get_json()
+ assert data['slug'] == 'default'
+ assert data['tokens'] == {}
+
+
+def test_installed_requires_auth(client):
+ assert client.get('/api/v1/themes/installed').status_code == 401
+
+
+def test_installed_lists_bundled_seeds(client, auth_headers):
+ resp = client.get('/api/v1/themes/installed', headers=auth_headers)
+ assert resp.status_code == 200
+ data = resp.get_json()
+ slugs = {t['slug'] for t in data['themes']}
+ # The bundled seeds ship with the panel and always list.
+ assert {'default', 'nord-deep', 'paper', 'phosphor'}.issubset(slugs)
+ assert data['default'] == 'default'
+
+
+def test_import_valid_theme_stores_and_lists(client, auth_headers):
+ resp = client.post('/api/v1/themes/import', json=VALID_THEME, headers=auth_headers)
+ assert resp.status_code == 201, resp.get_json()
+ stored = resp.get_json()
+ assert stored['slug'] == 'test-theme'
+ assert stored['tokens']['dark']['--surface'] == '#123456'
+ assert stored['source'] == 'import'
+
+ listing = client.get('/api/v1/themes/installed', headers=auth_headers).get_json()
+ assert 'test-theme' in {t['slug'] for t in listing['themes']}
+
+
+def test_import_sanitizes_malicious_token_values(client, auth_headers):
+ """url()/CSS-breakout values are dropped server-side; clean tokens survive."""
+ payload = {
+ **VALID_THEME,
+ 'slug': 'sneaky',
+ 'tokens': {'dark': {
+ '--surface': 'url(https://evil.example/x.png)', # exfil vector
+ '--text': '#fff}html{display:none', # CSS breakout
+ '--border': '#23272f', # legitimate
+ '--evil': '#000000', # not whitelisted
+ }},
+ }
+ resp = client.post('/api/v1/themes/import', json=payload, headers=auth_headers)
+ assert resp.status_code == 201, resp.get_json()
+ tokens = resp.get_json()['tokens']['dark']
+ assert tokens == {'--border': '#23272f'}
+ assert '--surface' not in tokens and '--text' not in tokens and '--evil' not in tokens
+
+
+def test_import_rejects_theme_with_no_valid_tokens(client, auth_headers):
+ payload = {**VALID_THEME, 'slug': 'all-bad', 'tokens': {'dark': {'--surface': 'url(x)'}}}
+ resp = client.post('/api/v1/themes/import', json=payload, headers=auth_headers)
+ assert resp.status_code == 400
+
+
+def test_import_rejects_reserved_default_slug(client, auth_headers):
+ payload = {**VALID_THEME, 'slug': 'default'}
+ resp = client.post('/api/v1/themes/import', json=payload, headers=auth_headers)
+ assert resp.status_code == 400
+
+
+def test_import_requires_admin(client, app):
+ resp = client.post('/api/v1/themes/import', json=VALID_THEME, headers=_dev_headers(app))
+ assert resp.status_code == 403
+
+
+def test_delete_installed_theme(client, auth_headers):
+ client.post('/api/v1/themes/import', json=VALID_THEME, headers=auth_headers)
+ resp = client.delete('/api/v1/themes/test-theme', headers=auth_headers)
+ assert resp.status_code == 200
+ listing = client.get('/api/v1/themes/installed', headers=auth_headers).get_json()
+ assert 'test-theme' not in {t['slug'] for t in listing['themes']}
+
+
+def test_bundled_theme_cannot_be_deleted(client, auth_headers):
+ resp = client.delete('/api/v1/themes/nord-deep', headers=auth_headers)
+ assert resp.status_code == 400
+
+
+def test_set_default_flows_to_public_active(client, auth_headers):
+ """Setting the panel default surfaces its tokens on the pre-auth channel."""
+ client.post('/api/v1/themes/import', json=VALID_THEME, headers=auth_headers)
+ resp = client.post('/api/v1/themes/default', json={'slug': 'test-theme'}, headers=auth_headers)
+ assert resp.status_code == 200
+
+ active = client.get('/api/v1/themes/public/active').get_json()
+ assert active['slug'] == 'test-theme'
+ assert active['tokens']['dark']['--surface'] == '#123456'
+
+
+def test_set_default_rejects_unknown_theme(client, auth_headers):
+ resp = client.post('/api/v1/themes/default', json={'slug': 'nope-nope'}, headers=auth_headers)
+ assert resp.status_code == 400
+
+
+def test_deleting_default_theme_reverts_to_stock(client, auth_headers):
+ client.post('/api/v1/themes/import', json=VALID_THEME, headers=auth_headers)
+ client.post('/api/v1/themes/default', json={'slug': 'test-theme'}, headers=auth_headers)
+ client.delete('/api/v1/themes/test-theme', headers=auth_headers)
+ active = client.get('/api/v1/themes/public/active').get_json()
+ assert active['slug'] == 'default'
diff --git a/frontend/scripts/sync-bundled-themes.mjs b/frontend/scripts/sync-bundled-themes.mjs
new file mode 100644
index 00000000..4bb524c3
--- /dev/null
+++ b/frontend/scripts/sync-bundled-themes.mjs
@@ -0,0 +1,59 @@
+#!/usr/bin/env node
+// Sync the bundled seed themes from the frontend (the authoring source of
+// truth) into the backend, so the pre-auth GET /themes/public/active default
+// and the offline registry fallback have the same theme data without a second
+// hand-maintained copy (plan 60). Mirrors the repo's other sync-* scripts.
+//
+// Run from anywhere: node frontend/scripts/sync-bundled-themes.mjs
+//
+// Writes:
+// backend/app/data/themes/<slug>.json (verbatim copies)
+// backend/app/data/themes_index.json (generated {schema_version, themes:[…]})
+
+import { readFileSync, writeFileSync, readdirSync, mkdirSync, rmSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+import { dirname, resolve, join } from 'node:path';
+
+const here = dirname(fileURLToPath(import.meta.url));
+const repoRoot = resolve(here, '..', '..');
+const srcDir = resolve(repoRoot, 'frontend', 'src', 'data', 'themes');
+const outDir = resolve(repoRoot, 'backend', 'app', 'data', 'themes');
+const indexPath = resolve(repoRoot, 'backend', 'app', 'data', 'themes_index.json');
+
+// Fresh copy of the themes dir so a removed seed theme doesn't linger.
+rmSync(outDir, { recursive: true, force: true });
+mkdirSync(outDir, { recursive: true });
+
+const files = readdirSync(srcDir).filter((f) => f.endsWith('.json')).sort();
+const summaries = [];
+
+for (const file of files) {
+ const raw = readFileSync(join(srcDir, file), 'utf8');
+ const theme = JSON.parse(raw);
+ writeFileSync(join(outDir, file), raw.endsWith('\n') ? raw : `${raw}\n`);
+ // The index carries only the light gallery metadata (not the full token
+ // maps) — install fetches the full theme.json when needed.
+ summaries.push({
+ slug: theme.slug,
+ name: theme.name,
+ author: theme.author || 'serverkit',
+ version: theme.version || '1.0.0',
+ description: theme.description || '',
+ base: theme.base || 'dark',
+ preview: theme.preview || [],
+ bundled: true,
+ });
+}
+
+// Stable order: default first, then alphabetical by name.
+summaries.sort((a, b) => {
+ if (a.slug === 'default') return -1;
+ if (b.slug === 'default') return 1;
+ return (a.name || a.slug).localeCompare(b.name || b.slug);
+});
+
+const index = { schema_version: 1, themes: summaries };
+writeFileSync(indexPath, `${JSON.stringify(index, null, 2)}\n`);
+
+console.log(`✓ synced ${files.length} bundled theme(s) → backend/app/data/themes/`);
+console.log(`✓ wrote themes_index.json (${summaries.length} entries)`);