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
Give common API errors stable codes and service wording
Juan Denis97a96d963baf
diff --git a/backend/app/api/admin.py b/backend/app/api/admin.pyindex 129bfe1a..751ee95c 100644--- a/backend/app/api/admin.py+++ b/backend/app/api/admin.py@@ -13,6 +13,7 @@ from app.services.audit_service import AuditServicefrom app.services.settings_service import SettingsServicefrom app.services.permission_service import PermissionServicefrom app.utils.domain import detect_request_domain, canonical_origin, is_valid_canonical_domain+from app.exceptions import not_foundadmin_bp = Blueprint('admin', __name__)@@ -94,7 +95,7 @@ def get_user(user_id):"""Get a specific user."""user = User.query.get(user_id)if not user:- return jsonify({'error': 'User not found'}), 404+ raise not_found('user')return jsonify({'user': user.to_dict()}), 200@@ -108,7 +109,7 @@ def update_user(user_id):user = User.query.get(user_id)if not user:- return jsonify({'error': 'User not found'}), 404+ raise not_found('user')changes = {}@@ -204,7 +205,7 @@ def delete_user(user_id):user = User.query.get(user_id)if not user:- return jsonify({'error': 'User not found'}), 404+ raise not_found('user')# Prevent self-deletionif user.id == current_user_id:@@ -221,9 +222,9 @@ def delete_user(user_id):from app.services.application_restore import applications_owned_byowned = applications_owned_by(user.id)if owned:- return jsonify({'error': f'User still owns {owned} application(s), '- 'including any in the Recycle Bin — delete or '- 'purge them first'}), 409+ return jsonify({'error': f'This user still owns {owned} service(s), '+ 'including any in the recycle bin. Delete or '+ 'purge them first.'}), 409username = user.usernameuser_id_deleted = user.id@@ -532,7 +533,7 @@ def get_user_permissions(user_id):"""Get a user's resolved permissions."""perms = PermissionService.get_user_permissions(user_id)if perms is None:- return jsonify({'error': 'User not found'}), 404+ raise not_found('user')return jsonify({'permissions': perms}), 200diff --git a/backend/app/api/api_analytics.py b/backend/app/api/api_analytics.pyindex cdfb6ad2..766b8257 100644--- a/backend/app/api/api_analytics.py+++ b/backend/app/api/api_analytics.py@@ -3,6 +3,7 @@ from flask import Blueprint, jsonify, requestfrom app.middleware.rbac import admin_required, auth_required, get_current_userfrom app.services.api_analytics_service import ApiAnalyticsServicefrom app.services.api_key_service import ApiKeyService+from app.exceptions import permission_deniedapi_analytics_bp = Blueprint('api_analytics', __name__)@@ -54,6 +55,6 @@ def key_usage(key_id):return jsonify({'error': 'API key not found'}), 404if not user.is_admin and api_key.user_id != user.id:- return jsonify({'error': 'Access denied'}), 403+ raise permission_denied()return jsonify(ApiAnalyticsService.get_key_usage(key_id, period))diff --git a/backend/app/api/api_keys.py b/backend/app/api/api_keys.pyindex 5801c362..74a00d35 100644--- a/backend/app/api/api_keys.py+++ b/backend/app/api/api_keys.py@@ -7,6 +7,7 @@ from app.middleware.api_scope_middleware import SCOPES, require_scopefrom app.services.api_key_service import ApiKeyServicefrom app.services.audit_service import AuditServicefrom app.models.audit_log import AuditLog+from app.exceptions import not_foundapi_keys_bp = Blueprint('api_keys', __name__)@@ -80,7 +81,7 @@ def get_key(key_id):"""Get API key details."""user = get_current_user()if not user:- return jsonify({'error': 'User not found'}), 404+ raise not_found('user')api_key = ApiKeyService.get_key(key_id, user.id)if not api_key:@@ -119,7 +120,7 @@ def revoke_key(key_id):"""Revoke an API key."""user = get_current_user()if not user:- return jsonify({'error': 'User not found'}), 404+ raise not_found('user')api_key = ApiKeyService.revoke_key(key_id, user.id)if not api_key:@@ -142,7 +143,7 @@ def rotate_key(key_id):"""Rotate an API key (revoke + recreate with same config)."""user = get_current_user()if not user:- return jsonify({'error': 'User not found'}), 404+ raise not_found('user')new_key, raw_key = ApiKeyService.rotate_key(key_id, user.id)if not new_key:diff --git a/backend/app/api/app_attachments.py b/backend/app/api/app_attachments.pyindex 134b068a..74eed5ba 100644--- a/backend/app/api/app_attachments.py+++ b/backend/app/api/app_attachments.py@@ -13,7 +13,7 @@ restart, so responses say ``redeploy_required``."""from flask import Blueprint, jsonify, request-from app.exceptions import NotFoundError, ValidationError+from app.exceptions import NotFoundError, ValidationError, not_foundfrom app.middleware.rbac import developer_required, get_current_user, viewer_requiredfrom app.models.app_attachment import AppAttachmentfrom app.services.app_attachment_service import (@@ -28,7 +28,7 @@ app_attachments_bp = Blueprint('app_attachments', __name__)def list_attachments(app_id):app = AppAttachmentService.live_app(app_id)if app is None or not ResourceGrantService.can_access_app(get_current_user(), app):- raise NotFoundError('Application not found')+ raise not_found('service')return jsonify({'attachments': [a.to_dict() for a in AppAttachmentService.list_for_app(app)],'kinds': AppAttachmentService.kinds_for(app)})@@ -57,7 +57,7 @@ def attach_service(app_id, kind):user = get_current_user()app = AppAttachmentService.live_app(app_id)if app is None or not ResourceGrantService.can_edit_app(user, app):- raise NotFoundError('Application not found')+ raise not_found('service')data = request.get_json(silent=True) or {}service_app_id = data.get('service_app_id')if not isinstance(service_app_id, int) or isinstance(service_app_id, bool):@@ -65,7 +65,7 @@ def attach_service(app_id, kind):kind = _kind_or_400(kind)service = AppAttachmentService.live_app(service_app_id)if service is None or not ResourceGrantService.can_access_app(user, service):- raise NotFoundError('Service not found')+ raise not_found('service')try:row, created = AppAttachmentService.attach(app, service, kind, user_id=user.id)except AttachmentError as exc:@@ -79,7 +79,7 @@ def detach(app_id, attachment_id):user = get_current_user()app = AppAttachmentService.live_app(app_id)if app is None or not ResourceGrantService.can_edit_app(user, app):- raise NotFoundError('Application not found')+ raise not_found('service')attachment = AppAttachmentService.get(app, attachment_id)if attachment is None:raise NotFoundError('Attachment not found')@@ -98,7 +98,7 @@ def get_pooler(app_id):from app.services import pooler_serviceapp = AppAttachmentService.live_app(app_id)if app is None or not ResourceGrantService.can_access_app(get_current_user(), app):- raise NotFoundError('Application not found')+ raise not_found('service')return jsonify({'available': pooler_service.is_postgres_engine(app),'enabled': bool(app.pooler_enabled),'host': pooler_service.container_name(app),@@ -111,7 +111,7 @@ def set_pooler(app_id):from app.services import pooler_serviceapp = AppAttachmentService.live_app(app_id)if app is None or not ResourceGrantService.can_edit_app(get_current_user(), app):- raise NotFoundError('Application not found')+ raise not_found('service')if not pooler_service.is_postgres_engine(app):raise ValidationError('Connection pooling is for an installed PostgreSQL')data = request.get_json(silent=True) or {}@@ -129,7 +129,7 @@ def get_hints(app_id):from app.services.bottleneck_hints_service import BottleneckHintsServiceapp = AppAttachmentService.live_app(app_id)if app is None or not ResourceGrantService.can_access_app(get_current_user(), app):- raise NotFoundError('Application not found')+ raise not_found('service')return jsonify({'hints': BottleneckHintsService.hints(app)})@@ -143,7 +143,7 @@ def set_immutable_assets(app_id):from app.services.site_domain_service import SiteDomainServiceapp = AppAttachmentService.live_app(app_id)if app is None or not ResourceGrantService.can_edit_app(get_current_user(), app):- raise NotFoundError('Application not found')+ raise not_found('service')data = request.get_json(silent=True) or {}if not isinstance(data.get('enabled'), bool):raise ValidationError("'enabled' must be true or false")diff --git a/backend/app/api/app_slots.py b/backend/app/api/app_slots.pyindex 81398bda..b750eae8 100644--- a/backend/app/api/app_slots.py+++ b/backend/app/api/app_slots.py@@ -19,7 +19,7 @@"""from flask import Blueprint, jsonify, request-from app.exceptions import NotFoundError, ValidationError+from app.exceptions import ValidationError, not_foundfrom app.middleware.rbac import developer_required, get_current_user, viewer_requiredfrom app.services.resource_grant_service import ResourceGrantServicefrom app.services.slot_deploy_service import SlotDeployService@@ -33,7 +33,7 @@ def _app(app_id, write=False):allowed = (ResourceGrantService.can_edit_app if writeelse ResourceGrantService.can_access_app)if app is None or not allowed(user, app):- raise NotFoundError('Application not found')+ raise not_found('service')return app, user@@ -98,7 +98,7 @@ def compose_split_apply(app_id):app, _ = _app(app_id, write=True)data = request.get_json(silent=True) or {}if data.get('confirm') is not True:- raise ValidationError("Moving the stateful services stops the app once; send "+ raise ValidationError("Moving the stateful services stops the service once; send ""{'confirm': true} after reading the preview")result = SlotDeployService.compose_split_apply(app)if not result.get('success'):diff --git a/backend/app/api/app_volumes.py b/backend/app/api/app_volumes.pyindex 621b7157..a137cc6d 100644--- a/backend/app/api/app_volumes.py+++ b/backend/app/api/app_volumes.py@@ -11,6 +11,7 @@ from app.models import Applicationfrom app.services.resource_grant_service import ResourceGrantServicefrom app.services.volume_service import VolumeService, VolumeErrorfrom app.middleware.rbac import get_current_user+from app.exceptions import not_found, permission_deniedapp_volumes_bp = Blueprint('app_volumes', __name__)@@ -20,11 +21,11 @@ def _load_app_for(app_id, *, write):user = get_current_user()app = Application.query_active().filter_by(id=app_id).first()if not app:- return None, None, (jsonify({'error': 'Application not found'}), 404)+ raise not_found('service')allowed = (ResourceGrantService.can_edit_app(user, app) if writeelse ResourceGrantService.can_access_app(user, app))if not allowed:- return None, None, (jsonify({'error': 'Access denied'}), 403)+ raise permission_denied()return user, app, Nonediff --git a/backend/app/api/apps.py b/backend/app/api/apps.pyindex 20b0f4be..c318baf7 100644--- a/backend/app/api/apps.py+++ b/backend/app/api/apps.py@@ -44,6 +44,8 @@ from app.services.upload_service import ()from app import pathsfrom app.middleware.rbac import get_current_user, require_admin_user+from app.error_reporting import unexpected_response+from app.exceptions import field_required, not_found, permission_deniedapps_bp = Blueprint('apps', __name__)@@ -134,10 +136,10 @@ def link_apps(app_id):app = Application.query_active().filter_by(id=app_id).first()if not app:- return jsonify({'error': 'Application not found'}), 404+ raise not_found('service')if not _can_edit_app(user, app):- return jsonify({'error': 'Access denied'}), 403+ raise permission_denied()data = request.get_json()if not data:@@ -147,7 +149,7 @@ def link_apps(app_id):as_environment = data.get('as_environment', 'development')if not target_app_id:- return jsonify({'error': 'target_app_id is required'}), 400+ raise field_required('target_app_id')valid_environments = ['production', 'development', 'staging']if as_environment not in valid_environments:@@ -155,16 +157,16 @@ def link_apps(app_id):target_app = Application.query_active().filter_by(id=target_app_id).first()if not target_app:- return jsonify({'error': 'Target application not found'}), 404+ return jsonify({'error': 'Target service not found'}), 404if not _can_edit_app(user, target_app):- return jsonify({'error': 'Access denied to target application'}), 403+ return jsonify({'error': "You don't have access to the target service"}), 403if app.app_type != target_app.app_type:- return jsonify({'error': 'Apps must be of the same type to link'}), 400+ return jsonify({'error': 'Only services of the same type can be linked'}), 400if app_id == target_app_id:- return jsonify({'error': 'Cannot link an app to itself'}), 400+ return jsonify({'error': "A service can't be linked to itself"}), 400# Set environment types based on as_environmentif as_environment == 'development':@@ -214,7 +216,7 @@ def link_apps(app_id):db.session.commit()response = {- 'message': 'Apps linked successfully',+ 'message': 'Services linked','app': app.to_dict(include_linked=True),'target_app': target_app.to_dict(include_linked=True)}@@ -233,10 +235,10 @@ def get_linked_apps(app_id):app = Application.query_active().filter_by(id=app_id).first()if not app:- return jsonify({'error': 'Application not found'}), 404+ raise not_found('service')if not _can_access_app(user, app):- return jsonify({'error': 'Access denied'}), 403+ raise permission_denied()linked_apps = []@@ -280,13 +282,13 @@ def unlink_apps(app_id):app = Application.query_active().filter_by(id=app_id).first()if not app:- return jsonify({'error': 'Application not found'}), 404+ raise not_found('service')if not _can_edit_app(user, app):- return jsonify({'error': 'Access denied'}), 403+ raise permission_denied()if not app.linked_app_id:- return jsonify({'error': 'App is not linked to any other app'}), 400+ return jsonify({'error': 'This service is not linked to another service'}), 400# Deliberately NOT query_active: this is the reciprocal half of a link the# caller is severing, not "an app to operate on". If the partner is already@@ -307,7 +309,7 @@ def unlink_apps(app_id):db.session.commit()return jsonify({- 'message': 'Apps unlinked successfully',+ 'message': 'Services unlinked','app': app.to_dict()}), 200@@ -321,10 +323,10 @@ def update_environment(app_id):app = Application.query_active().filter_by(id=app_id).first()if not app:- return jsonify({'error': 'Application not found'}), 404+ raise not_found('service')if not _can_edit_app(user, app):- return jsonify({'error': 'Access denied'}), 403+ raise permission_denied()data = request.get_json()if not data:@@ -430,10 +432,10 @@ def set_app_workspace(app_id):user = get_current_user()app = Application.query_active().filter_by(id=app_id).first()if not app:- return jsonify({'error': 'Application not found'}), 404+ raise not_found('service')# Use user.id (int) for comparisons — get_jwt_identity() is the stringified token id.if not user.is_admin and app.user_id != user.id:- return jsonify({'error': 'Access denied'}), 403+ raise permission_denied()target = (request.get_json() or {}).get('workspace_id')if target in (None, '', 'default'):@@ -535,7 +537,7 @@ def move_apps_to_project():db.session.commit()return jsonify({- 'message': f'Updated {len(updated)} application(s)',+ 'message': f'Updated {len(updated)} service(s)','apps': [a.to_dict() for a in updated],'skipped': skipped,}), 200@@ -616,10 +618,10 @@ def get_app(app_id):app = Application.query_active().filter_by(id=app_id).first()if not app:- return jsonify({'error': 'Application not found'}), 404+ raise not_found('service')if not _can_access_app(user, app):- return jsonify({'error': 'Access denied'}), 403+ raise permission_denied()# Single app requests include linked app info by defaultreturn jsonify({'app': _attach_deploy_config(app.to_dict(include_linked=True))}), 200@@ -636,9 +638,9 @@ def get_compose_services(app_id):user = get_current_user()app = Application.query_active().filter_by(id=app_id).first()if not app:- return jsonify({'error': 'Application not found'}), 404+ raise not_found('service')if not _can_access_app(user, app):- return jsonify({'error': 'Access denied'}), 403+ raise permission_denied()from app.services.compose_env_service import ComposeEnvServicereturn jsonify({'services': ComposeEnvService.list_services(app)}), 200@@ -654,9 +656,9 @@ def list_app_grants(app_id):user = get_current_user()app = Application.query_active().filter_by(id=app_id).first()if not app:- return jsonify({'error': 'Application not found'}), 404+ raise not_found('service')if not user.is_admin and app.user_id != user.id:- return jsonify({'error': 'Access denied'}), 403+ raise permission_denied()grants = ResourceGrantService.list_for_resource('application', app.id)return jsonify({'grants': [g.to_dict() for g in grants]}), 200@@ -669,16 +671,16 @@ def grant_app_access(app_id):user = get_current_user()app = Application.query_active().filter_by(id=app_id).first()if not app:- return jsonify({'error': 'Application not found'}), 404+ raise not_found('service')if not user.is_admin and app.user_id != user.id:- return jsonify({'error': 'Access denied'}), 403+ raise permission_denied()data = request.get_json() or {}grantee_id = data.get('user_id')if not grantee_id:- return jsonify({'error': 'user_id is required'}), 400+ raise field_required('user_id')grantee = User.query.get(grantee_id)if not grantee:- return jsonify({'error': 'User not found'}), 404+ raise not_found('user')if grantee.id == app.user_id:return jsonify({'error': 'The owner already has access'}), 400role = data.get('role') or 'editor'@@ -697,9 +699,9 @@ def revoke_app_access(app_id, grant_id):user = get_current_user()app = Application.query_active().filter_by(id=app_id).first()if not app:- return jsonify({'error': 'Application not found'}), 404+ raise not_found('service')if not user.is_admin and app.user_id != user.id:- return jsonify({'error': 'Access denied'}), 403+ raise permission_denied()ok = ResourceGrantService.revoke(grant_id, resource_type='application', resource_id=app.id)return jsonify({'success': ok}), (200 if ok else 404)@@ -747,7 +749,7 @@ def create_app_from_repository():deploy_repo_url = repo_urlif not clone_repo_url:- return jsonify({'error': 'repo_url is required'}), 400+ raise field_required('repo_url')valid_app_types = ['auto', 'docker', 'flask', 'django', 'php', 'static']if app_type not in valid_app_types:@@ -778,7 +780,7 @@ def create_app_from_repository():return jsonify({'error': str(exc)}), 400if os.path.exists(app_path):- return jsonify({'error': f'App directory already exists: {app_path}'}), 400+ return jsonify({'error': f'A service directory already exists at {app_path}. Choose another name.'}), 400clone_result = GitService.clone_repository(app_path, clone_repo_url, branch or None)if not clone_result.get('success'):@@ -896,9 +898,16 @@ def create_app_from_repository():'detection': detection,'manifest': manifest,}), 201- except Exception as exc:+ except RuntimeError as exc:+ # configure_deployment/configure_build failures carry the service's+ # own message, written for the caller.repository_application_service.abort_repository_creation(app)return jsonify({'error': str(exc)}), 400+ except Exception as exc:+ # Anything else is a crash: log it with the request id and keep its+ # text (paths, SQL, connection strings) out of the response.+ repository_application_service.abort_repository_creation(app)+ return unexpected_response(exc)@apps_bp.route('', methods=['POST'])@@ -960,7 +969,7 @@ def create_app():db.session.commit()return jsonify({- 'message': 'Application created successfully',+ 'message': 'Service created','app': app.to_dict()}), 201@@ -987,7 +996,7 @@ def create_manual_app():return jsonify({'error': f'Invalid app_type. Must be one of: {", ".join(valid_types)}'}), 400if not root_path:- return jsonify({'error': 'root_path is required'}), 400+ raise field_required('root_path')root_path = os.path.abspath(root_path)if not os.path.isdir(root_path):@@ -1195,7 +1204,12 @@ def upload_app_archive():os.remove(zippath)except Exception:pass- return jsonify({'error': str(exc)}), 400+ if isinstance(exc, ValueError):+ # upload_service's validation errors are written for the caller.+ return jsonify({'error': str(exc)}), 400+ # Anything else is a crash: logged with the request id, its text+ # (paths, SQL) kept out of the response.+ return unexpected_response(exc)@apps_bp.route('/<int:app_id>/versions', methods=['GET'])@@ -1207,10 +1221,10 @@ def get_app_versions(app_id):app = Application.query_active().filter_by(id=app_id).first()if not app:- return jsonify({'error': 'Application not found'}), 404+ raise not_found('service')if not _can_access_app(user, app):- return jsonify({'error': 'Access denied'}), 403+ raise permission_denied()if app.source != 'upload':return jsonify({'versions': [], 'current': None}), 200@@ -1220,8 +1234,10 @@ def get_app_versions(app_id):versions = list_versions(app_dir)current = get_current_version(app_dir)return jsonify({'versions': versions, 'current': current}), 200- except Exception as e:+ except ValueError as e:return jsonify({'error': str(e)}), 400+ except Exception as e:+ return unexpected_response(e)@apps_bp.route('/<int:app_id>/rollback', methods=['POST'])@@ -1233,18 +1249,18 @@ def rollback_app_version(app_id):app = Application.query_active().filter_by(id=app_id).first()if not app:- return jsonify({'error': 'Application not found'}), 404+ raise not_found('service')if not _can_edit_app(user, app):- return jsonify({'error': 'Access denied'}), 403+ raise permission_denied()if app.source != 'upload':- return jsonify({'error': 'Rollback is only supported for upload-based apps'}), 400+ return jsonify({'error': 'Rollback is only available for services deployed by upload'}), 400data = request.get_json() or {}target = data.get('version')if target is None:- return jsonify({'error': 'version is required'}), 400+ raise field_required('version')try:target = int(target)@@ -1271,8 +1287,11 @@ def rollback_app_version(app_id):'message': f'Rolled back to version {target}','app': _attach_deploy_config(app.to_dict(include_linked=True))}), 200- except Exception as e:+ except ValueError as e:+ # An unknown version is the caller's to fix.return jsonify({'error': str(e)}), 400+ except Exception as e:+ return unexpected_response(e)@apps_bp.route('/<int:app_id>', methods=['PUT'])@@ -1283,10 +1302,10 @@ def update_app(app_id):app = Application.query_active().filter_by(id=app_id).first()if not app:- return jsonify({'error': 'Application not found'}), 404+ raise not_found('service')if not _can_edit_app(user, app):- return jsonify({'error': 'Access denied'}), 403+ raise permission_denied()data = request.get_json()@@ -1334,7 +1353,7 @@ def update_app(app_id):db.session.commit()return jsonify({- 'message': 'Application updated successfully',+ 'message': 'Service updated','app': app.to_dict()}), 200@@ -1364,10 +1383,10 @@ def delete_app(app_id):app = Application.query_active().filter_by(id=app_id).first()if not app:- return jsonify({'error': 'Application not found'}), 404+ raise not_found('service')if not user.is_admin and app.user_id != user.id:- return jsonify({'error': 'Access denied'}), 403+ raise permission_denied()purge_now = str(request.args.get('purge', '')).lower() in ('1', 'true', 'yes')@@ -1381,14 +1400,14 @@ def delete_app(app_id):app._purge_remove_data = _remove_data_flag(app)ok, warning = recycle_bin_service.purge('application', app.id)return jsonify({- 'message': 'Application deleted permanently',+ 'message': 'Service deleted permanently','purged': ok,'cleanup': cleanup_results,'warning': warning,}), 200return jsonify({- 'message': 'Application moved to the recycle bin',+ 'message': 'Service moved to the recycle bin','recycle_bin': True,'cleanup': cleanup_results,}), 200@@ -1402,10 +1421,10 @@ def start_app(app_id):app = Application.query_active().filter_by(id=app_id).first()if not app:- return jsonify({'error': 'Application not found'}), 404+ raise not_found('service')if not _can_edit_app(user, app):- return jsonify({'error': 'Access denied'}), 403+ raise permission_denied()try:application_lifecycle_service.start_application(app, user_id=current_user_id)@@ -1413,7 +1432,7 @@ def start_app(app_id):return jsonify({'error': str(exc)}), 400return jsonify({- 'message': 'Application started',+ 'message': 'Service started','app': app.to_dict()}), 200@@ -1427,9 +1446,9 @@ def apply_image_update(app_id):app = Application.query_active().filter_by(id=app_id).first()if not app:- return jsonify({'error': 'Application not found'}), 404+ raise not_found('service')if not _can_edit_app(user, app):- return jsonify({'error': 'Access denied'}), 403+ raise permission_denied()# A slot app never recreates its live stack in place: the newest images# go through a slot deploy (pulled in its preflight, gated, switched).@@ -1447,7 +1466,7 @@ def apply_image_update(app_id):# Auto-apply is only safe for compose-managed apps; recreating a standalone# container would need its full run spec, which we don't store.if app.app_type != 'docker' or not app.root_path or not app.compose_file:- return jsonify({'error': 'Automatic update is only supported for docker-compose apps. '+ return jsonify({'error': 'Automatic update is only available for Docker Compose services. ''Pull and recreate this container manually.'}), 400# Pull the newest images for the project, then recreate changed containers.@@ -1492,9 +1511,9 @@ def get_sleep_policy(app_id):user = get_current_user()app = Application.query_active().filter_by(id=app_id).first()if not app:- return jsonify({'error': 'Application not found'}), 404+ raise not_found('service')if not _can_access_app(user, app):- return jsonify({'error': 'Access denied'}), 403+ raise permission_denied()return jsonify(ContainerSleepService.get_or_create_policy(app_id).to_dict())@@ -1504,9 +1523,9 @@ def update_sleep_policy(app_id):user = get_current_user()app = Application.query_active().filter_by(id=app_id).first()if not app:- return jsonify({'error': 'Application not found'}), 404+ raise not_found('service')if not _can_edit_app(user, app):- return jsonify({'error': 'Access denied'}), 403+ raise permission_denied()data = request.get_json() or {}policy = ContainerSleepService.set_policy(app_id, enabled=data.get('enabled'), idle_timeout_minutes=data.get('idle_timeout_minutes'))@@ -1519,13 +1538,13 @@ def sleep_app(app_id):user = get_current_user()app = Application.query_active().filter_by(id=app_id).first()if not app:- return jsonify({'error': 'Application not found'}), 404+ raise not_found('service')if not _can_edit_app(user, app):- return jsonify({'error': 'Access denied'}), 403+ raise permission_denied()result = ContainerSleepService.sleep_app(app_id)if not result.get('success'):return jsonify({'error': result['error']}), 400- return jsonify({'message': 'Application asleep', 'policy': result['policy'], 'app': app.to_dict()})+ return jsonify({'message': 'Service asleep', 'policy': result['policy'], 'app': app.to_dict()})@apps_bp.route('/<int:app_id>/wake', methods=['POST'])@@ -1534,13 +1553,13 @@ def wake_app(app_id):user = get_current_user()app = Application.query_active().filter_by(id=app_id).first()if not app:- return jsonify({'error': 'Application not found'}), 404+ raise not_found('service')if not _can_edit_app(user, app):- return jsonify({'error': 'Access denied'}), 403+ raise permission_denied()result = ContainerSleepService.wake_app(app_id)if not result.get('success'):return jsonify({'error': result['error']}), 400- return jsonify({'message': 'Application awake', 'policy': result['policy'], 'app': app.to_dict()})+ return jsonify({'message': 'Service awake', 'policy': result['policy'], 'app': app.to_dict()})@apps_bp.route('/sweep-idle', methods=['POST'])@@ -1592,9 +1611,9 @@ def get_app_resources(app_id):user = get_current_user()app = Application.query_active().filter_by(id=app_id).first()if not app:- return jsonify({'error': 'Application not found'}), 404+ raise not_found('service')if not _can_access_app(user, app):- return jsonify({'error': 'Access denied'}), 403+ raise permission_denied()usage = Noneif app.status == 'running' and not app.server_id:@@ -1625,9 +1644,9 @@ def update_app_resources(app_id):user = get_current_user()app = Application.query_active().filter_by(id=app_id).first()if not app:- return jsonify({'error': 'Application not found'}), 404+ raise not_found('service')if not _can_edit_app(user, app):- return jsonify({'error': 'Access denied'}), 403+ raise permission_denied()data = request.get_json() or {}try:@@ -1682,9 +1701,9 @@ def set_micro_cache(app_id):user = get_current_user()app = Application.query_active().filter_by(id=app_id).first()if not app:- return jsonify({'error': 'Application not found'}), 404+ raise not_found('service')if not _can_edit_app(user, app):- return jsonify({'error': 'Access denied'}), 403+ raise permission_denied()data = request.get_json() or {}if 'enabled' not in data:@@ -1740,9 +1759,9 @@ def purge_micro_cache(app_id):user = get_current_user()app = Application.query_active().filter_by(id=app_id).first()if not app:- return jsonify({'error': 'Application not found'}), 404+ raise not_found('service')if not _can_edit_app(user, app):- return jsonify({'error': 'Access denied'}), 403+ raise permission_denied()hosts = [d.name for d in app.live_domains if d.name]if not hosts:@@ -1765,10 +1784,10 @@ def stop_app(app_id):app = Application.query_active().filter_by(id=app_id).first()if not app:- return jsonify({'error': 'Application not found'}), 404+ raise not_found('service')if not _can_edit_app(user, app):- return jsonify({'error': 'Access denied'}), 403+ raise permission_denied()try:application_lifecycle_service.stop_application(app, user_id=current_user_id)@@ -1776,7 +1795,7 @@ def stop_app(app_id):return jsonify({'error': str(exc)}), 400return jsonify({- 'message': 'Application stopped',+ 'message': 'Service stopped','app': app.to_dict()}), 200@@ -1789,10 +1808,10 @@ def restart_app(app_id):app = Application.query_active().filter_by(id=app_id).first()if not app:- return jsonify({'error': 'Application not found'}), 404+ raise not_found('service')if not _can_edit_app(user, app):- return jsonify({'error': 'Access denied'}), 403+ raise permission_denied()try:application_lifecycle_service.restart_application(app, user_id=current_user_id)@@ -1800,7 +1819,7 @@ def restart_app(app_id):return jsonify({'error': str(exc)}), 400return jsonify({- 'message': 'Application restarted',+ 'message': 'Service restarted','app': app.to_dict()}), 200@@ -1819,9 +1838,9 @@ def get_app_related(app_id):user = get_current_user()app = Application.query_active().filter_by(id=app_id).first()if not app:- return jsonify({'error': 'Application not found'}), 404+ raise not_found('service')if not _can_access_app(user, app):- return jsonify({'error': 'Access denied'}), 403+ raise permission_denied()related = {'domains': [], 'databases': [], 'backup': None, 'deployments': {'count': 0}}@@ -1873,10 +1892,10 @@ def get_app_logs(app_id):app = Application.query_active().filter_by(id=app_id).first()if not app:- return jsonify({'error': 'Application not found'}), 404+ raise not_found('service')if not _can_access_app(user, app):- return jsonify({'error': 'Access denied'}), 403+ raise permission_denied()lines = request.args.get('lines', 100, type=int)log_type = request.args.get('type', 'all')@@ -1942,10 +1961,10 @@ def get_container_logs(app_id):app = Application.query_active().filter_by(id=app_id).first()if not app:- return jsonify({'error': 'Application not found'}), 404+ raise not_found('service')if not _can_access_app(user, app):- return jsonify({'error': 'Access denied'}), 403+ raise permission_denied()# Parse query parameterstail = request.args.get('tail', 100, type=int)@@ -1982,8 +2001,8 @@ def get_container_logs(app_id):if not container_id:return jsonify({- 'error': 'No container found for this application',- 'hint': 'The application may not have been started yet'+ 'error': 'No container found for this service',+ 'hint': 'Start the service, then try again'}), 404# Check container state@@ -2047,10 +2066,10 @@ def get_app_containers(app_id):app = Application.query_active().filter_by(id=app_id).first()if not app:- return jsonify({'error': 'Application not found'}), 404+ raise not_found('service')if not _can_access_app(user, app):- return jsonify({'error': 'Access denied'}), 403+ raise permission_denied()containers = DockerService.get_all_app_containers(app)@@ -2070,10 +2089,10 @@ def get_app_status(app_id):app = Application.query_active().filter_by(id=app_id).first()if not app:- return jsonify({'error': 'Application not found'}), 404+ raise not_found('service')if not _can_access_app(user, app):- return jsonify({'error': 'Access denied'}), 403+ raise permission_denied()# Manual / local apps: ask the real runtimeif app.source == 'manual':@@ -2162,10 +2181,10 @@ def _load_app_for_backup(app_id, edit=False):user = get_current_user()app = Application.query_active().filter_by(id=app_id).first()if not app:- return None, (jsonify({'error': 'Application not found'}), 404)+ raise not_found('service')allowed = _can_edit_app(user, app) if edit else _can_access_app(user, app)if not allowed:- return None, (jsonify({'error': 'Access denied'}), 403)+ raise permission_denied()return app, None@@ -2310,7 +2329,7 @@ def list_app_db_snapshots(app_id):from app.models.wordpress_site import DatabaseSnapshotsite = _wp_site_for_app(app)if not site:- return jsonify({'error': 'This application is not a WordPress site'}), 400+ return jsonify({'error': 'This service is not a WordPress site'}), 400snaps = (DatabaseSnapshot.query.filter_by(site_id=site.id).order_by(DatabaseSnapshot.created_at.desc()).all())return jsonify({'snapshots': [s.to_dict() for s in snaps], 'total': len(snaps)}), 200@@ -2327,7 +2346,7 @@ def create_app_db_snapshot(app_id):from app.services.db_sync_service import DatabaseSyncServicesite = _wp_site_for_app(app)if not site:- return jsonify({'error': 'This application is not a WordPress site'}), 400+ return jsonify({'error': 'This service is not a WordPress site'}), 400# Resolve the extension only once we know this IS a WordPress site — with# serverkit-wordpress uninstalled a non-WP app must get the 400, not an# import error (plan 52 Phase 5 graceful absence). A WP SITE with the@@ -2377,10 +2396,10 @@ def delete_app_db_snapshot(app_id, snapshot_id):from app.services.db_sync_service import DatabaseSyncServicesite = _wp_site_for_app(app)if not site:- return jsonify({'error': 'This application is not a WordPress site'}), 400+ return jsonify({'error': 'This service is not a WordPress site'}), 400snapshot = DatabaseSnapshot.query.filter_by(id=snapshot_id, site_id=site.id).first()if not snapshot:- return jsonify({'error': 'Snapshot not found'}), 404+ raise not_found('snapshot')DatabaseSyncService.delete_snapshot(snapshot.file_path)db.session.delete(snapshot)db.session.commit()diff --git a/backend/app/api/auth.py b/backend/app/api/auth.pyindex fa1b810a..37682986 100644--- a/backend/app/api/auth.py+++ b/backend/app/api/auth.py@@ -19,7 +19,9 @@ from app.services import login_link_servicefrom app.services import auth_throttle_servicefrom app.utils.client_ip import get_client_ipfrom app.utils.i18n import normalize_language-from app.exceptions import AuthenticationError, ConflictError, PermissionDeniedError, ValidationError+from app.exceptions import (+ AuthenticationError, ConflictError, PermissionDeniedError, ValidationError, not_found,+)logger = logging.getLogger(__name__)@@ -349,7 +351,7 @@ def create_login_link():target_id = data.get('user_id') or current.idtarget = User.query.get(target_id)if not target:- return jsonify({'error': 'User not found'}), 404+ raise not_found('user')bound_ip = (data.get('bound_ip') or '').strip() or Noneif bound_ip and len(bound_ip) > 64:@@ -565,7 +567,7 @@ def get_current_user():user = User.query.get(current_user_id)if not user:- return jsonify({'error': 'User not found'}), 404+ raise not_found('user')return jsonify({'user': user.to_dict()}), 200@@ -595,7 +597,7 @@ def update_current_user():user = User.query.get(current_user_id)if not user:- return jsonify({'error': 'User not found'}), 404+ raise not_found('user')data = request.get_json() or {}@@ -677,7 +679,7 @@ def passkey_register_options():user_id = get_jwt_identity()user = User.query.get(user_id)if not user:- return jsonify({'error': 'User not found'}), 404+ raise not_found('user')options = PasskeyService.begin_registration(user)return jsonify(options), 200@@ -690,7 +692,7 @@ def passkey_register():user_id = get_jwt_identity()user = User.query.get(user_id)if not user:- return jsonify({'error': 'User not found'}), 404+ raise not_found('user')data = request.get_json() or {}credential = data.get('credential')device_name = data.get('device_name', 'Passkey')diff --git a/backend/app/api/backups.py b/backend/app/api/backups.pyindex f13bd008..319b7247 100644--- a/backend/app/api/backups.py+++ b/backend/app/api/backups.py@@ -7,6 +7,7 @@ from app.services.backup_service import BackupServicefrom app.services.backup_policy_service import BackupPolicyService, BackupPolicyErrorfrom app.services.storage_provider_service import StorageProviderServicefrom app import db, paths+from app.exceptions import field_required, not_foundbackups_bp = Blueprint('backups', __name__)@@ -340,11 +341,11 @@ def backup_application():app_id = data.get('application_id')if not app_id:- return jsonify({'error': 'application_id is required'}), 400+ raise field_required('application_id')app = Application.query_active().filter_by(id=app_id).first()if not app:- return jsonify({'error': 'Application not found'}), 404+ raise not_found('service')result = BackupService.backup_application(app_name=app.name,@@ -409,7 +410,7 @@ def restore_application():data = request.get_json()if not data or 'backup_path' not in data:- return jsonify({'error': 'backup_path is required'}), 400+ raise field_required('backup_path')result = BackupService.restore_application(backup_path=data['backup_path'],@@ -576,7 +577,7 @@ def upload_to_remote():"""Upload a local backup to remote storage."""data = request.get_json()if not data or 'backup_path' not in data:- return jsonify({'error': 'backup_path is required'}), 400+ raise field_required('backup_path')backup_path = os.path.realpath(data['backup_path'])@@ -588,7 +589,7 @@ def upload_to_remote():elif os.path.isfile(backup_path):result = StorageProviderService.upload_file(backup_path)else:- return jsonify({'error': 'Backup not found'}), 404+ raise not_found('backup')return jsonify(result), 200 if result['success'] else 400@@ -630,7 +631,7 @@ def download_from_remote():"""Download a backup from remote storage to local."""data = request.get_json()if not data or 'remote_key' not in data:- return jsonify({'error': 'remote_key is required'}), 400+ raise field_required('remote_key')remote_key = data['remote_key']# Determine local path from remote keydiff --git a/backend/app/api/builds.py b/backend/app/api/builds.pyindex cd6e4424..60c970dd 100644--- a/backend/app/api/builds.py+++ b/backend/app/api/builds.py@@ -17,6 +17,7 @@ from app.models import User, Application, Deploymentfrom app.services.build_service import BuildServicefrom app.services.deployment_service import DeploymentServicefrom app.services.resource_grant_service import ResourceGrantService+from app.exceptions import not_found, permission_deniedbuilds_bp = Blueprint('builds', __name__)@@ -32,10 +33,10 @@ def get_build_config(app_id):app = Application.query_active().filter_by(id=app_id).first()if not app:- return jsonify({'error': 'Application not found'}), 404+ raise not_found('service')if not ResourceGrantService.can_access_app(user, app):- return jsonify({'error': 'Access denied'}), 403+ raise permission_denied()config = BuildService.get_app_build_config(app_id)if not config:@@ -50,7 +51,7 @@ def configure_build(app_id):"""Configure build settings for an app."""app = Application.query_active().filter_by(id=app_id).first()if not app:- return jsonify({'error': 'Application not found'}), 404+ raise not_found('service')data = request.get_json()if not data:@@ -96,10 +97,10 @@ def detect_build_method(app_id):app = Application.query_active().filter_by(id=app_id).first()if not app:- return jsonify({'error': 'Application not found'}), 404+ raise not_found('service')if not ResourceGrantService.can_access_app(user, app):- return jsonify({'error': 'Access denied'}), 403+ raise permission_denied()detection = BuildService.detect_build_method(app.root_path)return jsonify(detection), 200@@ -114,10 +115,10 @@ def get_nixpacks_plan(app_id):app = Application.query_active().filter_by(id=app_id).first()if not app:- return jsonify({'error': 'Application not found'}), 404+ raise not_found('service')if not ResourceGrantService.can_access_app(user, app):- return jsonify({'error': 'Access denied'}), 403+ raise permission_denied()result = BuildService.get_nixpacks_plan(app.root_path)return jsonify(result), 200 if result.get('success') else 400@@ -134,10 +135,10 @@ def trigger_build(app_id):app = Application.query_active().filter_by(id=app_id).first()if not app:- return jsonify({'error': 'Application not found'}), 404+ raise not_found('service')if not ResourceGrantService.can_edit_app(user, app):- return jsonify({'error': 'Access denied'}), 403+ raise permission_denied()data = request.get_json() or {}no_cache = data.get('no_cache', False)@@ -155,10 +156,10 @@ def get_build_logs(app_id):app = Application.query_active().filter_by(id=app_id).first()if not app:- return jsonify({'error': 'Application not found'}), 404+ raise not_found('service')if not ResourceGrantService.can_access_app(user, app):- return jsonify({'error': 'Access denied'}), 403+ raise permission_denied()limit = request.args.get('limit', 20, type=int)logs = BuildService.get_build_logs(app_id, limit)@@ -174,10 +175,10 @@ def get_build_log_detail(app_id, timestamp):app = Application.query_active().filter_by(id=app_id).first()if not app:- return jsonify({'error': 'Application not found'}), 404+ raise not_found('service')if not ResourceGrantService.can_access_app(user, app):- return jsonify({'error': 'Access denied'}), 403+ raise permission_denied()log = BuildService.get_build_log_detail(app_id, timestamp)if log:@@ -210,10 +211,10 @@ def deploy_app(app_id):app = Application.query_active().filter_by(id=app_id).first()if not app:- return jsonify({'error': 'Application not found'}), 404+ raise not_found('service')if not ResourceGrantService.can_edit_app(user, app):- return jsonify({'error': 'Access denied'}), 403+ raise permission_denied()data = request.get_json() or {}no_cache = data.get('no_cache', False)@@ -253,10 +254,10 @@ def get_deployments(app_id):app = Application.query_active().filter_by(id=app_id).first()if not app:- return jsonify({'error': 'Application not found'}), 404+ raise not_found('service')if not ResourceGrantService.can_access_app(user, app):- return jsonify({'error': 'Access denied'}), 403+ raise permission_denied()limit = request.args.get('limit', 20, type=int)offset = request.args.get('offset', 0, type=int)@@ -279,13 +280,13 @@ def get_deployment(deployment_id):deployment = Deployment.query.get(deployment_id)if not deployment:- return jsonify({'error': 'Deployment not found'}), 404+ raise not_found('deployment')app = Application.query_active().filter_by(id=deployment.app_id).first()if not app:- return jsonify({'error': 'Application not found'}), 404+ raise not_found('service')if not ResourceGrantService.can_access_app(user, app):- return jsonify({'error': 'Access denied'}), 403+ raise permission_denied()include_logs = request.args.get('include_logs', 'false').lower() == 'true'return jsonify(deployment.to_dict(include_logs=include_logs)), 200@@ -300,13 +301,13 @@ def get_deployment_diff(deployment_id):deployment = Deployment.query.get(deployment_id)if not deployment:- return jsonify({'error': 'Deployment not found'}), 404+ raise not_found('deployment')app = Application.query_active().filter_by(id=deployment.app_id).first()if not app:- return jsonify({'error': 'Application not found'}), 404+ raise not_found('service')if not ResourceGrantService.can_access_app(user, app):- return jsonify({'error': 'Access denied'}), 403+ raise permission_denied()diff = DeploymentService.get_deployment_diff(deployment_id)if diff:@@ -325,10 +326,10 @@ def rollback(app_id):app = Application.query_active().filter_by(id=app_id).first()if not app:- return jsonify({'error': 'Application not found'}), 404+ raise not_found('service')if not ResourceGrantService.can_edit_app(user, app):- return jsonify({'error': 'Access denied'}), 403+ raise permission_denied()data = request.get_json() or {}target_version = data.get('version') # Optional - if not provided, rolls back to previous@@ -351,10 +352,10 @@ def get_current_deployment(app_id):app = Application.query_active().filter_by(id=app_id).first()if not app:- return jsonify({'error': 'Application not found'}), 404+ raise not_found('service')if not ResourceGrantService.can_access_app(user, app):- return jsonify({'error': 'Access denied'}), 403+ raise permission_denied()deployment = DeploymentService.get_current_deployment(app_id)if deployment:diff --git a/backend/app/api/cron.py b/backend/app/api/cron.pyindex 902ba33b..f739a00b 100644--- a/backend/app/api/cron.py+++ b/backend/app/api/cron.py@@ -112,7 +112,7 @@ def create_job():application_id = _validate_application_id(data.get('application_id'))if application_id is _INVALID_APP:- return jsonify({'success': False, 'error': 'Application not found'}), 400+ return jsonify({'success': False, 'error': 'Service not found'}), 400result = CronService.add_job(schedule=schedule,@@ -138,7 +138,7 @@ def update_job(job_id):if set_application:application_id = _validate_application_id(data.get('application_id'))if application_id is _INVALID_APP:- return jsonify({'success': False, 'error': 'Application not found'}), 400+ return jsonify({'success': False, 'error': 'Service not found'}), 400result = CronService.update_job(job_id=job_id,diff --git a/backend/app/api/database_engines.py b/backend/app/api/database_engines.pyindex c96bbccf..52960bd4 100644--- a/backend/app/api/database_engines.py+++ b/backend/app/api/database_engines.py@@ -30,6 +30,7 @@ from app.services import database_engine_extension_service as extensionsfrom app.services import database_engine_service as enginesfrom app.services.deployment_job_service import DeploymentJobServicefrom app.services.template_service import TemplateService+from app.exceptions import not_found, permission_deniedlogger = logging.getLogger(__name__)@@ -139,9 +140,9 @@ def _require_app_access(app_id):return {'error': 'Unauthorized'}, 401app = Application.query_active().filter_by(id=app_id).first()if not app:- return {'error': 'Application not found'}, 404+ raise not_found('service')if not ResourceGrantService.can_access_app(user, app):- return {'error': 'Access denied'}, 403+ raise permission_denied()return Nonediff --git a/backend/app/api/databases.py b/backend/app/api/databases.pyindex b56641f0..7b11295e 100644--- a/backend/app/api/databases.py+++ b/backend/app/api/databases.py@@ -15,6 +15,7 @@ from app.services.db_process_service import DbProcessServicefrom app.services.managed_database_service import ManagedDatabaseServicefrom app.middleware.rbac import admin_required, get_current_user, require_admin_userfrom app.services.resource_grant_service import ResourceGrantService+from app.exceptions import field_required, not_found, permission_deniedlogger = logging.getLogger(__name__)@@ -72,7 +73,7 @@ def create_mysql_database():data = request.get_json()if not data or 'name' not in data:- return jsonify({'error': 'name is required'}), 400+ raise field_required('name')result = DatabaseService.mysql_create_database(data['name'],@@ -143,7 +144,7 @@ def restore_mysql_database(name):data = request.get_json()if not data or 'backup_path' not in data:- return jsonify({'error': 'backup_path is required'}), 400+ raise field_required('backup_path')result = DatabaseService.mysql_restore(name,@@ -174,7 +175,7 @@ def create_mysql_user():data = request.get_json()if not data or 'username' not in data:- return jsonify({'error': 'username is required'}), 400+ raise field_required('username')password = data.get('password') or DatabaseService.generate_password()@@ -231,7 +232,7 @@ def grant_mysql_privileges(username):data = request.get_json()if not data or 'database' not in data:- return jsonify({'error': 'database is required'}), 400+ raise field_required('database')result = DatabaseService.mysql_grant_privileges(username,@@ -250,7 +251,7 @@ def revoke_mysql_privileges(username):data = request.get_json()if not data or 'database' not in data:- return jsonify({'error': 'database is required'}), 400+ raise field_required('database')result = DatabaseService.mysql_revoke_privileges(username,@@ -279,7 +280,7 @@ def create_pg_database():data = request.get_json()if not data or 'name' not in data:- return jsonify({'error': 'name is required'}), 400+ raise field_required('name')result = DatabaseService.pg_create_database(data['name'],@@ -332,7 +333,7 @@ def restore_pg_database(name):data = request.get_json()if not data or 'backup_path' not in data:- return jsonify({'error': 'backup_path is required'}), 400+ raise field_required('backup_path')result = DatabaseService.pg_restore(name, data['backup_path'])return jsonify(result), 200 if result['success'] else 400@@ -355,7 +356,7 @@ def create_pg_user():data = request.get_json()if not data or 'username' not in data:- return jsonify({'error': 'username is required'}), 400+ raise field_required('username')password = data.get('password') or DatabaseService.generate_password()@@ -390,7 +391,7 @@ def grant_pg_privileges(username):data = request.get_json()if not data or 'database' not in data:- return jsonify({'error': 'database is required'}), 400+ raise field_required('database')result = DatabaseService.pg_grant_privileges(username,@@ -407,7 +408,7 @@ def revoke_pg_privileges(username):data = request.get_json()if not data or 'database' not in data:- return jsonify({'error': 'database is required'}), 400+ raise field_required('database')result = DatabaseService.pg_revoke_privileges(username,@@ -452,7 +453,7 @@ def execute_mysql_query(name):data = request.get_json()if not data or 'query' not in data:- return jsonify({'error': 'query is required'}), 400+ raise field_required('query')query = data['query']readonly = data.get('readonly', True)@@ -488,7 +489,7 @@ def execute_pg_query(name):data = request.get_json()if not data or 'query' not in data:- return jsonify({'error': 'query is required'}), 400+ raise field_required('query')query = data['query']readonly = data.get('readonly', True)@@ -669,13 +670,13 @@ def get_app_databases(app_id):app = Application.query_active().filter_by(id=app_id).first()if not app:- return jsonify({'error': 'Application not found'}), 404+ raise not_found('service')if not ResourceGrantService.can_access_app(user, app):- return jsonify({'error': 'Access denied'}), 403+ raise permission_denied()if app.app_type != 'docker' or not app.root_path:- return jsonify({'error': 'Application is not a Docker app'}), 400+ return jsonify({'error': 'This service is not a Docker service'}), 400db_info = DatabaseService.get_app_database_info(app.name, app.root_path)@@ -725,7 +726,7 @@ def execute_docker_query(container, database):data = request.get_json()if not data or 'query' not in data:- return jsonify({'error': 'query is required'}), 400+ raise field_required('query')query = data['query']readonly = data.get('readonly', True)@@ -777,7 +778,7 @@ def create_managed_database():engine = (data.get('engine') or '').strip().lower()name = data.get('name')if not name:- return jsonify({'error': 'name is required'}), 400+ raise field_required('name')if engine not in ('mysql', 'postgresql'):return jsonify({'error': 'engine must be mysql or postgresql'}), 400@@ -841,7 +842,7 @@ def get_managed_database(managed_id):"""Detail + a best-effort live-sync state (does the DB still exist?)."""managed = ManagedDatabaseService.get(managed_id)if not managed:- return jsonify({'error': 'Managed database not found'}), 404+ raise not_found('database')data = managed.to_dict()data['sync'] = ManagedDatabaseService.sync_state(managed)return jsonify({'database': data}), 200@@ -853,7 +854,7 @@ def delete_managed_database(managed_id):"""Untrack a managed database (optional ``?drop=true`` to also DROP it)."""managed = ManagedDatabaseService.get(managed_id)if not managed:- return jsonify({'error': 'Managed database not found'}), 404+ raise not_found('database')drop = str(request.args.get('drop', '')).lower() in ('1', 'true', 'yes')from flask_jwt_extended import get_jwt_identityManagedDatabaseService.delete(managed, drop=drop, user_id=get_jwt_identity())@@ -868,7 +869,7 @@ def reveal_managed_connection_uri(managed_id):from app.services.audit_service import AuditServicemanaged = ManagedDatabaseService.get(managed_id)if not managed:- return jsonify({'error': 'Managed database not found'}), 404+ raise not_found('database')uri = ManagedDatabaseService.build_connection_uri(managed, reveal=True)AuditService.log(action=getattr(AuditLog, 'ACTION_SECRET_REVEALED', 'secret.revealed'),@@ -885,7 +886,7 @@ def protect_managed_database(managed_id):"""Create/refresh a BackupPolicy for a managed database (real FK target)."""managed = ManagedDatabaseService.get(managed_id)if not managed:- return jsonify({'error': 'Managed database not found'}), 404+ raise not_found('database')data = request.get_json() or {}policy = ManagedDatabaseService.protect(managed, fields=data.get('policy'))return jsonify({'policy': policy.to_dict()}), 201@@ -897,7 +898,9 @@ def protect_managed_database(managed_id):# shapes (host engine vs docker container).def _process_error_response(result):- code = 400 if result['error'] == 'unsupported engine' else 502+ # The services tag the one client-caused failure with a code; the status+ # never depends on the wording of the error.+ code = 400 if result.get('code') == 'unsupported_engine' else 502return jsonify({'error': result['error']}), codediff --git a/backend/app/api/deploy.py b/backend/app/api/deploy.pyindex 6b269059..93ad6a47 100644--- a/backend/app/api/deploy.py+++ b/backend/app/api/deploy.py@@ -10,6 +10,7 @@ from app.middleware.rbac import admin_required, app_access_tier, developer_requifrom app.models import User, Applicationfrom app.services.git_service import GitServicefrom app.services.resource_grant_service import ResourceGrantService+from app.exceptions import not_found, permission_denieddeploy_bp = Blueprint('deploy', __name__)@@ -23,10 +24,10 @@ def get_deploy_config(app_id):app = Application.query_active().filter_by(id=app_id).first()if not app:- return jsonify({'error': 'Application not found'}), 404+ raise not_found('service')if not ResourceGrantService.can_access_app(user, app):- return jsonify({'error': 'Access denied'}), 403+ raise permission_denied()config = GitService.get_app_config(app_id)if not config:@@ -44,7 +45,7 @@ def configure_deployment(app_id):"""Configure Git deployment for an app."""app = Application.query_active().filter_by(id=app_id).first()if not app:- return jsonify({'error': 'Application not found'}), 404+ raise not_found('service')data = request.get_json()if not data:@@ -83,10 +84,10 @@ def trigger_deploy(app_id):app = Application.query_active().filter_by(id=app_id).first()if not app:- return jsonify({'error': 'Application not found'}), 404+ raise not_found('service')if not ResourceGrantService.can_edit_app(user, app):- return jsonify({'error': 'Access denied'}), 403+ raise permission_denied()data = request.get_json() or {}result = GitService.deploy(app_id, force=data.get('force', False))@@ -103,10 +104,10 @@ def pull_changes(app_id):app = Application.query_active().filter_by(id=app_id).first()if not app:- return jsonify({'error': 'Application not found'}), 404+ raise not_found('service')if not ResourceGrantService.can_edit_app(user, app):- return jsonify({'error': 'Access denied'}), 403+ raise permission_denied()data = request.get_json() or {}result = GitService.pull_changes(app.root_path, data.get('branch'))@@ -123,10 +124,10 @@ def get_git_status(app_id):app = Application.query_active().filter_by(id=app_id).first()if not app:- return jsonify({'error': 'Application not found'}), 404+ raise not_found('service')if not ResourceGrantService.can_access_app(user, app):- return jsonify({'error': 'Access denied'}), 403+ raise permission_denied()status = GitService.get_git_status(app.root_path)return jsonify(status), 200@@ -141,10 +142,10 @@ def get_commit_info(app_id):app = Application.query_active().filter_by(id=app_id).first()if not app:- return jsonify({'error': 'Application not found'}), 404+ raise not_found('service')if not ResourceGrantService.can_access_app(user, app):- return jsonify({'error': 'Access denied'}), 403+ raise permission_denied()commit_info = GitService.get_commit_info(app.root_path)if commit_info:@@ -165,11 +166,11 @@ def get_deployment_history():if app_id:app = Application.query_active().filter_by(id=app_id).first()if not app:- return jsonify({'error': 'Application not found'}), 404+ raise not_found('service')if not user or app_access_tier(user, app) is None:- return jsonify({'error': 'Access denied'}), 403+ raise permission_denied()elif not user or not user.is_admin:- return jsonify({'error': 'Access denied'}), 403+ raise permission_denied()history = GitService.get_deployment_history(app_id, limit)return jsonify({'deployments': history}), 200@@ -195,7 +196,7 @@ def clone_repository():base_dir = os.path.abspath(paths.APPS_DIR)app_path = os.path.abspath(data['app_path'])if app_path == base_dir or not app_path.startswith(base_dir + os.sep):- return jsonify({'error': 'app_path must be inside the managed apps directory'}), 400+ return jsonify({'error': 'app_path must be inside the managed services directory'}), 400result = GitService.clone_repository(app_path=app_path,@@ -215,10 +216,10 @@ def get_branches(app_id):app = Application.query_active().filter_by(id=app_id).first()if not app:- return jsonify({'error': 'Application not found'}), 404+ raise not_found('service')if not ResourceGrantService.can_access_app(user, app):- return jsonify({'error': 'Access denied'}), 403+ raise permission_denied()result = GitService.get_remote_branches(app.root_path)return jsonify(result), 200 if result.get('success') else 400@@ -249,11 +250,11 @@ def get_webhook_logs():if app_id:app = Application.query_active().filter_by(id=app_id).first()if not app:- return jsonify({'error': 'Application not found'}), 404+ raise not_found('service')if not user or app_access_tier(user, app) is None:- return jsonify({'error': 'Access denied'}), 403+ raise permission_denied()elif not user or not user.is_admin:- return jsonify({'error': 'Access denied'}), 403+ raise permission_denied()logs = GitService.get_webhook_logs(app_id, limit)return jsonify({'logs': logs}), 200diff --git a/backend/app/api/deployment_jobs.py b/backend/app/api/deployment_jobs.pyindex 0a837780..b285c3ac 100644--- a/backend/app/api/deployment_jobs.py+++ b/backend/app/api/deployment_jobs.py@@ -12,6 +12,7 @@ from app.models import User, Applicationfrom app.models.deployment_job import DeploymentJob, DeploymentJobLogfrom app.services.deployment_job_service import DeploymentJobServicefrom app.services.resource_grant_service import ResourceGrantService+from app.exceptions import not_found, permission_denieddeployment_jobs_bp = Blueprint('deployment_jobs', __name__)@@ -108,12 +109,12 @@ def list_deployment_jobs():if app_id:app = Application.query_active().filter_by(id=app_id).first()if not app:- return jsonify({'error': 'Application not found'}), 404+ raise not_found('service')if not user or app_access_tier(user, app) is None:- return jsonify({'error': 'Access denied'}), 403+ raise permission_denied()scoped_app = appelif not user or not user.is_admin:- return jsonify({'error': 'Access denied'}), 403+ raise permission_denied()jobs = DeploymentJobService.list_jobs(status=status,@@ -139,10 +140,10 @@ def get_deployment_job(job_id):include_plan = request.args.get('plan', 'false').lower() == 'true'job = DeploymentJob.query.get(job_id)if not job:- return jsonify({'error': 'Deployment job not found'}), 404+ raise not_found('deployment')user = get_current_user()if not user or not _job_visible_to(user, job):- return jsonify({'error': 'Access denied'}), 403+ raise permission_denied()return jsonify({'job': _job_payload(job, user, include_logs=include_logs, include_plan=include_plan,)}), 200@@ -155,15 +156,17 @@ def retry_deployment_job(job_id):(plan 51 D8). Only failed jobs may be retried."""job = DeploymentJob.query.get(job_id)if not job:- return jsonify({'error': 'Deployment job not found'}), 404+ raise not_found('deployment')user = get_current_user()if not user or not _job_operable_by(user, job):- return jsonify({'error': 'Access denied'}), 403+ raise permission_denied()result = DeploymentJobService.retry_job(job_id, user_id=get_jwt_identity())if not result.get('success'):- # Distinguish "no such job" from a state/enqueue error.- status = 404 if result.get('error') == 'Deployment job not found' else 400- return jsonify({'error': result.get('error')}), status+ # Distinguish "no such job" from a state/enqueue error by the result's+ # code, never by its wording.+ if result.get('code') == 'not_found':+ raise not_found('deployment')+ return jsonify({'error': result.get('error')}), 400if result.get('job'):# A retry creates a pending clone. It has neither a retry nor cancel# endpoint at this point, matching the capability contract above.@@ -177,10 +180,10 @@ def retry_deployment_job(job_id):def get_deployment_job_logs(job_id):job = DeploymentJob.query.get(job_id)if not job:- return jsonify({'error': 'Deployment job not found'}), 404+ raise not_found('deployment')user = get_current_user()if not user or not _job_visible_to(user, job):- return jsonify({'error': 'Access denied'}), 403+ raise permission_denied()after_id = request.args.get('after_id', type=int)query = DeploymentJobLog.query.filter_by(job_id=job_id)diff --git a/backend/app/api/deployments.py b/backend/app/api/deployments.pyindex ca425d06..7d37ead1 100644--- a/backend/app/api/deployments.py+++ b/backend/app/api/deployments.py@@ -16,6 +16,7 @@ from app.models import Applicationfrom app.models.deployment import Deploymentfrom app.models.webhook import GitDeploymentfrom app.middleware.rbac import get_current_user+from app.exceptions import not_found, permission_denieddeployments_bp = Blueprint('deployments', __name__)@@ -25,9 +26,9 @@ def _access(app_id):user = get_current_user()app = Application.query_active().filter_by(id=app_id).first()if not app:- return None, (jsonify({'error': 'Application not found'}), 404)+ raise not_found('service')if not ResourceGrantService.can_access_app(user, app):- return None, (jsonify({'error': 'Access denied'}), 403)+ raise permission_denied()return app, None@@ -70,7 +71,7 @@ def get_deployment(deployment_id):"""A versioned build Deployment by id (the release ledger detail)."""d = Deployment.query.get(deployment_id)if not d:- return jsonify({'error': 'Deployment not found'}), 404+ raise not_found('deployment')_, err = _access(d.app_id)if err:return errdiff --git a/backend/app/api/dns_cutover.py b/backend/app/api/dns_cutover.pyindex 48e9fdae..17bf7fd1 100644--- a/backend/app/api/dns_cutover.py+++ b/backend/app/api/dns_cutover.py@@ -13,6 +13,7 @@ from flask_jwt_extended import jwt_requiredfrom app.services.dns_cutover_service import DnsCutoverService, DnsCutoverErrorfrom app.middleware.rbac import require_admin_user+from app.exceptions import not_founddns_cutover_bp = Blueprint('dns_cutover', __name__)@@ -62,7 +63,7 @@ def list_snapshots():def get_snapshot(snapshot_id):snapshot = DnsCutoverService.get_snapshot(snapshot_id)if not snapshot:- return jsonify({'error': 'Snapshot not found'}), 404+ raise not_found('snapshot')return jsonify(snapshot.to_dict())@@ -77,7 +78,7 @@ def cutover():'snapshot so it can be reverted'}), 400snapshot = DnsCutoverService.get_snapshot(snapshot_id)if not snapshot:- return jsonify({'error': 'Snapshot not found'}), 404+ raise not_found('snapshot')try:result = DnsCutoverService.cutover(snapshot, target=data.get('target'),@@ -109,7 +110,7 @@ def revert(snapshot_id):require_admin_user()snapshot = DnsCutoverService.get_snapshot(snapshot_id)if not snapshot:- return jsonify({'error': 'Snapshot not found'}), 404+ raise not_found('snapshot')try:result = DnsCutoverService.revert(snapshot)return jsonify(result)diff --git a/backend/app/api/docker.py b/backend/app/api/docker.pyindex 7d1f17e8..807094a4 100644--- a/backend/app/api/docker.py+++ b/backend/app/api/docker.py@@ -614,7 +614,7 @@ def cleanup_all_apps():return jsonify({'success': True,- 'message': f'Removed {len(results)} apps',+ 'message': f'Removed {len(results)} services','results': results}), 200diff --git a/backend/app/api/domains.py b/backend/app/api/domains.pyindex d358a7f2..d54391a9 100644--- a/backend/app/api/domains.py+++ b/backend/app/api/domains.py@@ -10,6 +10,7 @@ from app.models import Domain, Application, Userfrom app.services.nginx_service import NginxServicefrom app.services.ssl_service import SSLService, get_acme_contact, remember_acme_contactfrom app.services.resource_grant_service import ResourceGrantService+from app.exceptions import already_exists, not_found, permission_denieddomains_bp = Blueprint('domains', __name__)@@ -126,16 +127,16 @@ def get_domain(domain_id):domain = Domain.query_active().filter_by(id=domain_id).first()if not domain:- return jsonify({'error': 'Domain not found'}), 404+ raise not_found('domain')# A soft-deleted app keeps its Domain rows (only the vhost is torn down), so# every route here has to resolve the parent live or a deleted app's domains# stay reachable — and operable, up to a real ACME order in enable_ssl.app = Application.query_active().filter_by(id=domain.application_id).first()if not app:- return jsonify({'error': 'Domain not found'}), 404+ raise not_found('domain')if not ResourceGrantService.can_access_app(user, app):- return jsonify({'error': 'Access denied'}), 403+ raise permission_denied()return jsonify({'domain': domain.to_dict()}), 200@@ -166,23 +167,23 @@ def create_domain():# Check if domain already existsif Domain.query_active().filter_by(name=name).first():- return jsonify({'error': 'Domain already exists'}), 409+ raise already_exists('domain')# Check if application exists and user has accessapp = Application.query_active().filter_by(id=application_id).first()if not app:- return jsonify({'error': 'Application not found'}), 404+ raise not_found('service')if not ResourceGrantService.can_edit_app(user, app):- return jsonify({'error': 'Access denied'}), 403+ raise permission_denied()# For Docker apps, validate port configurationport_warning = Noneif app.app_type == 'docker':if not app.port:return jsonify({- 'error': 'Docker app must have a port configured before adding domains',- 'hint': 'Update the application with a valid port number first'+ 'error': 'Set a port on this service before adding domains',+ 'hint': 'Open the service settings and set its port, then add the domain'}), 400# Check if port is accessible (warning only, don't block)@@ -281,9 +282,9 @@ def give_subdomain():app = (Application.query_active().filter_by(id=data.get('application_id')).first()if data.get('application_id') else None)if not app:- return jsonify({'error': 'Application not found'}), 404+ raise not_found('service')if not ResourceGrantService.can_edit_app(user, app):- return jsonify({'error': 'Access denied'}), 403+ raise permission_denied()from app.services.site_domain_service import SiteDomainServiceresult = SiteDomainService.give_subdomain(app, label=data.get('label'), base=data.get('base'))@@ -298,13 +299,13 @@ def update_domain(domain_id):domain = Domain.query_active().filter_by(id=domain_id).first()if not domain:- return jsonify({'error': 'Domain not found'}), 404+ raise not_found('domain')app = Application.query_active().filter_by(id=domain.application_id).first()if not app:- return jsonify({'error': 'Domain not found'}), 404+ raise not_found('domain')if not ResourceGrantService.can_edit_app(user, app):- return jsonify({'error': 'Access denied'}), 403+ raise permission_denied()data = request.get_json()@@ -334,13 +335,13 @@ def delete_domain(domain_id):domain = Domain.query_active().filter_by(id=domain_id).first()if not domain:- return jsonify({'error': 'Domain not found'}), 404+ raise not_found('domain')app = Application.query_active().filter_by(id=domain.application_id).first()if not app:- return jsonify({'error': 'Domain not found'}), 404+ raise not_found('domain')if not ResourceGrantService.can_edit_app(user, app):- return jsonify({'error': 'Access denied'}), 403+ raise permission_denied()application_id = domain.application_id# Soft delete: the vhost teardown below still happens, but the record keeps@@ -377,13 +378,13 @@ def enable_ssl(domain_id):domain = Domain.query_active().filter_by(id=domain_id).first()if not domain:- return jsonify({'error': 'Domain not found'}), 404+ raise not_found('domain')app = Application.query_active().filter_by(id=domain.application_id).first()if not app:- return jsonify({'error': 'Domain not found'}), 404+ raise not_found('domain')if not ResourceGrantService.can_edit_app(user, app):- return jsonify({'error': 'Access denied'}), 403+ raise permission_denied()data = request.get_json() or {}# An address on the request wins; otherwise the panel-wide ACME contact,@@ -439,13 +440,13 @@ def disable_ssl(domain_id):domain = Domain.query_active().filter_by(id=domain_id).first()if not domain:- return jsonify({'error': 'Domain not found'}), 404+ raise not_found('domain')app = Application.query_active().filter_by(id=domain.application_id).first()if not app:- return jsonify({'error': 'Domain not found'}), 404+ raise not_found('domain')if not ResourceGrantService.can_edit_app(user, app):- return jsonify({'error': 'Access denied'}), 403+ raise permission_denied()domain.ssl_enabled = Falsedb.session.commit()@@ -464,13 +465,13 @@ def renew_ssl(domain_id):domain = Domain.query_active().filter_by(id=domain_id).first()if not domain:- return jsonify({'error': 'Domain not found'}), 404+ raise not_found('domain')app = Application.query_active().filter_by(id=domain.application_id).first()if not app:- return jsonify({'error': 'Domain not found'}), 404+ raise not_found('domain')if not ResourceGrantService.can_edit_app(user, app):- return jsonify({'error': 'Access denied'}), 403+ raise permission_denied()if not domain.ssl_enabled:return jsonify({'error': 'SSL is not enabled for this domain'}), 400@@ -505,7 +506,7 @@ def verify_domain(domain_id):domain = Domain.query_active().filter_by(id=domain_id).first()if not domain:- return jsonify({'error': 'Domain not found'}), 404+ raise not_found('domain')try:ips = _resolve_host_ips(domain.name)@@ -576,13 +577,13 @@ def regenerate_nginx_config(app_id):app = Application.query_active().filter_by(id=app_id).first()if not app:- return jsonify({'error': 'Application not found'}), 404+ raise not_found('service')if app.app_type != 'docker':- return jsonify({'error': 'This endpoint is only for Docker apps'}), 400+ return jsonify({'error': 'This only works for Docker services'}), 400if not app.port:- return jsonify({'error': 'Application does not have a port configured'}), 400+ return jsonify({'error': 'This service has no port. Set one in the service settings.'}), 400# Get all domains for this app# query_active: a tombstone here would be written back into server_name,@@ -590,7 +591,7 @@ def regenerate_nginx_config(app_id):domains = [d.name for d in Domain.query_active().filter_by(application_id=app_id).all()]if not domains:- return jsonify({'error': 'No domains configured for this application'}), 400+ return jsonify({'error': 'This service has no domains. Add one first.'}), 400# Create nginx site configresult = NginxService.create_site(@@ -637,7 +638,7 @@ def diagnose_app_routing(app_id):app = Application.query_active().filter_by(id=app_id).first()if not app:- return jsonify({'error': 'Application not found'}), 404+ raise not_found('service')diagnosis = {'app': {@@ -731,10 +732,10 @@ def test_app_routing(app_id):"""app = Application.query_active().filter_by(id=app_id).first()if not app:- return jsonify({'error': 'Application not found'}), 404+ raise not_found('service')if not app.port:- return jsonify({'error': 'Application has no port configured'}), 400+ return jsonify({'error': 'This service has no port. Set one in the service settings.'}), 400# Get primary domain or first domaindomain = Domain.query_active().filter_by(application_id=app_id, is_primary=True).first()diff --git a/backend/app/api/env_vars.py b/backend/app/api/env_vars.pyindex ea2f823f..e3bf46ba 100644--- a/backend/app/api/env_vars.py+++ b/backend/app/api/env_vars.py@@ -13,6 +13,7 @@ from flask_jwt_extended import jwt_required, get_jwt_identityfrom app.models import Application, Userfrom app.services.env_service import EnvServicefrom app.services.resource_grant_service import ResourceGrantService+from app.exceptions import not_found, permission_deniedenv_vars_bp = Blueprint('env_vars', __name__)@@ -28,12 +29,12 @@ def check_app_access(app_id, user_id, write=False):app = Application.query_active().filter_by(id=app_id).first()if not app:- return None, None, jsonify({'error': 'Application not found'}), 404+ raise not_found('service')ok = (ResourceGrantService.can_edit_app(user, app) if writeelse ResourceGrantService.can_access_app(user, app))if not ok:- return None, None, jsonify({'error': 'Access denied'}), 403+ raise permission_denied()return user, app, None, Nonediff --git a/backend/app/api/environments.py b/backend/app/api/environments.pyindex d91af8a6..e7d2ccaf 100644--- a/backend/app/api/environments.py+++ b/backend/app/api/environments.py@@ -9,6 +9,7 @@ from flask_jwt_extended import jwt_requiredfrom app.services.project_service import ProjectServicefrom app.services.workspace_service import WorkspaceServicefrom app.middleware.rbac import get_current_user+from app.exceptions import permission_deniedenvironments_bp = Blueprint('environments', __name__)@@ -31,7 +32,7 @@ def _project_for_write(user, project_id):if not project:return None, (jsonify({'error': 'Project not found'}), 404)if not user.is_admin and project.workspace_id not in set(_accessible_workspace_ids(user)):- return None, (jsonify({'error': 'Access denied'}), 403)+ raise permission_denied()if not WorkspaceService.can_write_in_workspace(user, project.workspace_id):return None, (jsonify({'error': 'You have read-only access to this workspace'}), 403)return project, Nonediff --git a/backend/app/api/files.py b/backend/app/api/files.pyindex eabefd5d..3423a2d2 100644--- a/backend/app/api/files.py+++ b/backend/app/api/files.py@@ -2,7 +2,7 @@from flask import Blueprint, request, jsonify, send_filefrom app.error_reporting import unexpected_response-from app.exceptions import NotFoundError, PermissionDeniedError, ValidationError+from app.exceptions import NotFoundError, PermissionDeniedError, ValidationError, permission_deniedfrom ..middleware.rbac import permission_requiredfrom ..services.file_service import FileServicefrom ..services.storage_provider_service import StorageProviderService@@ -285,7 +285,7 @@ def download_file():raise ValidationError('Path is required')if not FileService.is_path_allowed(path):- return jsonify({'error': 'Access denied'}), 403+ raise permission_denied()if not os.path.exists(path):return jsonify({'error': 'File not found'}), 404@@ -319,7 +319,7 @@ def upload_file():# Upload writes straight to disk without going through FileService's# mutating methods, so it has to repeat the writable check itself.if not FileService.is_path_writable(destination):- return jsonify({'error': 'Access denied'}), 403+ raise permission_denied()if file.filename == '':return jsonify({'error': 'No file selected'}), 400diff --git a/backend/app/api/git.py b/backend/app/api/git.pyindex 8c8e892b..52f8daad 100644--- a/backend/app/api/git.py+++ b/backend/app/api/git.py@@ -17,6 +17,7 @@ from ..middleware.rbac import (from ..models import Application, GitWebhookfrom ..services.webhook_service import WebhookServicefrom ..services.git_deploy_service import GitDeployService+from app.exceptions import not_found, permission_deniedgit_bp = Blueprint('git', __name__)@@ -217,11 +218,11 @@ def get_deployment(deployment_id):deployment = GitDeployment.query.get(deployment_id)if deployment is None:- return jsonify({'success': False, 'error': 'Deployment not found'}), 404+ raise not_found('deployment')app = Application.query_active().filter_by(id=deployment.app_id).first()if app is None or app_access_tier(get_current_user(), app) is None:- return jsonify({'success': False, 'error': 'Access denied'}), 403+ raise permission_denied()include_logs = request.args.get('logs', 'false').lower() == 'true'result = GitDeployService.get_deployment(deployment_id, include_logs=include_logs)@@ -269,7 +270,7 @@ def get_webhook_deployments(webhook_id):if webhook is None:return jsonify({'success': False, 'error': 'Webhook not found'}), 404if not _webhook_visible_to(get_current_user(), webhook):- return jsonify({'success': False, 'error': 'Access denied'}), 403+ raise permission_denied()limit = request.args.get('limit', 20, type=int)deployments = GitDeployment.query.filter_by(webhook_id=webhook_id)\diff --git a/backend/app/api/managed_db_users.py b/backend/app/api/managed_db_users.pyindex efa7af29..6294d627 100644--- a/backend/app/api/managed_db_users.py+++ b/backend/app/api/managed_db_users.py@@ -13,6 +13,7 @@ from flask import Blueprint, request, jsonifyfrom app.middleware.rbac import admin_required, developer_requiredfrom app.services.managed_database_service import ManagedDatabaseServicefrom app.services.managed_db_user_service import ManagedDbUserService+from app.exceptions import not_foundlogger = logging.getLogger(__name__)@@ -22,7 +23,7 @@ managed_db_users_bp = Blueprint('managed_db_users', __name__)def _get_managed_or_404(managed_id):managed = ManagedDatabaseService.get(managed_id)if not managed:- return None, (jsonify({'error': 'Managed database not found'}), 404)+ raise not_found('database')return managed, None@@ -68,7 +69,7 @@ def delete_managed_db_user(managed_id, user_id):row = ManagedDatabaseUser.query.filter_by(id=user_id, managed_database_id=managed.id).first()if not row:- return jsonify({'error': 'User not found'}), 404+ raise not_found('user')result = ManagedDbUserService.delete_user(managed, row)if 'error' in result:return jsonify({'error': result['error']}), 400@@ -91,7 +92,7 @@ def launch_managed_db_sso(managed_id):descriptor = DbAdminSsoService.launch(managed, requested_by=getattr(user, 'id', None))if 'error' in descriptor:- status = 400 if descriptor['error'] != 'Docker required' else 503+ status = 503 if descriptor.get('code') == 'docker_required' else 400return jsonify({'error': descriptor['error']}), status# Build the browser-reachable URL from the panel host the client used.diff --git a/backend/app/api/manifests.py b/backend/app/api/manifests.pyindex 8f16f47d..e16b983b 100644--- a/backend/app/api/manifests.py+++ b/backend/app/api/manifests.py@@ -17,6 +17,7 @@ from app.services.manifest_spec_service import ManifestSpecService, ManifestErrofrom app.services.manifest_apply_service import ManifestApplyServicefrom app.services.manifest_persistence_service import ManifestPersistenceServicefrom app.middleware.rbac import require_admin_user+from app.exceptions import not_foundmanifests_bp = Blueprint('manifests', __name__)@@ -54,7 +55,7 @@ def scaffold_manifest():app = Application.query_active().filter_by(id=app_id).first()if not app:- return jsonify({'error': 'Application not found'}), 404+ raise not_found('service')fmt = (request.args.get('format') or 'json').lower()if fmt == 'yaml':@@ -175,9 +176,9 @@ def reset_bootstrap():app = (Application.query_active().filter_by(id=data.get('app_id')).first()if data.get('app_id') else None)if not app:- return jsonify({'error': 'Application not found'}), 404+ raise not_found('service')if (data.get('confirm') or '') != app.name:- return jsonify({'error': f'Type the app name "{app.name}" to confirm'}), 400+ return jsonify({'error': f'Type the service name "{app.name}" to confirm'}), 400app.bootstrap_done = Falsedb.session.commit()return jsonify({'success': True, 'app_id': app.id, 'bootstrap_done': False}), 200diff --git a/backend/app/api/mobile.py b/backend/app/api/mobile.pyindex 51986499..44086dd7 100644--- a/backend/app/api/mobile.py+++ b/backend/app/api/mobile.py@@ -2,6 +2,7 @@ from flask import Blueprint, request, jsonifyfrom flask_jwt_extended import jwt_required, get_jwt_identityfrom app.models.user import Userfrom app import db+from app.exceptions import not_foundmobile_bp = Blueprint('mobile', __name__)@@ -20,7 +21,7 @@ def register_push():user = User.query.get(user_id)if not user:- return jsonify({'error': 'User not found'}), 404+ raise not_found('user')# Store push subscription in user metadataimport jsondiff --git a/backend/app/api/previews.py b/backend/app/api/previews.pyindex 74eb1cb3..60fb6824 100644--- a/backend/app/api/previews.py+++ b/backend/app/api/previews.py@@ -14,6 +14,8 @@ from app.models.application_preview import ApplicationPreviewfrom app.services.preview_service import PreviewServicefrom app.services.resource_grant_service import ResourceGrantServicefrom app.middleware.rbac import get_current_user+from app.error_reporting import unexpected_response+from app.exceptions import not_foundpreviews_bp = Blueprint('previews', __name__)@@ -24,12 +26,12 @@ def _get_app_or_404(app_id, write=False):members). A caller without the needed tier gets a sealed 404 (no leak)."""app = Application.query_active().filter_by(id=app_id).first()if not app:- return None, (jsonify({'error': 'Application not found'}), 404)+ raise not_found('service')user = get_current_user()ok = ResourceGrantService.can_edit_app(user, app) if write \else ResourceGrantService.can_access_app(user, app)if not ok:- return None, (jsonify({'error': 'Application not found'}), 404)+ raise not_found('service')return app, None@@ -69,7 +71,8 @@ def update_preview_settings(app_id):try:result = PreviewService.enable_previews(app_id, data)except Exception as exc: # pragma: no cover - defensive- return jsonify({'error': str(exc)}), 400+ # Only a failed commit lands here: a crash, not the caller's mistake.+ return unexpected_response(exc)return jsonify(result), 200diff --git a/backend/app/api/private_urls.py b/backend/app/api/private_urls.pyindex fa0079d0..7d3df785 100644--- a/backend/app/api/private_urls.py+++ b/backend/app/api/private_urls.py@@ -9,6 +9,7 @@ from app.models import Application, Userfrom app.services.private_url_service import PrivateURLServicefrom app.services.nginx_service import NginxServicefrom app.services.resource_grant_service import ResourceGrantService+from app.exceptions import not_found, permission_deniedprivate_urls_bp = Blueprint('private_urls', __name__)@@ -31,10 +32,10 @@ def enable_private_url(app_id):app = Application.query_active().filter_by(id=app_id).first()if not app:- return jsonify({'error': 'Application not found'}), 404+ raise not_found('service')if not ResourceGrantService.can_edit_app(user, app):- return jsonify({'error': 'Access denied'}), 403+ raise permission_denied()# Check if already enabledif app.private_url_enabled:@@ -93,10 +94,10 @@ def get_private_url(app_id):app = Application.query_active().filter_by(id=app_id).first()if not app:- return jsonify({'error': 'Application not found'}), 404+ raise not_found('service')if not ResourceGrantService.can_access_app(user, app):- return jsonify({'error': 'Access denied'}), 403+ raise permission_denied()return jsonify({'private_url_enabled': app.private_url_enabled,@@ -123,13 +124,13 @@ def update_private_url(app_id):app = Application.query_active().filter_by(id=app_id).first()if not app:- return jsonify({'error': 'Application not found'}), 404+ raise not_found('service')if not ResourceGrantService.can_edit_app(user, app):- return jsonify({'error': 'Access denied'}), 403+ raise permission_denied()if not app.private_url_enabled:- return jsonify({'error': 'Private URL is not enabled for this app'}), 400+ return jsonify({'error': 'Private URL is not enabled for this service'}), 400data = request.get_json()if not data or 'slug' not in data:@@ -175,13 +176,13 @@ def disable_private_url(app_id):app = Application.query_active().filter_by(id=app_id).first()if not app:- return jsonify({'error': 'Application not found'}), 404+ raise not_found('service')if not ResourceGrantService.can_edit_app(user, app):- return jsonify({'error': 'Access denied'}), 403+ raise permission_denied()if not app.private_url_enabled:- return jsonify({'error': 'Private URL is not enabled for this app'}), 400+ return jsonify({'error': 'Private URL is not enabled for this service'}), 400old_slug = app.private_slugapp.private_slug = None@@ -212,13 +213,13 @@ def regenerate_private_url(app_id):app = Application.query_active().filter_by(id=app_id).first()if not app:- return jsonify({'error': 'Application not found'}), 404+ raise not_found('service')if not ResourceGrantService.can_edit_app(user, app):- return jsonify({'error': 'Access denied'}), 403+ raise permission_denied()if not app.private_url_enabled:- return jsonify({'error': 'Private URL is not enabled for this app'}), 400+ return jsonify({'error': 'Private URL is not enabled for this service'}), 400old_slug = app.private_slugnew_slug = PrivateURLService.generate_unique_slug()diff --git a/backend/app/api/projects.py b/backend/app/api/projects.pyindex 216b36cf..d0d08646 100644--- a/backend/app/api/projects.py+++ b/backend/app/api/projects.py@@ -13,6 +13,7 @@ from app.models.project import Projectfrom app.services.project_service import ProjectServicefrom app.services.workspace_service import WorkspaceServicefrom app.middleware.rbac import get_current_user+from app.exceptions import permission_deniedprojects_bp = Blueprint('projects', __name__)@@ -101,7 +102,7 @@ def get_project(project_id):if not project:return jsonify({'error': 'Project not found'}), 404if not _can_view_project(user, project):- return jsonify({'error': 'Access denied'}), 403+ raise permission_denied()result = project.to_dict(include_counts=True)result['environments'] = [e.to_dict(include_counts=True)@@ -117,7 +118,7 @@ def update_project(project_id):if not project:return jsonify({'error': 'Project not found'}), 404if not _can_view_project(user, project):- return jsonify({'error': 'Access denied'}), 403+ raise permission_denied()if not WorkspaceService.can_write_in_workspace(user, project.workspace_id):return jsonify({'error': 'You have read-only access to this workspace'}), 403@@ -140,7 +141,7 @@ def delete_project(project_id):if not project:return jsonify({'error': 'Project not found'}), 404if not _can_view_project(user, project):- return jsonify({'error': 'Access denied'}), 403+ raise permission_denied()if not WorkspaceService.can_write_in_workspace(user, project.workspace_id):return jsonify({'error': 'You have read-only access to this workspace'}), 403diff --git a/backend/app/api/python.py b/backend/app/api/python.pyindex 31549532..064bb9d4 100644--- a/backend/app/api/python.py+++ b/backend/app/api/python.py@@ -7,6 +7,7 @@ from app.middleware.rbac import admin_requiredfrom app.models import User, Applicationfrom app.services.python_service import PythonServicefrom app import db+from app.exceptions import not_found, permission_deniedpython_bp = Blueprint('python', __name__)@@ -21,13 +22,13 @@ def get_app_or_404(app_id, current_user_id):app = Application.query_active().filter_by(id=app_id).first()if not app:- return None, ({'error': 'Application not found'}, 404)+ raise not_found('service')if not ResourceGrantService.can_access_app(user, app):- return None, ({'error': 'Access denied'}, 403)+ raise permission_denied()if app.app_type not in ['flask', 'django']:- return None, ({'error': 'Application is not a Python app'}, 400)+ return None, ({'error': 'This service is not a Python service'}, 400)return app, None@@ -101,7 +102,7 @@ def create_flask_app():return jsonify({'success': True,'app_id': app.id,- 'message': 'Flask application created successfully'+ 'message': 'Flask service created'}), 201@@ -161,7 +162,7 @@ def create_django_app():'success': True,'app_id': app.id,'project_name': result.get('project_name'),- 'message': 'Django application created successfully'+ 'message': 'Django service created'}), 201@@ -395,7 +396,7 @@ def collect_static(app_id):return jsonify(error[0]), error[1]if app.app_type != 'django':- return jsonify({'error': 'Only supported for Django apps'}), 400+ return jsonify({'error': 'This only works for Django services'}), 400result = PythonService.collect_static(app.root_path, app.app_type)return jsonify(result), 200 if result['success'] else 400diff --git a/backend/app/api/recycle_bin.py b/backend/app/api/recycle_bin.pyindex 9fc1b89d..dd0df2db 100644--- a/backend/app/api/recycle_bin.py+++ b/backend/app/api/recycle_bin.py@@ -7,6 +7,7 @@ from flask import Blueprint, jsonify, requestfrom flask_jwt_extended import jwt_required, get_jwt_identityfrom app.middleware.rbac import admin_required+from app.exceptions import NotFoundErrorfrom app.services import recycle_bin_servicerecycle_bin_bp = Blueprint('recycle_bin', __name__)@@ -53,7 +54,9 @@ def purge(kind, record_id):except KeyError:return jsonify({'error': f'Unknown kind: {kind}'}), 400if not ok:- return jsonify({'error': err}), 404 if err == 'not found' else 400+ if err is recycle_bin_service.PURGE_NOT_FOUND:+ raise NotFoundError('Item not found in the recycle bin')+ return jsonify({'error': err}), 400return jsonify({'success': True})diff --git a/backend/app/api/restore_points.py b/backend/app/api/restore_points.pyindex 0083d84f..bb1f1fbe 100644--- a/backend/app/api/restore_points.py+++ b/backend/app/api/restore_points.py@@ -48,7 +48,7 @@ def _authorize_scope(user, scope_type, scope_id, *, write=False):ResourceGrantService.can_access_app(user, application))if not allowed:- raise PermissionDeniedError('Access denied to application scope')+ raise PermissionDeniedError("You don't have access to this service")return application_require_developer(user)diff --git a/backend/app/api/server_templates.py b/backend/app/api/server_templates.pyindex 6e1c9fc6..5ce4d069 100644--- a/backend/app/api/server_templates.py+++ b/backend/app/api/server_templates.py@@ -4,6 +4,7 @@ from app.services.server_template_service import ServerTemplateServicefrom app.services.audit_service import AuditServicefrom app.models.audit_log import AuditLogfrom app.middleware.rbac import admin_required, get_current_user+from app.exceptions import not_foundserver_templates_bp = Blueprint('server_templates', __name__)@@ -40,7 +41,7 @@ def create_from_library(key):def get_template(template_id):template = ServerTemplateService.get_template(template_id)if not template:- return jsonify({'error': 'Template not found'}), 404+ raise not_found('template')return jsonify(template.to_dict())@@ -77,7 +78,7 @@ def update_template(template_id):data = request.get_json()template = ServerTemplateService.update_template(template_id, data)if not template:- return jsonify({'error': 'Template not found'}), 404+ raise not_found('template')return jsonify(template.to_dict())diff --git a/backend/app/api/servers.py b/backend/app/api/servers.pyindex b0483219..12b1ee59 100644--- a/backend/app/api/servers.py+++ b/backend/app/api/servers.py@@ -26,7 +26,7 @@ from app.services.discovery_service import discovery_servicefrom app.services import connection_string as connection_string_codecfrom app.middleware.rbac import admin_required, auth_required, developer_required, get_current_userfrom app.middleware.api_scope_middleware import require_scope-from app.exceptions import ValidationError+from app.exceptions import ValidationError, agent_offline, field_required, not_found# Default token lifetime when the caller doesn't specify one. 7 days is@@ -186,7 +186,7 @@ def create_group():data = request.get_json()if not data.get('name'):- return jsonify({'error': 'Name is required'}), 400+ raise field_required('Name')group = ServerGroup(name=data['name'],@@ -437,7 +437,7 @@ def set_server_workspace(server_id):user = get_current_user()server = Server.query.get(server_id)if not server:- return jsonify({'error': 'Server not found'}), 404+ raise not_found('server')target = (request.get_json() or {}).get('workspace_id')if target in (None, '', 'default'):@@ -470,7 +470,7 @@ def get_server(server_id):"""Get a server by ID"""server = Server.query.get(server_id)if not server:- return jsonify({'error': 'Server not found'}), 404+ raise not_found('server')result = server.to_dict(include_metrics=True)# Surface the live transport so the UI can disable / banner features@@ -565,7 +565,7 @@ def update_server(server_id):"""Update a server"""server = Server.query.get(server_id)if not server:- return jsonify({'error': 'Server not found'}), 404+ raise not_found('server')data = request.get_json()@@ -598,7 +598,7 @@ def delete_server(server_id):"""Delete a server"""server = Server.query.get(server_id)if not server:- return jsonify({'error': 'Server not found'}), 404+ raise not_found('server')# Disconnect agent if connectedif agent_registry.is_agent_connected(server_id):@@ -621,7 +621,7 @@ def start_server_onboarding(server_id):server = Server.query.get(server_id)if not server:- return jsonify({'error': 'Server not found'}), 404+ raise not_found('server')try:status = ServerOnboardingService.start(server_id)@@ -638,7 +638,7 @@ def retry_server_onboarding(server_id):server = Server.query.get(server_id)if not server:- return jsonify({'error': 'Server not found'}), 404+ raise not_found('server')try:status = ServerOnboardingService.retry(server_id)@@ -655,7 +655,7 @@ def get_server_onboarding_status(server_id):server = Server.query.get(server_id)if not server:- return jsonify({'error': 'Server not found'}), 404+ raise not_found('server')try:status = ServerOnboardingService.get_status(server_id)@@ -679,7 +679,7 @@ def regenerate_token(server_id):"""server = Server.query.get(server_id)if not server:- return jsonify({'error': 'Server not found'}), 404+ raise not_found('server')data = request.get_json(silent=True) or {}expires_at = _resolve_token_expiry(data.get('expires_in'))@@ -800,7 +800,7 @@ def get_server_status(server_id):"""Get current server status and live metrics"""server = Server.query.get(server_id)if not server:- return jsonify({'error': 'Server not found'}), 404+ raise not_found('server')is_connected = agent_registry.is_agent_connected(server_id)@@ -827,13 +827,10 @@ def ping_server(server_id):"""Force a ping/health check on a server"""server = Server.query.get(server_id)if not server:- return jsonify({'error': 'Server not found'}), 404+ raise not_found('server')if not agent_registry.is_agent_connected(server_id):- return jsonify({- 'success': False,- 'error': 'Agent not connected'- })+ raise agent_offline()# Send system:metrics command to get fresh dataresult = dispatch_agent_command(@@ -853,7 +850,7 @@ def get_server_metrics(server_id):"""Get historical metrics for a server"""server = Server.query.get(server_id)if not server:- return jsonify({'error': 'Server not found'}), 404+ raise not_found('server')# Query parametersfrom_time = request.args.get('from')@@ -984,7 +981,7 @@ def get_command_history(server_id):"""Get command history for a server"""server = Server.query.get(server_id)if not server:- return jsonify({'error': 'Server not found'}), 404+ raise not_found('server')limit = request.args.get('limit', 50, type=int)@@ -1018,7 +1015,7 @@ def get_allowed_ips(server_id):"""Get allowed IPs for a server"""server = Server.query.get(server_id)if not server:- return jsonify({'error': 'Server not found'}), 404+ raise not_found('server')return jsonify({'allowed_ips': server.allowed_ips or [],@@ -1041,7 +1038,7 @@ def update_allowed_ips(server_id):"""server = Server.query.get(server_id)if not server:- return jsonify({'error': 'Server not found'}), 404+ raise not_found('server')data = request.get_json()allowed_ips = data.get('allowed_ips', [])@@ -1071,7 +1068,7 @@ def get_connection_info(server_id):"""Get connection info for a server (current IP, connected status, etc.)"""server = Server.query.get(server_id)if not server:- return jsonify({'error': 'Server not found'}), 404+ raise not_found('server')is_connected = agent_registry.is_agent_connected(server_id)agent = agent_registry.get_agent(server_id) if is_connected else None@@ -1102,13 +1099,10 @@ def rotate_api_key(server_id):"""server = Server.query.get(server_id)if not server:- return jsonify({'error': 'Server not found'}), 404+ raise not_found('server')if not agent_registry.is_agent_connected(server_id):- return jsonify({- 'error': 'Agent must be connected to rotate API key',- 'code': 'AGENT_OFFLINE'- }), 400+ raise agent_offline()# Check if there's already a pending rotationif server.api_key_rotation_id and server.api_key_rotation_expires:@@ -1176,7 +1170,7 @@ def get_server_security_alerts(server_id):"""Get security alerts for a specific server"""server = Server.query.get(server_id)if not server:- return jsonify({'error': 'Server not found'}), 404+ raise not_found('server')status = request.args.get('status')severity = request.args.get('severity')@@ -1556,7 +1550,7 @@ def remote_compose_ps(server_id):data = request.get_json()if not data or not data.get('project_path'):- return jsonify({'error': 'project_path is required'}), 400+ raise field_required('project_path')result = RemoteDockerService.compose_ps(server_id,@@ -1578,7 +1572,7 @@ def remote_compose_up(server_id):data = request.get_json()if not data or not data.get('project_path'):- return jsonify({'error': 'project_path is required'}), 400+ raise field_required('project_path')result = RemoteDockerService.compose_up(server_id,@@ -1602,7 +1596,7 @@ def remote_compose_down(server_id):data = request.get_json()if not data or not data.get('project_path'):- return jsonify({'error': 'project_path is required'}), 400+ raise field_required('project_path')result = RemoteDockerService.compose_down(server_id,@@ -1626,7 +1620,7 @@ def remote_compose_logs(server_id):data = request.get_json()if not data or not data.get('project_path'):- return jsonify({'error': 'project_path is required'}), 400+ raise field_required('project_path')result = RemoteDockerService.compose_logs(server_id,@@ -1650,7 +1644,7 @@ def remote_compose_restart(server_id):data = request.get_json()if not data or not data.get('project_path'):- return jsonify({'error': 'project_path is required'}), 400+ raise field_required('project_path')result = RemoteDockerService.compose_restart(server_id,@@ -1673,7 +1667,7 @@ def remote_compose_pull(server_id):data = request.get_json()if not data or not data.get('project_path'):- return jsonify({'error': 'project_path is required'}), 400+ raise field_required('project_path')result = RemoteDockerService.compose_pull(server_id,@@ -1781,7 +1775,7 @@ def terminal_input(session_id):data = request.get_json()if not data or not data.get('data'):- return jsonify({'error': 'data is required'}), 400+ raise field_required('data')result = TerminalService.send_input(session_id=session_id,@@ -1996,7 +1990,7 @@ def get_install_instructions(server_id):"""server = Server.query.get(server_id)if not server:- return jsonify({'error': 'Server not found'}), 404+ raise not_found('server')# Check if server has a valid registration tokenif not server.registration_token_hash:@@ -2328,13 +2322,10 @@ def trigger_agent_update(server_id):"""server = Server.query.get(server_id)if not server:- return jsonify({'error': 'Server not found'}), 404+ raise not_found('server')if not agent_registry.is_agent_connected(server_id):- return jsonify({- 'success': False,- 'error': 'Agent not connected'- }), 503+ raise agent_offline()# Get latest version inforelease = _get_latest_agent_release()@@ -2382,7 +2373,7 @@ def add_agent_version():data = request.get_json()if not data.get('version'):- return jsonify({'error': 'Version is required'}), 400+ raise field_required('Version')version = AgentVersion(version=data['version'],@@ -2435,7 +2426,7 @@ def start_staged_rollout():user_id = get_jwt_identity()if not version_id:- return jsonify({'error': 'version_id is required'}), 400+ raise field_required('version_id')result = fleet_service.staged_rollout(group_id, version_id, batch_size, delay_minutes,@@ -2595,9 +2586,9 @@ def remote_cron_add(server_id):schedule = (data.get('schedule') or '').strip()command = (data.get('command') or '').strip()if not schedule:- return jsonify({'error': 'schedule is required'}), 400+ raise field_required('schedule')if not command:- return jsonify({'error': 'command is required'}), 400+ raise field_required('command')result = RemoteCronService.add_job(server_id, schedule, command,@@ -2675,7 +2666,7 @@ def remote_cloudflared_create(server_id):data = request.get_json(silent=True) or {}name = (data.get('name') or '').strip()if not name:- return jsonify({'error': 'name is required'}), 400+ raise field_required('name')result = RemoteCloudflaredService.create_tunnel(server_id, name, user_id=user_id)return _agent_result(result, ok_status=201)@@ -2688,7 +2679,7 @@ def remote_cloudflared_route(server_id, tunnel_ref):data = request.get_json(silent=True) or {}hostname = (data.get('hostname') or '').strip()if not hostname:- return jsonify({'error': 'hostname is required'}), 400+ raise field_required('hostname')result = RemoteCloudflaredService.route_tunnel(server_id, tunnel_ref, hostname, user_id=user_id,@@ -2748,7 +2739,7 @@ def remote_packages_search(server_id):user_id = get_jwt_identity()query = (request.args.get('q') or '').strip()if not query:- return jsonify({'error': 'q is required'}), 400+ raise field_required('q')try:limit = int(request.args.get('limit', 100))except (TypeError, ValueError):@@ -2785,7 +2776,7 @@ def remote_packages_install(server_id):if isinstance(names, str):names = [names]if not names:- return jsonify({'error': 'names is required'}), 400+ raise field_required('names')result = RemotePackagesService.install_async(server_id, names, user_id=user_id)return _agent_result(result)@@ -2797,7 +2788,7 @@ def remote_packages_remove(server_id):data = request.get_json(silent=True) or {}name = (data.get('name') or '').strip()if not name:- return jsonify({'error': 'name is required'}), 400+ raise field_required('name')result = RemotePackagesService.remove(server_id, name, user_id=user_id)return _agent_result(result)@@ -2932,7 +2923,7 @@ def remote_runtimes_python_install(server_id):data = request.get_json(silent=True) or {}version = (data.get('version') or '').strip()if not version:- return jsonify({'error': 'version is required'}), 400+ raise field_required('version')result = RemoteRuntimesService.python_install(server_id, version, user_id=user_id)return _agent_result(result)@@ -2944,7 +2935,7 @@ def remote_runtimes_python_uninstall(server_id):data = request.get_json(silent=True) or {}version = (data.get('version') or '').strip()if not version:- return jsonify({'error': 'version is required'}), 400+ raise field_required('version')result = RemoteRuntimesService.python_uninstall(server_id, version, user_id=user_id)return _agent_result(result)@@ -2956,7 +2947,7 @@ def remote_runtimes_python_set_global(server_id):data = request.get_json(silent=True) or {}version = (data.get('version') or '').strip()if not version:- return jsonify({'error': 'version is required'}), 400+ raise field_required('version')result = RemoteRuntimesService.python_set_global(server_id, version, user_id=user_id)return _agent_result(result)@@ -3000,7 +2991,7 @@ def remote_file_browse(server_id):user_id = get_jwt_identity()path = request.args.get('path')if not path:- return jsonify({'error': 'path is required'}), 400+ raise field_required('path')result = RemoteFileService.list_directory(server_id, path, user_id=user_id)return _agent_result(result)@@ -3011,7 +3002,7 @@ def remote_file_read(server_id):user_id = get_jwt_identity()path = request.args.get('path')if not path:- return jsonify({'error': 'path is required'}), 400+ raise field_required('path')result = RemoteFileService.read_file(server_id, path, user_id=user_id)return _agent_result(result)@@ -3024,8 +3015,8 @@ def remote_file_write(server_id):path = (data.get('path') or '').strip()content = data.get('content')if not path:- return jsonify({'error': 'path is required'}), 400+ raise field_required('path')if content is None:- return jsonify({'error': 'content is required'}), 400+ raise field_required('content')result = RemoteFileService.write_file(server_id, path, content, user_id=user_id)return _agent_result(result)diff --git a/backend/app/api/snapshots.py b/backend/app/api/snapshots.pyindex d184f382..4d7708a4 100644--- a/backend/app/api/snapshots.py+++ b/backend/app/api/snapshots.py@@ -18,6 +18,7 @@ from app.models.application import Applicationfrom app.models.deployment_snapshot import DeploymentSnapshotfrom app.services.configuration_service import ConfigurationServicefrom app.services.resource_grant_service import ResourceGrantService+from app.exceptions import not_found, permission_deniedsnapshots_bp = Blueprint('snapshots', __name__)@@ -28,12 +29,12 @@ def _get_app_or_404(app_id, write=False):the needed tier gets a 403 (the resource itself exists)."""app = Application.query_active().filter_by(id=app_id).first()if not app:- return None, (jsonify({'error': 'Application not found'}), 404)+ raise not_found('service')user = get_current_user()ok = (ResourceGrantService.can_edit_app(user, app) if writeelse ResourceGrantService.can_access_app(user, app))if not ok:- return None, (jsonify({'error': 'Access denied'}), 403)+ raise permission_denied()return app, None@@ -43,7 +44,7 @@ def _get_snapshot_or_404(app_id, snap_id):id=snap_id, application_id=app_id).first()if not snap:- return None, (jsonify({'error': 'Snapshot not found'}), 404)+ raise not_found('config_checkpoint')return snap, Nonediff --git a/backend/app/api/survey.py b/backend/app/api/survey.pyindex bdfe936f..50269046 100644--- a/backend/app/api/survey.py+++ b/backend/app/api/survey.py@@ -9,6 +9,7 @@ from flask import Blueprint, jsonify, requestfrom app.middleware.rbac import admin_required, get_current_userfrom app.models.server import Serverfrom app.services import survey_service+from app.exceptions import not_foundsurvey_bp = Blueprint('survey', __name__)@@ -29,7 +30,7 @@ def run_survey(server_id):"""Fly a read-only survey against the server's agent and store the map."""server = Server.query.get(server_id)if server is None:- return jsonify({'error': 'Server not found'}), 404+ raise not_found('server')user = get_current_user()survey, error = survey_service.run_survey(server_id, user_id=getattr(user, 'id', None))@@ -51,7 +52,7 @@ def set_management_mode(server_id):server = Server.query.get(server_id)if server is None:- return jsonify({'error': 'Server not found'}), 404+ raise not_found('server')data = request.get_json(silent=True) or {}mode = (data.get('mode') or '').strip().lower()@@ -99,7 +100,7 @@ def observed_status(server_id):from app.services.agent_registry import agent_registryserver = Server.query.get(server_id)if server is None:- return jsonify({'error': 'Server not found'}), 404+ raise not_found('server')return jsonify({'management_mode': server.management_mode or 'managed','allow_agent_update_observed': bool(server.allow_agent_update_observed),@@ -113,7 +114,7 @@ def list_surveys(server_id):"""List survey snapshots for a server (newest first, without the map blob)."""server = Server.query.get(server_id)if server is None:- return jsonify({'error': 'Server not found'}), 404+ raise not_found('server')surveys = survey_service.list_surveys(server_id)return jsonify({'surveys': [s.to_dict(include_map=False) for s in surveys]}), 200diff --git a/backend/app/api/templates.py b/backend/app/api/templates.pyindex fa4bf93b..14c40299 100644--- a/backend/app/api/templates.py+++ b/backend/app/api/templates.py@@ -20,6 +20,7 @@ from app.services.repository_manifest_service import RepositoryManifestServicefrom app.services.resource_grant_service import ResourceGrantServicefrom app.utils.slug import app_name_clash_error, validate_app_namefrom app.error_reporting import unexpected_response+from app.exceptions import not_found, permission_deniedtemplates_bp = Blueprint('templates', __name__)@@ -372,7 +373,7 @@ def template_capacity(template_id):"""result = TemplateService.get_template(template_id)if not result.get('success'):- return jsonify({'error': 'Template not found'}), 404+ raise not_found('template')from app.services.capacity_service import check_fitreturn jsonify(check_fit(result['template'], request.args.get('server_id'))), 200@@ -515,10 +516,10 @@ def check_app_update(app_id):app = Application.query_active().filter_by(id=app_id).first()if not app:- return jsonify({'error': 'Application not found'}), 404+ raise not_found('service')if not ResourceGrantService.can_access_app(user, app):- return jsonify({'error': 'Access denied'}), 403+ raise permission_denied()result = TemplateService.check_updates(app_id)return jsonify(result), 200 if result.get('success') else 400@@ -532,7 +533,7 @@ def update_app(app_id):app = Application.query_active().filter_by(id=app_id).first()if not app:- return jsonify({'error': 'Application not found'}), 404+ raise not_found('service')result = TemplateService.update_app(app_id, user_id=current_user_id)return jsonify(result), 200 if result.get('success') else 400@@ -547,10 +548,10 @@ def get_app_template_info(app_id):app = Application.query_active().filter_by(id=app_id).first()if not app:- return jsonify({'error': 'Application not found'}), 404+ raise not_found('service')if not ResourceGrantService.can_access_app(user, app):- return jsonify({'error': 'Access denied'}), 403+ raise permission_denied()info = TemplateService.get_installed_info(app_id)if info:diff --git a/backend/app/api/themes.py b/backend/app/api/themes.pyindex 304a3f2f..3d17ce10 100644--- a/backend/app/api/themes.py+++ b/backend/app/api/themes.py@@ -14,6 +14,7 @@ import loggingfrom flask import Blueprint, jsonify, requestfrom flask_jwt_extended import jwt_required+from app.exceptions import NotFoundErrorfrom app.services import theme_servicefrom app.services.audit_service import AuditServicefrom app.models.audit_log import AuditLog@@ -93,8 +94,9 @@ def delete_theme(slug):user = require_admin_user()ok, derr = theme_service.delete_theme(slug)if not ok:- code = 404 if derr == 'Theme not found' else 400- return jsonify({'error': derr}), code+ if derr is theme_service.THEME_NOT_FOUND:+ raise NotFoundError(derr)+ return jsonify({'error': derr}), 400AuditService.log(action=AuditLog.ACTION_RESOURCE_DELETE,user_id=user.id,diff --git a/backend/app/api/two_factor.py b/backend/app/api/two_factor.pyindex fbb81696..9d85ec68 100644--- a/backend/app/api/two_factor.py+++ b/backend/app/api/two_factor.py@@ -13,6 +13,7 @@ from app.models import Userfrom app.services.totp_service import TOTPService, TwoFactorSetupfrom app.services import auth_throttle_servicefrom app.utils.client_ip import get_client_ip+from app.exceptions import not_foundlogger = logging.getLogger(__name__)@@ -27,7 +28,7 @@ def get_2fa_status():user = User.query.get(current_user_id)if not user:- return jsonify({'error': 'User not found'}), 404+ raise not_found('user')setup = TwoFactorSetup(user)@@ -49,7 +50,7 @@ def initiate_2fa_setup():user = User.query.get(current_user_id)if not user:- return jsonify({'error': 'User not found'}), 404+ raise not_found('user')if user.totp_enabled:return jsonify({'error': '2FA is already enabled'}), 400@@ -77,7 +78,7 @@ def confirm_2fa_setup():user = User.query.get(current_user_id)if not user:- return jsonify({'error': 'User not found'}), 404+ raise not_found('user')if user.totp_enabled:return jsonify({'error': '2FA is already enabled'}), 400@@ -109,7 +110,7 @@ def disable_2fa():user = User.query.get(current_user_id)if not user:- return jsonify({'error': 'User not found'}), 404+ raise not_found('user')if not user.totp_enabled:return jsonify({'error': '2FA is not enabled'}), 400@@ -142,7 +143,7 @@ def regenerate_backup_codes():user = User.query.get(current_user_id)if not user:- return jsonify({'error': 'User not found'}), 404+ raise not_found('user')if not user.totp_enabled:return jsonify({'error': '2FA is not enabled'}), 400diff --git a/backend/app/api/waf.py b/backend/app/api/waf.pyindex e2dc9cd6..0e6c0f8f 100644--- a/backend/app/api/waf.py+++ b/backend/app/api/waf.py@@ -13,6 +13,7 @@ from app.models.application import Applicationfrom app.services.waf_service import WafServicefrom app.services.resource_grant_service import ResourceGrantServicefrom app.middleware.rbac import get_current_user, require_admin_user+from app.exceptions import not_foundwaf_bp = Blueprint('waf', __name__)@@ -23,9 +24,9 @@ def _get_application_or_404(app_id):app (sealed-from-open, no existence leak)."""application = Application.query_active().filter_by(id=app_id).first()if not application:- return None, (jsonify({'error': 'Application not found'}), 404)+ raise not_found('service')if not ResourceGrantService.can_access_app(get_current_user(), application):- return None, (jsonify({'error': 'Application not found'}), 404)+ raise not_found('service')return application, Nonediff --git a/backend/app/exceptions.py b/backend/app/exceptions.pyindex 8ed5ccb3..3d64d0f3 100644--- a/backend/app/exceptions.py+++ b/backend/app/exceptions.py@@ -73,3 +73,100 @@ class DependencyUnavailableError(ApplicationError):status_code = 503code = 'dependency_unavailable'default_message = 'Dependency unavailable'+++class AgentOfflineError(DependencyUnavailableError):+ """The target server's agent is not connected, so nothing can reach it."""++ code = 'agent.offline'+ default_message = (+ "The server's agent is offline. Start the agent on that server, "+ 'then try again.'+ )+++# ---------------------------------------------------------------------------+# Stable codes the client translates (plan 88 §C).+#+# The frontend (``frontend/src/services/api/errorCodes.js``) swaps the server's+# English for its own translation when it knows the ``code``. A translated code+# must therefore mean exactly ONE message — a code whose text varied per call+# would lose its specifics on the client. So the dotted codes below come only+# from these factories, each with a fixed message (parameterised by ``details``+# at most). The class defaults (``not_found``, ``validation_error``,+# ``permission_denied``, ``conflict``) stay for raises that carry their own+# prose; the client shows that prose untranslated, as before.+#+# code message details+# not_found.<resource> "<Resource> not found" resource+# validation.required "<field> is required" field+# permission.denied PERMISSION_DENIED_MESSAGE -+# conflict.exists "<Resource> already exists" resource+# agent.offline AgentOfflineError's message -+#+# Resource words are the UI's nouns (plan 88 glossary), not model names: an+# ``Application`` row is a "service" to the person reading the toast.+# ---------------------------------------------------------------------------++RESOURCE_LABELS = {+ 'service': 'Service',+ 'server': 'Server',+ 'domain': 'Domain',+ 'database': 'Database',+ 'backup': 'Backup',+ 'snapshot': 'Snapshot',+ 'config_checkpoint': 'Config checkpoint',+ 'deployment': 'Deployment',+ 'template': 'Template',+ 'user': 'User',+}++PERMISSION_DENIED_MESSAGE = "You don't have permission to do this. Ask an admin for access."+++def _resource_label(resource):+ try:+ return RESOURCE_LABELS[resource]+ except KeyError: # a typo here would ship a code nobody translates+ raise ValueError(f'unknown resource kind {resource!r}; add it to RESOURCE_LABELS') from None+++def not_found(resource):+ """``NotFoundError`` for one resource kind: ``raise not_found('service')``."""+ return NotFoundError(+ f'{_resource_label(resource)} not found',+ code=f'not_found.{resource}',+ details={'resource': resource},+ )+++def field_required(field):+ """``ValidationError`` for a missing request field: ``raise field_required('name')``."""+ return ValidationError(+ f'{field} is required',+ code='validation.required',+ details={'field': field},+ )+++def permission_denied():+ """``PermissionDeniedError`` for a caller who may not act on this resource.++ The message is deliberately generic: it reveals nothing the status code+ doesn't, and tells the caller what they can do about it.+ """+ return PermissionDeniedError(PERMISSION_DENIED_MESSAGE, code='permission.denied')+++def already_exists(resource):+ """``ConflictError`` for a create that collides with an existing row."""+ return ConflictError(+ f'{_resource_label(resource)} already exists',+ code='conflict.exists',+ details={'resource': resource},+ )+++def agent_offline():+ """``AgentOfflineError`` (503) for a server whose agent is not connected."""+ return AgentOfflineError()diff --git a/backend/app/services/backup_policy_service.py b/backend/app/services/backup_policy_service.pyindex 212a9aa5..887c8cf3 100644--- a/backend/app/services/backup_policy_service.py+++ b/backend/app/services/backup_policy_service.py@@ -314,7 +314,7 @@ class BackupPolicyService:from app.models.application import Applicationapp = Application.query_active().filter_by(id=policy.target_id).first()if not app:- raise BackupPolicyError('Application not found')+ raise BackupPolicyError('Service not found')if not app.root_path:raise BackupPolicyError('Target path not found')return {diff --git a/backend/app/services/backup_service.py b/backend/app/services/backup_service.pyindex 40d361de..2ccc16ca 100644--- a/backend/app/services/backup_service.py+++ b/backend/app/services/backup_service.py@@ -422,7 +422,7 @@ class BackupService:return {'success': True,- 'message': f'Application restored to {restore_path}',+ 'message': f'Service restored to {restore_path}','restore_path': restore_path}@@ -996,7 +996,7 @@ class BackupService:if app:result = cls.backup_application(app.name, app.root_path, correlation_id=correlation_id)else:- result = {'success': False, 'error': f'Application "{target}" not found'}+ result = {'success': False, 'error': f'Service "{target}" not found'}elif backup_type == 'files':paths_list = [p.strip() for p in target.split(',') if p.strip()]diff --git a/backend/app/services/bootstrap_service.py b/backend/app/services/bootstrap_service.pyindex b5a24027..8086e3cf 100644--- a/backend/app/services/bootstrap_service.py+++ b/backend/app/services/bootstrap_service.py@@ -40,7 +40,7 @@ class BootstrapService:root = getattr(app, 'root_path', None)if not root:return {'success': False,- 'error': 'app has no deployed compose project to run bootstrap in'}+ 'error': 'This service has no deployed Compose project to run bootstrap in. Deploy it first.'}cmd = ['docker', 'compose', 'run', '--rm', service] + shlex.split(command)proc = run_checked(cmd, cwd=root, timeout=timeout_seconds or 300)if proc['returncode'] is None:diff --git a/backend/app/services/build_service.py b/backend/app/services/build_service.pyindex 7de69ec1..2e2d4af6 100644--- a/backend/app/services/build_service.py+++ b/backend/app/services/build_service.py@@ -620,7 +620,7 @@ class BuildService:"""build_config = cls.get_app_build_config(app_id)if not build_config:- return {'success': False, 'error': 'Build not configured for this app'}+ return {'success': False, 'error': 'Build is not set up for this service'}app_path = build_config['app_path']build_method = build_config.get('build_method', 'auto')diff --git a/backend/app/services/configuration_service.py b/backend/app/services/configuration_service.pyindex 8bed0683..35f8fc76 100644--- a/backend/app/services/configuration_service.py+++ b/backend/app/services/configuration_service.py@@ -393,7 +393,7 @@ class ConfigurationService:snapshot = DeploymentSnapshot.query.get(snapshot_id)if not snapshot:- return {'success': False, 'error': 'Snapshot not found'}+ return {'success': False, 'error': 'Config checkpoint not found'}# query_active(): restoring a snapshot rewrites env and redeploys, so a# tombstoned app must 404 here rather than be brought back to life@@ -401,7 +401,7 @@ class ConfigurationService:application = Application.query_active().filter_by(id=snapshot.application_id).first()if not application:- return {'success': False, 'error': 'Application not found'}+ return {'success': False, 'error': 'Service not found'}config = snapshot.get_config()result = {diff --git a/backend/app/services/container_sleep_service.py b/backend/app/services/container_sleep_service.pyindex 21c34fa4..f9409faa 100644--- a/backend/app/services/container_sleep_service.py+++ b/backend/app/services/container_sleep_service.py@@ -47,7 +47,7 @@ class ContainerSleepService:@classmethoddef _stop(cls, app):if app.server_id:- return {'success': False, 'error': 'Sleep is not yet supported for apps on remote servers'}+ return {'success': False, 'error': 'Sleep is not yet available for services on remote servers'}from app.services.slot_deploy_service import SlotDeployServiceif SlotDeployService.is_compose_slot_app(app):return SlotDeployService.live_action(app, 'stop')@@ -60,7 +60,7 @@ class ContainerSleepService:@classmethoddef _start(cls, app):if app.server_id:- return {'success': False, 'error': 'Wake is not yet supported for apps on remote servers'}+ return {'success': False, 'error': 'Wake is not yet available for services on remote servers'}from app.services.slot_deploy_service import SlotDeployServiceif SlotDeployService.is_compose_slot_app(app):return SlotDeployService.live_action(app, 'start')@@ -75,7 +75,7 @@ class ContainerSleepService:# query_active: this stops containers — never touch a tombstoned app.app = Application.query_active().filter_by(id=application_id).first()if not app:- return {'success': False, 'error': 'Application not found'}+ return {'success': False, 'error': 'Service not found'}result = cls._stop(app)if not result.get('success'):return result@@ -92,7 +92,7 @@ class ContainerSleepService:# the delete tore down.app = Application.query_active().filter_by(id=application_id).first()if not app:- return {'success': False, 'error': 'Application not found'}+ return {'success': False, 'error': 'Service not found'}result = cls._start(app)if not result.get('success'):return resultdiff --git a/backend/app/services/db_admin_sso_service.py b/backend/app/services/db_admin_sso_service.pyindex f04f5575..c44dadce 100644--- a/backend/app/services/db_admin_sso_service.py+++ b/backend/app/services/db_admin_sso_service.py@@ -132,9 +132,9 @@ class DbAdminSsoService:driver = _ADMINER_DRIVERS.get(managed.engine)if not driver:- return {'error': 'unsupported engine'}+ return {'error': 'unsupported engine', 'code': 'unsupported_engine'}if not cls._docker_available():- return {'error': 'Docker required'}+ return {'error': 'Docker required', 'code': 'docker_required'}expires_at = datetime.utcnow() + timedelta(minutes=SHADOW_TTL_MINUTES)username = f'sk_sso_{secrets.token_hex(3)}'diff --git a/backend/app/services/db_insights_service.py b/backend/app/services/db_insights_service.pyindex 15269232..1cf54131 100644--- a/backend/app/services/db_insights_service.py+++ b/backend/app/services/db_insights_service.py@@ -93,7 +93,7 @@ class DbInsightsService:engine = 'postgresql' if engine in db_exec.POSTGRES_ALIASES else engineengine = 'mysql' if engine in db_exec.MYSQL_ALIASES else engineif engine not in SUPPORTED_ENGINES:- return {'error': 'unsupported engine'}+ return {'error': 'unsupported engine', 'code': 'unsupported_engine'}if not target.get('container'):# Dockerised engines only (the host executors don't return# parse-friendly output).diff --git a/backend/app/services/db_process_service.py b/backend/app/services/db_process_service.pyindex a410f03b..2f61ce14 100644--- a/backend/app/services/db_process_service.py+++ b/backend/app/services/db_process_service.py@@ -62,7 +62,7 @@ class DbProcessService:"""engine = (target or {}).get('engine')if engine not in SUPPORTED_ENGINES:- return {'error': 'unsupported engine'}+ return {'error': 'unsupported engine', 'code': 'unsupported_engine'}sql = _MYSQL_PROCESSLIST if engine == 'mysql' else _PG_PROCESSLISTresult = cls._exec_sql(target, sql)@@ -83,7 +83,7 @@ class DbProcessService:"""engine = (target or {}).get('engine')if engine not in SUPPORTED_ENGINES:- return {'error': 'unsupported engine'}+ return {'error': 'unsupported engine', 'code': 'unsupported_engine'}try:pid = int(pid)except (TypeError, ValueError):diff --git a/backend/app/services/deployment_job_service.py b/backend/app/services/deployment_job_service.pyindex 36c2a170..cfa4e598 100644--- a/backend/app/services/deployment_job_service.py+++ b/backend/app/services/deployment_job_service.py@@ -75,7 +75,7 @@ class DeploymentJobService:if not cls._is_abandoned_install_dir(app_path):return {'success': False,- 'error': (f'App directory already exists: {app_path}. '+ 'error': (f'A service directory already exists at {app_path}. ''Remove it, or install under a different name.'),}# An install that failed part-way leaves its directory behind, and@@ -247,7 +247,7 @@ class DeploymentJobService:"""job = DeploymentJob.query.get(job_id)if not job:- return {'success': False, 'error': 'Deployment job not found'}+ return {'success': False, 'error': 'Deployment job not found', 'code': 'not_found'}if job.status != 'failed':return {'success': False,'error': 'Only failed deployments can be retried'}diff --git a/backend/app/services/deployment_service.py b/backend/app/services/deployment_service.pyindex 38261983..325b2e8d 100644--- a/backend/app/services/deployment_service.py+++ b/backend/app/services/deployment_service.py@@ -44,7 +44,7 @@ class DeploymentService:# a tombstoned app must fail here rather than be redeployed.app = Application.query_active().filter_by(id=app_id).first()if not app:- return {'success': False, 'error': 'Application not found'}+ return {'success': False, 'error': 'Service not found'}# Get git commit info if availablecommit_hash = None@@ -357,7 +357,7 @@ class DeploymentService:verdict = SlotDeployService.eligibility(app)if not verdict['eligible']:return {'success': False, 'still_serving': True,- 'error': 'Slot deploys are on but this app no longer qualifies: '+ 'error': 'Slot deploys are on but this service no longer qualifies: '+ ' '.join(verdict['reasons'])}try:return SlotDeployService.deploy_compose(app, deployment, log=log_callback)@@ -458,7 +458,7 @@ class DeploymentService:verdict = SlotDeployService.eligibility(app)if not verdict['eligible']:return {'success': False, 'still_serving': True,- 'error': 'Slot deploys are on but this app no longer qualifies: '+ 'error': 'Slot deploys are on but this service no longer qualifies: '+ ' '.join(verdict['reasons'])+ ' Turn slot deploys off to deploy in place.'}return SlotDeployService.deploy_container(app, deployment, image_tag, env, volumes,@@ -585,7 +585,7 @@ class DeploymentService:# query_active: a rollback re-deploys code and restarts the app.app = Application.query_active().filter_by(id=app_id).first()if not app:- return {'success': False, 'error': 'Application not found'}+ return {'success': False, 'error': 'Service not found'}current = Deployment.get_current(app_id)if not current:diff --git a/backend/app/services/domain_attach_service.py b/backend/app/services/domain_attach_service.pyindex 2616612e..8f170ef5 100644--- a/backend/app/services/domain_attach_service.py+++ b/backend/app/services/domain_attach_service.py@@ -58,7 +58,7 @@ class DomainAttachService:or ``{'success': False, 'error': msg}`` on an invalid host / DB failure."""if not app:- return {'success': False, 'error': 'An application is required'}+ return {'success': False, 'error': 'Choose a service'}host = cls._normalize_host(host)if not host or '.' not in host:@@ -85,7 +85,7 @@ class DomainAttachService:clash = Domain.query_active().filter_by(name=host).first()if clash and clash.application_id != app.id:return {'success': False,- 'error': f'{host} is already attached to another app'}+ 'error': f'{host} is already attached to another service'}domain = Domain(name=host, is_primary=bool(make_primary),application_id=app.id)db.session.add(domain)diff --git a/backend/app/services/drift_service.py b/backend/app/services/drift_service.pyindex 846d1937..3f80abf2 100644--- a/backend/app/services/drift_service.py+++ b/backend/app/services/drift_service.py@@ -413,7 +413,7 @@ def _nginx_repair(app_id):app = Application.query_active().filter_by(id=app_id).first()if app is None:- return {'success': False, 'error': f'Application {app_id} not found'}+ return {'success': False, 'error': 'Service not found'}res = SiteDomainService.write_app_vhost(app)if res.get('warning') and not (res.get('nginx') or {}).get('success'):return {'success': False, 'error': res['warning']}@@ -500,7 +500,7 @@ def _compose_repair(app_id):app = Application.query_active().filter_by(id=app_id).first()if app is None:- return {'success': False, 'error': f'Application {app_id} not found'}+ return {'success': False, 'error': 'Service not found'}written = ComposeEnvService.refresh_for_project(app.root_path, app.compose_file)# Apply the regenerated override the same way a deploy does.up = DockerService.compose_up(app.root_path, detach=True,@@ -594,9 +594,9 @@ def _manifest_repair(app_id):app = Application.query_active().filter_by(id=app_id).first()if app is None:- return {'success': False, 'error': f'Application {app_id} not found'}+ return {'success': False, 'error': 'Service not found'}if not app.project_id:- return {'success': False, 'error': f'Application {app_id} is not manifest-managed'}+ return {'success': False, 'error': 'This service is not managed by a manifest'}result = ManifestApplyService.apply_stored(app.project_id)ok = bool(result.get('success', False))return {diff --git a/backend/app/services/env_service.py b/backend/app/services/env_service.pyindex 15bd115c..2ff6e523 100644--- a/backend/app/services/env_service.py+++ b/backend/app/services/env_service.py@@ -148,7 +148,7 @@ class EnvService:return None, False, errorapp = Application.query_active().filter_by(id=application_id).first()if not app:- return None, False, 'Application not found'+ return None, False, 'Service not found'norm_target = None if target_service in ('', _UNSET) else target_serviceexisting = EnvService.get_env_var(application_id, key)@@ -269,7 +269,7 @@ class EnvService:# Check if application existsapp = Application.query_active().filter_by(id=application_id).first()if not app:- return None, False, "Application not found"+ return None, False, "Service not found"# Check if key already existsexisting = EnvService.get_env_var(application_id, key)diff --git a/backend/app/services/environment_health_service.py b/backend/app/services/environment_health_service.pyindex 9c98f36a..b57616b9 100644--- a/backend/app/services/environment_health_service.py+++ b/backend/app/services/environment_health_service.py@@ -245,7 +245,7 @@ class EnvironmentHealthService:app = site.applicationif not app or not app.root_path:- return {'success': False, 'error': 'No application root path'}+ return {'success': False, 'error': 'This service has no root path'}env_dir = app.root_pathusage = {diff --git a/backend/app/services/environment_pipeline_service.py b/backend/app/services/environment_pipeline_service.pyindex 8a7ea46a..d94de957 100644--- a/backend/app/services/environment_pipeline_service.py+++ b/backend/app/services/environment_pipeline_service.py@@ -107,7 +107,7 @@ class EnvironmentPipelineService:prod_app = prod_site.applicationif not prod_app:- return {'success': False, 'error': 'Production application not found'}+ return {'success': False, 'error': 'Production service not found'}# Check for existing environment of same type (except multidev)if env_type != 'multidev':diff --git a/backend/app/services/git_deploy_service.py b/backend/app/services/git_deploy_service.pyindex 6aeae092..5aa6d8a0 100644--- a/backend/app/services/git_deploy_service.py+++ b/backend/app/services/git_deploy_service.py@@ -45,7 +45,7 @@ class GitDeployService:# code and rebuilds/restarts containers, so a tombstone must not deploy.app = Application.query_active().filter_by(id=app_id).first()if not app:- return {'success': False, 'error': 'Application not found'}+ return {'success': False, 'error': 'Service not found'}webhook = GitWebhook.query.get(webhook_id) if webhook_id else None@@ -187,7 +187,7 @@ class GitDeployService:app = Application.query_active().filter_by(id=app_id).first()if not app:- return {'success': False, 'error': 'Application not found'}+ return {'success': False, 'error': 'Service not found'}# Get current deploymentcurrent = GitDeployment.query.filter_by(app_id=app_id, status='success')\@@ -324,7 +324,7 @@ class GitDeployService:app = Application.query_active().filter_by(id=app_id).first()if not app:- return {'success': False, 'error': 'Application not found'}+ return {'success': False, 'error': 'Service not found'}# Find webhook for this app to get settingswebhook = GitWebhook.query.filter_by(app_id=app_id, is_active=True).first()diff --git a/backend/app/services/git_service.py b/backend/app/services/git_service.pyindex 661b0ca3..77a948ce 100644--- a/backend/app/services/git_service.py+++ b/backend/app/services/git_service.py@@ -448,7 +448,7 @@ class GitService:"""Handle incoming webhook."""app_config = cls.get_app_config(app_id)if not app_config:- return {'success': False, 'error': 'App not configured'}+ return {'success': False, 'error': 'This service has no Git deployment set up'}if not app_config.get('auto_deploy', True):return {'success': False, 'error': 'Auto-deploy disabled'}diff --git a/backend/app/services/image_update_service.py b/backend/app/services/image_update_service.pyindex 1b491891..e62e9585 100644--- a/backend/app/services/image_update_service.py+++ b/backend/app/services/image_update_service.py@@ -5,7 +5,7 @@ import loggingfrom datetime import datetimefrom app import db-from app.exceptions import NotFoundError, ValidationError+from app.exceptions import ValidationError, not_foundfrom app.models import Applicationfrom app.models.image_update import ImageUpdateCheckfrom app.services.docker_service import DockerService@@ -55,7 +55,7 @@ class ImageUpdateService:# (and a `docker login` when a private registry is bound).app = Application.query_active().filter_by(id=application_id).first()if not app:- raise NotFoundError('Application not found')+ raise not_found('service')image_ref = app.docker_imageif not image_ref:raise ValidationError('Application has no Docker image')diff --git a/backend/app/services/nginx_service.py b/backend/app/services/nginx_service.pyindex 3381383c..87b49cf5 100644--- a/backend/app/services/nginx_service.py+++ b/backend/app/services/nginx_service.py@@ -680,7 +680,7 @@ location /p/ {{)elif app_type in ['flask', 'django', 'python']:if not port:- return {'success': False, 'error': 'Port is required for Python apps'}+ return {'success': False, 'error': 'Python services need a port'}config = cls.PYTHON_SITE_TEMPLATE.format(name=name,domains=domains_str,@@ -689,7 +689,7 @@ location /p/ {{)elif app_type == 'docker':if not port:- return {'success': False, 'error': 'Port is required for Docker apps'}+ return {'success': False, 'error': 'Docker services need a port'}config = cls.DOCKER_SITE_TEMPLATE.format(name=name,domains=domains_str,@@ -697,7 +697,7 @@ location /p/ {{)elif app_type == 'remote':if not upstream:- return {'success': False, 'error': 'upstream (host:port) is required for remote apps'}+ return {'success': False, 'error': 'Services on remote servers need an upstream (host:port)'}config = cls.REMOTE_UPSTREAM_TEMPLATE.format(name=name,domains=domains_str,@@ -710,7 +710,7 @@ location /p/ {{root_path=root_path)else:- return {'success': False, 'error': f'Unknown app type: {app_type}'}+ return {'success': False, 'error': f'Unknown service type: {app_type}'}if immutable_assets:config = cls._with_immutable_assets(config, app_type)diff --git a/backend/app/services/preview_service.py b/backend/app/services/preview_service.pyindex 543f6841..90836b58 100644--- a/backend/app/services/preview_service.py+++ b/backend/app/services/preview_service.py@@ -408,7 +408,7 @@ class PreviewService:# containers) — never for a deleted app.app = Application.query_active().filter_by(id=application_id).first()if not app:- return {'error': 'application not found'}+ return {'error': 'Service not found'}open_prs = cls._fetch_open_prs(app)active = ApplicationPreview.query.filter(@@ -482,7 +482,7 @@ class PreviewService:app = Application.query_active().filter_by(id=payload.get('application_id')).first()if not app:- return {'error': 'application not found'}+ return {'error': 'Service not found'}return cls.create_preview(app, payload.get('pr') or payload)@classmethoddiff --git a/backend/app/services/python_service.py b/backend/app/services/python_service.pyindex 72b5e6ae..e8f0c57b 100644--- a/backend/app/services/python_service.py+++ b/backend/app/services/python_service.py@@ -251,7 +251,7 @@ SECRET_KEY={secrets.token_hex(32)}return {'success': True,'app_path': app_path,- 'message': 'Flask application created successfully'+ 'message': 'Flask service created'}except Exception as e:return {'success': False, 'error': str(e)}@@ -336,7 +336,7 @@ application = get_wsgi_application()'success': True,'app_path': app_path,'project_name': project_name,- 'message': 'Django application created successfully'+ 'message': 'Django service created'}except Exception as e:return {'success': False, 'error': str(e)}@@ -557,7 +557,7 @@ application = get_wsgi_application()elif app_type == 'flask':# Flask-Migratereturn PythonService.run_command(app_path, 'flask db upgrade')- return {'success': False, 'error': 'Unknown app type'}+ return {'success': False, 'error': 'Unknown service type'}@staticmethoddef collect_static(app_path, app_type='django'):diff --git a/backend/app/services/recycle_bin_service.py b/backend/app/services/recycle_bin_service.pyindex 989c5360..d6bbe37a 100644--- a/backend/app/services/recycle_bin_service.py+++ b/backend/app/services/recycle_bin_service.py@@ -148,12 +148,18 @@ def _run_purge_hook(entry, row):return f'purged, but cleanup failed: {exc}'+# purge()'s error for a missing row. Callers compare against this constant+# (`err is PURGE_NOT_FOUND`), never against the wording, so rephrasing the+# message can't turn the route's 404 into a 400.+PURGE_NOT_FOUND = 'not found'++def purge(kind, record_id):"""Delete for real. The only irreversible action in this module."""entry = _entry(kind)row = entry['model'].query.filter_by(id=record_id).first()if row is None:- return False, 'not found'+ return False, PURGE_NOT_FOUNDif row.deleted_at is None:return False, 'record is not in the recycle bin'warning = _run_purge_hook(entry, row)diff --git a/backend/app/services/site_domain_service.py b/backend/app/services/site_domain_service.pyindex 1fc04e20..9012be1a 100644--- a/backend/app/services/site_domain_service.py+++ b/backend/app/services/site_domain_service.py@@ -626,7 +626,7 @@ class SiteDomainService:# success with a URL that was never published.existing = Domain.query_active().filter_by(name=host).first()if existing and existing.application_id != app.id:- return {'success': False, 'error': f'{host} is already used by another app.'}+ return {'success': False, 'error': f'{host} is already used by another service.'}try:if not existing:diff --git a/backend/app/services/slot_deploy_service.py b/backend/app/services/slot_deploy_service.pyindex b28df0d2..b5644cd8 100644--- a/backend/app/services/slot_deploy_service.py+++ b/backend/app/services/slot_deploy_service.py@@ -296,7 +296,7 @@ class SlotDeployService:return {'success': True, 'slots': cls.status(app)}if deploy_settings.get(app, 'compose_data_split'):return {'success': False,- 'error': 'This app\'s stateful services live in a shared data project now; '+ 'error': 'This service\'s stateful containers live in a shared data project now; ''it keeps deploying through slots.'}# Opting out keeps the slots until the next deploy, which goes back to# the in-place path and folds them away (release_slots).@@ -315,7 +315,7 @@ class SlotDeployService:"""from app.services.deployment_service import DeploymentServiceif not app.slot_deploys_enabled or app.active_slot not in SLOTS:- return {'success': False, 'error': 'Slot deploys are not on for this app.'}+ return {'success': False, 'error': 'Slot deploys are not on for this service.'}standby = AppSlot.query.filter_by(application_id=app.id,slot=other(app.active_slot)).first()if (standby is None or standby.state not in ('standby', 'stopped')diff --git a/backend/app/services/template_service.py b/backend/app/services/template_service.pyindex c82d9123..96489911 100644--- a/backend/app/services/template_service.py+++ b/backend/app/services/template_service.py@@ -1931,7 +1931,7 @@ class TemplateService:# Create app directoryapp_path = os.path.join(cls.INSTALLED_DIR, app_name)if os.path.exists(app_path):- return {'success': False, 'error': f"App directory already exists: {app_path}"}+ return {'success': False, 'error': f"A service directory already exists at {app_path}. Choose another name."}try:os.makedirs(app_path, exist_ok=True)@@ -2234,7 +2234,7 @@ class TemplateService:installed = config.get('installed', {}).get(str(app_id))if not installed:- return {'success': False, 'error': 'App not installed from template'}+ return {'success': False, 'error': 'This service was not installed from a template'}template_id = installed['template_id']installed_version = installed['template_version']@@ -2316,11 +2316,11 @@ class TemplateService:installed = config.get('installed', {}).get(str(app_id))if not installed:- return {'success': False, 'error': 'App not installed from template'}+ return {'success': False, 'error': 'This service was not installed from a template'}app = Application.query_active().filter_by(id=app_id).first()if not app:- return {'success': False, 'error': 'Application not found'}+ return {'success': False, 'error': 'Service not found'}template_id = installed['template_id']app_path = app.root_path@@ -2509,15 +2509,15 @@ class TemplateService:target_app = Application.query_active().filter_by(id=target_app_id).first()if not source_app or not target_app:- return {'success': False, 'error': 'App not found'}+ return {'success': False, 'error': 'Service not found'}if not source_app.root_path or not target_app.root_path:- return {'success': False, 'error': 'Apps must have root_path set'}+ return {'success': False, 'error': 'Both services need a root path'}# Read source app's .env filesource_env_path = os.path.join(source_app.root_path, '.env')if not os.path.exists(source_env_path):- return {'success': False, 'error': 'Source app .env file not found'}+ return {'success': False, 'error': 'The source service has no .env file'}try:env_vars = {}@@ -2540,7 +2540,7 @@ class TemplateService:db_config[key] = env_vars[key]if not db_config:- return {'success': False, 'error': 'No database credentials found in source app'}+ return {'success': False, 'error': 'No database credentials found in the source service'}# Set target table prefix (default different from source)source_prefix = env_vars.get('TABLE_PREFIX', env_vars.get('WORDPRESS_TABLE_PREFIX', 'wp_'))diff --git a/backend/app/services/theme_service.py b/backend/app/services/theme_service.pyindex 615cece2..c42e0bfc 100644--- a/backend/app/services/theme_service.py+++ b/backend/app/services/theme_service.py@@ -124,6 +124,11 @@ def import_theme(raw, source='import'):return row.to_dict(), None+# delete_theme()'s error for an unknown slug; the route compares against this+# constant (`err is THEME_NOT_FOUND`), never against the wording.+THEME_NOT_FOUND = 'Theme not found'++def delete_theme(slug):"""Uninstall an installed theme. Bundled seeds cannot be deleted. If thedeleted theme was the panel default, revert the default to the stock look.@@ -137,7 +142,7 @@ def delete_theme(slug):# return 400 (can't) vs 404 (nonexistent).if slug in _bundled_map():return False, 'Bundled themes cannot be removed'- return False, 'Theme not found'+ return False, THEME_NOT_FOUNDdb.session.delete(row)if get_default_slug() == slug:set_default_slug(DEFAULT_THEME_SLUG)diff --git a/backend/app/services/waf_service.py b/backend/app/services/waf_service.pyindex 47435b32..30bb457a 100644--- a/backend/app/services/waf_service.py+++ b/backend/app/services/waf_service.py@@ -433,7 +433,7 @@ class WafService:application = Application.query_active().filter_by(id=application_id).first()if not application:- return {'success': False, 'error': 'Application not found'}+ return {'success': False, 'error': 'Service not found'}policy = WafPolicy.query.filter_by(application_id=application_id).first()if policy is None:diff --git a/backend/app/services/webhook_service.py b/backend/app/services/webhook_service.pyindex 254c3e52..a517399e 100644--- a/backend/app/services/webhook_service.py+++ b/backend/app/services/webhook_service.py@@ -63,7 +63,7 @@ class WebhookService:# push fire deploys and outbound callbacks for a deleted app.app = Application.query_active().filter_by(id=app_id).first()if not app:- return {'success': False, 'error': 'Application not found'}+ return {'success': False, 'error': 'Service not found'}# Generate secure tokenssecret = secrets.token_hex(32)diff --git a/backend/app/sockets.py b/backend/app/sockets.pyindex 1e99ee95..85dd7da8 100644--- a/backend/app/sockets.py+++ b/backend/app/sockets.py@@ -641,7 +641,7 @@ def handle_subscribe_container_logs(data):data = data if isinstance(data, dict) else {}app_id = data.get('app_id')if not user or not _app_visible(user, app_id):- emit('error', {'message': 'Application access denied'})+ emit('error', {'message': "You don't have access to this service"})returntail = data.get('tail', 100)since = data.get('since')@@ -658,7 +658,7 @@ def handle_subscribe_container_logs(data):try:app = Application.query_active().filter_by(id=app_id).first()if not app:- emit('container_log_error', {'message': 'Application not found', 'app_id': app_id})+ emit('container_log_error', {'message': 'Service not found', 'app_id': app_id})returnexcept Exception as e:emit('container_log_error', {'message': f'Database error: {str(e)}', 'app_id': app_id})@@ -683,7 +683,7 @@ def handle_subscribe_container_logs(data):if not container_id:emit('container_log_error', {- 'message': 'No container found for this application',+ 'message': 'No container found for this service','app_id': app_id,'hint': 'The application may not have been started yet'})diff --git a/backend/tests/ERROR_SHAPE_CEILING b/backend/tests/ERROR_SHAPE_CEILINGindex 765f5bf7..8163eed6 100644--- a/backend/tests/ERROR_SHAPE_CEILING+++ b/backend/tests/ERROR_SHAPE_CEILING@@ -1 +1 @@-1150+850diff --git a/backend/tests/test_application_soft_delete.py b/backend/tests/test_application_soft_delete.pyindex a0e5a1a5..1376237c 100644--- a/backend/tests/test_application_soft_delete.py+++ b/backend/tests/test_application_soft_delete.py@@ -333,7 +333,7 @@ def test_deleting_a_user_who_owns_applications_is_refused(app, client, auth_headres = client.delete(f'/api/v1/admin/users/{owner_id}', headers=auth_headers)assert res.status_code == 409, res.get_json()- assert 'application' in res.get_json()['error']+ assert 'service' in res.get_json()['error']def test_purge_honours_an_explicit_remove_data_false(app, dead_app, monkeypatch):diff --git a/backend/tests/test_config_checkpoint_alias.py b/backend/tests/test_config_checkpoint_alias.pyindex 3754bf9f..86b4c99b 100644--- a/backend/tests/test_config_checkpoint_alias.py+++ b/backend/tests/test_config_checkpoint_alias.py@@ -14,7 +14,9 @@ def test_config_checkpoints_resolves_same_handler(app, client, auth_headers):ckpts = client.get('/api/v1/apps/999999/config-checkpoints', headers=auth_headers)assert snaps.status_code == 404assert ckpts.status_code == 404- assert ckpts.get_json() == snaps.get_json()+ # Same body apart from the per-request id the typed error carries.+ strip = lambda body: {k: v for k, v in body.items() if k != 'request_id'} # noqa: E731+ assert strip(ckpts.get_json()) == strip(snaps.get_json())def test_both_route_spaces_registered(route_rules):diff --git a/backend/tests/test_db_admin_sso.py b/backend/tests/test_db_admin_sso.pyindex 459250b8..8f79a1b8 100644--- a/backend/tests/test_db_admin_sso.py+++ b/backend/tests/test_db_admin_sso.py@@ -124,13 +124,13 @@ def test_launch_reuses_running_adminer(app, managed, sql_log, monkeypatch):def test_launch_without_docker_is_clean_error(app, managed, monkeypatch):monkeypatch.setattr(DbAdminSsoService, '_docker_available',classmethod(lambda cls: False))- assert DbAdminSsoService.launch(managed) == {'error': 'Docker required'}+ assert DbAdminSsoService.launch(managed) == {'error': 'Docker required', 'code': 'docker_required'}assert ManagedDatabaseUser.query.count() == 0 # nothing minteddef test_launch_unsupported_engine(app, docker_stub):mongo = ManagedDatabaseService.record_provisioned('mongodb', 'logs')- assert DbAdminSsoService.launch(mongo) == {'error': 'unsupported engine'}+ assert DbAdminSsoService.launch(mongo) == {'error': 'unsupported engine', 'code': 'unsupported_engine'}def test_launch_adminer_failure_revokes_credential(app, managed, sql_log, monkeypatch):diff --git a/backend/tests/test_db_insights.py b/backend/tests/test_db_insights.pyindex 1daff42f..973f1cd8 100644--- a/backend/tests/test_db_insights.py+++ b/backend/tests/test_db_insights.py@@ -81,7 +81,7 @@ def test_empty_counters_mean_no_ratio_not_zero(monkeypatch):({'engine': 'postgresql'}, 'insights need a Docker database container'),])def test_refused_targets(target, error):- assert DbInsightsService.insights(target) == {'error': error}+ assert DbInsightsService.insights(target)['error'] == errorclass TestEnablePgStatStatements:diff --git a/backend/tests/test_db_processes.py b/backend/tests/test_db_processes.pyindex 51c1a08a..f59f1e8e 100644--- a/backend/tests/test_db_processes.py+++ b/backend/tests/test_db_processes.py@@ -103,7 +103,7 @@ class TestListProcessesErrors:@pytest.mark.parametrize('engine', ['sqlite', 'mongodb', 'redis', None, ''])def test_unsupported_engine(self, engine):result = DbProcessService.list_processes({'engine': engine})- assert result == {'error': 'unsupported engine'}+ assert result == {'error': 'unsupported engine', 'code': 'unsupported_engine'}def test_exec_failure_surfaces_error(self, monkeypatch):_stub_exec(monkeypatch, success=False, error='docker: command not found')@@ -148,7 +148,7 @@ class TestKillProcess:def test_unsupported_engine(self, monkeypatch):calls = _stub_exec(monkeypatch)result = DbProcessService.kill_process({'engine': 'sqlite'}, 1)- assert result == {'error': 'unsupported engine'}+ assert result == {'error': 'unsupported engine', 'code': 'unsupported_engine'}assert calls == []def test_exec_failure(self, monkeypatch):@@ -297,7 +297,7 @@ class TestProcessAPI:def test_list_unsupported_engine_is_400(self, client, auth_headers, monkeypatch):monkeypatch.setattr(DbProcessService, 'list_processes',- staticmethod(lambda target: {'error': 'unsupported engine'}))+ staticmethod(lambda target: {'error': 'unsupported engine', 'code': 'unsupported_engine'}))resp = client.get('/api/v1/databases/docker/c1/processes?type=redis', headers=auth_headers)assert resp.status_code == 400assert resp.get_json() == {'error': 'unsupported engine'}diff --git a/backend/tests/test_dns_give_subdomain.py b/backend/tests/test_dns_give_subdomain.pyindex 05ac153e..541c1034 100644--- a/backend/tests/test_dns_give_subdomain.py+++ b/backend/tests/test_dns_give_subdomain.py@@ -180,7 +180,7 @@ def test_give_subdomain_rejects_label_taken_by_other_app(app, monkeypatch):a = _mk_app(name='Mine', port=8800)res = SiteDomainService.give_subdomain(a, label='shared')- assert res['success'] is False and 'another app' in res['error']+ assert res['success'] is False and 'another service' in res['error']# ── endpoints ────────────────────────────────────────────────────────────────diff --git a/backend/tests/test_domain_attach_service.py b/backend/tests/test_domain_attach_service.pyindex e35dcafe..6eac8fe1 100644--- a/backend/tests/test_domain_attach_service.py+++ b/backend/tests/test_domain_attach_service.py@@ -140,7 +140,7 @@ def test_host_owned_by_other_app_is_rejected(client, auth_headers, app):assert DomainAttachService.attach(a1, 'shared.example.com', ssl='off')['success'] is Trueresult = DomainAttachService.attach(a2, 'shared.example.com', ssl='off')assert result['success'] is False- assert 'another app' in result['error']+ assert 'another service' in result['error']# ── SSL best-effort ──────────────────────────────────────────────────────────diff --git a/backend/tests/test_managed_db_users.py b/backend/tests/test_managed_db_users.pyindex a181ad2b..0ddab636 100644--- a/backend/tests/test_managed_db_users.py+++ b/backend/tests/test_managed_db_users.py@@ -274,7 +274,9 @@ def test_api_404_on_unknown_database(app, client, auth_headers):_register_bp(app)resp = client.get('/api/v1/managed-databases/99999/users', headers=auth_headers)assert resp.status_code == 404- assert resp.get_json() == {'error': 'Managed database not found'}+ body = resp.get_json()+ assert body['error'] == 'Database not found'+ assert body['code'] == 'not_found.database'def test_api_bad_grants_is_400(app, client, auth_headers, managed, sql_log):diff --git a/backend/tests/test_typed_error_codes.py b/backend/tests/test_typed_error_codes.pynew file mode 100644index 00000000..99c3ff48--- /dev/null+++ b/backend/tests/test_typed_error_codes.py@@ -0,0 +1,97 @@+"""Plan 88 §C: the common error families carry a stable, translatable `code`.++The frontend swaps the server's English for its own translation when it knows+the code (``frontend/src/services/api/errorCodes.js``), so these tests pin both+halves of that contract: the body a route returns, and that every+``not_found.<resource>`` the backend can mint has a client entry.+"""++import os+import re++import pytest++from app import db+from app.exceptions import (+ PERMISSION_DENIED_MESSAGE, RESOURCE_LABELS, already_exists, field_required, not_found,+)++ERROR_CODES_JS = os.path.join(+ os.path.dirname(__file__), '..', '..', 'frontend', 'src', 'services', 'api', 'errorCodes.js')+++def test_missing_service_has_a_resource_code(client, auth_headers):+ resp = client.get('/api/v1/apps/999999', headers=auth_headers)+ body = resp.get_json()+ assert resp.status_code == 404+ assert body['error'] == 'Service not found'+ assert body['code'] == 'not_found.service'+ assert body['details'] == {'resource': 'service'}+ assert body['request_id'] == resp.headers['X-Request-ID']+++def test_missing_server_has_a_resource_code(client, auth_headers):+ resp = client.post('/api/v1/servers/no-such-server/ping', headers=auth_headers)+ assert resp.status_code == 404+ assert resp.get_json()['code'] == 'not_found.server'+++def test_offline_agent_is_503_agent_offline(app, client, auth_headers):+ from tests.factories import make_server+ with app.app_context():+ server_id = make_server(db, name='offline-box').id+ resp = client.post(f'/api/v1/servers/{server_id}/ping', headers=auth_headers)+ assert resp.status_code == 503+ assert resp.get_json()['code'] == 'agent.offline'+++def test_duplicate_domain_is_conflict_exists(app, client, auth_headers):+ from app.models import Domain+ from tests.factories import make_application+ with app.app_context():+ app_id = make_application(db, name='dup', port=8001).id+ db.session.add(Domain(name='dup.example.com', application_id=app_id))+ db.session.commit()+ resp = client.post('/api/v1/domains', headers=auth_headers,+ json={'name': 'dup.example.com', 'application_id': app_id})+ body = resp.get_json()+ assert resp.status_code == 409+ assert body['code'] == 'conflict.exists'+ assert body['details'] == {'resource': 'domain'}+++def test_purging_a_missing_record_is_still_404(client, auth_headers):+ """The status used to come from `err == 'not found'`; rewording the message+ must not be able to turn it into a 400."""+ resp = client.delete('/api/v1/recycle-bin/domain/999999', headers=auth_headers)+ assert resp.status_code == 404+ assert resp.get_json()['code'] == 'not_found'+++def test_deleting_an_unknown_theme_is_still_404(client, auth_headers):+ resp = client.delete('/api/v1/themes/no-such-theme', headers=auth_headers)+ assert resp.status_code == 404+++def test_factories_mint_one_message_per_code():+ assert str(not_found('service')) == 'Service not found'+ required = field_required('name')+ assert (required.code, required.details, required.status_code) == (+ 'validation.required', {'field': 'name'}, 400)+ assert already_exists('domain').code == 'conflict.exists'+ with pytest.raises(ValueError):+ not_found('widget') # an unlisted kind would ship an untranslated code+++def test_permission_denied_message_matches_the_client():+ with open(ERROR_CODES_JS, encoding='utf-8') as f:+ source = f.read()+ assert PERMISSION_DENIED_MESSAGE in source+++def test_every_resource_kind_has_a_client_translation():+ with open(ERROR_CODES_JS, encoding='utf-8') as f:+ translated = set(re.findall(r"'not_found\.([a-z_]+)'", f.read()))+ assert translated == set(RESOURCE_LABELS), (+ 'add the missing not_found.<resource> entries to errorCodes.js '+ '(or drop the unused kind from RESOURCE_LABELS)')diff --git a/docs/MIGRATION_INVENTORY.md b/docs/MIGRATION_INVENTORY.mdindex 5f91bbb9..e24dd309 100644--- a/docs/MIGRATION_INVENTORY.md+++ b/docs/MIGRATION_INVENTORY.md@@ -16,7 +16,7 @@ debt. Regenerate with `python scripts/generate-migration-inventory.py`.| Routes on bare @jwt_required() | auth_required() / role decorators | 600 | 600 | REGISTERED EXCEPTION: JWT-only is the deliberate default; conversion grants API-key access and happens per route, on decision || HTTP statuses chosen by sniffing error text | typed errors from app.exceptions | 0 | 0 | INVARIANT at 0 - migration completed 2026-08-19 || API crashes swallowed without recording | app.error_reporting | 0 | 0 | INVARIANT at 0 |-| Hand-shaped {'error': ...} bodies in app/api | typed errors + the global handler | 1132 | 1150 | migrate when touched; new endpoints raise |+| Hand-shaped {'error': ...} bodies in app/api | typed errors + the global handler | 850 | 850 | migrate when touched; new endpoints raise || Raw subprocess calls outside the runners | app/utils/system.py runners | 24 | 24 | migrate when touched || Controller-boundary violations (routes doing service work) | service layer extraction | 491 | 491 | migrate when touched (first-wave ratchet) || raw api.* calls in pages/ | E1: useServerQuery/useServerMutation | 398 | 398 | migrate when touched |