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: Phase 2 developer experience — build packs, config snapshots, catalog certification
Juan Denisa550f16baf42
diff --git a/backend/app/__init__.py b/backend/app/__init__.pyindex 28443456..681bb1fd 100644--- a/backend/app/__init__.py+++ b/backend/app/__init__.py@@ -163,6 +163,14 @@ def create_app(config_name=None):from app.api.container_status import container_status_bpapp.register_blueprint(container_status_bp, url_prefix='/api/v1/status')+ # Register blueprints - Build packs (zero-Dockerfile detection)+ from app.api.buildpacks import buildpacks_bp+ app.register_blueprint(buildpacks_bp, url_prefix='/api/v1/buildpacks')++ # Register blueprints - Deployment config snapshots + diff+ from app.api.snapshots import snapshots_bp+ app.register_blueprint(snapshots_bp, url_prefix='/api/v1/apps')+# Register blueprints - Notificationsfrom app.api.notifications import notifications_bpapp.register_blueprint(notifications_bp, url_prefix='/api/v1/notifications')diff --git a/backend/app/api/apps.py b/backend/app/api/apps.pyindex 9959def8..fabfe181 100644--- a/backend/app/api/apps.py+++ b/backend/app/api/apps.py@@ -524,6 +524,11 @@ def create_app_from_repository():dockerfile_path = (data.get('dockerfile_path') or '').strip() or Nonecustom_build_cmd = (data.get('custom_build_cmd') or '').strip() or Nonecustom_start_cmd = (data.get('custom_start_cmd') or '').strip() or None+ # Build-pack plan/overrides (optional). Provided by the detection step in the+ # New Service wizard. Persisted on the Application so the generated Dockerfile+ # is reproducible and the Build tab can render the plan.+ buildpack_plan = data.get('buildpack_plan') if isinstance(data.get('buildpack_plan'), dict) else None+ buildpack_overrides = data.get('buildpack_overrides') if isinstance(data.get('buildpack_overrides'), dict) else Noneif not name or len(name) < 2:return jsonify({'error': 'Service name must be at least 2 characters'}), 400@@ -606,6 +611,18 @@ def create_app_from_repository():custom_build_cmd = custom_build_cmd or recommended.get('custom_build_cmd')custom_start_cmd = custom_start_cmd or recommended.get('custom_start_cmd')+ # When the build method routes through the build-pack layer, persist the+ # (possibly overridden) plan on the Application so the generated Dockerfile is+ # reproducible. Detect from the freshly-cloned source if no plan was supplied.+ buildpack_type = None+ if resolved_build_method in ('nixpacks', 'auto'):+ from app.services.buildpack_service import BuildpackService+ effective_plan = buildpack_plan or BuildpackService.detect(app_path)+ if buildpack_overrides:+ effective_plan = BuildpackService.apply_overrides(effective_plan, buildpack_overrides)+ buildpack_plan = effective_plan+ buildpack_type = (effective_plan or {}).get('builder')+app = Application(name=name,app_type=resolved_app_type,@@ -613,6 +630,9 @@ def create_app_from_repository():root_path=app_path,user_id=current_user_id,port=port,+ buildpack_type=buildpack_type,+ buildpack_plan=json.dumps(buildpack_plan) if buildpack_plan else None,+ buildpack_overrides=json.dumps(buildpack_overrides) if buildpack_overrides else None,)try:@@ -636,6 +656,8 @@ def create_app_from_repository():dockerfile_path=dockerfile_path,custom_build_cmd=custom_build_cmd,custom_start_cmd=custom_start_cmd,+ buildpack_plan=buildpack_plan,+ buildpack_overrides=buildpack_overrides,)if not build_result.get('success'):raise RuntimeError(build_result.get('error', 'Failed to configure build'))diff --git a/backend/app/api/buildpacks.py b/backend/app/api/buildpacks.pynew file mode 100644index 00000000..edfbf2c6--- /dev/null+++ b/backend/app/api/buildpacks.py@@ -0,0 +1,134 @@+"""+Build Packs API — zero-Dockerfile detection + Dockerfile/compose generation.++Mounted at /api/v1/buildpacks (registered in app/__init__.py).++Two endpoints:+ * POST /detect — clone a repo to a throwaway workspace, run BuildpackService+ .detect(), return the plan + a generated Dockerfile preview.+ Results are cached by (repo_url, commit) so repeated detects+ on an unchanged repo are cheap. Accepts an already-cloned+ ``path`` to skip cloning (used by tests / advanced callers).+ * POST /generate — pure: given a plan dict, return Dockerfile + compose.+"""++import os+import shutil+import tempfile++from flask import Blueprint, request, jsonify+from flask_jwt_extended import jwt_required, get_jwt_identity++from app.services.buildpack_service import BuildpackService+from app.services.git_service import GitService+from app.services.source_connection_service import SourceConnectionService++buildpacks_bp = Blueprint('buildpacks', __name__)+++def _build_response(plan: dict, app_name: str = 'app') -> dict:+ """Attach generated artifacts to a plan for the client."""+ return {+ 'plan': plan,+ 'dockerfile': BuildpackService.generate_dockerfile(plan),+ 'compose': BuildpackService.generate_compose(plan, app_name),+ }+++@buildpacks_bp.route('/detect', methods=['POST'])+@jwt_required()+def detect():+ """Detect the build pack for a repository.++ Body: {repo_url?, branch?, source_connection_id?, repository_full_name?, path?}++ If ``path`` is supplied it is used directly (no clone). Otherwise the repo is+ cloned shallowly to a temp workspace, inspected, and the workspace removed.+ """+ data = request.get_json() or {}+ current_user_id = get_jwt_identity()++ explicit_path = (data.get('path') or '').strip() or None+ repo_url = (data.get('repo_url') or '').strip()+ branch = (data.get('branch') or '').strip() or None+ source_connection_id = data.get('source_connection_id')+ repository_full_name = (data.get('repository_full_name') or '').strip()+ app_name = (data.get('name') or 'app').strip() or 'app'++ # ---- Path supplied: detect in place, no clone. --------------------------+ if explicit_path:+ if not os.path.isdir(explicit_path):+ return jsonify({'error': f'Path does not exist: {explicit_path}'}), 400+ plan = BuildpackService.detect(explicit_path)+ return jsonify(_build_response(plan, app_name)), 200++ # ---- Resolve the clone URL (optionally via a stored source connection). --+ clone_url = repo_url+ display_url = repo_url+ if source_connection_id:+ try:+ source_repo = SourceConnectionService.get_authenticated_clone_url(+ user_id=current_user_id,+ connection_id=int(source_connection_id),+ full_name=repository_full_name,+ )+ clone_url = source_repo['clone_url']+ display_url = source_repo['public_url']+ except (TypeError, ValueError) as exc:+ return jsonify({'error': str(exc)}), 400+ except Exception as exc: # pragma: no cover - defensive+ return jsonify({'error': f'Failed to resolve source connection: {exc}'}), 400++ if not clone_url:+ return jsonify({'error': 'repo_url or path is required'}), 400++ # ---- Cache hit on (display_url, branch)? --------------------------------+ cache_key_url = display_url or clone_url+ cached = BuildpackService.get_cached_plan(cache_key_url, branch)+ if cached:+ return jsonify({**_build_response(cached, app_name), 'cached': True}), 200++ # ---- Clone shallowly to a throwaway workspace, detect, clean up. --------+ workdir = tempfile.mkdtemp(prefix='serverkit-buildpack-')+ clone_target = os.path.join(workdir, 'repo')+ try:+ clone_result = GitService.clone_repository(clone_target, clone_url, branch)+ if not clone_result.get('success'):+ err = clone_result.get('error') or 'Failed to clone repository'+ # Never leak the authenticated clone URL (it may embed a token).+ if clone_url != display_url and display_url:+ err = err.replace(clone_url, display_url)+ return jsonify({'error': err}), 400++ commit = None+ info = GitService.get_commit_info(clone_target)+ if info:+ commit = info.get('hash') or info.get('commit')++ plan = BuildpackService.detect(clone_target)+ BuildpackService.cache_plan(cache_key_url, plan, commit or branch)+ return jsonify(_build_response(plan, app_name)), 200+ except Exception as exc: # pragma: no cover - defensive+ return jsonify({'error': str(exc)}), 400+ finally:+ shutil.rmtree(workdir, ignore_errors=True)+++@buildpacks_bp.route('/generate', methods=['POST'])+@jwt_required()+def generate():+ """Generate a Dockerfile + compose from a plan (pure, no clone).++ Body: {plan, overrides?, name?}+ """+ data = request.get_json() or {}+ plan = data.get('plan')+ if not isinstance(plan, dict):+ return jsonify({'error': 'plan (object) is required'}), 400++ overrides = data.get('overrides')+ if overrides:+ plan = BuildpackService.apply_overrides(plan, overrides)++ app_name = (data.get('name') or 'app').strip() or 'app'+ return jsonify(_build_response(plan, app_name)), 200diff --git a/backend/app/api/snapshots.py b/backend/app/api/snapshots.pynew file mode 100644index 00000000..2327ee7a--- /dev/null+++ b/backend/app/api/snapshots.py@@ -0,0 +1,142 @@+"""+Deployment config snapshot API.++Mounted by the app factory at ``/api/v1/apps``. Exposes the immutable+configuration snapshots captured before each deployment: list, fetch, diff and+restore. Diffs and listings never leak secret values — env values are already+masked at snapshot time.+"""++from flask import Blueprint, request, jsonify+from flask_jwt_extended import jwt_required, get_jwt_identity++from app.middleware.rbac import developer_required, get_current_user+from app.models.application import Application+from app.models.deployment_snapshot import DeploymentSnapshot+from app.services.configuration_service import ConfigurationService++snapshots_bp = Blueprint('snapshots', __name__)+++def _get_app_or_404(app_id):+ """Return (app, None) or (None, error_response)."""+ app = Application.query.get(app_id)+ if not app:+ return None, (jsonify({'error': 'Application not found'}), 404)+ return app, None+++def _get_snapshot_or_404(app_id, snap_id):+ """Return (snapshot, None) or (None, error_response). Scoped to the app."""+ snap = DeploymentSnapshot.query.filter_by(+ id=snap_id, application_id=app_id+ ).first()+ if not snap:+ return None, (jsonify({'error': 'Snapshot not found'}), 404)+ return snap, None+++@snapshots_bp.route('/<int:app_id>/snapshots', methods=['GET'])+@jwt_required()+def list_snapshots(app_id):+ """List config snapshots for an app, newest first."""+ app, err = _get_app_or_404(app_id)+ if err:+ return err++ try:+ limit = min(int(request.args.get('limit', 50)), 200)+ except (TypeError, ValueError):+ limit = 50++ snapshots = (+ DeploymentSnapshot.query.filter_by(application_id=app_id)+ .order_by(DeploymentSnapshot.created_at.desc(), DeploymentSnapshot.id.desc())+ .limit(limit)+ .all()+ )+ # List view omits the full config payload to keep responses light.+ return jsonify({+ 'snapshots': [s.to_dict(include_config=False) for s in snapshots]+ }), 200+++@snapshots_bp.route('/<int:app_id>/snapshots/<int:snap_id>', methods=['GET'])+@jwt_required()+def get_snapshot(app_id, snap_id):+ """Fetch a single snapshot, including its resolved config."""+ _, err = _get_app_or_404(app_id)+ if err:+ return err+ snap, err = _get_snapshot_or_404(app_id, snap_id)+ if err:+ return err+ return jsonify({'snapshot': snap.to_dict(include_config=True)}), 200+++@snapshots_bp.route('/<int:app_id>/snapshots/<int:snap_id>/diff', methods=['GET'])+@jwt_required()+def diff_snapshot(app_id, snap_id):+ """Diff a snapshot against another (default: the previous snapshot).++ Query param ``against`` accepts another snapshot id or the literal+ ``previous`` (default).+ """+ _, err = _get_app_or_404(app_id)+ if err:+ return err+ snap, err = _get_snapshot_or_404(app_id, snap_id)+ if err:+ return err++ against = request.args.get('against', 'previous')++ if against == 'previous' or against in (None, ''):+ other = (+ DeploymentSnapshot.query.filter(+ DeploymentSnapshot.application_id == app_id,+ DeploymentSnapshot.created_at < snap.created_at,+ )+ .order_by(DeploymentSnapshot.created_at.desc(), DeploymentSnapshot.id.desc())+ .first()+ )+ else:+ try:+ other_id = int(against)+ except (TypeError, ValueError):+ return jsonify({'error': "Invalid 'against' parameter"}), 400+ other, e404 = _get_snapshot_or_404(app_id, other_id)+ if e404:+ return e404++ old_config = other.get_config() if other else {}+ new_config = snap.get_config()+ diff = ConfigurationService.diff_configs(old_config, new_config)++ return jsonify({+ 'snapshot_id': snap.id,+ 'against_id': other.id if other else None,+ 'diff': diff,+ 'summary': ConfigurationService.summarize_diff(diff),+ 'has_changes': ConfigurationService.has_changes(diff),+ }), 200+++@snapshots_bp.route('/<int:app_id>/snapshots/<int:snap_id>/restore', methods=['POST'])+@jwt_required()+@developer_required+def restore_snapshot(app_id, snap_id):+ """Restore a snapshot's config (env/domains) and trigger a redeploy."""+ _, err = _get_app_or_404(app_id)+ if err:+ return err+ snap, err = _get_snapshot_or_404(app_id, snap_id)+ if err:+ return err++ user = get_current_user()+ user_id = user.id if user else get_jwt_identity()++ result = ConfigurationService.restore_snapshot(snap.id, user_id=user_id)+ status = 200 if result.get('success') else 400+ return jsonify(result), statusdiff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.pyindex 121ccdfb..c62f6331 100644--- a/backend/app/models/__init__.py+++ b/backend/app/models/__init__.py@@ -4,6 +4,7 @@ from app.models.domain import Domainfrom app.models.env_variable import EnvironmentVariable, EnvironmentVariableHistoryfrom app.models.notification_preferences import NotificationPreferencesfrom app.models.deployment import Deployment, DeploymentDiff+from app.models.deployment_snapshot import DeploymentSnapshotfrom app.models.deployment_job import DeploymentJob, DeploymentJobLogfrom app.models.system_settings import SystemSettingsfrom app.models.audit_log import AuditLog@@ -57,7 +58,7 @@ from app.models.domain_registration import DomainRegistration__all__ = ['User', 'Application', 'Domain', 'EnvironmentVariable', 'EnvironmentVariableHistory',- 'NotificationPreferences', 'Deployment', 'DeploymentDiff', 'DeploymentJob', 'DeploymentJobLog', 'SystemSettings', 'AuditLog',+ 'NotificationPreferences', 'Deployment', 'DeploymentDiff', 'DeploymentSnapshot', 'DeploymentJob', 'DeploymentJobLog', 'SystemSettings', 'AuditLog','MetricsHistory', 'Workflow', 'WorkflowExecution', 'WorkflowLog', 'GitWebhook', 'WebhookLog', 'GitDeployment','Server', 'ServerGroup', 'ServerMetrics', 'ServerCommand', 'AgentSession', 'AgentVersion', 'AgentRollout', 'ServerOnboardingLog', 'SecurityAlert','WordPressSite', 'DatabaseSnapshot', 'SyncJob', 'WordPressVulnerability',diff --git a/backend/app/models/application.py b/backend/app/models/application.pyindex 3657b74d..3020419f 100644--- a/backend/app/models/application.py+++ b/backend/app/models/application.py@@ -20,6 +20,13 @@ class Application(db.Model):docker_image = db.Column(db.String(200), nullable=True)container_id = db.Column(db.String(100), nullable=True)+ # Build packs (zero-Dockerfile deploys). When the build method routes through+ # the build-pack layer, the detected plan and any user overrides are persisted+ # here so the generated Dockerfile is reproducible and the UI can show it.+ buildpack_type = db.Column(db.String(20), nullable=True) # 'nixpacks' | 'static' | 'dockerfile-present' | 'unknown'+ buildpack_plan = db.Column(db.Text, nullable=True) # JSON: the detected build plan+ buildpack_overrides = db.Column(db.Text, nullable=True) # JSON: user overrides applied to the plan+# Source / lifecycle: github (repo clone), template (built-in template),# manual (local path already on server), upload (zip upload managed by ServerKit)source = db.Column(db.String(20), default='github', nullable=False)@@ -73,6 +80,9 @@ class Application(db.Model):'root_path': self.root_path,'docker_image': self.docker_image,'container_id': self.container_id,+ 'buildpack_type': self.buildpack_type,+ 'buildpack_plan': json.loads(self.buildpack_plan) if self.buildpack_plan else None,+ 'buildpack_overrides': json.loads(self.buildpack_overrides) if self.buildpack_overrides else None,'source': self.source,'compose_file': self.compose_file,'systemd_unit': self.systemd_unit,diff --git a/backend/app/models/deployment_snapshot.py b/backend/app/models/deployment_snapshot.pynew file mode 100644index 00000000..74a32e75--- /dev/null+++ b/backend/app/models/deployment_snapshot.py@@ -0,0 +1,102 @@+"""+DeploymentSnapshot Model - Immutable snapshots of an app's resolved config.++Before every deployment we capture a point-in-time, immutable snapshot of the+application's *resolved configuration* — env var keys (with masked values),+domains, image/tag, build method/plan, volumes, and nginx overrides — together+with a SHA-256 hash of the canonical config. This lets us:++- show a deployment timeline with a "config changed" indicator,+- diff two snapshots without ever leaking secret values, and+- restore a previous configuration (env vars + domains) and redeploy.++This is intentionally SEPARATE from ``DeploymentDiff`` (which tracks FILE-level+git diffs). Snapshots are about *configuration*, not source files.+"""++from datetime import datetime+import json++from app import db+++class DeploymentSnapshot(db.Model):+ """An immutable snapshot of an application's resolved configuration."""+ __tablename__ = 'deployment_snapshots'++ id = db.Column(db.Integer, primary_key=True)++ # The app this snapshot belongs to (indexed for "list snapshots for app").+ application_id = db.Column(+ db.Integer, db.ForeignKey('applications.id'), nullable=False, index=True+ )++ # The deployment this snapshot was captured for, if any. Nullable because a+ # snapshot may be captured outside a deploy (e.g. a manual checkpoint) and+ # because a deploy that fails before its Deployment row is created should+ # still be able to record a snapshot.+ deployment_id = db.Column(+ db.Integer, db.ForeignKey('deployments.id'), nullable=True, index=True+ )++ # SHA-256 hex digest of the canonical config JSON. Used for dedupe + a stable+ # "did the config change?" signal.+ snapshot_hash = db.Column(db.String(64), nullable=False)++ # The full resolved config as canonical JSON (sorted keys). Secret *values*+ # are already masked before this is written — the row never stores plaintext+ # secrets.+ config_json = db.Column(db.Text, nullable=False, default='{}')++ # Short human label describing what changed vs the previous snapshot,+ # e.g. "3 env vars changed" or "image updated". Best-effort, may be empty.+ summary = db.Column(db.String(255), nullable=True)++ created_at = db.Column(db.DateTime, default=datetime.utcnow)++ # Use a UNIQUE backref name so we don't have to edit application.py /+ # deployment.py (another agent owns those). The Application gains a+ # ``config_snapshots`` collection; the Deployment gains ``config_snapshots``+ # too via a distinct backref.+ application = db.relationship(+ 'Application', backref=db.backref('config_snapshots', lazy='dynamic')+ )+ deployment = db.relationship(+ 'Deployment', backref=db.backref('config_snapshots', lazy='dynamic')+ )++ def get_config(self):+ """Return the parsed config dict (empty dict on any parse error)."""+ try:+ return json.loads(self.config_json) if self.config_json else {}+ except (json.JSONDecodeError, TypeError):+ return {}++ def to_dict(self, include_config=True):+ """Convert to dictionary for API responses."""+ result = {+ 'id': self.id,+ 'application_id': self.application_id,+ 'deployment_id': self.deployment_id,+ 'snapshot_hash': self.snapshot_hash,+ 'summary': self.summary,+ 'created_at': self.created_at.isoformat() if self.created_at else None,+ }+ if include_config:+ result['config'] = self.get_config()+ return result++ @classmethod+ def get_latest(cls, application_id):+ """Return the most recent snapshot for an app, or None."""+ return (+ cls.query.filter_by(application_id=application_id)+ .order_by(cls.created_at.desc(), cls.id.desc())+ .first()+ )++ def __repr__(self):+ return (+ f'<DeploymentSnapshot app={self.application_id} '+ f'hash={self.snapshot_hash[:8] if self.snapshot_hash else "?"}>'+ )diff --git a/backend/app/services/build_service.py b/backend/app/services/build_service.pyindex 35a2cd4f..5799209d 100644--- a/backend/app/services/build_service.py+++ b/backend/app/services/build_service.py@@ -103,7 +103,9 @@ class BuildService:env_vars: Dict = None,cache_enabled: bool = True,timeout: int = None,- keep_deployments: int = 5) -> Dict:+ keep_deployments: int = 5,+ buildpack_plan: Dict = None,+ buildpack_overrides: Dict = None) -> Dict:"""Configure build settings for an app.Args:@@ -133,6 +135,8 @@ class BuildService:'cache_enabled': cache_enabled,'timeout': timeout or cls.DEFAULT_TIMEOUT,'keep_deployments': keep_deployments,+ 'buildpack_plan': buildpack_plan,+ 'buildpack_overrides': buildpack_overrides,'created_at': datetime.now().isoformat(),'last_build': None,'build_count': 0@@ -351,6 +355,77 @@ class BuildService:cls._save_build_log(app_id, build_log)return {'success': False, 'error': str(e), 'build_log': build_log}+ @classmethod+ def build_with_buildpack(cls, app_id: int, app_path: str,+ plan: Dict = None,+ overrides: Dict = None,+ image_tag: str = None,+ build_args: Dict = None,+ no_cache: bool = False,+ timeout: int = None,+ log_callback: Callable[[str], None] = None) -> Optional[Dict]:+ """Build via the transparent build-pack layer.++ Detects the stack (or uses a persisted plan), generates a Dockerfile into+ the build workspace, then delegates to the standard ``build_with_dockerfile``+ path. Returns ``None`` (so the caller can fall back to nixpacks) when no+ Dockerfile can be generated — i.e. the stack is 'unknown', or the repo+ already ships its own Dockerfile (let the dockerfile path handle that).+ """+ # Imported lazily to keep BuildService importable without the buildpack+ # module (and to avoid any import cycle).+ from app.services.buildpack_service import BuildpackService++ # Reuse a persisted plan if available; otherwise detect from the source.+ effective_plan = plan or BuildpackService.detect(app_path)+ if overrides:+ effective_plan = BuildpackService.apply_overrides(effective_plan, overrides)++ builder = (effective_plan or {}).get('builder')+ # Repo ships its own Dockerfile, or we can't confidently generate one —+ # signal the caller to fall back rather than writing a junk Dockerfile.+ if builder in ('dockerfile-present', 'unknown', None):+ return None++ dockerfile = BuildpackService.generate_dockerfile(effective_plan)+ if not dockerfile or dockerfile.lstrip().startswith('# Unable'):+ return None++ # Write the generated Dockerfile under a ServerKit-specific name so we+ # never clobber a user file, and build it from the source directory.+ generated_name = 'Dockerfile.serverkit'+ generated_path = os.path.join(app_path, generated_name)+ try:+ with open(generated_path, 'w', encoding='utf-8') as fh:+ fh.write(dockerfile)+ except OSError as exc:+ return {'success': False, 'error': f'Could not write generated Dockerfile: {exc}'}++ if log_callback:+ log_callback(f'[buildpack] Generated {generated_name} for '+ f"{effective_plan.get('language') or 'app'} "+ f"({effective_plan.get('framework') or 'generic'})")++ result = cls.build_with_dockerfile(+ app_id=app_id,+ app_path=app_path,+ dockerfile_path=generated_name,+ image_tag=image_tag,+ build_args=build_args,+ no_cache=no_cache,+ timeout=timeout,+ log_callback=log_callback,+ )+ # Annotate the build log so it's clear this was a build-pack build.+ if isinstance(result, dict) and result.get('build_log'):+ result['build_log']['build_method'] = 'buildpack'+ result['build_log']['buildpack'] = {+ 'builder': builder,+ 'language': effective_plan.get('language'),+ 'framework': effective_plan.get('framework'),+ }+ return result+@classmethoddef build_with_nixpacks(cls, app_id: int, app_path: str,image_tag: str = None,@@ -569,6 +644,23 @@ class BuildService:log_callback=log_callback)elif build_method == 'nixpacks':+ # Transparent build-pack path: prefer generating a Dockerfile from the+ # BuildpackService plan and building it via the standard Docker path —+ # this is reproducible and inspectable. Fall back to the opaque+ # nixpacks binary only if generation isn't possible (unknown stack or+ # a Dockerfile is already present in the repo).+ buildpack = cls.build_with_buildpack(+ app_id=app_id,+ app_path=app_path,+ plan=build_config.get('buildpack_plan'),+ overrides=build_config.get('buildpack_overrides'),+ build_args=build_config.get('build_args'),+ no_cache=no_cache or not build_config.get('cache_enabled', True),+ timeout=timeout,+ log_callback=log_callback,+ )+ if buildpack is not None:+ return buildpackreturn cls.build_with_nixpacks(app_id=app_id,app_path=app_path,diff --git a/backend/app/services/buildpack_service.py b/backend/app/services/buildpack_service.pynew file mode 100644index 00000000..ccaa9b06--- /dev/null+++ b/backend/app/services/buildpack_service.py@@ -0,0 +1,696 @@+"""+Buildpack Service — zero-Dockerfile, transparent build planning.++Where ``build_service.py`` shells out to nixpacks (an opaque external binary),+this service produces a *transparent* build plan from a cloned repository:++ * ``detect(repo_path)`` — pure, filesystem-only stack detection.+ * ``generate_dockerfile(plan)`` — a readable Dockerfile for the detected stack.+ * ``generate_compose(plan, name)`` — a compose wrapper for the generated image.+ * ``apply_overrides(plan, overrides)`` — merge user tweaks onto a plan.++Everything here is deterministic and side-effect free: it reads files and+returns strings/dicts. It NEVER executes a build, clones, or runs a container —+that is the job of the API layer (clone) and ``build_service`` (docker build).++The plan dict shape (the contract the API + UI rely on):++ {+ 'builder': 'nixpacks' | 'static' | 'dockerfile-present' | 'unknown',+ 'language': str | None,+ 'framework': str | None,+ 'versions': {'node': '20', 'python': '3.11', ...},+ 'build_command': str | None,+ 'start_command': str | None,+ 'port': int | None,+ 'confidence': float, # 0.0–1.0+ 'notes': [str, ...],+ }++``builder`` semantics:+ * ``dockerfile-present`` — repo already ships a Dockerfile; we defer to it.+ * ``static`` — no server runtime, just files to serve (nginx).+ * ``nixpacks`` — a real language/runtime we can generate for.+ * ``unknown`` — no confident match; caller should ask the user.+"""++import json+import os+import re+import hashlib+from typing import Dict, List, Optional++from app.services.cache_service import CacheService+++class BuildpackService:+ """Transparent build-pack detection and Dockerfile/compose generation."""++ # Cache TTL for a (repo_url, commit) detection result.+ CACHE_TTL = 1800 # 30 minutes++ # Sane defaults baked into generated Dockerfiles when the repo gives no hint.+ DEFAULT_NODE_VERSION = '20'+ DEFAULT_PYTHON_VERSION = '3.11'+ DEFAULT_GO_VERSION = '1.22'+ DEFAULT_PHP_VERSION = '8.3'+ DEFAULT_PORT = 3000++ # ------------------------------------------------------------------ #+ # Detection+ # ------------------------------------------------------------------ #+ @classmethod+ def detect(cls, repo_path: str) -> Dict:+ """Inspect a cloned repo and return a build plan.++ Pure / filesystem-only / deterministic — safe to unit-test with a temp+ directory full of marker files.+ """+ plan = {+ 'builder': 'unknown',+ 'language': None,+ 'framework': None,+ 'versions': {},+ 'build_command': None,+ 'start_command': None,+ 'port': None,+ 'confidence': 0.0,+ 'notes': [],+ }++ if not repo_path or not os.path.isdir(repo_path):+ plan['notes'].append('Repository path does not exist or is not a directory.')+ return plan++ try:+ files = set(os.listdir(repo_path))+ except OSError as exc:+ plan['notes'].append(f'Could not read repository: {exc}')+ return plan++ # 1) An existing Dockerfile always wins — we defer to the author's build.+ if 'Dockerfile' in files:+ plan.update({+ 'builder': 'dockerfile-present',+ 'confidence': 1.0,+ })+ plan['notes'].append('Repository ships a Dockerfile; ServerKit will build it directly.')+ # Still try to name the language for display purposes only.+ lang = cls._guess_language(files)+ if lang:+ plan['language'] = lang+ return plan++ # 2) Language-specific detection, in priority order.+ for detector in (+ cls._detect_node,+ cls._detect_python,+ cls._detect_go,+ cls._detect_php,+ cls._detect_ruby,+ cls._detect_rust,+ cls._detect_static,+ ):+ if detector(repo_path, files, plan):+ break++ # 3) A Procfile, if present, is an authoritative start command.+ cls._apply_procfile(repo_path, files, plan)++ if plan['builder'] == 'unknown':+ plan['notes'].append(+ 'No clear language/framework match. Pick a build method manually '+ 'or add a Dockerfile.'+ )++ return plan++ # ---- per-language detectors (each returns True if it claimed the repo) ----++ @classmethod+ def _detect_node(cls, repo_path: str, files: set, plan: Dict) -> bool:+ if 'package.json' not in files:+ return False++ pkg = cls._read_json(os.path.join(repo_path, 'package.json')) or {}+ scripts = pkg.get('scripts') or {}+ deps = {**(pkg.get('dependencies') or {}), **(pkg.get('devDependencies') or {})}++ plan['builder'] = 'nixpacks'+ plan['language'] = 'node'+ plan['confidence'] = 0.85++ # Node version from "engines" or .nvmrc.+ node_version = None+ engines = pkg.get('engines') or {}+ if isinstance(engines.get('node'), str):+ m = re.search(r'(\d+)', engines['node'])+ if m:+ node_version = m.group(1)+ if not node_version:+ nvmrc = os.path.join(repo_path, '.nvmrc')+ if os.path.isfile(nvmrc):+ try:+ with open(nvmrc, 'r', encoding='utf-8') as fh:+ m = re.search(r'(\d+)', fh.read())+ if m:+ node_version = m.group(1)+ except OSError:+ pass+ plan['versions']['node'] = node_version or cls.DEFAULT_NODE_VERSION++ # Framework + start/build defaults.+ framework = None+ port = None+ if 'next' in deps or any(f in files for f in ('next.config.js', 'next.config.mjs', 'next.config.ts')):+ framework, port = 'nextjs', 3000+ plan['start_command'] = scripts.get('start') or 'next start'+ elif 'nuxt' in deps or 'nuxt3' in deps:+ framework, port = 'nuxt', 3000+ plan['start_command'] = scripts.get('start') or 'node .output/server/index.mjs'+ elif 'vite' in deps:+ framework, port = 'vite', 4173+ plan['start_command'] = scripts.get('start') or 'vite preview --host --port 4173'+ elif 'express' in deps or 'fastify' in deps or 'koa' in deps:+ framework, port = ('express' if 'express' in deps else 'node'), 3000+ plan['start_command'] = scripts.get('start') or 'node index.js'+ else:+ port = 3000+ plan['start_command'] = scripts.get('start') or 'node index.js'++ plan['framework'] = framework+ plan['port'] = port+ if scripts.get('build'):+ plan['build_command'] = 'npm run build'+ plan['notes'].append(+ f"Detected Node.js{f' ({framework})' if framework else ''}; "+ f"using Node {plan['versions']['node']}."+ )+ return True++ @classmethod+ def _detect_python(cls, repo_path: str, files: set, plan: Dict) -> bool:+ markers = {'requirements.txt', 'pyproject.toml', 'Pipfile', 'setup.py'}+ if not (markers & files):+ return False++ plan['builder'] = 'nixpacks'+ plan['language'] = 'python'+ plan['confidence'] = 0.8+ plan['versions']['python'] = cls._python_version(repo_path, files)+ plan['port'] = 8000++ framework, start = cls._python_framework(repo_path, files)+ plan['framework'] = framework+ plan['start_command'] = start++ if 'requirements.txt' in files:+ plan['build_command'] = 'pip install --no-cache-dir -r requirements.txt'+ elif 'pyproject.toml' in files:+ plan['build_command'] = 'pip install --no-cache-dir .'+ elif 'Pipfile' in files:+ plan['build_command'] = 'pip install --no-cache-dir pipenv && pipenv install --system --deploy'++ plan['notes'].append(+ f"Detected Python{f' ({framework})' if framework else ''}; "+ f"using Python {plan['versions']['python']}."+ )+ return True++ @classmethod+ def _detect_go(cls, repo_path: str, files: set, plan: Dict) -> bool:+ if 'go.mod' not in files:+ return False+ plan['builder'] = 'nixpacks'+ plan['language'] = 'go'+ plan['confidence'] = 0.8+ plan['versions']['go'] = cls._go_version(repo_path)+ plan['port'] = 8080+ plan['build_command'] = 'go build -o /app/server ./...'+ plan['start_command'] = '/app/server'+ plan['notes'].append(f"Detected Go module; using Go {plan['versions']['go']}.")+ return True++ @classmethod+ def _detect_php(cls, repo_path: str, files: set, plan: Dict) -> bool:+ if 'composer.json' not in files:+ return False+ plan['builder'] = 'nixpacks'+ plan['language'] = 'php'+ plan['confidence'] = 0.7+ plan['versions']['php'] = cls.DEFAULT_PHP_VERSION+ plan['port'] = 8080+ plan['build_command'] = 'composer install --no-dev --no-interaction --optimize-autoloader'++ composer = cls._read_json(os.path.join(repo_path, 'composer.json')) or {}+ require = composer.get('require') or {}+ if 'laravel/framework' in require or 'artisan' in files:+ plan['framework'] = 'laravel'+ plan['notes'].append('Detected Laravel.')+ # Serve the public/ docroot if present, else the repo root.+ docroot = 'public' if os.path.isdir(os.path.join(repo_path, 'public')) else '.'+ plan['start_command'] = f'php -S 0.0.0.0:8080 -t {docroot}'+ plan['notes'].append(f"Detected PHP; using PHP {plan['versions']['php']}.")+ return True++ @classmethod+ def _detect_ruby(cls, repo_path: str, files: set, plan: Dict) -> bool:+ if 'Gemfile' not in files:+ return False+ plan['builder'] = 'nixpacks'+ plan['language'] = 'ruby'+ plan['confidence'] = 0.65+ plan['versions']['ruby'] = '3.3'+ plan['port'] = 3000+ plan['build_command'] = 'bundle install'+ if 'config.ru' in files or os.path.isfile(os.path.join(repo_path, 'bin', 'rails')):+ plan['framework'] = 'rails'+ plan['start_command'] = 'bundle exec rails server -b 0.0.0.0 -p 3000'+ else:+ plan['start_command'] = 'bundle exec ruby app.rb'+ plan['notes'].append('Detected Ruby.')+ return True++ @classmethod+ def _detect_rust(cls, repo_path: str, files: set, plan: Dict) -> bool:+ if 'Cargo.toml' not in files:+ return False+ plan['builder'] = 'nixpacks'+ plan['language'] = 'rust'+ plan['confidence'] = 0.7+ plan['versions']['rust'] = '1'+ plan['port'] = 8080+ plan['build_command'] = 'cargo build --release'+ plan['start_command'] = './target/release/app'+ plan['notes'].append('Detected Rust crate.')+ return True++ @classmethod+ def _detect_static(cls, repo_path: str, files: set, plan: Dict) -> bool:+ # Only treat as static if there's an index.html and no server runtime.+ if 'index.html' not in files and not os.path.isdir(os.path.join(repo_path, 'public')):+ return False+ plan['builder'] = 'static'+ plan['language'] = 'static'+ plan['framework'] = None+ plan['confidence'] = 0.6+ plan['port'] = 80+ plan['start_command'] = "nginx -g 'daemon off;'"+ plan['notes'].append('Detected a static site; will be served with nginx.')+ return True++ # ------------------------------------------------------------------ #+ # Detection helpers+ # ------------------------------------------------------------------ #+ @staticmethod+ def _read_json(path: str) -> Optional[Dict]:+ try:+ with open(path, 'r', encoding='utf-8') as fh:+ return json.load(fh)+ except (OSError, json.JSONDecodeError):+ return None++ @classmethod+ def _guess_language(cls, files: set) -> Optional[str]:+ """Best-effort language label (display only, used for dockerfile-present)."""+ if 'package.json' in files:+ return 'node'+ if {'requirements.txt', 'pyproject.toml', 'Pipfile', 'setup.py'} & files:+ return 'python'+ if 'go.mod' in files:+ return 'go'+ if 'composer.json' in files:+ return 'php'+ if 'Gemfile' in files:+ return 'ruby'+ if 'Cargo.toml' in files:+ return 'rust'+ return None++ @classmethod+ def _python_version(cls, repo_path: str, files: set) -> str:+ # .python-version takes precedence.+ pv = os.path.join(repo_path, '.python-version')+ if os.path.isfile(pv):+ try:+ with open(pv, 'r', encoding='utf-8') as fh:+ m = re.search(r'(\d+\.\d+)', fh.read())+ if m:+ return m.group(1)+ except OSError:+ pass+ # pyproject.toml requires-python (e.g. ">=3.11").+ if 'pyproject.toml' in files:+ try:+ with open(os.path.join(repo_path, 'pyproject.toml'), 'r', encoding='utf-8') as fh:+ m = re.search(r'requires-python\s*=\s*["\'][^0-9]*(\d+\.\d+)', fh.read())+ if m:+ return m.group(1)+ except OSError:+ pass+ return cls.DEFAULT_PYTHON_VERSION++ @classmethod+ def _python_framework(cls, repo_path: str, files: set):+ """Return (framework, start_command) for a Python repo."""+ reqs = ''+ for fname in ('requirements.txt', 'pyproject.toml', 'Pipfile'):+ fpath = os.path.join(repo_path, fname)+ if os.path.isfile(fpath):+ try:+ with open(fpath, 'r', encoding='utf-8') as fh:+ reqs += fh.read().lower()+ except OSError:+ pass++ if 'manage.py' in files or 'django' in reqs:+ wsgi_module = cls._django_wsgi_module(repo_path)+ return 'django', f'gunicorn --bind 0.0.0.0:8000 {wsgi_module}.wsgi'+ if 'fastapi' in reqs:+ return 'fastapi', 'uvicorn main:app --host 0.0.0.0 --port 8000'+ if 'flask' in reqs:+ return 'flask', 'gunicorn --bind 0.0.0.0:8000 app:app'+ return None, 'python main.py'++ @staticmethod+ def _django_wsgi_module(repo_path: str) -> str:+ """Find the Django project package (the dir containing wsgi.py)."""+ try:+ for entry in sorted(os.listdir(repo_path)):+ wsgi = os.path.join(repo_path, entry, 'wsgi.py')+ if os.path.isfile(wsgi):+ return entry+ except OSError:+ pass+ return 'app'++ @classmethod+ def _go_version(cls, repo_path: str) -> str:+ try:+ with open(os.path.join(repo_path, 'go.mod'), 'r', encoding='utf-8') as fh:+ m = re.search(r'^go\s+(\d+\.\d+)', fh.read(), re.MULTILINE)+ if m:+ return m.group(1)+ except OSError:+ pass+ return cls.DEFAULT_GO_VERSION++ @classmethod+ def _apply_procfile(cls, repo_path: str, files: set, plan: Dict) -> None:+ """A Procfile ``web:`` line overrides the inferred start command."""+ if 'Procfile' not in files:+ return+ try:+ with open(os.path.join(repo_path, 'Procfile'), 'r', encoding='utf-8') as fh:+ for line in fh:+ m = re.match(r'\s*web\s*:\s*(.+)', line)+ if m:+ plan['start_command'] = m.group(1).strip()+ plan['notes'].append('Start command taken from Procfile (web:).')+ if plan['builder'] == 'unknown':+ plan['builder'] = 'nixpacks'+ plan['confidence'] = max(plan['confidence'], 0.5)+ break+ except OSError:+ pass++ # ------------------------------------------------------------------ #+ # Overrides+ # ------------------------------------------------------------------ #+ @classmethod+ def apply_overrides(cls, plan: Dict, overrides: Optional[Dict]) -> Dict:+ """Merge user overrides onto a plan, returning a NEW plan (non-mutating).++ Recognized override keys: node_version, python_version, go_version,+ php_version, build_command, start_command, port.+ """+ merged = json.loads(json.dumps(plan or {})) # deep copy via JSON+ merged.setdefault('versions', {})+ merged.setdefault('notes', [])+ if not overrides:+ return merged++ version_keys = {+ 'node_version': 'node',+ 'python_version': 'python',+ 'go_version': 'go',+ 'php_version': 'php',+ 'ruby_version': 'ruby',+ 'rust_version': 'rust',+ }+ for ov_key, lang_key in version_keys.items():+ val = overrides.get(ov_key)+ if val:+ merged['versions'][lang_key] = str(val)++ if overrides.get('build_command') is not None:+ merged['build_command'] = overrides['build_command'] or None+ if overrides.get('start_command') is not None:+ merged['start_command'] = overrides['start_command'] or None+ if overrides.get('port') not in (None, ''):+ try:+ merged['port'] = int(overrides['port'])+ except (TypeError, ValueError):+ pass++ merged['overridden'] = True+ return merged++ # ------------------------------------------------------------------ #+ # Generation+ # ------------------------------------------------------------------ #+ @classmethod+ def generate_dockerfile(cls, plan: Dict) -> str:+ """Return a Dockerfile string for the detected stack.++ Never executes anything — pure string generation.+ """+ plan = plan or {}+ language = (plan.get('language') or '').lower()+ builder = plan.get('builder')++ if builder == 'dockerfile-present':+ return (+ '# Repository already provides a Dockerfile.\n'+ '# ServerKit will build that file directly; no generation needed.\n'+ )++ if language == 'node':+ return cls._dockerfile_node(plan)+ if language == 'python':+ return cls._dockerfile_python(plan)+ if language == 'go':+ return cls._dockerfile_go(plan)+ if language == 'php':+ return cls._dockerfile_php(plan)+ if language == 'static' or builder == 'static':+ return cls._dockerfile_static(plan)+ if language == 'ruby':+ return cls._dockerfile_ruby(plan)+ if language == 'rust':+ return cls._dockerfile_rust(plan)++ return (+ '# Unable to generate a Dockerfile: the build pack could not confidently\n'+ '# detect this stack. Add a Dockerfile or choose a build method manually.\n'+ )++ @classmethod+ def _port(cls, plan: Dict) -> int:+ port = plan.get('port')+ try:+ return int(port) if port else cls.DEFAULT_PORT+ except (TypeError, ValueError):+ return cls.DEFAULT_PORT++ @classmethod+ def _dockerfile_node(cls, plan: Dict) -> str:+ version = plan.get('versions', {}).get('node', cls.DEFAULT_NODE_VERSION)+ port = cls._port(plan)+ build = plan.get('build_command')+ start = plan.get('start_command') or 'node index.js'+ lines = [+ f'# syntax=docker/dockerfile:1',+ f'FROM node:{version}-slim',+ 'WORKDIR /app',+ 'COPY package*.json ./',+ 'RUN npm install --omit=dev || npm install',+ 'COPY . .',+ ]+ if build:+ lines.append(f'RUN {build}')+ lines += [+ 'ENV NODE_ENV=production',+ f'EXPOSE {port}',+ f'CMD {cls._cmd(start)}',+ ]+ return '\n'.join(lines) + '\n'++ @classmethod+ def _dockerfile_python(cls, plan: Dict) -> str:+ version = plan.get('versions', {}).get('python', cls.DEFAULT_PYTHON_VERSION)+ port = cls._port(plan)+ build = plan.get('build_command') or 'pip install --no-cache-dir -r requirements.txt'+ start = plan.get('start_command') or 'python main.py'+ lines = [+ f'# syntax=docker/dockerfile:1',+ f'FROM python:{version}-slim',+ 'WORKDIR /app',+ 'ENV PYTHONUNBUFFERED=1 PIP_NO_CACHE_DIR=1',+ 'COPY . .',+ f'RUN {build}',+ f'EXPOSE {port}',+ f'CMD {cls._cmd(start)}',+ ]+ return '\n'.join(lines) + '\n'++ @classmethod+ def _dockerfile_go(cls, plan: Dict) -> str:+ version = plan.get('versions', {}).get('go', cls.DEFAULT_GO_VERSION)+ port = cls._port(plan)+ build = plan.get('build_command') or 'go build -o /app/server ./...'+ lines = [+ f'# syntax=docker/dockerfile:1',+ f'FROM golang:{version} AS build',+ 'WORKDIR /src',+ 'COPY go.* ./',+ 'RUN go mod download',+ 'COPY . .',+ f'RUN {build}',+ '',+ 'FROM gcr.io/distroless/base-debian12',+ 'COPY --from=build /app/server /app/server',+ f'EXPOSE {port}',+ 'ENTRYPOINT ["/app/server"]',+ ]+ return '\n'.join(lines) + '\n'++ @classmethod+ def _dockerfile_php(cls, plan: Dict) -> str:+ version = plan.get('versions', {}).get('php', cls.DEFAULT_PHP_VERSION)+ port = cls._port(plan)+ build = plan.get('build_command')+ start = plan.get('start_command') or f'php -S 0.0.0.0:{port} -t .'+ lines = [+ f'# syntax=docker/dockerfile:1',+ f'FROM php:{version}-cli',+ 'WORKDIR /app',+ 'COPY . .',+ ]+ if build:+ lines += [+ 'RUN curl -sS https://getcomposer.org/installer | php -- '+ '--install-dir=/usr/local/bin --filename=composer || true',+ f'RUN {build} || true',+ ]+ lines += [+ f'EXPOSE {port}',+ f'CMD {cls._cmd(start)}',+ ]+ return '\n'.join(lines) + '\n'++ @classmethod+ def _dockerfile_static(cls, plan: Dict) -> str:+ build = plan.get('build_command')+ # If there's a build step (e.g. a static-site generator), build with node+ # then copy the artifacts into nginx.+ if build:+ node_version = plan.get('versions', {}).get('node', cls.DEFAULT_NODE_VERSION)+ return '\n'.join([+ '# syntax=docker/dockerfile:1',+ f'FROM node:{node_version}-slim AS build',+ 'WORKDIR /app',+ 'COPY package*.json ./',+ 'RUN npm install',+ 'COPY . .',+ f'RUN {build}',+ '',+ 'FROM nginx:alpine',+ 'COPY --from=build /app/dist /usr/share/nginx/html',+ 'EXPOSE 80',+ 'CMD ["nginx", "-g", "daemon off;"]',+ ]) + '\n'+ return '\n'.join([+ '# syntax=docker/dockerfile:1',+ 'FROM nginx:alpine',+ 'COPY . /usr/share/nginx/html',+ 'EXPOSE 80',+ 'CMD ["nginx", "-g", "daemon off;"]',+ ]) + '\n'++ @classmethod+ def _dockerfile_ruby(cls, plan: Dict) -> str:+ version = plan.get('versions', {}).get('ruby', '3.3')+ port = cls._port(plan)+ build = plan.get('build_command') or 'bundle install'+ start = plan.get('start_command') or 'bundle exec ruby app.rb'+ return '\n'.join([+ '# syntax=docker/dockerfile:1',+ f'FROM ruby:{version}-slim',+ 'WORKDIR /app',+ 'COPY . .',+ f'RUN {build}',+ f'EXPOSE {port}',+ f'CMD {cls._cmd(start)}',+ ]) + '\n'++ @classmethod+ def _dockerfile_rust(cls, plan: Dict) -> str:+ version = plan.get('versions', {}).get('rust', '1')+ port = cls._port(plan)+ build = plan.get('build_command') or 'cargo build --release'+ start = plan.get('start_command') or './target/release/app'+ return '\n'.join([+ '# syntax=docker/dockerfile:1',+ f'FROM rust:{version} AS build',+ 'WORKDIR /src',+ 'COPY . .',+ f'RUN {build}',+ '',+ 'FROM debian:bookworm-slim',+ 'WORKDIR /app',+ 'COPY --from=build /src/target/release/ /app/',+ f'EXPOSE {port}',+ f'CMD {cls._cmd(start)}',+ ]) + '\n'++ @staticmethod+ def _cmd(command: str) -> str:+ """Render a shell command as a Docker CMD exec-form array."""+ return json.dumps(['sh', '-c', command])++ @classmethod+ def generate_compose(cls, plan: Dict, app_name: str) -> str:+ """Return a docker-compose snippet wrapping the generated image."""+ plan = plan or {}+ safe_name = re.sub(r'[^a-z0-9_-]', '-', (app_name or 'app').lower()).strip('-') or 'app'+ port = cls._port(plan)+ return '\n'.join([+ 'services:',+ f' {safe_name}:',+ ' build:',+ ' context: .',+ ' dockerfile: Dockerfile',+ f' image: serverkit-{safe_name}:latest',+ ' restart: unless-stopped',+ ' ports:',+ f' - "{port}:{port}"',+ ]) + '\n'++ # ------------------------------------------------------------------ #+ # Caching+ # ------------------------------------------------------------------ #+ @classmethod+ def plan_cache_key(cls, repo_url: str, commit: Optional[str] = None) -> str:+ """Stable cache key for a (repo, commit) detection result."""+ raw = f'{repo_url or ""}@{commit or "HEAD"}'+ digest = hashlib.sha256(raw.encode('utf-8')).hexdigest()[:24]+ return f'buildpack:plan:{digest}'++ @classmethod+ def get_cached_plan(cls, repo_url: str, commit: Optional[str] = None) -> Optional[Dict]:+ return CacheService.get(cls.plan_cache_key(repo_url, commit))++ @classmethod+ def cache_plan(cls, repo_url: str, plan: Dict, commit: Optional[str] = None) -> None:+ CacheService.set(cls.plan_cache_key(repo_url, commit), plan, ttl=cls.CACHE_TTL)diff --git a/backend/app/services/configuration_service.py b/backend/app/services/configuration_service.pynew file mode 100644index 00000000..109147a2--- /dev/null+++ b/backend/app/services/configuration_service.py@@ -0,0 +1,447 @@+"""+Configuration Service - Resolve, hash, diff, snapshot & restore app config.++This service produces an IMMUTABLE, deterministic snapshot of an application's+*resolved configuration* (env var keys + masked values, domains, image/tag,+build method/plan, volumes, nginx overrides) before a deployment, hashes it+(SHA-256 over canonical JSON), and can diff two snapshots without ever leaking+secret values.++Design notes+------------+* ``generate_config`` / ``hash_config`` / ``diff_configs`` are PURE and fully+ unit-testable. ``generate_config`` accepts an Application-like object but only+ reads attributes; the heavy lifting (env/domains/volumes extraction) is+ delegated to small helpers that also accept plain data so tests can drive+ them without a DB.+* Secret *values* are never stored. Secret env vars are masked to ``MASK``;+ non-secret env values are stored verbatim (they're already visible config).+* Ordering is deterministic (sorted keys / sorted lists) so equal config →+ equal hash regardless of insertion order.+"""++import hashlib+import json+import logging+import os++from app import db+from app.utils.sensitive_data_filter import MASK, is_sensitive_key++logger = logging.getLogger(__name__)+++class ConfigurationService:+ """Build, hash, diff, snapshot and restore application configuration."""++ # ------------------------------------------------------------------ #+ # Pure helpers (no DB) — fully unit-testable #+ # ------------------------------------------------------------------ #++ @staticmethod+ def mask_env_value(key, value, is_secret):+ """Return the value to store for an env var.++ Secret-flagged vars and vars whose *name* looks sensitive are masked;+ everything else is stored verbatim (already-visible config).+ """+ if is_secret or is_sensitive_key(key):+ return MASK+ return value if value is not None else ''++ @classmethod+ def build_config(cls, *, env=None, domains=None, image_tag=None,+ build_method=None, buildpack_plan=None, volumes=None,+ nginx_overrides=None):+ """Assemble a deterministic config dict from plain pieces.++ This is the pure core of :meth:`generate_config`. ``env`` is a list of+ dicts shaped like ``{'key', 'value', 'is_secret'}``.+ """+ env = env or []+ env_map = {}+ for ev in env:+ key = ev.get('key')+ if not key:+ continue+ env_map[key] = cls.mask_env_value(+ key, ev.get('value'), ev.get('is_secret', False)+ )++ config = {+ 'env': dict(sorted(env_map.items())),+ 'env_keys': sorted(env_map.keys()),+ 'domains': sorted(domains or []),+ 'image_tag': image_tag,+ 'build_method': build_method,+ 'volumes': sorted(volumes or []),+ }+ # Optional keys only present when known — keeps hashes stable for apps+ # that don't use buildpacks / nginx overrides.+ if buildpack_plan is not None:+ config['buildpack_plan'] = buildpack_plan+ if nginx_overrides is not None:+ config['nginx_overrides'] = nginx_overrides+ return config++ @staticmethod+ def hash_config(config):+ """SHA-256 hex digest of the canonical JSON for ``config``.++ Canonical = sorted keys + compact separators, so logically-equal configs+ produce identical hashes regardless of key insertion order.+ """+ canonical = json.dumps(+ config, sort_keys=True, separators=(',', ':'), default=str+ )+ return hashlib.sha256(canonical.encode('utf-8')).hexdigest()++ @staticmethod+ def _diff_string_list(old_list, new_list):+ """Return ``{'added': [...], 'removed': [...]}`` for two string lists."""+ old_set = set(old_list or [])+ new_set = set(new_list or [])+ return {+ 'added': sorted(new_set - old_set),+ 'removed': sorted(old_set - new_set),+ }++ @classmethod+ def diff_configs(cls, old, new):+ """Structured diff between two config dicts.++ Never leaks secret values: for env we only report KEYS and whether a+ value *changed* (booleans), not the values themselves.+ """+ old = old or {}+ new = new or {}++ old_env = old.get('env', {}) or {}+ new_env = new.get('env', {}) or {}+ old_keys = set(old_env.keys())+ new_keys = set(new_env.keys())++ changed_keys = sorted(+ k for k in (old_keys & new_keys) if old_env.get(k) != new_env.get(k)+ )++ env_diff = {+ 'added': sorted(new_keys - old_keys),+ 'removed': sorted(old_keys - new_keys),+ 'changed': changed_keys,+ }++ diff = {+ 'env': env_diff,+ 'domains': cls._diff_string_list(+ old.get('domains'), new.get('domains')+ ),+ 'volumes': cls._diff_string_list(+ old.get('volumes'), new.get('volumes')+ ),+ 'image': {+ 'old': old.get('image_tag'),+ 'new': new.get('image_tag'),+ 'changed': old.get('image_tag') != new.get('image_tag'),+ },+ 'build_method': {+ 'old': old.get('build_method'),+ 'new': new.get('build_method'),+ 'changed': old.get('build_method') != new.get('build_method'),+ },+ }+ return diff++ @staticmethod+ def has_changes(diff):+ """True if a diff produced by :meth:`diff_configs` contains any change."""+ env = diff.get('env', {})+ if env.get('added') or env.get('removed') or env.get('changed'):+ return True+ for section in ('domains', 'volumes'):+ s = diff.get(section, {})+ if s.get('added') or s.get('removed'):+ return True+ if diff.get('image', {}).get('changed'):+ return True+ if diff.get('build_method', {}).get('changed'):+ return True+ return False++ @classmethod+ def summarize_diff(cls, diff):+ """Short human label for a diff, e.g. "3 env vars changed; image updated"."""+ parts = []+ env = diff.get('env', {})+ env_count = (+ len(env.get('added', [])) + len(env.get('removed', []))+ + len(env.get('changed', []))+ )+ if env_count:+ parts.append(f"{env_count} env var{'s' if env_count != 1 else ''} changed")++ dom = diff.get('domains', {})+ dom_count = len(dom.get('added', [])) + len(dom.get('removed', []))+ if dom_count:+ parts.append(f"{dom_count} domain{'s' if dom_count != 1 else ''} changed")++ vol = diff.get('volumes', {})+ vol_count = len(vol.get('added', [])) + len(vol.get('removed', []))+ if vol_count:+ parts.append(f"{vol_count} volume{'s' if vol_count != 1 else ''} changed")++ if diff.get('image', {}).get('changed'):+ parts.append('image updated')+ if diff.get('build_method', {}).get('changed'):+ parts.append('build method changed')++ return '; '.join(parts) if parts else 'no config changes'++ # ------------------------------------------------------------------ #+ # DB-backed resolution #+ # ------------------------------------------------------------------ #++ @staticmethod+ def _resolve_env(application):+ """Resolve env vars as a list of ``{key, value, is_secret}`` dicts."""+ try:+ from app.models.env_variable import EnvironmentVariable+ rows = EnvironmentVariable.query.filter_by(+ application_id=application.id+ ).all()+ return [+ {'key': r.key, 'value': r.value, 'is_secret': bool(r.is_secret)}+ for r in rows+ ]+ except Exception as e: # pragma: no cover - defensive+ logger.warning('Could not resolve env vars for app %s: %s',+ getattr(application, 'id', '?'), e)+ return []++ @staticmethod+ def _resolve_domains(application):+ """Resolve domain names attached to the app."""+ try:+ return [d.name for d in (application.domains or [])]+ except Exception: # pragma: no cover - defensive+ return []++ @staticmethod+ def _resolve_volumes(application):+ """Best-effort extraction of named/host volumes from the compose file.++ Read-only: parses the app's compose file if present. Returns a sorted,+ de-duplicated list of volume strings. Never raises.+ """+ volumes = []+ try:+ root = getattr(application, 'root_path', None)+ if not root:+ return []+ compose_name = getattr(application, 'compose_file', None) or 'docker-compose.yml'+ compose_path = os.path.join(root, compose_name)+ if not os.path.exists(compose_path):+ return []+ try:+ import yaml # optional dependency+ except ImportError:+ return []+ with open(compose_path, 'r', encoding='utf-8') as f:+ data = yaml.safe_load(f) or {}+ services = data.get('services', {}) or {}+ for svc in services.values():+ if not isinstance(svc, dict):+ continue+ for vol in (svc.get('volumes') or []):+ if isinstance(vol, str):+ volumes.append(vol)+ elif isinstance(vol, dict):+ src = vol.get('source')+ tgt = vol.get('target')+ if src or tgt:+ volumes.append(f"{src or ''}:{tgt or ''}")+ # Top-level named volumes+ for vol_name in (data.get('volumes', {}) or {}).keys():+ volumes.append(vol_name)+ except Exception as e: # pragma: no cover - defensive+ logger.debug('Volume resolution failed for app %s: %s',+ getattr(application, 'id', '?'), e)+ return sorted(set(volumes))++ @staticmethod+ def _resolve_build(application):+ """Resolve (build_method, image_tag, buildpack_plan) for the app."""+ build_method = None+ image_tag = getattr(application, 'docker_image', None)+ buildpack_plan = None+ try:+ from app.services.build_service import BuildService+ cfg = BuildService.get_app_build_config(application.id)+ if cfg:+ build_method = cfg.get('build_method')+ buildpack_plan = cfg.get('buildpack') or cfg.get('build_plan')+ except Exception: # pragma: no cover - defensive+ pass+ return build_method, image_tag, buildpack_plan++ @classmethod+ def generate_config(cls, application):+ """Build the deterministic resolved-config dict for an Application.++ Reads only; does not write. Secret values are masked.+ """+ env = cls._resolve_env(application)+ domains = cls._resolve_domains(application)+ volumes = cls._resolve_volumes(application)+ build_method, image_tag, buildpack_plan = cls._resolve_build(application)++ return cls.build_config(+ env=env,+ domains=domains,+ image_tag=image_tag,+ build_method=build_method,+ buildpack_plan=buildpack_plan,+ volumes=volumes,+ nginx_overrides=None,+ )++ # ------------------------------------------------------------------ #+ # Snapshot lifecycle #+ # ------------------------------------------------------------------ #++ @classmethod+ def create_snapshot(cls, application, deployment=None):+ """Capture an immutable config snapshot for ``application``.++ Dedupe: if the most recent snapshot for the app has the same hash, the+ existing row is returned unchanged (no duplicate write).++ Returns the (existing or new) :class:`DeploymentSnapshot`.+ """+ from app.models.deployment_snapshot import DeploymentSnapshot++ config = cls.generate_config(application)+ snapshot_hash = cls.hash_config(config)++ latest = DeploymentSnapshot.get_latest(application.id)+ if latest and latest.snapshot_hash == snapshot_hash:+ # Identical config — reuse the existing snapshot.+ return latest++ # Summary relative to the previous snapshot (if any).+ if latest:+ prev_config = latest.get_config()+ summary = cls.summarize_diff(cls.diff_configs(prev_config, config))+ else:+ summary = 'initial config snapshot'++ snapshot = DeploymentSnapshot(+ application_id=application.id,+ deployment_id=getattr(deployment, 'id', None) if deployment else None,+ snapshot_hash=snapshot_hash,+ config_json=json.dumps(config, sort_keys=True, separators=(',', ':')),+ summary=summary,+ )+ db.session.add(snapshot)+ db.session.commit()+ return snapshot++ @classmethod+ def restore_snapshot(cls, snapshot_id, user_id=None):+ """Restore a snapshot's config to the app and trigger a redeploy.++ Best-effort. Restores env vars (non-masked values only — masked secrets+ are left untouched so we never overwrite a real secret with ``MASK``) and+ domains, then enqueues a redeploy job. Returns a result dict.+ """+ from app.models.deployment_snapshot import DeploymentSnapshot+ from app.models.application import Application++ snapshot = DeploymentSnapshot.query.get(snapshot_id)+ if not snapshot:+ return {'success': False, 'error': 'Snapshot not found'}++ application = Application.query.get(snapshot.application_id)+ if not application:+ return {'success': False, 'error': 'Application not found'}++ config = snapshot.get_config()+ result = {+ 'success': True,+ 'snapshot_id': snapshot_id,+ 'application_id': application.id,+ 'restored': {'env': [], 'domains_noop': True},+ 'skipped_secrets': [],+ 'redeploy': None,+ 'warnings': [],+ }++ # --- Restore env vars (skip masked secret values) ---------------- #+ try:+ from app.services.env_service import EnvService+ for key, value in (config.get('env', {}) or {}).items():+ if value == MASK:+ # Don't clobber a real secret with the mask placeholder.+ result['skipped_secrets'].append(key)+ continue+ _, _, err = EnvService.set_env_var(+ application.id, key, value, user_id=user_id+ )+ if err:+ result['warnings'].append(f'env {key}: {err}')+ else:+ result['restored']['env'].append(key)+ except Exception as e: # pragma: no cover - defensive+ result['warnings'].append(f'env restore failed: {e}')++ # --- Trigger a redeploy (best-effort) ---------------------------- #+ # Prefer the jobs SDK when a deploy handler is registered (keeps the+ # request snappy / async); otherwise fall back to a direct synchronous+ # DeploymentService.deploy(). Either way, restoring config above is the+ # primary, already-committed effect — a redeploy failure here does not+ # fail the restore.+ result['redeploy'] = cls._trigger_redeploy(application, snapshot_id, user_id)+ if result['redeploy'] and not result['redeploy'].get('triggered'):+ err = result['redeploy'].get('error')+ if err:+ result['warnings'].append(f'redeploy not triggered: {err}')++ return result++ @staticmethod+ def _trigger_redeploy(application, snapshot_id, user_id):+ """Best-effort redeploy: jobs SDK if a handler exists, else direct call."""+ # 1) Jobs SDK path — only if a handler is registered for the kind.+ try:+ from app.jobs import registry+ from app.plugins_sdk import jobs+ if 'deployment.deploy' in set(registry.registered_kinds()):+ job = jobs.enqueue(+ 'deployment.deploy',+ payload={+ 'app_id': application.id,+ 'trigger': 'restore',+ 'snapshot_id': snapshot_id,+ 'user_id': user_id,+ },+ owner_type='application',+ owner_id=application.id,+ )+ return {'triggered': True, 'mode': 'job', 'job': job}+ except Exception as e: # pragma: no cover - defensive+ logger.debug('Jobs redeploy path failed, falling back: %s', e)++ # 2) Direct synchronous path.+ try:+ from app.services.deployment_service import DeploymentService+ deploy_result = DeploymentService.deploy(+ application.id, user_id=user_id, trigger='rollback'+ )+ return {+ 'triggered': bool(deploy_result.get('success')),+ 'mode': 'direct',+ 'result': deploy_result,+ 'error': deploy_result.get('error'),+ }+ except Exception as e:+ return {'triggered': False, 'error': str(e)}diff --git a/backend/app/services/deployment_service.py b/backend/app/services/deployment_service.pyindex 4f9f69f2..39ac981d 100644--- a/backend/app/services/deployment_service.py+++ b/backend/app/services/deployment_service.py@@ -104,6 +104,14 @@ class DeploymentService:build_config = BuildService.get_app_build_config(app_id)try:+ # Capture an immutable config snapshot at deploy start. Best-effort:+ # a snapshot failure must never block a deployment.+ try:+ from app.services.configuration_service import ConfigurationService+ ConfigurationService.create_snapshot(app, deployment)+ except Exception as snap_err:+ logger.warning('Config snapshot capture failed (deploy): %s', snap_err)+# Update app statusapp.status = 'deploying'db.session.commit()@@ -367,6 +375,14 @@ class DeploymentService:app.status = 'deploying'db.session.commit()+ # Capture an immutable config snapshot before rolling back, so the+ # timeline records the pre-rollback config. Best-effort.+ try:+ from app.services.configuration_service import ConfigurationService+ ConfigurationService.create_snapshot(app, current)+ except Exception as snap_err:+ logger.warning('Config snapshot capture failed (rollback): %s', snap_err)+# Create new deployment record for the rollbackversion = Deployment.get_next_version(app_id)rollback_deployment = Deployment(diff --git a/backend/app/services/git_deploy_service.py b/backend/app/services/git_deploy_service.pyindex 86908e06..d608f21e 100644--- a/backend/app/services/git_deploy_service.py+++ b/backend/app/services/git_deploy_service.py@@ -4,9 +4,12 @@ import osimport jsonimport shutilimport subprocess+import loggingfrom datetime import datetimefrom typing import Dict, Optional+logger = logging.getLogger(__name__)+class GitDeployService:"""Service for managing git-based deployments."""@@ -65,6 +68,16 @@ class GitDeployService:snapshot = cls._create_snapshot(app)deployment.snapshot_data = json.dumps(snapshot)+ # Also capture an immutable *config* snapshot (env keys + masked+ # values, domains, image, volumes, build method) for the deployment+ # timeline / config diff. Best-effort: never block a deploy. Note we+ # don't link a Deployment FK here — this path uses GitDeployment.+ try:+ from app.services.configuration_service import ConfigurationService+ ConfigurationService.create_snapshot(app)+ except Exception as cfg_err:+ logger.warning('Config snapshot capture failed (git deploy): %s', cfg_err)+logs = []# Step 1: Pre-deployment scriptdiff --git a/backend/config.py b/backend/config.pyindex 270e31b2..0551fae1 100644--- a/backend/config.py+++ b/backend/config.py@@ -88,6 +88,17 @@ class Config:SSL_MODE = _resolve_ssl_mode()HSTS_ENABLED = SSL_MODE == 'secure'+ # ── Build packs ─────────────────────────────────────────────────────+ # Path to the optional nixpacks binary (used by build_service's opaque+ # nixpacks path). The transparent build-pack layer (buildpack_service)+ # generates a Dockerfile instead and does not require this. Workspace dir+ # is where build packs clone/stage sources for detection + generation.+ NIXPACKS_BIN = os.environ.get('NIXPACKS_BIN', 'nixpacks')+ BUILDPACK_WORKSPACE_DIR = os.environ.get(+ 'BUILDPACK_WORKSPACE_DIR',+ os.path.join(os.environ.get('SERVERKIT_CACHE_DIR', '/var/cache/serverkit'), 'buildpacks'),+ )+class DevelopmentConfig(Config):DEBUG = Truediff --git a/backend/migrations/versions/030_buildpacks_snapshots.py b/backend/migrations/versions/030_buildpacks_snapshots.pynew file mode 100644index 00000000..04cc8a54--- /dev/null+++ b/backend/migrations/versions/030_buildpacks_snapshots.py@@ -0,0 +1,68 @@+"""Build packs + deployment config snapshots.++Adds:+- applications.buildpack_type / buildpack_plan / buildpack_overrides+- deployment_snapshots (immutable resolved-config snapshot per deploy, with hash)++Backs zero-Dockerfile build-pack deploys (detected plan persisted on the app) and+the deployment config snapshot + diff/restore engine.++Idempotent: MigrationService runs _fix_missing_columns() + db.create_all() on boot+before Alembic, so guard on the live schema.++Revision ID: 030_buildpacks_snapshots+Revises: 029_server_onboarding+Create Date: 2026-06-23+"""+from alembic import op+import sqlalchemy as sa++revision = '030_buildpacks_snapshots'+down_revision = '029_server_onboarding'+branch_labels = None+depends_on = None+++def upgrade():+ conn = op.get_bind()+ inspector = sa.inspect(conn)+ existing = set(inspector.get_table_names())++ if 'applications' in existing:+ cols = {c['name'] for c in inspector.get_columns('applications')}+ if 'buildpack_type' not in cols:+ op.add_column('applications', sa.Column('buildpack_type', sa.String(20), nullable=True))+ if 'buildpack_plan' not in cols:+ op.add_column('applications', sa.Column('buildpack_plan', sa.Text, nullable=True))+ if 'buildpack_overrides' not in cols:+ op.add_column('applications', sa.Column('buildpack_overrides', sa.Text, nullable=True))++ if 'deployment_snapshots' not in existing:+ op.create_table(+ 'deployment_snapshots',+ sa.Column('id', sa.Integer, nullable=False),+ sa.Column('application_id', sa.Integer, nullable=False),+ sa.Column('deployment_id', sa.Integer, nullable=True),+ sa.Column('snapshot_hash', sa.String(64), nullable=False),+ sa.Column('config_json', sa.Text, nullable=False, server_default='{}'),+ sa.Column('summary', sa.String(255), nullable=True),+ sa.Column('created_at', sa.DateTime, nullable=True),+ sa.PrimaryKeyConstraint('id'),+ sa.ForeignKeyConstraint(['application_id'], ['applications.id']),+ sa.ForeignKeyConstraint(['deployment_id'], ['deployments.id']),+ )+ op.create_index('ix_deployment_snapshots_application_id', 'deployment_snapshots', ['application_id'])+ op.create_index('ix_deployment_snapshots_deployment_id', 'deployment_snapshots', ['deployment_id'])+++def downgrade():+ conn = op.get_bind()+ inspector = sa.inspect(conn)+ existing = set(inspector.get_table_names())+ if 'deployment_snapshots' in existing:+ op.drop_table('deployment_snapshots')+ if 'applications' in existing:+ cols = {c['name'] for c in inspector.get_columns('applications')}+ for col in ('buildpack_overrides', 'buildpack_plan', 'buildpack_type'):+ if col in cols:+ op.drop_column('applications', col)diff --git a/backend/templates/index.json b/backend/templates/index.jsonindex 6d1747b5..307ff1f5 100644--- a/backend/templates/index.json+++ b/backend/templates/index.json@@ -1,447 +1,1143 @@{"version": "1.0.0",- "updated_at": "2025-01-18",+ "updated_at": "2026-06-23","templates": [{"id": "uptime-kuma","name": "Uptime Kuma","version": "1.23",- "description": "Self-hosted monitoring tool for tracking uptime of websites and services",- "categories": ["monitoring", "devops"]+ "description": "A fancy self-hosted monitoring tool for websites and services",+ "categories": [+ "monitoring",+ "devops"+ ]},{"id": "portainer","name": "Portainer","version": "2.19",- "description": "Container management platform for Docker, Swarm, and Kubernetes",- "categories": ["docker", "management", "devops"]+ "description": "Lightweight Docker management UI with container visualization",+ "categories": [+ "devops",+ "docker",+ "management"+ ]},{"id": "ghost","name": "Ghost","version": "5.75","description": "Professional publishing platform for blogs and newsletters",- "categories": ["blog", "cms", "publishing"]+ "categories": [+ "cms",+ "blog",+ "publishing"+ ]},{"id": "nextcloud","name": "Nextcloud","version": "28.0",- "description": "Self-hosted productivity platform with file sync, collaboration, and office suite",- "categories": ["storage", "collaboration", "productivity"]+ "description": "Self-hosted productivity platform with file sync and collaboration",+ "categories": [+ "storage",+ "collaboration",+ "productivity"+ ]},{"id": "gitea","name": "Gitea","version": "1.21",- "description": "Lightweight self-hosted Git service with issue tracking and CI/CD",- "categories": ["git", "development", "devops"]+ "description": "Lightweight self-hosted Git service",+ "categories": [+ "devops",+ "git",+ "development"+ ]},{"id": "nginx-proxy-manager","name": "Nginx Proxy Manager","version": "2.10",- "description": "Easy-to-use reverse proxy with SSL certificate management",- "categories": ["proxy", "ssl", "networking"]+ "description": "Easy-to-use reverse proxy with SSL management",+ "categories": [+ "networking",+ "proxy",+ "ssl"+ ]},{"id": "grafana","name": "Grafana","version": "10.2",- "description": "Open-source analytics and interactive visualization platform",- "categories": ["monitoring", "analytics", "visualization"]+ "description": "Open-source analytics and interactive visualization platform for metrics, logs, and traces",+ "categories": [+ "monitoring",+ "analytics",+ "visualization"+ ]},{"id": "prometheus","name": "Prometheus","version": "2.48",- "description": "Open-source monitoring and alerting toolkit for reliability",- "categories": ["monitoring", "metrics", "alerting"]+ "description": "Open-source monitoring and alerting toolkit designed for reliability and scalability",+ "categories": [+ "monitoring",+ "metrics",+ "alerting"+ ]},{"id": "netdata","name": "Netdata","version": "1.44",- "description": "Real-time performance and health monitoring for systems",- "categories": ["monitoring", "metrics", "realtime"]+ "description": "Real-time performance and health monitoring for systems and applications",+ "categories": [+ "monitoring",+ "metrics",+ "realtime"+ ]},{"id": "loki","name": "Grafana Loki","version": "2.9",- "description": "Horizontally scalable log aggregation system",- "categories": ["monitoring", "logging", "observability"]+ "description": "Horizontally scalable, highly available log aggregation system inspired by Prometheus",+ "categories": [+ "monitoring",+ "logging",+ "observability"+ ]},{"id": "jaeger","name": "Jaeger","version": "1.52",- "description": "Open-source distributed tracing system for microservices",- "categories": ["monitoring", "tracing", "observability"]+ "description": "Open-source distributed tracing system for monitoring and troubleshooting microservices",+ "categories": [+ "monitoring",+ "tracing",+ "observability"+ ]},{"id": "jenkins","name": "Jenkins","version": "2.426",- "description": "Leading open-source automation server for CI/CD",- "categories": ["devops", "ci-cd", "automation"]+ "description": "Leading open-source automation server for building, deploying, and automating projects",+ "categories": [+ "devops",+ "ci-cd",+ "automation"+ ]},{"id": "drone","name": "Drone CI","version": "2.22",- "description": "Container-native continuous integration platform",- "categories": ["devops", "ci-cd", "docker"]+ "description": "Container-native continuous integration platform with simple pipeline configuration",+ "categories": [+ "devops",+ "ci-cd",+ "docker"+ ]},{"id": "gitlab-runner","name": "GitLab Runner","version": "16.6",- "description": "Application that works with GitLab CI/CD to run jobs",- "categories": ["devops", "ci-cd", "gitlab"]+ "description": "Application that works with GitLab CI/CD to run jobs in a pipeline",+ "categories": [+ "devops",+ "ci-cd",+ "gitlab"+ ]},{"id": "sonarqube","name": "SonarQube","version": "10.3",- "description": "Continuous inspection of code quality and security",- "categories": ["devops", "code-quality", "security"]+ "description": "Continuous inspection of code quality and security vulnerabilities",+ "categories": [+ "devops",+ "code-quality",+ "security"+ ]},{"id": "registry","name": "Docker Registry","version": "2.8",- "description": "Private Docker container image registry",- "categories": ["devops", "docker", "registry"]+ "description": "Private Docker container image registry for storing and distributing container images",+ "categories": [+ "devops",+ "docker",+ "registry"+ ]},{"id": "vault","name": "HashiCorp Vault","version": "1.15",- "description": "Secrets management and data protection platform",- "categories": ["devops", "security", "secrets"]+ "description": "Secrets management and data protection platform for securing sensitive data",+ "categories": [+ "devops",+ "security",+ "secrets"+ ]},{"id": "wordpress","name": "WordPress","version": "6.4",- "description": "World's most popular content management system",- "categories": ["cms", "blog", "website"]+ "description": "World's most popular content management system for blogs and websites",+ "categories": [+ "cms",+ "blog",+ "website"+ ]},{"id": "wordpress-external-db","name": "WordPress (External Database)","version": "6.4",- "description": "WordPress CMS with external MySQL database support for dev/prod environments",- "categories": ["cms", "blog", "website", "development"]+ "description": "WordPress CMS connecting to an existing external MySQL database. Use this for dev/prod setups sharing the same database with different table prefixes.",+ "categories": [+ "cms",+ "blog",+ "website",+ "development"+ ]},{"id": "strapi","name": "Strapi","version": "4.15",- "description": "Open-source headless CMS with customizable API",- "categories": ["cms", "headless", "api"]+ "description": "Open-source headless CMS with customizable API and admin panel",+ "categories": [+ "cms",+ "headless",+ "api"+ ]},{"id": "directus","name": "Directus","version": "10.8",- "description": "Open-source data platform with instant REST and GraphQL API",- "categories": ["cms", "headless", "api", "database"]+ "description": "Open-source data platform with instant REST and GraphQL API for any SQL database",+ "categories": [+ "cms",+ "headless",+ "api",+ "database"+ ]},{"id": "payload","name": "Payload CMS","version": "2.5",- "description": "Modern TypeScript headless CMS with powerful admin panel",- "categories": ["cms", "headless", "typescript"]+ "description": "Modern TypeScript headless CMS with powerful admin panel and customization",+ "categories": [+ "cms",+ "headless",+ "typescript"+ ]},{"id": "grav","name": "Grav CMS","version": "1.7","description": "Modern flat-file CMS that is fast, simple, and flexible",- "categories": ["cms", "flat-file", "blog"]+ "categories": [+ "cms",+ "flat-file",+ "blog"+ ]},{"id": "jellyfin","name": "Jellyfin","version": "10.8",- "description": "Free and open-source media server for streaming",- "categories": ["media", "streaming", "entertainment"]+ "description": "Free and open-source media server for streaming movies, TV shows, music, and more",+ "categories": [+ "media",+ "streaming",+ "entertainment"+ ]},{"id": "plex","name": "Plex Media Server","version": "1.32",- "description": "Organize and stream your personal media collection",- "categories": ["media", "streaming", "entertainment"]+ "description": "Organize and stream your personal media collection to any device",+ "categories": [+ "media",+ "streaming",+ "entertainment"+ ]},{"id": "photoprism","name": "PhotoPrism","version": "231128",- "description": "AI-powered photo management with face recognition",- "categories": ["media", "photos", "ai"]+ "description": "AI-powered photo management application with face recognition and auto-tagging",+ "categories": [+ "media",+ "photos",+ "ai"+ ]},{"id": "immich","name": "Immich","version": "1.91",- "description": "High-performance self-hosted photo and video backup",- "categories": ["media", "photos", "backup"]+ "description": "High-performance self-hosted photo and video backup solution with mobile apps",+ "categories": [+ "media",+ "photos",+ "backup"+ ]},{"id": "navidrome","name": "Navidrome","version": "0.50",- "description": "Modern music server and streamer compatible with Subsonic",- "categories": ["media", "music", "streaming"]+ "description": "Modern music server and streamer compatible with Subsonic/Airsonic",+ "categories": [+ "media",+ "music",+ "streaming"+ ]},{"id": "rocketchat","name": "Rocket.Chat","version": "6.5",- "description": "Open-source team communication platform",- "categories": ["collaboration", "chat", "communication"]+ "description": "Open-source team communication platform with chat, video, and file sharing",+ "categories": [+ "collaboration",+ "chat",+ "communication"+ ]},{"id": "mattermost","name": "Mattermost","version": "9.2",- "description": "Open-source Slack alternative for secure team collaboration",- "categories": ["collaboration", "chat", "communication"]+ "description": "Open-source Slack alternative for secure team collaboration and messaging",+ "categories": [+ "collaboration",+ "chat",+ "communication"+ ]},{"id": "matrix-synapse","name": "Matrix Synapse","version": "1.98",- "description": "Decentralized communication server for federated messaging",- "categories": ["collaboration", "chat", "federation"]+ "description": "Decentralized communication server for secure, federated messaging",+ "categories": [+ "collaboration",+ "chat",+ "federation"+ ]},{"id": "jitsi","name": "Jitsi Meet","version": "9111",- "description": "Secure, fully featured video conferencing",- "categories": ["collaboration", "video", "conferencing"]+ "description": "Secure, fully featured, and completely free video conferencing",+ "categories": [+ "collaboration",+ "video",+ "conferencing"+ ]},{"id": "minio","name": "MinIO","version": "2024-01",- "description": "High-performance, S3-compatible object storage",- "categories": ["storage", "s3", "cloud"]+ "description": "High-performance, S3-compatible object storage for cloud-native applications",+ "categories": [+ "storage",+ "s3",+ "cloud"+ ]},{"id": "seafile","name": "Seafile","version": "11.0",- "description": "Open-source file sync and share platform",- "categories": ["storage", "sync", "collaboration"]+ "description": "Open-source file sync and share platform with built-in collaboration",+ "categories": [+ "storage",+ "sync",+ "collaboration"+ ]},{"id": "filebrowser","name": "File Browser","version": "2.27",- "description": "Web-based file manager with upload and sharing",- "categories": ["storage", "files", "management"]+ "description": "Web-based file manager with upload, download, and file sharing features",+ "categories": [+ "storage",+ "files",+ "management"+ ]},{"id": "syncthing","name": "Syncthing","version": "1.27",- "description": "Continuous file synchronization for peer-to-peer sync",- "categories": ["storage", "sync", "backup"]+ "description": "Continuous file synchronization for decentralized, peer-to-peer sync",+ "categories": [+ "storage",+ "sync",+ "backup"+ ]},{"id": "duplicati","name": "Duplicati","version": "2.0","description": "Free backup software to store encrypted backups online",- "categories": ["storage", "backup", "encryption"]+ "categories": [+ "storage",+ "backup",+ "encryption"+ ]},{"id": "bookstack","name": "BookStack","version": "23.12",- "description": "Simple, self-hosted platform for organizing information",- "categories": ["productivity", "wiki", "documentation"]+ "description": "Simple, self-hosted platform for organizing and storing information",+ "categories": [+ "productivity",+ "wiki",+ "documentation"+ ]},{"id": "wikijs","name": "Wiki.js","version": "2.5","description": "Modern and powerful wiki app built on Node.js",- "categories": ["productivity", "wiki", "documentation"]+ "categories": [+ "productivity",+ "wiki",+ "documentation"+ ]},{"id": "outline","name": "Outline","version": "0.74",- "description": "Beautiful, real-time collaborative team wiki",- "categories": ["productivity", "wiki", "collaboration"]+ "description": "Beautiful, real-time collaborative team wiki and knowledge base",+ "categories": [+ "productivity",+ "wiki",+ "collaboration"+ ]},{"id": "excalidraw","name": "Excalidraw","version": "0.17",- "description": "Virtual whiteboard for sketching hand-drawn diagrams",- "categories": ["productivity", "diagrams", "whiteboard"]+ "description": "Virtual whiteboard for sketching hand-drawn like diagrams",+ "categories": [+ "productivity",+ "diagrams",+ "whiteboard"+ ]},{"id": "n8n","name": "n8n","version": "1.22",- "description": "Extendable workflow automation tool",- "categories": ["productivity", "automation", "integration"]+ "description": "Extendable workflow automation tool for connecting apps and services",+ "categories": [+ "productivity",+ "automation",+ "integration"+ ]},{"id": "vaultwarden","name": "Vaultwarden","version": "1.30","description": "Lightweight Bitwarden-compatible password manager server",- "categories": ["security", "passwords", "privacy"]+ "categories": [+ "security",+ "passwords",+ "privacy"+ ]},{"id": "authelia","name": "Authelia","version": "4.37","description": "Authentication and authorization server providing 2FA and SSO",- "categories": ["security", "authentication", "sso"]+ "categories": [+ "security",+ "authentication",+ "sso"+ ]},{"id": "keycloak","name": "Keycloak","version": "23.0",- "description": "Open-source identity and access management",- "categories": ["security", "authentication", "sso"]+ "description": "Open-source identity and access management for modern applications",+ "categories": [+ "security",+ "authentication",+ "sso"+ ]},{"id": "crowdsec","name": "CrowdSec","version": "1.6",- "description": "Collaborative security engine for detecting threats",- "categories": ["security", "firewall", "threat-detection"]+ "description": "Collaborative security engine for detecting and blocking threats",+ "categories": [+ "security",+ "firewall",+ "threat-detection"+ ]},{"id": "phpmyadmin","name": "phpMyAdmin","version": "5.2","description": "Web-based MySQL and MariaDB administration tool",- "categories": ["database", "mysql", "management"]+ "categories": [+ "database",+ "mysql",+ "management"+ ]},{"id": "pgadmin","name": "pgAdmin 4","version": "8.2",- "description": "Web-based PostgreSQL administration platform",- "categories": ["database", "postgresql", "management"]+ "description": "Web-based PostgreSQL administration and development platform",+ "categories": [+ "database",+ "postgresql",+ "management"+ ]},{"id": "redis-commander","name": "Redis Commander","version": "0.8",- "description": "Web-based Redis management tool",- "categories": ["database", "redis", "management"]+ "description": "Web-based Redis management tool for viewing and editing data",+ "categories": [+ "database",+ "redis",+ "management"+ ]},{"id": "mongo-express","name": "Mongo Express","version": "1.0",- "description": "Web-based MongoDB admin interface",- "categories": ["database", "mongodb", "management"]+ "description": "Web-based MongoDB admin interface for managing databases and collections",+ "categories": [+ "database",+ "mongodb",+ "management"+ ]},{"id": "homeassistant","name": "Home Assistant","version": "2024.1",- "description": "Open-source home automation platform",- "categories": ["home-automation", "iot", "smart-home"]+ "description": "Open-source home automation platform with focus on local control and privacy",+ "categories": [+ "home-automation",+ "iot",+ "smart-home"+ ]},{"id": "nodered","name": "Node-RED","version": "3.1",- "description": "Flow-based programming tool for IoT",- "categories": ["home-automation", "automation", "iot"]+ "description": "Flow-based programming tool for wiring together hardware devices and APIs",+ "categories": [+ "home-automation",+ "automation",+ "iot"+ ]},{"id": "mosquitto","name": "Eclipse Mosquitto","version": "2.0",- "description": "Lightweight MQTT message broker",- "categories": ["home-automation", "iot", "messaging"]+ "description": "Lightweight MQTT message broker for IoT and home automation",+ "categories": [+ "home-automation",+ "iot",+ "messaging"+ ]},{"id": "zigbee2mqtt","name": "Zigbee2MQTT","version": "1.35",- "description": "Bridge Zigbee devices to MQTT",- "categories": ["home-automation", "iot", "zigbee"]+ "description": "Bridge Zigbee devices to MQTT without proprietary bridges or gateways",+ "categories": [+ "home-automation",+ "iot",+ "zigbee"+ ]},{"id": "code-server","name": "Code Server","version": "4.20",- "description": "VS Code in the browser with full IDE features",- "categories": ["development", "ide", "productivity"]+ "description": "VS Code in the browser with full IDE features and extensions support",+ "categories": [+ "development",+ "ide",+ "productivity"+ ]},{"id": "traefik","name": "Traefik","version": "3.0",- "description": "Modern HTTP reverse proxy with automatic HTTPS",- "categories": ["networking", "proxy", "ssl"]+ "description": "Modern HTTP reverse proxy and load balancer with automatic HTTPS",+ "categories": [+ "networking",+ "proxy",+ "ssl"+ ]},{"id": "caddy","name": "Caddy","version": "2.7","description": "Fast, multi-platform web server with automatic HTTPS",- "categories": ["networking", "proxy", "ssl"]+ "categories": [+ "networking",+ "proxy",+ "ssl"+ ]},{"id": "plausible","name": "Plausible Analytics","version": "2.0",- "description": "Privacy-friendly alternative to Google Analytics",- "categories": ["analytics", "privacy", "monitoring"]+ "description": "Privacy-friendly, lightweight alternative to Google Analytics",+ "categories": [+ "analytics",+ "privacy",+ "monitoring"+ ]},{"id": "umami","name": "Umami","version": "2.9",- "description": "Simple, fast, privacy-focused analytics",- "categories": ["analytics", "privacy", "monitoring"]+ "description": "Simple, fast, privacy-focused alternative to Google Analytics",+ "categories": [+ "analytics",+ "privacy",+ "monitoring"+ ]},{"id": "php-app","name": "PHP Application","version": "8.3",- "description": "Custom PHP application with Apache. Supports PHP 8.0-8.3.",- "categories": ["development", "web", "custom"]+ "description": "Custom PHP application with Apache. Supports PHP 8.0-8.3. Perfect for Laravel, WordPress themes, or any PHP project.",+ "categories": [+ "development",+ "web",+ "custom"+ ]},{"id": "flask-hello-world","name": "Flask - Hello World","version": "1.0",- "description": "Simple Flask debug app. Shows server info, port, and connection status. No database needed.",- "categories": ["development", "api", "testing"]+ "description": "Simple Flask app for testing and debugging. Shows server info, port, and connection status. No database needed.",+ "categories": [+ "development",+ "api",+ "testing"+ ]},{"id": "python-app","name": "Python Application","version": "3.12",- "description": "Custom Python application. Supports Flask, FastAPI, Django.",- "categories": ["development", "api", "custom"]+ "description": "Custom Python application. Supports Python 3.9-3.12. Perfect for Flask, FastAPI, Django, or any Python project.",+ "categories": [+ "development",+ "api",+ "custom"+ ]},{"id": "node-app","name": "Node.js Application","version": "20",- "description": "Custom Node.js application. Supports Express, Next.js.",- "categories": ["development", "api", "custom"]+ "description": "Custom Node.js application. Supports Node 18-21. Perfect for Express, Next.js, or any Node.js project.",+ "categories": [+ "development",+ "api",+ "custom"+ ]+ },+ {+ "id": "actualbudget",+ "name": "Actual Budget",+ "version": "1.0",+ "description": "Privacy-first personal budgeting app using envelope budgeting with optional bank sync.",+ "categories": [+ "finance",+ "productivity"+ ]+ },+ {+ "id": "anythingllm",+ "name": "AnythingLLM",+ "version": "1.0",+ "description": "All-in-one private ChatGPT-style app with built-in RAG, AI agents, and document workspaces.",+ "categories": [+ "ai",+ "llm",+ "chat",+ "rag"+ ]+ },+ {+ "id": "audiobookshelf",+ "name": "Audiobookshelf",+ "version": "1.0",+ "description": "Self-hosted server for managing and streaming your audiobooks, podcasts, and ebooks.",+ "categories": [+ "media",+ "audiobooks"+ ]+ },+ {+ "id": "authentik",+ "name": "Authentik",+ "version": "1.0",+ "description": "Open-source identity provider for single sign-on with OIDC, SAML, and LDAP.",+ "categories": [+ "security",+ "identity",+ "sso"+ ]+ },+ {+ "id": "beszel",+ "name": "Beszel",+ "version": "1.0",+ "description": "Lightweight server monitoring hub with historical metrics and alerts.",+ "categories": [+ "monitoring"+ ]+ },+ {+ "id": "calibre-web",+ "name": "Calibre-Web",+ "version": "1.0",+ "description": "Clean web interface for browsing, reading, and downloading books from a Calibre ebook library.",+ "categories": [+ "media",+ "ebooks",+ "productivity"+ ]+ },+ {+ "id": "chatwoot",+ "name": "Chatwoot",+ "version": "1.0",+ "description": "Open-source customer engagement suite with live chat and a shared inbox.",+ "categories": [+ "business",+ "support",+ "communication"+ ]+ },+ {+ "id": "chroma",+ "name": "Chroma",+ "version": "1.0",+ "description": "Open-source vector database for embeddings and semantic search in AI and RAG applications.",+ "categories": [+ "ai",+ "database",+ "search"+ ]+ },+ {+ "id": "documenso",+ "name": "Documenso",+ "version": "1.0",+ "description": "Open-source document signing platform for sending and signing documents online.",+ "categories": [+ "business",+ "documents",+ "productivity"+ ]+ },+ {+ "id": "firefly-iii",+ "name": "Firefly III",+ "version": "1.0",+ "description": "Self-hosted personal finance manager for budgeting, accounts, and money tracking.",+ "categories": [+ "finance",+ "productivity"+ ]+ },+ {+ "id": "flowise",+ "name": "Flowise",+ "version": "1.0",+ "description": "Low-code drag-and-drop builder for LLM agents and chains.",+ "categories": [+ "ai",+ "llm",+ "workflow",+ "low-code"+ ]+ },+ {+ "id": "freshrss",+ "name": "FreshRSS",+ "version": "1.0",+ "description": "Free, self-hosted RSS and Atom feed aggregator for following news and websites in one place.",+ "categories": [+ "news",+ "rss",+ "productivity"+ ]+ },+ {+ "id": "gotify",+ "name": "Gotify",+ "version": "1.0",+ "description": "Self-hosted push notification server with Android client support.",+ "categories": [+ "notifications",+ "messaging"+ ]+ },+ {+ "id": "jellyseerr",+ "name": "Jellyseerr",+ "version": "1.0",+ "description": "Media request and discovery portal for Jellyfin/Plex and the PVR apps",+ "categories": [+ "media",+ "automation"+ ]+ },+ {+ "id": "karakeep",+ "name": "Karakeep",+ "version": "1.0",+ "description": "Self-hosted bookmark-everything app (formerly Hoarder) that saves links, notes, and images with AI tagging and full-text search.",+ "categories": [+ "productivity",+ "bookmarks"+ ]+ },+ {+ "id": "langflow",+ "name": "Langflow",+ "version": "1.0",+ "description": "Visual framework for building multi-agent and RAG applications.",+ "categories": [+ "ai",+ "llm",+ "workflow",+ "rag"+ ]+ },+ {+ "id": "librechat",+ "name": "LibreChat",+ "version": "1.0",+ "description": "Open-source multi-model chat UI (OpenAI, Anthropic, Google, local) with conversation search.",+ "categories": [+ "ai",+ "llm",+ "chat"+ ]+ },+ {+ "id": "linkding",+ "name": "linkding",+ "version": "1.0",+ "description": "Minimal, fast self-hosted bookmark manager.",+ "categories": [+ "productivity",+ "bookmarks"+ ]+ },+ {+ "id": "litellm",+ "name": "LiteLLM",+ "version": "1.0",+ "description": "OpenAI-compatible proxy and gateway that routes requests across 100+ LLM providers.",+ "categories": [+ "ai",+ "llm",+ "gateway"+ ]+ },+ {+ "id": "meilisearch",+ "name": "Meilisearch",+ "version": "1.0",+ "description": "Lightning-fast, typo-tolerant search engine that many apps rely on for instant full-text search.",+ "categories": [+ "search",+ "database"+ ]+ },+ {+ "id": "memos",+ "name": "Memos",+ "version": "1.0",+ "description": "Lightweight, privacy-first note-taking and micro-blogging app.",+ "categories": [+ "notes",+ "productivity"+ ]+ },+ {+ "id": "metabase",+ "name": "Metabase",+ "version": "1.0",+ "description": "Open-source business intelligence and dashboards tool for exploring your data.",+ "categories": [+ "analytics",+ "business",+ "productivity"+ ]+ },+ {+ "id": "miniflux",+ "name": "Miniflux",+ "version": "1.0",+ "description": "Minimalist and fast self-hosted RSS feed reader backed by PostgreSQL.",+ "categories": [+ "news",+ "rss"+ ]+ },+ {+ "id": "nodebb",+ "name": "NodeBB",+ "version": "1.0",+ "description": "Modern, real-time forum and community platform built on Node.js.",+ "categories": [+ "community",+ "forum",+ "business"+ ]+ },+ {+ "id": "ntfy",+ "name": "ntfy",+ "version": "1.0",+ "description": "Simple HTTP-based pub/sub service that pushes notifications to your phone or desktop via a POST.",+ "categories": [+ "notifications",+ "messaging"+ ]+ },+ {+ "id": "ollama-webui",+ "name": "Ollama + Open WebUI",+ "version": "1.0",+ "description": "Local LLM inference with Ollama and a friendly chat interface (Open WebUI).",+ "categories": [+ "ai",+ "llm",+ "chat"+ ]+ },+ {+ "id": "paperless-ngx",+ "name": "Paperless-ngx",+ "version": "1.0",+ "description": "Document management system that scans, OCRs, indexes and archives your documents into a searchable online archive.",+ "categories": [+ "documents",+ "productivity"+ ]+ },+ {+ "id": "pihole",+ "name": "Pi-hole",+ "version": "1.0",+ "description": "Network-wide ad-blocking DNS sinkhole with a web dashboard.",+ "categories": [+ "networking",+ "dns",+ "security"+ ]+ },+ {+ "id": "plane",+ "name": "Plane",+ "version": "1.0",+ "description": "Open-source project management and issue tracking with cycles, modules, and views (a Jira/Linear alternative).",+ "categories": [+ "productivity",+ "project-management"+ ]+ },+ {+ "id": "posthog",+ "name": "PostHog",+ "version": "1.0",+ "description": "Open-source product analytics with session replay, feature flags, A/B testing, and event autocapture.",+ "categories": [+ "analytics",+ "business"+ ]+ },+ {+ "id": "prompture-hub",+ "name": "Prompture Hub",+ "version": "0.0.2",+ "description": "Self-hosted LLM gateway. Hold real provider keys server-side, issue scoped hub keys, and meter every call. Drop-in OpenAI-compatible API.",+ "categories": [+ "ai",+ "llm",+ "gateway",+ "prompture"+ ]+ },+ {+ "id": "prowlarr",+ "name": "Prowlarr",+ "version": "1.0",+ "description": "Indexer manager and proxy that integrates your indexers with the PVR apps",+ "categories": [+ "media",+ "automation"+ ]+ },+ {+ "id": "qbittorrent",+ "name": "qBittorrent",+ "version": "1.0",+ "description": "Open-source BitTorrent client with a full-featured web UI",+ "categories": [+ "media",+ "downloads"+ ]+ },+ {+ "id": "qdrant",+ "name": "Qdrant",+ "version": "1.0",+ "description": "Vector similarity search engine for AI/LLM and semantic-search applications.",+ "categories": [+ "ai",+ "database",+ "search"+ ]+ },+ {+ "id": "radarr",+ "name": "Radarr",+ "version": "1.0",+ "description": "PVR for movies that monitors, grabs, sorts, and renames films automatically",+ "categories": [+ "media",+ "automation"+ ]+ },+ {+ "id": "searxng",+ "name": "SearXNG",+ "version": "1.0",+ "description": "Privacy-respecting metasearch engine that aggregates results from many sources without tracking you.",+ "categories": [+ "search",+ "privacy"+ ]+ },+ {+ "id": "signoz",+ "name": "SigNoz",+ "version": "1.0",+ "description": "OpenTelemetry-native observability platform for traces, metrics, and logs (an open-source APM alternative to Datadog).",+ "categories": [+ "monitoring",+ "observability",+ "apm"+ ]+ },+ {+ "id": "sonarr",+ "name": "Sonarr",+ "version": "1.0",+ "description": "PVR for TV series that monitors, grabs, sorts, and renames episodes automatically",+ "categories": [+ "media",+ "automation"+ ]+ },+ {+ "id": "stirling-pdf",+ "name": "Stirling PDF",+ "version": "1.0",+ "description": "Local web toolkit for splitting, merging, converting and OCR-ing PDF files.",+ "categories": [+ "documents",+ "productivity",+ "pdf"+ ]+ },+ {+ "id": "typesense",+ "name": "Typesense",+ "version": "1.0",+ "description": "Typo-tolerant search engine optimized for fast, instant search-as-you-type experiences.",+ "categories": [+ "search",+ "database"+ ]+ },+ {+ "id": "vikunja",+ "name": "Vikunja",+ "version": "1.0",+ "description": "Self-hosted to-do list and task and project manager.",+ "categories": [+ "productivity",+ "tasks"+ ]+ },+ {+ "id": "wg-easy",+ "name": "WG-Easy",+ "version": "1.0",+ "description": "The easiest way to run WireGuard VPN with a web admin UI.",+ "categories": [+ "networking",+ "vpn",+ "security"+ ]}],"categories": [@@ -469,6 +1165,86 @@"custom","web","api",- "testing"+ "testing",+ "ai",+ "alerting",+ "apm",+ "audiobooks",+ "authentication",+ "backup",+ "bookmarks",+ "business",+ "chat",+ "cloud",+ "code-quality",+ "communication",+ "community",+ "conferencing",+ "diagrams",+ "dns",+ "documentation",+ "documents",+ "downloads",+ "ebooks",+ "encryption",+ "entertainment",+ "federation",+ "files",+ "finance",+ "firewall",+ "flat-file",+ "forum",+ "gateway",+ "gitlab",+ "headless",+ "ide",+ "identity",+ "integration",+ "llm",+ "logging",+ "low-code",+ "management",+ "messaging",+ "metrics",+ "mongodb",+ "music",+ "mysql",+ "news",+ "notes",+ "notifications",+ "observability",+ "passwords",+ "pdf",+ "photos",+ "postgresql",+ "privacy",+ "project-management",+ "prompture",+ "publishing",+ "rag",+ "realtime",+ "redis",+ "registry",+ "rss",+ "s3",+ "search",+ "secrets",+ "smart-home",+ "sso",+ "streaming",+ "support",+ "sync",+ "tasks",+ "threat-detection",+ "tracing",+ "typescript",+ "video",+ "visualization",+ "vpn",+ "website",+ "whiteboard",+ "wiki",+ "workflow",+ "zigbee"]}diff --git a/backend/tests/test_buildpacks.py b/backend/tests/test_buildpacks.pynew file mode 100644index 00000000..cd46ce99--- /dev/null+++ b/backend/tests/test_buildpacks.py@@ -0,0 +1,244 @@+"""Unit tests for the transparent build-pack layer (BuildpackService).++Pure / no network / no Flask app needed — detection runs against temp dirs full+of marker files, and generation is pure string production.+"""++import json++import pytest++from app.services.buildpack_service import BuildpackService+++# --------------------------------------------------------------------------- #+# detect()+# --------------------------------------------------------------------------- #+def test_detect_node_express(tmp_path):+ (tmp_path / 'package.json').write_text(json.dumps({+ 'name': 'demo',+ 'dependencies': {'express': '^4.18.0'},+ 'scripts': {'start': 'node server.js'},+ 'engines': {'node': '>=20'},+ }), encoding='utf-8')++ plan = BuildpackService.detect(str(tmp_path))++ assert plan['builder'] == 'nixpacks'+ assert plan['language'] == 'node'+ assert plan['framework'] == 'express'+ assert plan['versions']['node'] == '20'+ assert plan['start_command'] == 'node server.js'+ assert plan['port'] == 3000+ assert plan['confidence'] > 0+++def test_detect_node_nextjs_build_command(tmp_path):+ (tmp_path / 'package.json').write_text(json.dumps({+ 'dependencies': {'next': '14.0.0', 'react': '18'},+ 'scripts': {'build': 'next build', 'start': 'next start'},+ }), encoding='utf-8')+ (tmp_path / 'next.config.js').write_text('module.exports = {}', encoding='utf-8')++ plan = BuildpackService.detect(str(tmp_path))++ assert plan['framework'] == 'nextjs'+ assert plan['build_command'] == 'npm run build'+++def test_detect_python_flask(tmp_path):+ (tmp_path / 'requirements.txt').write_text('Flask==3.0\ngunicorn\n', encoding='utf-8')+ (tmp_path / 'app.py').write_text('app = None\n', encoding='utf-8')++ plan = BuildpackService.detect(str(tmp_path))++ assert plan['builder'] == 'nixpacks'+ assert plan['language'] == 'python'+ assert plan['framework'] == 'flask'+ assert 'gunicorn' in plan['start_command']+ assert plan['build_command'].startswith('pip install')+++def test_detect_python_version_from_pyproject(tmp_path):+ (tmp_path / 'pyproject.toml').write_text(+ '[project]\nname="x"\nrequires-python = ">=3.12"\n', encoding='utf-8')++ plan = BuildpackService.detect(str(tmp_path))++ assert plan['language'] == 'python'+ assert plan['versions']['python'] == '3.12'+++def test_detect_go(tmp_path):+ (tmp_path / 'go.mod').write_text('module example.com/app\n\ngo 1.21\n', encoding='utf-8')++ plan = BuildpackService.detect(str(tmp_path))++ assert plan['builder'] == 'nixpacks'+ assert plan['language'] == 'go'+ assert plan['versions']['go'] == '1.21'+ assert plan['build_command'] == 'go build -o /app/server ./...'+++def test_detect_static(tmp_path):+ (tmp_path / 'index.html').write_text('<html></html>', encoding='utf-8')++ plan = BuildpackService.detect(str(tmp_path))++ assert plan['builder'] == 'static'+ assert plan['language'] == 'static'+ assert plan['port'] == 80+++def test_detect_dockerfile_present_wins(tmp_path):+ # Dockerfile present alongside a package.json — defer to the author's build.+ (tmp_path / 'Dockerfile').write_text('FROM node:20\n', encoding='utf-8')+ (tmp_path / 'package.json').write_text('{}', encoding='utf-8')++ plan = BuildpackService.detect(str(tmp_path))++ assert plan['builder'] == 'dockerfile-present'+ assert plan['confidence'] == 1.0+ assert plan['language'] == 'node' # still labeled for display+++def test_detect_unknown(tmp_path):+ (tmp_path / 'README.md').write_text('# nothing here', encoding='utf-8')++ plan = BuildpackService.detect(str(tmp_path))++ assert plan['builder'] == 'unknown'+ assert plan['confidence'] == 0.0+ assert plan['notes']+++def test_detect_missing_path():+ plan = BuildpackService.detect('/path/that/does/not/exist/xyz')+ assert plan['builder'] == 'unknown'+ assert plan['notes']+++def test_procfile_overrides_start_command(tmp_path):+ (tmp_path / 'requirements.txt').write_text('flask\n', encoding='utf-8')+ (tmp_path / 'Procfile').write_text('web: gunicorn wsgi:application\n', encoding='utf-8')++ plan = BuildpackService.detect(str(tmp_path))++ assert plan['start_command'] == 'gunicorn wsgi:application'+++# --------------------------------------------------------------------------- #+# generate_dockerfile()+# --------------------------------------------------------------------------- #+def test_generate_dockerfile_node():+ plan = {+ 'builder': 'nixpacks', 'language': 'node', 'framework': 'express',+ 'versions': {'node': '20'}, 'build_command': 'npm run build',+ 'start_command': 'node server.js', 'port': 3000,+ }+ df = BuildpackService.generate_dockerfile(plan)+ assert 'FROM node:20-slim' in df+ assert 'npm run build' in df+ assert 'EXPOSE 3000' in df+ assert 'server.js' in df+++def test_generate_dockerfile_python():+ plan = {+ 'builder': 'nixpacks', 'language': 'python', 'framework': 'flask',+ 'versions': {'python': '3.11'},+ 'build_command': 'pip install --no-cache-dir -r requirements.txt',+ 'start_command': 'gunicorn app:app', 'port': 8000,+ }+ df = BuildpackService.generate_dockerfile(plan)+ assert 'FROM python:3.11-slim' in df+ assert 'pip install' in df+ assert 'EXPOSE 8000' in df+ assert 'gunicorn app:app' in df+++def test_generate_dockerfile_go_multistage():+ plan = {+ 'builder': 'nixpacks', 'language': 'go', 'versions': {'go': '1.22'},+ 'build_command': 'go build -o /app/server ./...', 'port': 8080,+ 'start_command': '/app/server',+ }+ df = BuildpackService.generate_dockerfile(plan)+ assert 'FROM golang:1.22 AS build' in df+ assert 'distroless' in df+ assert 'EXPOSE 8080' in df+++def test_generate_dockerfile_static_nginx():+ plan = {'builder': 'static', 'language': 'static', 'port': 80, 'versions': {}}+ df = BuildpackService.generate_dockerfile(plan)+ assert 'FROM nginx:alpine' in df+ assert '/usr/share/nginx/html' in df+++def test_generate_dockerfile_present_is_noop():+ plan = {'builder': 'dockerfile-present', 'language': 'node'}+ df = BuildpackService.generate_dockerfile(plan)+ assert 'already provides a Dockerfile' in df+++def test_generate_dockerfile_unknown():+ plan = {'builder': 'unknown'}+ df = BuildpackService.generate_dockerfile(plan)+ assert 'Unable to generate' in df+++def test_generate_compose():+ plan = {'builder': 'nixpacks', 'language': 'node', 'port': 3000, 'versions': {}}+ compose = BuildpackService.generate_compose(plan, 'My App!')+ assert 'services:' in compose+ assert 'my-app' in compose+ assert '"3000:3000"' in compose+++# --------------------------------------------------------------------------- #+# apply_overrides()+# --------------------------------------------------------------------------- #+def test_apply_overrides_merges():+ plan = {+ 'builder': 'nixpacks', 'language': 'node', 'versions': {'node': '18'},+ 'build_command': 'npm run build', 'start_command': 'node index.js',+ 'port': 3000, 'notes': [],+ }+ merged = BuildpackService.apply_overrides(plan, {+ 'node_version': '20',+ 'build_command': 'npm run compile',+ 'start_command': 'node dist/main.js',+ 'port': 8080,+ })+ assert merged['versions']['node'] == '20'+ assert merged['build_command'] == 'npm run compile'+ assert merged['start_command'] == 'node dist/main.js'+ assert merged['port'] == 8080+ # Original plan must be untouched (non-mutating).+ assert plan['versions']['node'] == '18'+ assert plan['port'] == 3000+++def test_apply_overrides_none_is_safe():+ plan = {'builder': 'nixpacks', 'language': 'go', 'versions': {'go': '1.22'}}+ merged = BuildpackService.apply_overrides(plan, None)+ assert merged['versions']['go'] == '1.22'+++def test_apply_overrides_bad_port_ignored():+ plan = {'builder': 'nixpacks', 'port': 3000, 'versions': {}}+ merged = BuildpackService.apply_overrides(plan, {'port': 'not-a-number'})+ assert merged['port'] == 3000+++# --------------------------------------------------------------------------- #+# cache key+# --------------------------------------------------------------------------- #+def test_plan_cache_key_stable_and_distinct():+ k1 = BuildpackService.plan_cache_key('https://github.com/a/b.git', 'abc')+ k2 = BuildpackService.plan_cache_key('https://github.com/a/b.git', 'abc')+ k3 = BuildpackService.plan_cache_key('https://github.com/a/b.git', 'def')+ assert k1 == k2+ assert k1 != k3+ assert k1.startswith('buildpack:plan:')diff --git a/backend/tests/test_config_snapshots.py b/backend/tests/test_config_snapshots.pynew file mode 100644index 00000000..0f075819--- /dev/null+++ b/backend/tests/test_config_snapshots.py@@ -0,0 +1,257 @@+"""Tests for the deployment config snapshot + diff engine.++Covers the PURE core (hash stability, order-independence, diff detection, no+secret leakage) and the DB-backed snapshot lifecycle (dedupe, restore result).+"""++import json++import pytest++# Import the snapshot model at module load so its table is registered with+# SQLAlchemy metadata before the conftest `app` fixture runs create_all().+# (The parent agent wires this import into models/__init__.py globally; we+# import it directly here so our own tests are self-contained.)+import app.models.deployment_snapshot # noqa: F401+from app.models.deployment_snapshot import DeploymentSnapshot+from app.services.configuration_service import ConfigurationService+from app.utils.sensitive_data_filter import MASK+++# --------------------------------------------------------------------------- #+# Pure: hashing #+# --------------------------------------------------------------------------- #++def test_hash_config_is_stable():+ cfg = ConfigurationService.build_config(+ env=[{'key': 'A', 'value': '1', 'is_secret': False}],+ domains=['example.com'],+ image_tag='img:1',+ build_method='dockerfile',+ volumes=['data:/data'],+ )+ h1 = ConfigurationService.hash_config(cfg)+ h2 = ConfigurationService.hash_config(cfg)+ assert h1 == h2+ assert len(h1) == 64 # SHA-256 hex+++def test_hash_config_is_order_independent():+ cfg_a = ConfigurationService.build_config(+ env=[+ {'key': 'A', 'value': '1', 'is_secret': False},+ {'key': 'B', 'value': '2', 'is_secret': False},+ ],+ domains=['a.com', 'b.com'],+ )+ cfg_b = ConfigurationService.build_config(+ env=[+ {'key': 'B', 'value': '2', 'is_secret': False},+ {'key': 'A', 'value': '1', 'is_secret': False},+ ],+ domains=['b.com', 'a.com'],+ )+ assert ConfigurationService.hash_config(cfg_a) == ConfigurationService.hash_config(cfg_b)+++def test_hash_changes_when_value_changes():+ base = ConfigurationService.build_config(+ env=[{'key': 'A', 'value': '1', 'is_secret': False}]+ )+ changed = ConfigurationService.build_config(+ env=[{'key': 'A', 'value': '2', 'is_secret': False}]+ )+ assert ConfigurationService.hash_config(base) != ConfigurationService.hash_config(changed)+++# --------------------------------------------------------------------------- #+# Pure: masking #+# --------------------------------------------------------------------------- #++def test_secret_values_are_masked_in_config():+ cfg = ConfigurationService.build_config(+ env=[+ {'key': 'PUBLIC', 'value': 'visible', 'is_secret': False},+ {'key': 'API_TOKEN', 'value': 'super-secret', 'is_secret': True},+ ]+ )+ assert cfg['env']['PUBLIC'] == 'visible'+ assert cfg['env']['API_TOKEN'] == MASK+ # The raw secret must never appear anywhere in the serialized config.+ import json+ assert 'super-secret' not in json.dumps(cfg)+++def test_sensitive_key_name_is_masked_even_without_flag():+ # Key *name* looks sensitive → masked even if is_secret is False.+ cfg = ConfigurationService.build_config(+ env=[{'key': 'DB_PASSWORD', 'value': 'hunter2', 'is_secret': False}]+ )+ assert cfg['env']['DB_PASSWORD'] == MASK+ import json+ assert 'hunter2' not in json.dumps(cfg)+++# --------------------------------------------------------------------------- #+# Pure: diffing #+# --------------------------------------------------------------------------- #++def test_diff_detects_env_add_remove_change():+ old = ConfigurationService.build_config(env=[+ {'key': 'KEEP', 'value': 'same', 'is_secret': False},+ {'key': 'GONE', 'value': 'x', 'is_secret': False},+ {'key': 'CHANGED', 'value': 'old', 'is_secret': False},+ ])+ new = ConfigurationService.build_config(env=[+ {'key': 'KEEP', 'value': 'same', 'is_secret': False},+ {'key': 'NEW', 'value': 'y', 'is_secret': False},+ {'key': 'CHANGED', 'value': 'new', 'is_secret': False},+ ])+ diff = ConfigurationService.diff_configs(old, new)+ assert diff['env']['added'] == ['NEW']+ assert diff['env']['removed'] == ['GONE']+ assert diff['env']['changed'] == ['CHANGED']+ assert ConfigurationService.has_changes(diff)+++def test_diff_detects_image_and_domain_change():+ old = ConfigurationService.build_config(+ image_tag='img:1', domains=['a.com'], build_method='dockerfile'+ )+ new = ConfigurationService.build_config(+ image_tag='img:2', domains=['a.com', 'b.com'], build_method='nixpacks'+ )+ diff = ConfigurationService.diff_configs(old, new)+ assert diff['image']['changed'] is True+ assert diff['image']['old'] == 'img:1'+ assert diff['image']['new'] == 'img:2'+ assert diff['domains']['added'] == ['b.com']+ assert diff['build_method']['changed'] is True+++def test_diff_never_leaks_secret_values():+ old = ConfigurationService.build_config(+ env=[{'key': 'API_TOKEN', 'value': 'old-secret', 'is_secret': True}]+ )+ new = ConfigurationService.build_config(+ env=[{'key': 'API_TOKEN', 'value': 'new-secret', 'is_secret': True}]+ )+ diff = ConfigurationService.diff_configs(old, new)+ import json+ serialized = json.dumps(diff)+ assert 'old-secret' not in serialized+ assert 'new-secret' not in serialized+ # Both masked to the same MASK, so the key is NOT reported as changed+ # (we cannot tell — and must not leak). That's the safe behavior.+ assert 'API_TOKEN' not in diff['env']['changed']+++def test_no_change_diff_is_empty():+ cfg = ConfigurationService.build_config(+ env=[{'key': 'A', 'value': '1', 'is_secret': False}], image_tag='img:1'+ )+ diff = ConfigurationService.diff_configs(cfg, cfg)+ assert ConfigurationService.has_changes(diff) is False+ assert ConfigurationService.summarize_diff(diff) == 'no config changes'+++# --------------------------------------------------------------------------- #+# DB-backed: snapshot lifecycle #+# --------------------------------------------------------------------------- #++def _make_app(db):+ from app.models.application import Application+ from app.models.user import User+ from werkzeug.security import generate_password_hash++ user = User(+ email='[email protected]', username='snaptest',+ password_hash=generate_password_hash('x'), role=User.ROLE_ADMIN,+ is_active=True,+ )+ db.session.add(user)+ db.session.commit()++ app_row = Application(+ name='snap-app', app_type='docker', user_id=user.id,+ docker_image='img:1', root_path='/tmp/nonexistent-snap-app',+ )+ db.session.add(app_row)+ db.session.commit()+ return app_row, user+++def test_create_snapshot_dedupes_identical_config(app):+ # The `app` fixture already runs inside an app_context with create_all().+ from app import db++ app_row, _user = _make_app(db)++ snap1 = ConfigurationService.create_snapshot(app_row)+ snap2 = ConfigurationService.create_snapshot(app_row)++ # Identical config → same row returned, no duplicate.+ assert snap1.id == snap2.id+ assert DeploymentSnapshot.query.filter_by(+ application_id=app_row.id+ ).count() == 1++ # Mutate config → a new snapshot is created.+ app_row.docker_image = 'img:2'+ db.session.commit()+ snap3 = ConfigurationService.create_snapshot(app_row)+ assert snap3.id != snap1.id+ assert DeploymentSnapshot.query.filter_by(+ application_id=app_row.id+ ).count() == 2+ assert snap3.snapshot_hash != snap1.snapshot_hash+++def test_snapshot_config_masks_secret_env(app):+ from app import db+ from app.services.env_service import EnvService++ app_row, user = _make_app(db)++ EnvService.set_env_var(app_row.id, 'PUBLIC', 'visible', is_secret=False, user_id=user.id)+ EnvService.set_env_var(app_row.id, 'SECRET_TOKEN', 'topsecret', is_secret=True, user_id=user.id)++ snap = ConfigurationService.create_snapshot(app_row)+ config = snap.get_config()+ assert config['env']['PUBLIC'] == 'visible'+ assert config['env']['SECRET_TOKEN'] == MASK+ assert 'topsecret' not in json.dumps(config)+++def test_restore_snapshot_returns_sensible_result(app):+ from app import db+ from app.services.env_service import EnvService++ app_row, user = _make_app(db)++ EnvService.set_env_var(app_row.id, 'FEATURE_FLAG', 'on', is_secret=False, user_id=user.id)+ EnvService.set_env_var(app_row.id, 'SECRET_TOKEN', 'topsecret', is_secret=True, user_id=user.id)++ snap = ConfigurationService.create_snapshot(app_row)++ # Change the value, then restore the snapshot.+ EnvService.set_env_var(app_row.id, 'FEATURE_FLAG', 'off', is_secret=False, user_id=user.id)++ result = ConfigurationService.restore_snapshot(snap.id, user_id=user.id)+ assert result['success'] is True+ assert 'FEATURE_FLAG' in result['restored']['env']+ # Masked secret is skipped (not overwritten with the mask placeholder).+ assert 'SECRET_TOKEN' in result['skipped_secrets']++ # The non-secret value was restored to the snapshot's value.+ restored = EnvService.get_env_var(app_row.id, 'FEATURE_FLAG')+ assert restored.value == 'on'+ # The real secret value is untouched.+ secret = EnvService.get_env_var(app_row.id, 'SECRET_TOKEN')+ assert secret.value == 'topsecret'+++def test_restore_missing_snapshot_returns_error(app):+ result = ConfigurationService.restore_snapshot(999999)+ assert result['success'] is False+ assert 'error' in resultdiff --git a/backend/tests/test_template_catalog_validation.py b/backend/tests/test_template_catalog_validation.pynew file mode 100644index 00000000..3087feea--- /dev/null+++ b/backend/tests/test_template_catalog_validation.py@@ -0,0 +1,251 @@+"""Catalog certification: prove EVERY bundled service template conforms to the+documented schema (``docs/TEMPLATE_CATALOG_SCHEMA.md``) and that the committed+``index.json`` stays in lock-step with what is actually on disk.++Unlike ``test_service_templates.py`` (which parametrizes per file and checks a+few roadmap-specific conventions), this module loads the WHOLE catalog and+asserts the universal contract in aggregate, **collecting every failure and+reporting them together** instead of stopping at the first one. The assertions+mirror the real implementation in ``TemplateService`` rather than the prose:++ * parses + passes ``validate_template`` and ``validate_catalog_entry``+ * a unique, slug-shaped ``id`` that matches the filename stem+ * a ``name``+ * at least one of ``compose`` / ``dockerfile`` / ``ports``+ * every ``${VAR}`` referenced in compose / files / scripts is either declared+ in ``variables``, a recognized magic variable (``${SERVICE_*}``), or a+ built-in injected by the installer (``APP_NAME``)+ * the committed ``index.json`` lists exactly the template ids on disk, with a+ well-formed entry per template++These checks are pure: no Docker, no network, no DB. They certify only — they+do not change how any template installs.+"""+import json+import os+import re++import yaml++from app.services.template_service import TemplateService++TEMPLATES_DIR = TemplateService.LOCAL_TEMPLATES_DIR+INDEX_PATH = os.path.join(TEMPLATES_DIR, "index.json")++# Built-in variables the installer always injects into the substitution map+# (see ``_prepare_install_variables`` / ``install_template`` — both seed+# ``{'APP_NAME': app_name}`` before resolving declared/magic variables).+BUILTIN_VARS = {"APP_NAME"}++# Magic-variable prefixes recognized by ``TemplateService`` (single source of+# truth: the service's own table, so this test tracks the code if it grows).+MAGIC_PREFIXES = tuple(prefix for prefix, _ in TemplateService.MAGIC_PREFIXES)++# The exact ``${VAR}`` substitution pattern the installer uses+# (``TemplateService.substitute_variables``).+VAR_PATTERN = re.compile(r"\$\{([A-Z_][A-Z0-9_]*)\}")+++def _template_files():+ return sorted(+ f for f in os.listdir(TEMPLATES_DIR) if f.endswith((".yaml", ".yml"))+ )+++def _load_raw(filename):+ with open(os.path.join(TEMPLATES_DIR, filename), encoding="utf-8") as fh:+ return yaml.safe_load(fh)+++def _declared_var_names(template):+ """Names declared under ``variables`` (list OR dict form, both supported)."""+ names = set()+ raw = template.get("variables", [])+ if isinstance(raw, list):+ for var in raw:+ if isinstance(var, dict) and "name" in var:+ names.add(var["name"])+ elif isinstance(raw, dict):+ names.update(raw.keys())+ return names+++def _is_magic(name):+ return any(name.startswith(prefix) for prefix in MAGIC_PREFIXES)+++def _scan_var_refs(node, out):+ """Collect every ``${VAR}`` token under a (possibly nested) compose/files/+ scripts node, mirroring how the installer walks the structure."""+ if isinstance(node, str):+ out.update(VAR_PATTERN.findall(node))+ elif isinstance(node, dict):+ for value in node.values():+ _scan_var_refs(value, out)+ elif isinstance(node, list):+ for item in node:+ _scan_var_refs(item, out)+++# ---------------------------------------------------------------------------+# Catalog-wide certification (one test, all failures collected)+# ---------------------------------------------------------------------------++def test_every_template_conforms_to_schema():+ """Load every bundled template and assert the universal contract, gathering+ all violations into one report so a single run shows the full picture."""+ failures = []+ seen_ids = {}++ files = _template_files()+ assert files, "no templates found on disk"++ for filename in files:+ stem = filename.rsplit(".", 1)[0]++ # --- parse + the loader's own validator ---------------------------+ result = TemplateService.parse_template(os.path.join(TEMPLATES_DIR, filename))+ if not result.get("success"):+ failures.append(+ f"{filename}: parse/validate_template failed: "+ f"{result.get('errors') or result.get('error')}"+ )+ continue+ template = result["template"]++ # --- catalog-level validator (id slug, var types, magic tokens) ---+ catalog = TemplateService.validate_catalog_entry(template)+ if not catalog.get("valid"):+ failures.append(+ f"{filename}: validate_catalog_entry failed: {catalog.get('errors')}"+ )++ # --- id: present, unique, slug, matches filename stem -------------+ tid = template.get("id")+ if not tid:+ failures.append(f"{filename}: missing 'id'")+ else:+ if tid != stem:+ failures.append(f"{filename}: id '{tid}' != filename stem '{stem}'")+ if tid in seen_ids:+ failures.append(+ f"{filename}: duplicate id '{tid}' (also in {seen_ids[tid]})"+ )+ else:+ seen_ids[tid] = filename++ # --- name ---------------------------------------------------------+ if not template.get("name"):+ failures.append(f"{filename}: missing 'name'")++ # --- at least one of compose / dockerfile / ports -----------------+ if not any(k in template for k in ("compose", "dockerfile", "ports")):+ failures.append(+ f"{filename}: must define at least one of compose/dockerfile/ports"+ )++ # --- every ${VAR} referenced resolves -----------------------------+ refs = set()+ _scan_var_refs(template.get("compose", {}), refs)+ _scan_var_refs(template.get("files", []), refs)+ _scan_var_refs(template.get("scripts", {}), refs)++ declared = _declared_var_names(template)+ for ref in sorted(refs):+ if ref in BUILTIN_VARS or ref in declared or _is_magic(ref):+ continue+ failures.append(+ f"{filename}: references undeclared variable '${{{ref}}}' "+ f"(not declared, not a magic var, not a built-in)"+ )++ assert not failures, "Catalog schema violations:\n" + "\n".join(failures)+++def test_index_json_matches_templates_on_disk():+ """The committed ``index.json`` must list exactly the template ids that exist+ on disk (and vice-versa), each as a well-formed entry. This is the curated,+ hand-shaped repo index (id/name/version/description/categories) — distinct+ from ``build_repo_index()`` — so we assert the committed file directly."""+ assert os.path.exists(INDEX_PATH), "index.json is missing"+ with open(INDEX_PATH, encoding="utf-8") as fh:+ index = json.load(fh)++ disk_ids = {f.rsplit(".", 1)[0] for f in _template_files()}+ index_entries = index.get("templates", [])+ index_ids = {e.get("id") for e in index_entries}++ failures = []++ missing_from_index = sorted(disk_ids - index_ids)+ if missing_from_index:+ failures.append(f"on disk but NOT in index.json: {missing_from_index}")++ stale_in_index = sorted(index_ids - disk_ids)+ if stale_in_index:+ failures.append(f"in index.json but NOT on disk: {stale_in_index}")++ # No duplicate ids inside the index.+ seen = set()+ for entry in index_entries:+ eid = entry.get("id")+ if eid in seen:+ failures.append(f"duplicate id in index.json: '{eid}'")+ seen.add(eid)++ # Each entry is well-formed (the curated lean shape).+ for entry in index_entries:+ for field in ("id", "name", "version", "description"):+ if not entry.get(field):+ failures.append(f"index entry '{entry.get('id')}' missing '{field}'")+ if not isinstance(entry.get("categories", []), list):+ failures.append(+ f"index entry '{entry.get('id')}' has non-list 'categories'"+ )++ assert not failures, "index.json out of sync:\n" + "\n".join(failures)+++def test_index_entry_fields_match_template_source():+ """Each index entry's name/version/description should reflect the actual+ template YAML (so the curated index can't drift from the source files)."""+ with open(INDEX_PATH, encoding="utf-8") as fh:+ index = json.load(fh)+ by_id = {e["id"]: e for e in index["templates"] if e.get("id")}++ failures = []+ for filename in _template_files():+ template = _load_raw(filename)+ tid = template.get("id")+ entry = by_id.get(tid)+ if entry is None:+ continue # absence is already reported by the sync test+ if entry.get("name") != template.get("name"):+ failures.append(+ f"{tid}: index name {entry.get('name')!r} != "+ f"template {template.get('name')!r}"+ )+ if str(entry.get("version")) != str(template.get("version")):+ failures.append(+ f"{tid}: index version {entry.get('version')!r} != "+ f"template {template.get('version')!r}"+ )++ assert not failures, "index.json fields drifted from templates:\n" + "\n".join(+ failures+ )+++def test_build_repo_index_covers_disk():+ """``build_repo_index()`` (the publishable generated index consumed by the+ repo-sync flow) must enumerate every template currently on disk."""+ generated = TemplateService.build_repo_index()+ disk_ids = {f.rsplit(".", 1)[0] for f in _template_files()}+ generated_ids = {t["id"] for t in generated["templates"]}++ assert generated["count"] == len(_template_files())+ assert generated_ids == disk_ids, (+ "build_repo_index() drift -- "+ f"missing: {sorted(disk_ids - generated_ids)}, "+ f"extra: {sorted(generated_ids - disk_ids)}"+ )diff --git a/frontend/src/components/buildpack/BuildpackPreview.jsx b/frontend/src/components/buildpack/BuildpackPreview.jsxnew file mode 100644index 00000000..cb064705--- /dev/null+++ b/frontend/src/components/buildpack/BuildpackPreview.jsx@@ -0,0 +1,213 @@+import { useMemo, useState } from 'react';+import { Boxes, ChevronDown, FileCode2, Layers, Terminal, Zap } from 'lucide-react';+import { Input } from '@/components/ui/input';+import { Label } from '@/components/ui/label';++// Map a plan's language to the primary version-override field.+const VERSION_FIELD = {+ node: { key: 'node_version', label: 'Node version', versionKey: 'node' },+ python: { key: 'python_version', label: 'Python version', versionKey: 'python' },+ go: { key: 'go_version', label: 'Go version', versionKey: 'go' },+ php: { key: 'php_version', label: 'PHP version', versionKey: 'php' },+ ruby: { key: 'ruby_version', label: 'Ruby version', versionKey: 'ruby' },+ rust: { key: 'rust_version', label: 'Rust version', versionKey: 'rust' },+};++const BUILDER_LABEL = {+ nixpacks: 'Build pack',+ static: 'Static site',+ 'dockerfile-present': 'Existing Dockerfile',+ unknown: 'Not detected',+};++function confidenceLabel(confidence) {+ if (confidence >= 0.85) return 'High';+ if (confidence >= 0.6) return 'Medium';+ if (confidence > 0) return 'Low';+ return 'None';+}++/**+ * BuildpackPreview — renders a detected build plan, lets the user override the+ * runtime version / build command / start command / port, and shows the+ * generated Dockerfile (collapsible). Override changes are emitted via onChange.+ *+ * Props:+ * plan — the detected plan dict from /buildpacks/detect+ * dockerfile — generated Dockerfile string (preview)+ * overrides — current overrides object (controlled)+ * onChange — (overrides) => void+ * loading — bool, shows a loading shell+ */+function BuildpackPreview({ plan, dockerfile, overrides = {}, onChange, loading = false }) {+ const [dockerfileOpen, setDockerfileOpen] = useState(false);++ const versionField = useMemo(() => {+ if (!plan?.language) return null;+ return VERSION_FIELD[plan.language] || null;+ }, [plan]);++ if (loading) {+ return (+ <div className="buildpack-preview buildpack-preview--loading">+ <div className="buildpack-preview__head">+ <Zap size={16} className="spinning" />+ <span>Detecting build pack…</span>+ </div>+ </div>+ );+ }++ if (!plan) return null;++ const builder = plan.builder || 'unknown';+ const unknown = builder === 'unknown';+ const present = builder === 'dockerfile-present';++ const emit = (key, value) => {+ if (!onChange) return;+ const next = { ...overrides };+ if (value === '' || value === null || value === undefined) {+ delete next[key];+ } else {+ next[key] = value;+ }+ onChange(next);+ };++ const versionValue = versionField+ ? (overrides[versionField.key] ?? plan.versions?.[versionField.versionKey] ?? '')+ : '';+ const buildValue = overrides.build_command ?? plan.build_command ?? '';+ const startValue = overrides.start_command ?? plan.start_command ?? '';+ const portValue = overrides.port ?? plan.port ?? '';++ return (+ <div className={`buildpack-preview ${unknown ? 'buildpack-preview--unknown' : ''}`}>+ <div className="buildpack-preview__head">+ <span className="buildpack-preview__head-icon">+ <Boxes size={16} />+ </span>+ <div className="buildpack-preview__head-text">+ <strong>{BUILDER_LABEL[builder] || builder}</strong>+ <span>+ {present+ ? 'This repository ships its own Dockerfile — ServerKit will build it directly.'+ : unknown+ ? 'Could not confidently detect the stack. Pick a build method manually or add a Dockerfile.'+ : 'ServerKit will generate a Dockerfile from the detected stack.'}+ </span>+ </div>+ <span className="buildpack-preview__confidence" data-level={confidenceLabel(plan.confidence).toLowerCase()}>+ {confidenceLabel(plan.confidence)}+ </span>+ </div>++ <div className="buildpack-preview__facts">+ <div className="buildpack-preview__fact">+ <span><Layers size={13} /> Language</span>+ <strong>{plan.language || '—'}</strong>+ </div>+ <div className="buildpack-preview__fact">+ <span><Zap size={13} /> Framework</span>+ <strong>{plan.framework || 'Generic'}</strong>+ </div>+ <div className="buildpack-preview__fact">+ <span><Boxes size={13} /> Port</span>+ <strong>{plan.port || 'Auto'}</strong>+ </div>+ </div>++ {plan.notes?.length > 0 && (+ <ul className="buildpack-preview__notes">+ {plan.notes.map((note, i) => (+ <li key={i}>{note}</li>+ ))}+ </ul>+ )}++ {!present && !unknown && (+ <div className="buildpack-preview__overrides">+ {versionField && (+ <div className="buildpack-preview__field">+ <Label htmlFor="bp-version">{versionField.label}</Label>+ <Input+ id="bp-version"+ value={versionValue}+ onChange={(e) => emit(versionField.key, e.target.value)}+ placeholder={plan.versions?.[versionField.versionKey] || 'default'}+ autoComplete="off"+ />+ </div>+ )}+ <div className="buildpack-preview__field">+ <Label htmlFor="bp-port">Port</Label>+ <Input+ id="bp-port"+ type="number"+ value={portValue}+ onChange={(e) => emit('port', e.target.value)}+ placeholder={String(plan.port || '')}+ min="1"+ max="65535"+ />+ </div>+ <div className="buildpack-preview__field buildpack-preview__field--wide">+ <Label htmlFor="bp-build">Build command</Label>+ <Input+ id="bp-build"+ value={buildValue}+ onChange={(e) => emit('build_command', e.target.value)}+ placeholder={plan.build_command || 'No build step'}+ autoComplete="off"+ />+ </div>+ <div className="buildpack-preview__field buildpack-preview__field--wide">+ <Label htmlFor="bp-start">Start command</Label>+ <Input+ id="bp-start"+ value={startValue}+ onChange={(e) => emit('start_command', e.target.value)}+ placeholder={plan.start_command || ''}+ autoComplete="off"+ />+ </div>+ </div>+ )}++ {dockerfile && !present && (+ <div className="buildpack-preview__dockerfile">+ <button+ type="button"+ className="buildpack-preview__dockerfile-toggle"+ onClick={() => setDockerfileOpen((open) => !open)}+ aria-expanded={dockerfileOpen}+ >+ <span>+ <FileCode2 size={15} />+ Generated Dockerfile+ </span>+ <ChevronDown+ size={16}+ className={dockerfileOpen ? 'buildpack-preview__chevron--open' : ''}+ />+ </button>+ {dockerfileOpen && (+ <pre className="buildpack-preview__code">+ <code>{dockerfile}</code>+ </pre>+ )}+ </div>+ )}++ {present && dockerfile && (+ <div className="buildpack-preview__present-note">+ <Terminal size={14} />+ <span>Using the repository's own Dockerfile.</span>+ </div>+ )}+ </div>+ );+}++export default BuildpackPreview;diff --git a/frontend/src/components/deployments/ConfigDiffModal.jsx b/frontend/src/components/deployments/ConfigDiffModal.jsxnew file mode 100644index 00000000..a0c82bba--- /dev/null+++ b/frontend/src/components/deployments/ConfigDiffModal.jsx@@ -0,0 +1,208 @@+import { useState, useEffect } from 'react';+import { RotateCcw, X } from 'lucide-react';+import api from '../../services/api';+import { Button } from '@/components/ui/button';+import { useToast } from '../../contexts/ToastContext';++// Modal showing a structured config diff between a snapshot and another+// (default: the previous snapshot). Env vars are compared by KEY only — values+// are never shown, so secrets can't leak. Sections: env (added/removed/changed+// keys), domains, image/tag, build method, volumes. A Restore button re-applies+// the snapshot's config and triggers a redeploy.++function DiffList({ title, added = [], removed = [], changed = [] }) {+ const hasAny = added.length || removed.length || changed.length;+ if (!hasAny) {+ return (+ <div className="config-diff__section">+ <h4 className="config-diff__section-title">{title}</h4>+ <p className="config-diff__none">No changes</p>+ </div>+ );+ }+ return (+ <div className="config-diff__section">+ <h4 className="config-diff__section-title">{title}</h4>+ <ul className="config-diff__lines">+ {added.map((k) => (+ <li key={`a-${k}`} className="config-diff__line config-diff__line--add">+ <span className="config-diff__sign">+</span> {k}+ </li>+ ))}+ {removed.map((k) => (+ <li key={`r-${k}`} className="config-diff__line config-diff__line--remove">+ <span className="config-diff__sign">−</span> {k}+ </li>+ ))}+ {changed.map((k) => (+ <li key={`c-${k}`} className="config-diff__line config-diff__line--change">+ <span className="config-diff__sign">~</span> {k}+ </li>+ ))}+ </ul>+ </div>+ );+}++function ScalarDiff({ title, oldVal, newVal, changed }) {+ return (+ <div className="config-diff__section">+ <h4 className="config-diff__section-title">{title}</h4>+ {changed ? (+ <div className="config-diff__scalar">+ <span className="config-diff__old">{oldVal || '—'}</span>+ <span className="config-diff__arrow">→</span>+ <span className="config-diff__new">{newVal || '—'}</span>+ </div>+ ) : (+ <p className="config-diff__none">No change ({newVal || '—'})</p>+ )}+ </div>+ );+}++const ConfigDiffModal = ({ appId, snapId, against = 'previous', onClose, onRestored }) => {+ const toast = useToast();+ const [diff, setDiff] = useState(null);+ const [meta, setMeta] = useState(null);+ const [loading, setLoading] = useState(true);+ const [error, setError] = useState(null);+ const [restoring, setRestoring] = useState(false);+ const [confirmRestore, setConfirmRestore] = useState(false);++ useEffect(() => {+ let cancelled = false;+ (async () => {+ try {+ setLoading(true);+ const res = await api.getSnapshotDiff(appId, snapId, against);+ if (cancelled) return;+ setDiff(res.diff);+ setMeta({+ summary: res.summary,+ hasChanges: res.has_changes,+ againstId: res.against_id,+ });+ setError(null);+ } catch (err) {+ if (!cancelled) setError(err.message);+ } finally {+ if (!cancelled) setLoading(false);+ }+ })();+ return () => {+ cancelled = true;+ };+ }, [appId, snapId, against]);++ async function handleRestore() {+ setRestoring(true);+ try {+ const res = await api.restoreSnapshot(appId, snapId);+ if (res.success) {+ toast.success('Configuration restored. Redeploy triggered.');+ if (onRestored) onRestored(res);+ } else {+ toast.error(res.error || 'Restore failed');+ }+ } catch (err) {+ toast.error(err.message);+ } finally {+ setRestoring(false);+ setConfirmRestore(false);+ }+ }++ return (+ <div className="modal-overlay" onClick={onClose}>+ <div+ className="modal config-diff"+ onClick={(e) => e.stopPropagation()}+ >+ <div className="modal-header">+ <h2>Configuration diff</h2>+ <button className="modal-close" onClick={onClose} aria-label="Close">+ <X size={18} />+ </button>+ </div>++ <div className="config-diff__body">+ {loading && <p className="config-diff__loading">Loading diff…</p>}+ {error && <div className="alert alert-danger">{error}</div>}++ {!loading && !error && diff && (+ <>+ {meta && (+ <p className="config-diff__summary">+ {meta.hasChanges+ ? meta.summary+ : 'No configuration changes vs the compared snapshot.'}+ </p>+ )}++ <DiffList+ title="Environment variables"+ added={diff.env?.added}+ removed={diff.env?.removed}+ changed={diff.env?.changed}+ />+ <DiffList+ title="Domains"+ added={diff.domains?.added}+ removed={diff.domains?.removed}+ />+ <DiffList+ title="Volumes"+ added={diff.volumes?.added}+ removed={diff.volumes?.removed}+ />+ <ScalarDiff+ title="Image / tag"+ oldVal={diff.image?.old}+ newVal={diff.image?.new}+ changed={diff.image?.changed}+ />+ <ScalarDiff+ title="Build method"+ oldVal={diff.build_method?.old}+ newVal={diff.build_method?.new}+ changed={diff.build_method?.changed}+ />+ </>+ )}+ </div>++ <div className="modal-actions">+ {confirmRestore ? (+ <>+ <span className="config-diff__confirm-text">+ Restore this configuration and redeploy?+ </span>+ <Button+ variant="outline"+ onClick={() => setConfirmRestore(false)}+ disabled={restoring}+ >+ Cancel+ </Button>+ <Button onClick={handleRestore} disabled={restoring}>+ {restoring ? 'Restoring…' : 'Confirm restore'}+ </Button>+ </>+ ) : (+ <>+ <Button variant="outline" onClick={onClose}>+ Close+ </Button>+ <Button onClick={() => setConfirmRestore(true)} disabled={loading || !!error}>+ <RotateCcw size={14} /> Restore this config+ </Button>+ </>+ )}+ </div>+ </div>+ </div>+ );+};++export default ConfigDiffModal;diff --git a/frontend/src/components/deployments/DeploymentTimeline.jsx b/frontend/src/components/deployments/DeploymentTimeline.jsxnew file mode 100644index 00000000..cba2f99f--- /dev/null+++ b/frontend/src/components/deployments/DeploymentTimeline.jsx@@ -0,0 +1,151 @@+import { useState, useEffect, useCallback } from 'react';+import { GitBranch, Box, Clock, FileDiff } from 'lucide-react';+import api from '../../services/api';+import { Pill } from '@/components/ds';+import { Button } from '@/components/ui/button';+import ConfigDiffModal from './ConfigDiffModal';++// Vertical timeline of an app's config snapshots. Each node shows the image /+// build method, a "config changed" badge (derived from the per-snapshot+// summary), and the capture time. Clicking a node opens the config diff vs the+// previous snapshot. Snapshots never carry secret values (masked at capture).++function formatTime(iso) {+ if (!iso) return '';+ try {+ return new Date(iso).toLocaleString();+ } catch {+ return iso;+ }+}++// A snapshot's `summary` reads like "no config changes" when nothing changed,+// or e.g. "3 env vars changed; image updated" otherwise.+function snapshotChanged(summary) {+ if (!summary) return false;+ const s = summary.toLowerCase();+ return !(s === 'no config changes' || s === 'initial config snapshot');+}++const DeploymentTimeline = ({ appId }) => {+ const [snapshots, setSnapshots] = useState([]);+ const [loading, setLoading] = useState(true);+ const [error, setError] = useState(null);+ const [activeDiff, setActiveDiff] = useState(null); // { snapId }++ const loadSnapshots = useCallback(async () => {+ try {+ setLoading(true);+ const res = await api.getAppSnapshots(appId);+ setSnapshots(res.snapshots || []);+ setError(null);+ } catch (err) {+ setError(err.message);+ } finally {+ setLoading(false);+ }+ }, [appId]);++ useEffect(() => {+ loadSnapshots();+ }, [loadSnapshots]);++ if (loading) {+ return <div className="deploy-timeline__loading">Loading deployment timeline…</div>;+ }++ if (error) {+ return <div className="alert alert-danger">{error}</div>;+ }++ if (snapshots.length === 0) {+ return (+ <div className="deploy-timeline deploy-timeline--empty">+ <Clock size={20} />+ <p>No configuration snapshots yet. One is captured before each deployment.</p>+ </div>+ );+ }++ return (+ <div className="deploy-timeline">+ <ol className="deploy-timeline__list">+ {snapshots.map((snap, idx) => {+ const cfg = snap.config || {};+ const changed = snapshotChanged(snap.summary);+ const isLatest = idx === 0;+ return (+ <li key={snap.id} className="deploy-timeline__item">+ <span+ className={+ 'deploy-timeline__marker' ++ (isLatest ? ' deploy-timeline__marker--current' : '')+ }+ aria-hidden="true"+ />+ <div className="deploy-timeline__card">+ <div className="deploy-timeline__row">+ <div className="deploy-timeline__meta">+ {isLatest && <Pill kind="green">Current</Pill>}+ {changed && (+ <Pill kind="amber" dot={false}>+ Config changed+ </Pill>+ )}+ <span className="deploy-timeline__time">+ <Clock size={13} /> {formatTime(snap.created_at)}+ </span>+ </div>+ <Button+ variant="outline"+ size="sm"+ onClick={() => setActiveDiff({ snapId: snap.id })}+ >+ <FileDiff size={14} /> View diff+ </Button>+ </div>++ <div className="deploy-timeline__details">+ {cfg.image_tag && (+ <span className="deploy-timeline__chip">+ <Box size={13} /> {cfg.image_tag}+ </span>+ )}+ {cfg.build_method && (+ <span className="deploy-timeline__chip">+ <GitBranch size={13} /> {cfg.build_method}+ </span>+ )}+ {cfg.env_keys && (+ <span className="deploy-timeline__chip">+ {cfg.env_keys.length} env var+ {cfg.env_keys.length === 1 ? '' : 's'}+ </span>+ )}+ </div>++ {snap.summary && (+ <p className="deploy-timeline__summary">{snap.summary}</p>+ )}+ </div>+ </li>+ );+ })}+ </ol>++ {activeDiff && (+ <ConfigDiffModal+ appId={appId}+ snapId={activeDiff.snapId}+ onClose={() => setActiveDiff(null)}+ onRestored={() => {+ setActiveDiff(null);+ loadSnapshots();+ }}+ />+ )}+ </div>+ );+};++export default DeploymentTimeline;diff --git a/frontend/src/pages/ApplicationDetail.jsx b/frontend/src/pages/ApplicationDetail.jsxindex e835fd32..8c691f43 100644--- a/frontend/src/pages/ApplicationDetail.jsx+++ b/frontend/src/pages/ApplicationDetail.jsx@@ -15,6 +15,8 @@ import LinkedAppsSection from '../components/LinkedAppsSection';import LinkAppModal from '../components/LinkAppModal';import ContainerOpsPanel from '../components/apps/ContainerOpsPanel';import WafPanel from '../components/apps/WafPanel';+import DeploymentTimeline from '../components/deployments/DeploymentTimeline';+import BuildpackPreview from '../components/buildpack/BuildpackPreview';import { getServiceType, getStatusConfig } from '../utils/serviceTypes';import { Button } from '@/components/ui/button';import { Input } from '@/components/ui/input';@@ -258,7 +260,7 @@ const ApplicationDetail = () => {</TabsContent>)}<TabsContent value="build">- <BuildTab appId={app.id} appPath={app.path} />+ <BuildTab appId={app.id} appPath={app.path} app={app} /></TabsContent><TabsContent value="deploy"><DeployTab appId={app.id} appPath={app.path} />@@ -868,7 +870,7 @@ const CommandsTab = ({ appId, appType }) => {);};-const BuildTab = ({ appId, appPath }) => {+const BuildTab = ({ appId, appPath, app }) => {const toast = useToast();const { confirm: confirmBuild, confirmState: confirmBuildState, handleConfirm: handleBuildConfirm, handleCancel: handleBuildCancel } = useConfirm();const [buildConfig, setBuildConfig] = useState(null);@@ -883,6 +885,19 @@ const BuildTab = ({ appId, appPath }) => {const [selectedLog, setSelectedLog] = useState(null);const [buildLogs, setBuildLogs] = useState([]);const [error, setError] = useState(null);+ const [bpDockerfile, setBpDockerfile] = useState(null);++ // When the app was created from a detected build pack, fetch a read-only+ // preview of the generated Dockerfile for transparency.+ useEffect(() => {+ let active = true;+ if (app?.buildpack_plan) {+ api.generateBuildpack(app.buildpack_plan, app.buildpack_overrides || {}, app.name)+ .then((res) => { if (active) setBpDockerfile(res?.dockerfile || null); })+ .catch(() => {});+ }+ return () => { active = false; };+ }, [app?.buildpack_plan, app?.buildpack_overrides, app?.name]);const [configForm, setConfigForm] = useState({buildMethod: 'auto',@@ -1067,6 +1082,17 @@ const BuildTab = ({ appId, appPath }) => {</div>)}+ {app?.buildpack_plan && (+ <div className="card">+ <h3>Build Pack</h3>+ <BuildpackPreview+ plan={app.buildpack_plan}+ dockerfile={bpDockerfile}+ overrides={app.buildpack_overrides || {}}+ />+ </div>+ )}+<div className="card"><div className="card-header-row"><h3>Build Configuration</h3>@@ -1647,6 +1673,18 @@ const DeployTab = ({ appId, appPath }) => {</>)}+ {/* Config snapshot timeline + diff — additive, independent of git+ config so it shows the deploy history & config changes for any app. */}+ <div className="card deploy-timeline-card">+ <h3>Deployment Timeline</h3>+ <p className="deploy-timeline-card__hint">+ An immutable configuration snapshot (env keys, domains, image, build+ method, volumes) is captured before each deployment. Secret values are+ masked. Open a snapshot to diff it against the previous one or restore it.+ </p>+ <DeploymentTimeline appId={appId} />+ </div>+{showConfigModal && (<div className="modal-overlay" onClick={() => setShowConfigModal(false)}><div className="modal" onClick={e => e.stopPropagation()}>diff --git a/frontend/src/pages/NewService.jsx b/frontend/src/pages/NewService.jsxindex fdc6de59..e5236abe 100644--- a/frontend/src/pages/NewService.jsx+++ b/frontend/src/pages/NewService.jsx@@ -26,6 +26,7 @@ import { Button } from '@/components/ui/button';import { Input } from '@/components/ui/input';import { Label } from '@/components/ui/label';import { Switch } from '@/components/ui/switch';+import BuildpackPreview from '@/components/buildpack/BuildpackPreview';const APP_TYPE_OPTIONS = [{ value: 'auto', label: 'Auto-detect' },@@ -138,6 +139,12 @@ const NewService = () => {const [advancedOpen, setAdvancedOpen] = useState(false);const [submitting, setSubmitting] = useState(false);+ // Build-pack detection (zero-Dockerfile). Runs when a repo is selected and+ // the build method routes through the build pack (auto / nixpacks).+ const [buildpack, setBuildpack] = useState(null);+ const [buildpackLoading, setBuildpackLoading] = useState(false);+ const [buildpackOverrides, setBuildpackOverrides] = useState({});+// Manual / local service fieldsconst [localPath, setLocalPath] = useState('');const [composeFile, setComposeFile] = useState('');@@ -265,6 +272,52 @@ const NewService = () => {}}, [selectedRepo, nameTouched]);+ // Build-pack detection. Only repo-based sources (github/manual/template) and+ // only when the build method routes through the build pack. Resets overrides+ // whenever the underlying repository changes.+ const buildpackEligible = (buildMethod === 'auto' || buildMethod === 'nixpacks')+ && (sourceMode === 'github' || sourceMode === 'manual' || sourceMode === 'template');++ useEffect(() => {+ if (!buildpackEligible) {+ setBuildpack(null);+ setBuildpackLoading(false);+ return undefined;+ }++ const body = { branch: branch || 'main', name: detectedServiceName || 'app' };+ if (sourceMode === 'github' && selectedRepo && githubConnection) {+ body.source_connection_id = githubConnection.id;+ body.repository_full_name = selectedRepo.full_name;+ body.repo_url = `https://github.com/${selectedRepo.full_name}.git`;+ } else if (sourceMode === 'template' && selectedTemplate) {+ body.repo_url = selectedTemplate.repoUrl;+ } else if (sourceMode === 'manual' && normalizedManualRepo) {+ body.repo_url = normalizedManualRepo;+ } else {+ setBuildpack(null);+ return undefined;+ }++ let cancelled = false;+ setBuildpackLoading(true);+ setBuildpackOverrides({});+ api.detectBuildpack(body)+ .then((data) => {+ if (!cancelled) setBuildpack(data);+ })+ .catch(() => {+ // Detection is best-effort; the user can still pick a method.+ if (!cancelled) setBuildpack(null);+ })+ .finally(() => {+ if (!cancelled) setBuildpackLoading(false);+ });++ return () => { cancelled = true; };+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [buildpackEligible, sourceMode, selectedRepo, selectedTemplate, normalizedManualRepo, branch, githubConnection]);+async function handleConnectGithub() {try {const redirectUri = `${window.location.origin}/connections/callback/github`;@@ -361,6 +414,12 @@ const NewService = () => {if (recommended.dockerfile_path) payload.dockerfile_path = recommended.dockerfile_path;if (recommended.custom_build_cmd) payload.custom_build_cmd = recommended.custom_build_cmd;if (recommended.custom_start_cmd) payload.custom_start_cmd = recommended.custom_start_cmd;+ if (buildpackEligible && buildpack?.plan) {+ payload.buildpack_plan = buildpack.plan;+ if (Object.keys(buildpackOverrides).length > 0) {+ payload.buildpack_overrides = buildpackOverrides;+ }+ }if (sourceMode === 'github') {payload.source_connection_id = githubConnection.id;@@ -836,6 +895,16 @@ const NewService = () => {</div>)}+ {buildpackEligible && (buildpackLoading || buildpack?.plan) && (+ <BuildpackPreview+ plan={buildpack?.plan}+ dockerfile={buildpack?.dockerfile}+ overrides={buildpackOverrides}+ onChange={setBuildpackOverrides}+ loading={buildpackLoading}+ />+ )}+<div className="new-service-page__summary"><div><span>Source</span>diff --git a/frontend/src/services/api/buildpacks.js b/frontend/src/services/api/buildpacks.jsnew file mode 100644index 00000000..48fcf862--- /dev/null+++ b/frontend/src/services/api/buildpacks.js@@ -0,0 +1,21 @@+// Build Packs API — transparent, zero-Dockerfile build planning.+// Backend blueprint mounted at /api/v1/buildpacks.++// Detect the stack for a repository and return a build plan + generated+// Dockerfile/compose preview. Body: { repo_url?, branch?, source_connection_id?,+// repository_full_name?, path?, name? }.+export async function detectBuildpack(body) {+ return this.request('/buildpacks/detect', {+ method: 'POST',+ body,+ });+}++// Generate a Dockerfile + compose from a plan (pure, no clone).+// Body: { plan, overrides?, name? }.+export async function generateBuildpack(plan, overrides, name) {+ return this.request('/buildpacks/generate', {+ method: 'POST',+ body: { plan, overrides, name },+ });+}diff --git a/frontend/src/services/api/index.js b/frontend/src/services/api/index.jsindex a26b12c2..5b7529f7 100644--- a/frontend/src/services/api/index.js+++ b/frontend/src/services/api/index.js@@ -25,6 +25,8 @@ import * as telemetryMethods from './telemetry.js';import * as jobMethods from './jobs.js';import * as backupProtectionMethods from './backupProtection.js';import * as containerStatusMethods from './containerStatus.js';+import * as buildpackMethods from './buildpacks.js';+import * as snapshotMethods from './snapshots.js';class ApiService extends ApiClient {constructor() {@@ -57,6 +59,8 @@ class ApiService extends ApiClient {jobMethods,backupProtectionMethods,containerStatusMethods,+ buildpackMethods,+ snapshotMethods,];for (const mod of modules) {for (const [key, fn] of Object.entries(mod)) {diff --git a/frontend/src/services/api/snapshots.js b/frontend/src/services/api/snapshots.jsnew file mode 100644index 00000000..33e67fec--- /dev/null+++ b/frontend/src/services/api/snapshots.js@@ -0,0 +1,21 @@+// Deployment config snapshots + diff/restore.+// Mounted by the backend at /api/v1/apps.++export async function getAppSnapshots(appId, limit = 50) {+ return this.request(`/apps/${appId}/snapshots?limit=${limit}`);+}++export async function getAppSnapshot(appId, snapId) {+ return this.request(`/apps/${appId}/snapshots/${snapId}`);+}++export async function getSnapshotDiff(appId, snapId, against = 'previous') {+ const query = against ? `?against=${encodeURIComponent(against)}` : '';+ return this.request(`/apps/${appId}/snapshots/${snapId}/diff${query}`);+}++export async function restoreSnapshot(appId, snapId) {+ return this.request(`/apps/${appId}/snapshots/${snapId}/restore`, {+ method: 'POST',+ });+}diff --git a/frontend/src/styles/components/_buildpack.scss b/frontend/src/styles/components/_buildpack.scssnew file mode 100644index 00000000..32ed4d54--- /dev/null+++ b/frontend/src/styles/components/_buildpack.scss@@ -0,0 +1,226 @@+// ============================================+// BUILD PACK PREVIEW+// Transparent zero-Dockerfile build planning. Rendered in the New Service+// wizard (detection step) and the service Build tab.+// ============================================++.buildpack-preview {+ display: flex;+ flex-direction: column;+ gap: $space-4;+ padding: $space-4;+ background: $bg-card;+ border: 1px solid $border-subtle;+ border-radius: $radius-lg;++ &--unknown {+ border-color: fade($warning, 40%);+ }++ &--loading {+ opacity: 0.8;+ }++ // ---- Header -------------------------------------------------------+ &__head {+ display: flex;+ align-items: flex-start;+ gap: $space-3;+ }++ &__head-icon {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ width: 32px;+ height: 32px;+ flex-shrink: 0;+ border-radius: $radius-md;+ background: fade($accent-primary-raw, 12%);+ color: $accent-primary;+ }++ &__head-text {+ display: flex;+ flex-direction: column;+ gap: $space-1;+ flex: 1;+ min-width: 0;++ strong {+ font-size: $font-size-base;+ font-weight: $font-weight-semibold;+ color: $text-primary;+ }++ span {+ font-size: $font-size-sm;+ color: $text-secondary;+ line-height: 1.5;+ }+ }++ &__confidence {+ flex-shrink: 0;+ padding: $space-1 $space-2;+ font-size: $font-size-xs;+ font-weight: $font-weight-medium;+ text-transform: uppercase;+ letter-spacing: 0.04em;+ border-radius: $radius-sm;+ background: $bg-hover;+ color: $text-tertiary;++ &[data-level='high'] {+ background: fade($success, 15%);+ color: $success;+ }++ &[data-level='medium'] {+ background: fade($warning, 15%);+ color: $warning;+ }++ &[data-level='low'] {+ background: fade($danger, 12%);+ color: $danger;+ }+ }++ // ---- Facts grid ---------------------------------------------------+ &__facts {+ display: grid;+ grid-template-columns: repeat(3, 1fr);+ gap: $space-3;+ }++ &__fact {+ display: flex;+ flex-direction: column;+ gap: $space-1;+ padding: $space-3;+ background: $bg-body;+ border-radius: $radius-md;++ span {+ display: inline-flex;+ align-items: center;+ gap: $space-1;+ font-size: $font-size-xs;+ text-transform: uppercase;+ letter-spacing: 0.04em;+ color: $text-tertiary;+ }++ strong {+ font-size: $font-size-sm;+ font-weight: $font-weight-medium;+ color: $text-primary;+ text-transform: capitalize;+ }+ }++ // ---- Notes --------------------------------------------------------+ &__notes {+ margin: 0;+ padding-left: $space-4;+ display: flex;+ flex-direction: column;+ gap: $space-1;++ li {+ font-size: $font-size-sm;+ color: $text-secondary;+ line-height: 1.5;+ }+ }++ // ---- Overrides ----------------------------------------------------+ &__overrides {+ display: grid;+ grid-template-columns: repeat(2, 1fr);+ gap: $space-3;+ }++ &__field {+ display: flex;+ flex-direction: column;+ gap: $space-2;++ &--wide {+ grid-column: 1 / -1;+ }+ }++ // ---- Dockerfile preview ------------------------------------------+ &__dockerfile {+ display: flex;+ flex-direction: column;+ border: 1px solid $border-subtle;+ border-radius: $radius-md;+ overflow: hidden;+ }++ &__dockerfile-toggle {+ display: flex;+ align-items: center;+ justify-content: space-between;+ padding: $space-3;+ background: $bg-hover;+ border: none;+ cursor: pointer;+ color: $text-primary;+ font-size: $font-size-sm;+ font-weight: $font-weight-medium;+ transition: background $transition-fast;++ &:hover {+ background: $bg-card;+ }++ span {+ display: inline-flex;+ align-items: center;+ gap: $space-2;+ }+ }++ &__chevron--open {+ transform: rotate(180deg);+ }++ &__code {+ margin: 0;+ padding: $space-4;+ background: $bg-body;+ font-family: $font-mono;+ font-size: $font-size-sm;+ line-height: 1.6;+ color: $text-primary;+ max-height: 360px;+ overflow: auto;+ white-space: pre;++ code {+ font-family: inherit;+ }+ }++ &__present-note {+ display: inline-flex;+ align-items: center;+ gap: $space-2;+ font-size: $font-size-sm;+ color: $text-secondary;+ }+}++@media (max-width: 640px) {+ .buildpack-preview__facts {+ grid-template-columns: 1fr;+ }++ .buildpack-preview__overrides {+ grid-template-columns: 1fr;+ }+}diff --git a/frontend/src/styles/components/_deployments.scss b/frontend/src/styles/components/_deployments.scssnew file mode 100644index 00000000..78f4b173--- /dev/null+++ b/frontend/src/styles/components/_deployments.scss@@ -0,0 +1,265 @@+// ============================================+// DEPLOYMENT TIMELINE + CONFIG DIFF+// ============================================+// Vertical snapshot timeline and the config diff modal in an app's Deploy tab.+// Themed via design-system tokens (no inline styles).++// ---------------------------------------------------------------- Timeline+.deploy-timeline {+ display: flex;+ flex-direction: column;+ gap: $space-4;++ &--empty {+ align-items: center;+ gap: $space-2;+ padding: $space-8;+ color: $text-secondary;+ text-align: center;+ background: $bg-card;+ border: 1px dashed $border-subtle;+ border-radius: $radius-lg;++ svg {+ color: $text-tertiary;+ }+ }++ &__loading {+ color: $text-secondary;+ padding: $space-4 0;+ }++ &__list {+ list-style: none;+ margin: 0;+ padding: 0;+ position: relative;+ }++ // The vertical spine that connects markers.+ &__item {+ position: relative;+ padding-left: $space-8;+ padding-bottom: $space-4;++ &::before {+ content: '';+ position: absolute;+ left: 7px;+ top: 0;+ bottom: 0;+ width: 2px;+ background: $border-subtle;+ }++ &:last-child::before {+ bottom: auto;+ height: 16px;+ }+ }++ &__marker {+ position: absolute;+ left: 0;+ top: 4px;+ width: 16px;+ height: 16px;+ border-radius: $radius-full;+ background: $bg-elevated;+ border: 2px solid $border-subtle;+ z-index: 1;++ &--current {+ background: $success;+ border-color: $success;+ box-shadow: 0 0 0 4px $success-bg;+ }+ }++ &__card {+ background: $bg-card;+ border: 1px solid $border-subtle;+ border-radius: $radius-lg;+ padding: $space-4;+ display: flex;+ flex-direction: column;+ gap: $space-3;+ }++ &__row {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: $space-3;+ flex-wrap: wrap;+ }++ &__meta {+ display: flex;+ align-items: center;+ gap: $space-2;+ flex-wrap: wrap;+ }++ &__time {+ display: inline-flex;+ align-items: center;+ gap: $space-1;+ color: $text-tertiary;+ font-size: 0.8125rem;+ }++ &__details {+ display: flex;+ flex-wrap: wrap;+ gap: $space-2;+ }++ &__chip {+ display: inline-flex;+ align-items: center;+ gap: $space-1;+ padding: 2px $space-2;+ background: $bg-elevated;+ border: 1px solid $border-subtle;+ border-radius: $radius-md;+ color: $text-secondary;+ font-size: 0.8125rem;+ font-family: $font-mono;+ }++ &__summary {+ margin: 0;+ color: $text-secondary;+ font-size: 0.8125rem;+ }+}++// ---------------------------------------------------------------- Timeline card+.deploy-timeline-card {+ &__hint {+ margin: 0 0 $space-4;+ color: $text-secondary;+ font-size: 0.8125rem;+ max-width: 70ch;+ }+}++// ---------------------------------------------------------------- Config diff+.config-diff {+ max-width: 640px;+ width: 100%;++ &__body {+ display: flex;+ flex-direction: column;+ gap: $space-4;+ max-height: 60vh;+ overflow-y: auto;+ padding: $space-2 0;+ }++ &__loading {+ color: $text-secondary;+ }++ &__summary {+ margin: 0;+ padding: $space-2 $space-3;+ background: $bg-elevated;+ border-radius: $radius-md;+ color: $text-secondary;+ font-size: 0.875rem;+ }++ &__section {+ display: flex;+ flex-direction: column;+ gap: $space-2;+ }++ &__section-title {+ margin: 0;+ font-size: 0.8125rem;+ font-weight: 600;+ color: $text-secondary;+ text-transform: uppercase;+ letter-spacing: 0.04em;+ }++ &__none {+ margin: 0;+ color: $text-tertiary;+ font-size: 0.8125rem;+ }++ &__lines {+ list-style: none;+ margin: 0;+ padding: 0;+ display: flex;+ flex-direction: column;+ gap: 2px;+ }++ &__line {+ display: flex;+ align-items: center;+ gap: $space-2;+ padding: 2px $space-2;+ border-radius: $radius-sm;+ font-family: $font-mono;+ font-size: 0.8125rem;++ &--add {+ background: $success-bg;+ color: $success;+ }++ &--remove {+ background: $danger-bg;+ color: $danger;+ }++ &--change {+ background: $warning-bg;+ color: $warning;+ }+ }++ &__sign {+ font-weight: 700;+ width: 12px;+ display: inline-block;+ text-align: center;+ }++ &__scalar {+ display: flex;+ align-items: center;+ gap: $space-2;+ flex-wrap: wrap;+ font-family: $font-mono;+ font-size: 0.8125rem;+ }++ &__old {+ color: $danger;+ text-decoration: line-through;+ }++ &__new {+ color: $success;+ }++ &__arrow {+ color: $text-tertiary;+ }++ &__confirm-text {+ margin-right: auto;+ color: $text-secondary;+ font-size: 0.875rem;+ }+}diff --git a/frontend/src/styles/main.scss b/frontend/src/styles/main.scssindex b82255d6..727ee2fc 100644--- a/frontend/src/styles/main.scss+++ b/frontend/src/styles/main.scss@@ -71,6 +71,8 @@@import 'components/container-status';@import 'components/api-key-scopes';@import 'components/onboarding-wizard';+@import 'components/buildpack';+@import 'components/deployments';// --------------------------------------------// 5. PAGE-SPECIFIC STYLES