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(services): cross-cutting catalog improvements (#24-#28)

Juan Denis9e46afb15df8
diff --git a/backend/app/api/templates.py b/backend/app/api/templates.py
index 78a121a4..7a9839d4 100644
--- a/backend/app/api/templates.py
+++ b/backend/app/api/templates.py
@@ -388,6 +388,27 @@ def sync_templates():
return jsonify(result), 200
+@templates_bp.route('/repos/index', methods=['GET'])
+@jwt_required()
+def repo_index():
+ """Return the index.json describing the locally-bundled templates.
+
+ This is the document a template repository serves at ``<repo>/index.json``;
+ exposing it lets this instance act as (or seed) a community template repo.
+ """
+ return jsonify(TemplateService.build_repo_index()), 200
+
+
+@templates_bp.route('/repos/index/export', methods=['POST'])
+@jwt_required()
+@admin_required
+def export_repo_index():
+ """Write index.json next to the bundled templates so the directory can be
+ published as a repository."""
+ result = TemplateService.export_repo_index()
+ return jsonify(result), 200 if result.get('success') else 400
+
+
# ==================== LOCAL TEMPLATE MANAGEMENT ====================
@templates_bp.route('/local', methods=['POST'])
diff --git a/backend/app/services/deployment_job_service.py b/backend/app/services/deployment_job_service.py
index 41706faa..e738efa8 100644
--- a/backend/app/services/deployment_job_service.py
+++ b/backend/app/services/deployment_job_service.py
@@ -169,6 +169,35 @@ class DeploymentJobService:
'port_accessible': port_accessible,
}
+ # Optional auto-domain: when the template opts in (top-level `auto_domain: true`)
+ # and a managed-sites base domain is configured, publish the app at
+ # <slug>.<base_domain> with an nginx vhost. HTTPS is applied ONLY if the
+ # base domain's wildcard cert is already set up (HTTP otherwise) — this never
+ # forces SSL. Best-effort and non-fatal; remote-server installs are skipped
+ # (the panel's nginx can't proxy a container on another host). See
+ # SiteDomainService.give_subdomain.
+ auto_domain = bool(plan.get('auto_domain'))
+ if not auto_domain:
+ try:
+ tmpl = TemplateService.get_template(plan.get('template_id'))
+ auto_domain = bool(tmpl.get('success') and tmpl['template'].get('auto_domain'))
+ except Exception:
+ auto_domain = False
+ if auto_domain and not job.target_server_id and app.app_type == 'docker' and app.port:
+ try:
+ from app.services.site_domain_service import SiteDomainService
+ dom = SiteDomainService.give_subdomain(app)
+ result['auto_domain'] = dom
+ if dom.get('success'):
+ DeploymentPlanRunner(job).log(
+ 'info', f"Published at {dom.get('url')}", dom)
+ else:
+ DeploymentPlanRunner(job).log(
+ 'warn', f"Auto-domain skipped: {dom.get('error')}", dom)
+ except Exception as exc:
+ result['auto_domain'] = {'success': False, 'error': str(exc)}
+ DeploymentPlanRunner(job).log('warn', f"Auto-domain failed: {exc}")
+
job.app_id = app.id
job.set_result({**job.get_result(), **result})
db.session.commit()
diff --git a/backend/app/services/template_service.py b/backend/app/services/template_service.py
index 2ce06d7d..f8a7b6cf 100644
--- a/backend/app/services/template_service.py
+++ b/backend/app/services/template_service.py
@@ -401,6 +401,49 @@ class TemplateService:
return templates
+ @classmethod
+ def build_repo_index(cls, repo_name: str = 'serverkit-official') -> Dict:
+ """Build the ``index.json`` document that describes the locally-bundled
+ templates as a publishable repository.
+
+ This is the exact shape :meth:`fetch_remote_templates` / :meth:`sync_templates`
+ consume from ``<repo_url>/index.json`` (templates served at
+ ``<repo_url>/templates/<id>.yaml``). Publishing a repo is then just:
+ host the ``templates/*.yaml`` files plus this ``index.json``. Lets
+ Prompture Hub & friends ship template updates without a panel release.
+ """
+ templates = [
+ {
+ 'id': t['id'],
+ 'name': t.get('name'),
+ 'version': t.get('version'),
+ 'description': t.get('description'),
+ 'icon': t.get('icon'),
+ 'categories': t.get('categories', []),
+ }
+ for t in cls.list_local_templates()
+ ]
+ return {
+ 'name': repo_name,
+ 'schema_version': cls.SCHEMA_VERSION,
+ 'generated_at': datetime.now().isoformat(),
+ 'count': len(templates),
+ 'templates': templates,
+ }
+
+ @classmethod
+ def export_repo_index(cls, dest_path: str = None) -> Dict:
+ """Write :meth:`build_repo_index` to ``dest_path`` (defaults to
+ ``index.json`` alongside the bundled templates). Returns a status dict."""
+ index = cls.build_repo_index()
+ path = dest_path or os.path.join(cls.LOCAL_TEMPLATES_DIR, 'index.json')
+ try:
+ with open(path, 'w', encoding='utf-8') as f:
+ json.dump(index, f, indent=2)
+ return {'success': True, 'path': path, 'count': index['count']}
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
@classmethod
def fetch_remote_templates(cls, repo_url: str) -> List[Dict]:
"""Fetch templates from a remote repository."""
@@ -1152,8 +1195,14 @@ class TemplateService:
except Exception:
variables = {}
- # Add any new variables with defaults
- for var_name, var_config in template.get('variables', {}).items():
+ # Add any new variables with defaults. Templates may declare variables as
+ # a list ([{name: ...}, ...]) or a dict ({NAME: {...}}); normalize to dict
+ # so converted templates (which use the list form) update correctly.
+ template_vars = template.get('variables', {})
+ if isinstance(template_vars, list):
+ template_vars = {v['name']: v for v in template_vars
+ if isinstance(v, dict) and 'name' in v}
+ for var_name, var_config in template_vars.items():
if var_name not in variables:
variables[var_name] = cls.generate_value(var_config)
@@ -1182,6 +1231,20 @@ class TemplateService:
with open(compose_path, 'w') as f:
f.write(compose_content)
+ # Re-render any template-defined files and re-apply their bind mounts,
+ # so templates that ship config via a `files:` section (e.g. litellm,
+ # signoz, posthog) keep working across updates instead of losing the
+ # mounted config when the compose is regenerated.
+ if 'files' in template:
+ files_result = cls._process_template_files(
+ template['files'], app_path, compose_path, variables
+ )
+ if not files_result.get('success'):
+ # Roll back to the backed-up compose and abort the update.
+ if os.path.exists(backup_path):
+ shutil.copy(backup_path, compose_path)
+ return files_result
+
# Update installation info
install_info['template_version'] = template.get('version')
install_info['updated_at'] = datetime.now().isoformat()
diff --git a/frontend/src/pages/Templates.jsx b/frontend/src/pages/Templates.jsx
index 2623efdd..05365bbb 100644
--- a/frontend/src/pages/Templates.jsx
+++ b/frontend/src/pages/Templates.jsx
@@ -20,7 +20,10 @@ const FEATURED_TEMPLATES = [
'uptime-kuma', 'gitea', 'vaultwarden', 'jellyfin', 'ghost', 'n8n'
];
-// Icon mapping for templates
+// Icon strategy: every template ships an inline lucide-style base64 SVG in its
+// YAML `icon:` field (rendered first by renderIcon). This map is the keyed
+// fallback used when a template has no inline icon or it fails to load, so the
+// grid never shows a broken image. Keep ids here in sync with backend/templates.
const TEMPLATE_ICONS = {
// AI / LLM
'prompture-hub': Cpu,
@@ -295,7 +298,51 @@ const Templates = () => {
database: Database,
'home-automation': Home,
analytics: TrendingUp,
- iot: Cpu
+ iot: Cpu,
+ // AI / LLM
+ ai: Cpu,
+ llm: Cpu,
+ gateway: Server,
+ rag: Cpu,
+ chat: MessageSquare,
+ 'low-code': Workflow,
+ workflow: Workflow,
+ // Search
+ search: Search,
+ vector: Database,
+ // Notifications / messaging
+ notifications: MessageSquare,
+ messaging: MessageSquare,
+ communication: MessageSquare,
+ support: MessageSquare,
+ // Documents / news
+ documents: FileText,
+ pdf: FileText,
+ notes: FileText,
+ rss: Newspaper,
+ news: Newspaper,
+ // Finance / business
+ finance: TrendingUp,
+ business: TrendingUp,
+ // Productivity / tasks
+ tasks: Workflow,
+ 'project-management': Workflow,
+ bookmarks: BookOpen,
+ ebooks: BookOpen,
+ audiobooks: Music,
+ automation: Workflow,
+ downloads: HardDrive,
+ // Identity / networking / privacy
+ identity: Shield,
+ sso: Shield,
+ vpn: Shield,
+ privacy: Lock,
+ dns: Globe,
+ forum: Users,
+ community: Users,
+ // Observability
+ observability: BarChart3,
+ apm: BarChart3
};
const Icon = icons[category] || Container;
return <Icon size={14} />;