Skip to content

ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.

fix(recovery): restore models + migration chain 056-074, cron_run_service, rbac authz

Juan Denisce97d75d609c
diff --git a/backend/app/middleware/rbac.py b/backend/app/middleware/rbac.py
index acad1e44..341e5c6a 100644
--- a/backend/app/middleware/rbac.py
+++ b/backend/app/middleware/rbac.py
@@ -4,6 +4,10 @@ from flask import g, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity, verify_jwt_in_request
from app.models import User
+# App capability tiers, ranked low->high. The single ordering behind
+# app_access_tier / require_app_member and the membership visibility model.
+_APP_ROLE_RANK = {'viewer': 1, 'member': 2, 'admin': 3, 'owner': 4}
+
def get_current_user():
"""Get the current authenticated user (via API key or JWT)."""
@@ -157,3 +161,92 @@ def viewer_required(fn):
return jsonify({'error': 'Access denied'}), 403
return fn(*args, **kwargs)
return wrapper
+
+
+def require_workspace_access(workspace_id, user):
+ """Return a 403 response tuple if `user` is neither a panel admin nor a member
+ of the workspace, else None. Plain guard (not a decorator) so callers that
+ already resolved the workspace id can drop it inline."""
+ from app.services.workspace_service import WorkspaceService
+ if user.is_admin:
+ return None
+ if WorkspaceService.get_user_role(workspace_id, user.id) is None:
+ return jsonify({'error': 'Workspace access denied'}), 403
+ return None
+
+
+def require_workspace_role(workspace_id, user, roles):
+ """Return a 403 response tuple unless `user` is a panel admin or their
+ workspace membership role is one of `roles`, else None."""
+ from app.services.workspace_service import WorkspaceService
+ if user.is_admin:
+ return None
+ if WorkspaceService.get_user_role(workspace_id, user.id) not in roles:
+ return jsonify({'error': 'Insufficient permissions'}), 403
+ return None
+
+
+def app_access_tier(user, application):
+ """Fold every path to an application into ONE capability tier
+ ('owner'|'admin'|'member'|'viewer') or None (no access):
+
+ - panel admin or the app's owner -> 'owner'
+ - ResourceGrant 'editor' -> 'member' (may operate, not administer)
+ - ResourceGrant 'viewer' -> 'viewer' (read-only)
+ - member of the app's workspace -> that workspace role
+ - otherwise -> None
+
+ The highest tier wins. This is the single seam behind require_app_member and
+ the membership visibility model (plan 19 Decision 2).
+ """
+ if user.is_admin or application.user_id == user.id:
+ return 'owner'
+
+ from app.services.resource_grant_service import ResourceGrantService
+ from app.services.workspace_service import WorkspaceService
+
+ best = None
+ grant_role = ResourceGrantService.grant_role(user.id, 'application', application.id)
+ if grant_role == 'editor':
+ best = 'member'
+ elif grant_role == 'viewer':
+ best = 'viewer'
+
+ ws_id = getattr(application, 'workspace_id', None)
+ if ws_id is not None:
+ ws_role = WorkspaceService.get_user_role(ws_id, user.id)
+ if ws_role:
+ if best is None or _APP_ROLE_RANK[ws_role] > _APP_ROLE_RANK[best]:
+ best = ws_role
+ return best
+
+
+def require_app_member(min_role='viewer', arg='app_id'):
+ """Decorator: the caller must reach the application named by view kwarg `arg`
+ with an effective tier >= `min_role` (see app_access_tier). Resolves the app,
+ 404s when it is missing (no info leak), 403s on insufficient access, and
+ stashes the resolved Application on `g.current_application` for the view.
+
+ Tiers: read surfaces use min_role='viewer'; member-write surfaces 'member';
+ app-scoped destructive surfaces 'admin' (workspace admin/owner or panel admin).
+ """
+ def decorator(fn):
+ @wraps(fn)
+ @auth_required()
+ def wrapper(*args, **kwargs):
+ user = get_current_user()
+ if not user:
+ return jsonify({'error': 'User not found'}), 404
+ if not user.is_active:
+ return jsonify({'error': 'Account is deactivated'}), 403
+ from app.models.application import Application
+ application = Application.query.get(kwargs.get(arg))
+ if application is None:
+ return jsonify({'error': 'Not found'}), 404
+ tier = app_access_tier(user, application)
+ if tier is None or _APP_ROLE_RANK[tier] < _APP_ROLE_RANK[min_role]:
+ return jsonify({'error': 'Access denied'}), 403
+ g.current_application = application
+ return fn(*args, **kwargs)
+ return wrapper
+ return decorator
diff --git a/backend/app/models/app_volume.py b/backend/app/models/app_volume.py
index a6f83980..3feb5c3d 100644
--- a/backend/app/models/app_volume.py
+++ b/backend/app/models/app_volume.py
@@ -29,6 +29,7 @@ class AppVolume(db.Model):
driver = db.Column(db.String(40), nullable=False, default='local')
read_only = db.Column(db.Boolean, nullable=False, default=False)
size_bytes = db.Column(db.BigInteger, nullable=True) # denormalized last-measured size
+ declared_size = db.Column(db.String(40), nullable=True) # operator/manifest-declared size cap, e.g. "10Gi" (plan 35)
created_at = db.Column(db.DateTime, default=datetime.utcnow)
updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
diff --git a/backend/app/models/application.py b/backend/app/models/application.py
index cacf957a..9d9f171e 100644
--- a/backend/app/models/application.py
+++ b/backend/app/models/application.py
@@ -65,6 +65,11 @@ class Application(db.Model):
# Traefik/Caddy). NULL is treated as the default. See app/utils/ingress.py.
ingress_plane = db.Column(db.String(20), nullable=True)
+ # Appliance tier (plan 35): typed port declarations (JSON list of
+ # {container, host, protocol, ...}) and a one-shot bootstrap-completed flag.
+ ports = db.Column(db.Text, nullable=True)
+ bootstrap_done = db.Column(db.Boolean, nullable=False, server_default='0', default=False)
+
# Upload versioning
version = db.Column(db.Integer, default=0, nullable=False)
upload_path = db.Column(db.String(500), nullable=True)
diff --git a/backend/app/models/dns_cutover_snapshot.py b/backend/app/models/dns_cutover_snapshot.py
new file mode 100644
index 00000000..a72758ef
--- /dev/null
+++ b/backend/app/models/dns_cutover_snapshot.py
@@ -0,0 +1,86 @@
+"""Reversible DNS cutover snapshot model."""
+import json
+from datetime import datetime
+
+from app import db
+
+
+class DnsCutoverSnapshot(db.Model):
+ """A point-in-time capture of a domain's live DNS records, taken right before
+ a migration cutover flips them to the new box (plan 27 Phase 6 #13, Decision 6).
+
+ ServerKit's DNS activity ledger (:class:`~app.models.dns_change.DnsChange`)
+ only records the *after* value of each write, so it cannot power a revert. A
+ cutover therefore snapshots the domain's existing records
+ (name / type / content / ttl) into this row *first*; the revert step then
+ re-applies that snapshot to restore the old target.
+
+ ``status`` walks ``captured`` -> ``cutover`` -> ``reverted``:
+
+ * **captured** — records saved, nothing changed yet.
+ * **cutover** — the record(s) were repointed at the new box.
+ * **reverted** — the snapshot was re-applied, restoring the pre-cutover state.
+ * **reverted_with_deletions** — as *reverted*, plus records the cutover
+ *created* (no predecessor in the snapshot) were deleted (plan 31 #3).
+ """
+
+ __tablename__ = 'dns_cutover_snapshots'
+
+ STATUSES = ('captured', 'cutover', 'reverted', 'reverted_with_deletions')
+
+ id = db.Column(db.Integer, primary_key=True)
+ domain = db.Column(db.String(256), nullable=False, index=True)
+ provider = db.Column(db.String(64), nullable=True)
+ provider_zone_id = db.Column(db.String(128), nullable=True)
+
+ # JSON list of the records captured before cutover (the world to restore).
+ records_json = db.Column(db.Text, nullable=True)
+ # JSON list of records the cutover CREATED (no snapshot predecessor); revert
+ # deletes these so the world is restored byte-for-byte (plan 31 #3).
+ created_records_json = db.Column(db.Text, nullable=True)
+
+ status = db.Column(db.String(24), nullable=False, default='captured')
+ created_at = db.Column(db.DateTime, nullable=False, default=datetime.utcnow,
+ index=True)
+ applied_at = db.Column(db.DateTime, nullable=True)
+
+ def get_records(self):
+ if not self.records_json:
+ return []
+ try:
+ data = json.loads(self.records_json)
+ return data if isinstance(data, list) else []
+ except (json.JSONDecodeError, TypeError):
+ return []
+
+ def set_records(self, records):
+ self.records_json = json.dumps(list(records or []))
+
+ def get_created_records(self):
+ if not self.created_records_json:
+ return []
+ try:
+ data = json.loads(self.created_records_json)
+ return data if isinstance(data, list) else []
+ except (json.JSONDecodeError, TypeError):
+ return []
+
+ def set_created_records(self, records):
+ self.created_records_json = json.dumps(list(records or []))
+
+ def to_dict(self):
+ return {
+ 'id': self.id,
+ 'domain': self.domain,
+ 'provider': self.provider,
+ 'provider_zone_id': self.provider_zone_id,
+ 'status': self.status,
+ 'records': self.get_records(),
+ 'record_count': len(self.get_records()),
+ 'created_records': self.get_created_records(),
+ 'created_at': self.created_at.isoformat() + 'Z' if self.created_at else None,
+ 'applied_at': self.applied_at.isoformat() + 'Z' if self.applied_at else None,
+ }
+
+ def __repr__(self):
+ return f'<DnsCutoverSnapshot {self.domain} {self.status}>'
diff --git a/backend/app/models/email.py b/backend/app/models/email.py
index 41a1a961..07e57578 100644
--- a/backend/app/models/email.py
+++ b/backend/app/models/email.py
@@ -145,6 +145,9 @@ class DNSProviderConfig(db.Model):
api_secret = db.Column(db.String(500))
api_email = db.Column(db.String(255))
is_default = db.Column(db.Boolean, default=False)
+ # Cloudflare Origin CA — the private key the panel generated for the CSR when
+ # issuing an Origin certificate for this provider's zones (plan 36 Origin CA).
+ origin_ca_key = db.Column(db.Text, nullable=True)
created_at = db.Column(db.DateTime, default=datetime.utcnow)
domains = db.relationship('EmailDomain', backref='dns_provider', lazy=True)
diff --git a/backend/app/models/fleet_doctor_result.py b/backend/app/models/fleet_doctor_result.py
new file mode 100644
index 00000000..630eb2ac
--- /dev/null
+++ b/backend/app/models/fleet_doctor_result.py
@@ -0,0 +1,72 @@
+"""Fleet-doctor per-server result model."""
+import json
+from datetime import datetime
+
+from app import db
+
+
+class FleetDoctorResult(db.Model):
+ """One row per ``(server_id, check_key)`` recorded by the fleet health sweep
+ (Fleet Parity Sweep, plan 26 Phase 2, Decision 3).
+
+ The panel-host doctor keeps its ``doctor_last_report`` settings blob; the
+ fleet sweep instead records each remote server's per-check outcome as a ROW
+ here so the report API can merge the two and the repair layer can act on an
+ individual finding.
+
+ ``status`` is one of ``ok`` / ``warn`` / ``fail`` / ``error``. ``repairable``
+ marks findings the allowlisted repair layer can act on; ``repair_ref`` carries
+ the JSON descriptor of that repair action.
+ """
+
+ __tablename__ = 'fleet_doctor_results'
+
+ STATUS_OK = 'ok'
+ STATUS_WARN = 'warn'
+ STATUS_FAIL = 'fail'
+ STATUS_ERROR = 'error'
+ STATUSES = (STATUS_OK, STATUS_WARN, STATUS_FAIL, STATUS_ERROR)
+
+ id = db.Column(db.Integer, primary_key=True)
+ server_id = db.Column(db.String(36), db.ForeignKey('servers.id'),
+ nullable=False, index=True)
+ check_key = db.Column(db.String(160), nullable=False, index=True)
+ status = db.Column(db.String(16), nullable=False, server_default='ok')
+ title = db.Column(db.String(200), nullable=True)
+ detail = db.Column(db.Text, nullable=True)
+ repairable = db.Column(db.Boolean, nullable=False, server_default=db.false())
+ repair_ref = db.Column(db.Text, nullable=True)
+ ran_at = db.Column(db.DateTime, nullable=False, default=datetime.utcnow,
+ index=True)
+
+ __table_args__ = (
+ db.UniqueConstraint('server_id', 'check_key',
+ name='uq_fleet_doctor_server_check'),
+ )
+
+ def get_repair_ref(self):
+ if not self.repair_ref:
+ return None
+ try:
+ return json.loads(self.repair_ref)
+ except (json.JSONDecodeError, TypeError):
+ return None
+
+ def set_repair_ref(self, ref):
+ self.repair_ref = json.dumps(ref) if ref else None
+
+ def to_dict(self):
+ return {
+ 'id': self.id,
+ 'server_id': self.server_id,
+ 'check_key': self.check_key,
+ 'status': self.status,
+ 'title': self.title,
+ 'detail': self.detail,
+ 'repairable': bool(self.repairable),
+ 'repair_ref': self.get_repair_ref(),
+ 'ran_at': self.ran_at.isoformat() + 'Z' if self.ran_at else None,
+ }
+
+ def __repr__(self):
+ return f'<FleetDoctorResult {self.server_id} {self.check_key} {self.status}>'
diff --git a/backend/app/services/cron_run_service.py b/backend/app/services/cron_run_service.py
new file mode 100644
index 00000000..f9bea9fc
--- /dev/null
+++ b/backend/app/services/cron_run_service.py
@@ -0,0 +1,112 @@
+"""Cron run ingest + history + failure alerts.
+
+Records the runs reported by the ``serverkit-cron-run`` shim, exposes run
+history / success-rate for the UI, and fires edge-triggered failure/recovery
+notifications (Decision: transition-based like environment-health, never a
+cooldown timer).
+"""
+from datetime import datetime
+
+from app import db
+from app.models.cron_run import (
+ CronRun,
+ OUTPUT_TAIL_LIMIT,
+ STATUS_SUCCESS,
+ STATUS_FAILURE,
+)
+
+
+def _parse_dt(value):
+ if not value:
+ return None
+ if isinstance(value, datetime):
+ return value
+ try:
+ dt = datetime.fromisoformat(str(value).replace('Z', '+00:00'))
+ if dt.tzinfo is not None:
+ dt = dt.astimezone(tz=None).replace(tzinfo=None)
+ return dt
+ except (ValueError, TypeError):
+ return None
+
+
+class CronRunService:
+ """Stateless helpers over the CronRun table."""
+
+ @staticmethod
+ def _last_status(job_id):
+ """Status of the most recent completed run for a job, or None."""
+ last = (CronRun.query
+ .filter_by(job_id=job_id)
+ .order_by(CronRun.id.desc())
+ .first())
+ return last.status if last else None
+
+ @classmethod
+ def record_run(cls, job_id, started_at=None, finished_at=None,
+ exit_code=None, output_tail=None):
+ """Insert a completed run. Returns (run, transition) where transition is
+ 'failure' (fresh failure edge), 'recovery' (fresh success-after-failure
+ edge), or None (no status change / first-ever success)."""
+ prev = cls._last_status(job_id)
+ status = STATUS_SUCCESS if exit_code == 0 else STATUS_FAILURE
+
+ tail = output_tail or ''
+ if len(tail) > OUTPUT_TAIL_LIMIT:
+ tail = tail[-OUTPUT_TAIL_LIMIT:]
+
+ run = CronRun(
+ job_id=job_id,
+ started_at=_parse_dt(started_at),
+ finished_at=_parse_dt(finished_at) or datetime.utcnow(),
+ exit_code=exit_code,
+ status=status,
+ output_tail=tail or None,
+ )
+ db.session.add(run)
+ db.session.commit()
+
+ transition = None
+ if status == STATUS_FAILURE and prev != STATUS_FAILURE:
+ transition = 'failure'
+ elif status == STATUS_SUCCESS and prev == STATUS_FAILURE:
+ transition = 'recovery'
+ return run, transition
+
+ @staticmethod
+ def recent_runs(job_id, limit=10):
+ runs = (CronRun.query
+ .filter_by(job_id=job_id)
+ .order_by(CronRun.id.desc())
+ .limit(limit)
+ .all())
+ return [r.to_dict() for r in runs]
+
+ @staticmethod
+ def stats(job_id, window=20):
+ """Success-rate over the last `window` runs + the last run summary."""
+ runs = (CronRun.query
+ .filter_by(job_id=job_id)
+ .order_by(CronRun.id.desc())
+ .limit(window)
+ .all())
+ total = len(runs)
+ if not total:
+ return {
+ 'total': 0,
+ 'success': 0,
+ 'failure': 0,
+ 'success_rate': None,
+ 'last_status': None,
+ 'last_run': None,
+ }
+ success = sum(1 for r in runs if r.status == STATUS_SUCCESS)
+ last = runs[0]
+ return {
+ 'total': total,
+ 'success': success,
+ 'failure': total - success,
+ 'success_rate': round(success / total, 3),
+ 'last_status': last.status,
+ 'last_run': last.finished_at.isoformat() if last.finished_at else None,
+ }
diff --git a/backend/migrations/versions/056_cron_runs.py b/backend/migrations/versions/056_cron_runs.py
new file mode 100644
index 00000000..0308c44b
--- /dev/null
+++ b/backend/migrations/versions/056_cron_runs.py
@@ -0,0 +1,50 @@
+"""Cron run records.
+
+Adds the cron_runs table: one row per tracked execution of a panel cron job
+(job_id, timing, exit code, status, output tail). See app/models/cron_run.py and
+the serverkit-cron-run shim.
+
+Idempotent: MigrationService runs _fix_missing_columns() + db.create_all() on
+boot before Alembic, so guard on the live schema.
+
+Revision ID: 056_cron_runs
+Revises: 055_manifest_env_refs
+Create Date: 2026-07-05
+"""
+from alembic import op
+import sqlalchemy as sa
+
+revision = '056_cron_runs'
+down_revision = '055_manifest_env_refs'
+branch_labels = None
+depends_on = None
+
+
+def upgrade():
+ conn = op.get_bind()
+ inspector = sa.inspect(conn)
+ tables = set(inspector.get_table_names())
+
+ if 'cron_runs' not in tables:
+ op.create_table(
+ 'cron_runs',
+ sa.Column('id', sa.Integer(), nullable=False),
+ sa.Column('job_id', sa.String(length=64), nullable=False),
+ sa.Column('started_at', sa.DateTime(), nullable=True),
+ sa.Column('finished_at', sa.DateTime(), nullable=True),
+ sa.Column('exit_code', sa.Integer(), nullable=True),
+ sa.Column('status', sa.String(length=16), nullable=False,
+ server_default='running'),
+ sa.Column('output_tail', sa.Text(), nullable=True),
+ sa.Column('created_at', sa.DateTime(), nullable=True),
+ sa.PrimaryKeyConstraint('id'),
+ )
+ op.create_index('ix_cron_runs_job_id', 'cron_runs', ['job_id'])
+ op.create_index('ix_cron_runs_created_at', 'cron_runs', ['created_at'])
+
+
+def downgrade():
+ conn = op.get_bind()
+ inspector = sa.inspect(conn)
+ if 'cron_runs' in set(inspector.get_table_names()):
+ op.drop_table('cron_runs')
diff --git a/backend/migrations/versions/057_user_setup_snoozes.py b/backend/migrations/versions/057_user_setup_snoozes.py
new file mode 100644
index 00000000..364514ab
--- /dev/null
+++ b/backend/migrations/versions/057_user_setup_snoozes.py
@@ -0,0 +1,41 @@
+"""Per-user Setup Health item snoozes.
+
+Adds users.setup_snoozes (Text, JSON { item_key: iso_expiry }) so a user can mute
+a personal setup item (e.g. "secure your account"). Panel-item snoozes live in a
+SettingsService map, not here. See app/services/setup_health_service.py (plan 22
+Phase 6).
+
+Idempotent: MigrationService runs _fix_missing_columns() + db.create_all() on
+boot before Alembic, so guard on the live schema.
+
+Revision ID: 057_user_setup_snoozes
+Revises: 056_cron_runs
+Create Date: 2026-07-05
+"""
+from alembic import op
+import sqlalchemy as sa
+
+revision = '057_user_setup_snoozes'
+down_revision = '056_cron_runs'
+branch_labels = None
+depends_on = None
+
+
+def upgrade():
+ conn = op.get_bind()
+ inspector = sa.inspect(conn)
+ if 'users' not in set(inspector.get_table_names()):
+ return
+ cols = {c['name'] for c in inspector.get_columns('users')}
+ if 'setup_snoozes' not in cols:
+ op.add_column('users', sa.Column('setup_snoozes', sa.Text(), nullable=True))
+
+
+def downgrade():
+ conn = op.get_bind()
+ inspector = sa.inspect(conn)
+ if 'users' not in set(inspector.get_table_names()):
+ return
+ cols = {c['name'] for c in inspector.get_columns('users')}
+ if 'setup_snoozes' in cols:
+ op.drop_column('users', 'setup_snoozes')
diff --git a/backend/migrations/versions/060_notification_digest.py b/backend/migrations/versions/060_notification_digest.py
new file mode 100644
index 00000000..6e1a9c71
--- /dev/null
+++ b/backend/migrations/versions/060_notification_digest.py
@@ -0,0 +1,50 @@
+"""Notification digests — per-user cadence (plan 24 Phase 3).
+
+Adds ``digest_cadence`` ('off'|'daily'|'weekly', default 'off' — preserves the
+pre-digest immediate-send behavior) and ``digest_last_sent_at`` to
+``notification_preferences``. The digest itself reuses the existing
+``notification_deliveries`` table via a new status value ``queued_digest`` (no
+schema change for the status — it's a plain string column).
+
+Idempotent: MigrationService runs _fix_missing_columns() + db.create_all() on
+boot before Alembic, so guard on the live schema.
+
+Revision ID: 060_notification_digest
+Revises: 059_notification_prefs_events
+Create Date: 2026-07-05
+"""
+from alembic import op
+import sqlalchemy as sa
+
+revision = '060_notification_digest'
+down_revision = '059_notification_prefs_events'
+branch_labels = None
+depends_on = None
+
+
+def upgrade():
+ conn = op.get_bind()
+ inspector = sa.inspect(conn)
+ if 'notification_preferences' not in set(inspector.get_table_names()):
+ return
+ cols = {c['name'] for c in inspector.get_columns('notification_preferences')}
+ if 'digest_cadence' not in cols:
+ op.add_column('notification_preferences',
+ sa.Column('digest_cadence', sa.String(length=12),
+ nullable=True, server_default='off'))
+ if 'digest_last_sent_at' not in cols:
+ op.add_column('notification_preferences',
+ sa.Column('digest_last_sent_at', sa.DateTime(),
+ nullable=True))
+
+
+def downgrade():
+ conn = op.get_bind()
+ inspector = sa.inspect(conn)
+ if 'notification_preferences' not in set(inspector.get_table_names()):
+ return
+ cols = {c['name'] for c in inspector.get_columns('notification_preferences')}
+ if 'digest_last_sent_at' in cols:
+ op.drop_column('notification_preferences', 'digest_last_sent_at')
+ if 'digest_cadence' in cols:
+ op.drop_column('notification_preferences', 'digest_cadence')
diff --git a/backend/migrations/versions/062_notification_action_link.py b/backend/migrations/versions/062_notification_action_link.py
new file mode 100644
index 00000000..8d6c12d1
--- /dev/null
+++ b/backend/migrations/versions/062_notification_action_link.py
@@ -0,0 +1,49 @@
+"""Notification deep links (plan 24 Phase 5).
+
+Adds ``action_path`` + ``action_label`` to ``notifications``: a relative deep
+link to the notification's subject, computed at send time (catalog link builder
+or producer override) and persisted so a later route move never breaks old rows.
+Bell/history navigate to it; email/chat resolve it to an absolute URL.
+
+Idempotent: MigrationService runs _fix_missing_columns() + db.create_all() on
+boot before Alembic, so guard on the live schema.
+
+Revision ID: 062_notification_action_link
+Revises: 061_chat_webhook_connections
+Create Date: 2026-07-05
+"""
+from alembic import op
+import sqlalchemy as sa
+
+revision = '062_notification_action_link'
+down_revision = '061_chat_webhook_connections'
+branch_labels = None
+depends_on = None
+
+
+def upgrade():
+ conn = op.get_bind()
+ inspector = sa.inspect(conn)
+ if 'notifications' not in set(inspector.get_table_names()):
+ return
+ cols = {c['name'] for c in inspector.get_columns('notifications')}
+ if 'action_path' not in cols:
+ op.add_column('notifications',
+ sa.Column('action_path', sa.String(length=512),
+ nullable=True))
+ if 'action_label' not in cols:
+ op.add_column('notifications',
+ sa.Column('action_label', sa.String(length=120),
+ nullable=True))
+
+
+def downgrade():
+ conn = op.get_bind()
+ inspector = sa.inspect(conn)
+ if 'notifications' not in set(inspector.get_table_names()):
+ return
+ cols = {c['name'] for c in inspector.get_columns('notifications')}
+ if 'action_label' in cols:
+ op.drop_column('notifications', 'action_label')
+ if 'action_path' in cols:
+ op.drop_column('notifications', 'action_path')
diff --git a/backend/migrations/versions/063_fleet_doctor_results.py b/backend/migrations/versions/063_fleet_doctor_results.py
new file mode 100644
index 00000000..6c4ffb71
--- /dev/null
+++ b/backend/migrations/versions/063_fleet_doctor_results.py
@@ -0,0 +1,60 @@
+"""Fleet doctor per-server results (Fleet Parity Sweep, plan 26 Phase 2).
+
+Adds ``fleet_doctor_results`` — one row per ``(server_id, check_key)`` so the
+fleet health sweep records per-server outcomes as ROWS, not a panel-host blob
+(Decision 3). The panel-host doctor keeps its ``doctor_last_report`` settings
+blob; the report API merges the two.
+
+Idempotent: MigrationService runs _fix_missing_columns() + db.create_all() on
+boot before Alembic, so guard on the live schema (the table may already exist).
+
+Revision ID: 063_fleet_doctor_results
+Revises: 062_notification_action_link
+Create Date: 2026-07-05
+"""
+from alembic import op
+import sqlalchemy as sa
+
+revision = '063_fleet_doctor_results'
+down_revision = '062_notification_action_link'
+branch_labels = None
+depends_on = None
+
+
+def upgrade():
+ conn = op.get_bind()
+ inspector = sa.inspect(conn)
+ tables = set(inspector.get_table_names())
+
+ if 'fleet_doctor_results' not in tables:
+ op.create_table(
+ 'fleet_doctor_results',
+ sa.Column('id', sa.Integer(), nullable=False),
+ sa.Column('server_id', sa.String(length=36), nullable=False),
+ sa.Column('check_key', sa.String(length=160), nullable=False),
+ sa.Column('status', sa.String(length=16), nullable=False,
+ server_default='ok'),
+ sa.Column('title', sa.String(length=200), nullable=True),
+ sa.Column('detail', sa.Text(), nullable=True),
+ sa.Column('repairable', sa.Boolean(), nullable=False,
+ server_default=sa.false()),
+ sa.Column('repair_ref', sa.Text(), nullable=True),
+ sa.Column('ran_at', sa.DateTime(), nullable=False),
+ sa.ForeignKeyConstraint(['server_id'], ['servers.id']),
+ sa.PrimaryKeyConstraint('id'),
+ sa.UniqueConstraint('server_id', 'check_key',
+ name='uq_fleet_doctor_server_check'),
+ )
+ op.create_index('ix_fleet_doctor_results_server_id',
+ 'fleet_doctor_results', ['server_id'])
+ op.create_index('ix_fleet_doctor_results_check_key',
+ 'fleet_doctor_results', ['check_key'])
+ op.create_index('ix_fleet_doctor_results_ran_at',
+ 'fleet_doctor_results', ['ran_at'])
+
+
+def downgrade():
+ conn = op.get_bind()
+ inspector = sa.inspect(conn)
+ if 'fleet_doctor_results' in set(inspector.get_table_names()):
+ op.drop_table('fleet_doctor_results')
diff --git a/backend/migrations/versions/064_server_surveys.py b/backend/migrations/versions/064_server_surveys.py
new file mode 100644
index 00000000..722f6823
--- /dev/null
+++ b/backend/migrations/versions/064_server_surveys.py
@@ -0,0 +1,51 @@
+"""Server survey snapshots (Adoption/Import/Coexistence, plan 27 Phase 2).
+
+Adds ``server_surveys`` — one immutable row per read-only survey "flight" of a
+paired server (Decision 3: snapshots, not live state). Each row records the
+catalog version it was flown with and the normalized Server Map JSON, so any two
+flights of the same server can be diffed.
+
+Idempotent: MigrationService runs _fix_missing_columns() + db.create_all() on
+boot before Alembic, so guard on the live schema (the table may already exist).
+
+Revision ID: 064_server_surveys
+Revises: 063_fleet_doctor_results
+Create Date: 2026-07-05
+"""
+from alembic import op
+import sqlalchemy as sa
+
+revision = '064_server_surveys'
+down_revision = '063_fleet_doctor_results'
+branch_labels = None
+depends_on = None
+
+
+def upgrade():
+ conn = op.get_bind()
+ inspector = sa.inspect(conn)
+ tables = set(inspector.get_table_names())
+
+ if 'server_surveys' not in tables:
+ op.create_table(
+ 'server_surveys',
+ sa.Column('id', sa.Integer(), nullable=False),
+ sa.Column('server_id', sa.String(length=36), nullable=False),
+ sa.Column('catalog_version', sa.Integer(), nullable=False,
+ server_default='1'),
+ sa.Column('taken_at', sa.DateTime(), nullable=False),
+ sa.Column('map_json', sa.Text(), nullable=True),
+ sa.ForeignKeyConstraint(['server_id'], ['servers.id']),
+ sa.PrimaryKeyConstraint('id'),
+ )
+ op.create_index('ix_server_surveys_server_id',
+ 'server_surveys', ['server_id'])
+ op.create_index('ix_server_surveys_taken_at',
+ 'server_surveys', ['taken_at'])
+
+
+def downgrade():
+ conn = op.get_bind()
+ inspector = sa.inspect(conn)
+ if 'server_surveys' in set(inspector.get_table_names()):
+ op.drop_table('server_surveys')
diff --git a/backend/migrations/versions/065_server_management_mode.py b/backend/migrations/versions/065_server_management_mode.py
new file mode 100644
index 00000000..3f936524
--- /dev/null
+++ b/backend/migrations/versions/065_server_management_mode.py
@@ -0,0 +1,43 @@
+"""Server management mode — managed | observed (plan 27, Decision 1).
+
+Adds ``servers.management_mode`` (default ``managed``) so a paired box can be
+adopted read-only ("observed") without ServerKit fighting another panel over
+web-server config ownership. Existing rows backfill to ``managed`` — no server
+is ever auto-downgraded (Decision 4).
+
+Idempotent: MigrationService runs _fix_missing_columns() + db.create_all() on
+boot before Alembic, so guard on the live schema.
+
+Revision ID: 065_server_management_mode
+Revises: 064_server_surveys
+Create Date: 2026-07-05
+"""
+from alembic import op
+import sqlalchemy as sa
+
+revision = '065_server_management_mode'
+down_revision = '064_server_surveys'
+branch_labels = None
+depends_on = None
+
+
+def upgrade():
+ conn = op.get_bind()
+ inspector = sa.inspect(conn)
+ if 'servers' not in set(inspector.get_table_names()):
+ return
+ cols = {c['name'] for c in inspector.get_columns('servers')}
+ if 'management_mode' not in cols:
+ op.add_column('servers',
+ sa.Column('management_mode', sa.String(length=16),
+ nullable=False, server_default='managed'))
+
+
+def downgrade():
+ conn = op.get_bind()
+ inspector = sa.inspect(conn)
+ if 'servers' not in set(inspector.get_table_names()):
+ return
+ cols = {c['name'] for c in inspector.get_columns('servers')}
+ if 'management_mode' in cols:
+ op.drop_column('servers', 'management_mode')
diff --git a/backend/migrations/versions/067_dns_cutover_created_records.py b/backend/migrations/versions/067_dns_cutover_created_records.py
new file mode 100644
index 00000000..828641aa
--- /dev/null
+++ b/backend/migrations/versions/067_dns_cutover_created_records.py
@@ -0,0 +1,41 @@
+"""Reversible DNS cutover — created-record tracking (plan 31 #1/#3, Decision 3).
+
+Adds ``dns_cutover_snapshots.created_records_json`` — the records a cutover
+CREATED (no same-(type,name) predecessor in the snapshot). Revert DELETES these
+so the world is restored byte-for-byte, not just the captured values.
+
+Idempotent: MigrationService runs _fix_missing_columns() + db.create_all() on
+boot before Alembic, so guard on the live schema (the column may already exist).
+
+Revision ID: 067_dns_cutover_created_records
+Revises: 066_dns_cutover_snapshots
+Create Date: 2026-07-06
+"""
+from alembic import op
+import sqlalchemy as sa
+
+revision = '067_dns_cutover_created_records'
+down_revision = '066_dns_cutover_snapshots'
+branch_labels = None
+depends_on = None
+
+
+def upgrade():
+ conn = op.get_bind()
+ inspector = sa.inspect(conn)
+ if 'dns_cutover_snapshots' not in set(inspector.get_table_names()):
+ return
+ cols = {c['name'] for c in inspector.get_columns('dns_cutover_snapshots')}
+ if 'created_records_json' not in cols:
+ op.add_column('dns_cutover_snapshots',
+ sa.Column('created_records_json', sa.Text(), nullable=True))
+
+
+def downgrade():
+ conn = op.get_bind()
+ inspector = sa.inspect(conn)
+ if 'dns_cutover_snapshots' not in set(inspector.get_table_names()):
+ return
+ cols = {c['name'] for c in inspector.get_columns('dns_cutover_snapshots')}
+ if 'created_records_json' in cols:
+ op.drop_column('dns_cutover_snapshots', 'created_records_json')
diff --git a/backend/migrations/versions/068_server_allow_agent_update_observed.py b/backend/migrations/versions/068_server_allow_agent_update_observed.py
new file mode 100644
index 00000000..0c527e8a
--- /dev/null
+++ b/backend/migrations/versions/068_server_allow_agent_update_observed.py
@@ -0,0 +1,43 @@
+"""Observed-mode agent:update break-glass (plan 31 #10, Decision 6).
+
+Adds ``servers.allow_agent_update_observed`` (default False). Observed servers
+refuse ``agent:update`` unless this per-server override is set, so plan 27's
+read-only promise covers the agent binary itself instead of silently permitting
+a re-flash.
+
+Idempotent: MigrationService runs _fix_missing_columns() + db.create_all() on
+boot before Alembic, so guard on the live schema.
+
+Revision ID: 068_server_allow_agent_update_observed
+Revises: 067_dns_cutover_created_records
+Create Date: 2026-07-06
+"""
+from alembic import op
+import sqlalchemy as sa
+
+revision = '068_server_allow_agent_update_observed'
+down_revision = '067_dns_cutover_created_records'
+branch_labels = None
+depends_on = None
+
+
+def upgrade():
+ conn = op.get_bind()
+ inspector = sa.inspect(conn)
+ if 'servers' not in set(inspector.get_table_names()):
+ return
+ cols = {c['name'] for c in inspector.get_columns('servers')}
+ if 'allow_agent_update_observed' not in cols:
+ op.add_column('servers',
+ sa.Column('allow_agent_update_observed', sa.Boolean(),
+ nullable=False, server_default='0'))
+
+
+def downgrade():
+ conn = op.get_bind()
+ inspector = sa.inspect(conn)
+ if 'servers' not in set(inspector.get_table_names()):
+ return
+ cols = {c['name'] for c in inspector.get_columns('servers')}
+ if 'allow_agent_update_observed' in cols:
+ op.drop_column('servers', 'allow_agent_update_observed')
diff --git a/backend/migrations/versions/069_email_bounce_state.py b/backend/migrations/versions/069_email_bounce_state.py
new file mode 100644
index 00000000..cd48d64b
--- /dev/null
+++ b/backend/migrations/versions/069_email_bounce_state.py
@@ -0,0 +1,56 @@
+"""Email bounce/complaint suppression state (plan 33 Phase 4, roadmap #24).
+
+Adds ``email_bounce_state`` — one row per address a provider reported a bounce
+or complaint for. Drives the auto-mute of a hard-bouncing address and the
+"email bouncing" badge in a user's notification settings.
+
+Idempotent: MigrationService runs _fix_missing_columns() + db.create_all() on
+boot before Alembic, so guard on the live schema (the table may already exist).
+
+Revision ID: 069_email_bounce_state
+Revises: 068_server_allow_agent_update_observed
+Create Date: 2026-07-06
+"""
+from alembic import op
+import sqlalchemy as sa
+
+revision = '069_email_bounce_state'
+down_revision = '068_server_allow_agent_update_observed'
+branch_labels = None
+depends_on = None
+
+
+def upgrade():
+ conn = op.get_bind()
+ inspector = sa.inspect(conn)
+ tables = set(inspector.get_table_names())
+
+ if 'email_bounce_state' not in tables:
+ op.create_table(
+ 'email_bounce_state',
+ sa.Column('id', sa.Integer(), nullable=False),
+ sa.Column('email', sa.String(length=255), nullable=False),
+ sa.Column('consecutive_bounces', sa.Integer(), nullable=False,
+ server_default='0'),
+ sa.Column('total_events', sa.Integer(), nullable=False,
+ server_default='0'),
+ sa.Column('muted', sa.Boolean(), nullable=False, server_default='0'),
+ sa.Column('muted_at', sa.DateTime(), nullable=True),
+ sa.Column('last_kind', sa.String(length=20), nullable=True),
+ sa.Column('last_reason', sa.String(length=500), nullable=True),
+ sa.Column('last_event_at', sa.DateTime(), nullable=True),
+ sa.Column('created_at', sa.DateTime(), nullable=True),
+ sa.Column('updated_at', sa.DateTime(), nullable=True),
+ sa.PrimaryKeyConstraint('id'),
+ )
+ op.create_index('ix_email_bounce_state_email', 'email_bounce_state',
+ ['email'], unique=True)
+ op.create_index('ix_email_bounce_state_muted', 'email_bounce_state',
+ ['muted'])
+
+
+def downgrade():
+ conn = op.get_bind()
+ inspector = sa.inspect(conn)
+ if 'email_bounce_state' in set(inspector.get_table_names()):
+ op.drop_table('email_bounce_state')
diff --git a/backend/migrations/versions/070_app_ports.py b/backend/migrations/versions/070_app_ports.py
new file mode 100644
index 00000000..07d2655a
--- /dev/null
+++ b/backend/migrations/versions/070_app_ports.py
@@ -0,0 +1,40 @@
+"""Typed application port declarations (Appliance tier, plan 35).
+
+Adds ``applications.ports`` — a JSON list of typed port declarations
+({container, host, protocol, ...}) that the appliance-tier ports+blockers rail
+reads. Nullable; NULL means "no declared ports" (legacy apps use ``port``).
+
+Idempotent: MigrationService runs _fix_missing_columns() + db.create_all() on
+boot before Alembic, so guard on the live schema.
+
+Revision ID: 070_app_ports
+Revises: 069_email_bounce_state
+Create Date: 2026-07-07
+"""
+from alembic import op
+import sqlalchemy as sa
+
+revision = '070_app_ports'
+down_revision = '069_email_bounce_state'
+branch_labels = None
+depends_on = None
+
+
+def upgrade():
+ conn = op.get_bind()
+ inspector = sa.inspect(conn)
+ if 'applications' not in set(inspector.get_table_names()):
+ return
+ cols = {c['name'] for c in inspector.get_columns('applications')}
+ if 'ports' not in cols:
+ op.add_column('applications', sa.Column('ports', sa.Text(), nullable=True))
+
+
+def downgrade():
+ conn = op.get_bind()
+ inspector = sa.inspect(conn)
+ if 'applications' not in set(inspector.get_table_names()):
+ return
+ cols = {c['name'] for c in inspector.get_columns('applications')}
+ if 'ports' in cols:
+ op.drop_column('applications', 'ports')
diff --git a/backend/migrations/versions/071_app_volume_declared_size.py b/backend/migrations/versions/071_app_volume_declared_size.py
new file mode 100644
index 00000000..c3250976
--- /dev/null
+++ b/backend/migrations/versions/071_app_volume_declared_size.py
@@ -0,0 +1,42 @@
+"""Declared volume size (Appliance tier, plan 35).
+
+Adds ``app_volumes.declared_size`` — the operator/manifest-declared size cap for
+a volume (e.g. "10Gi"), distinct from ``size_bytes`` (the last-measured actual
+usage). Nullable.
+
+Idempotent: MigrationService runs _fix_missing_columns() + db.create_all() on
+boot before Alembic, so guard on the live schema.
+
+Revision ID: 071_app_volume_declared_size
+Revises: 070_app_ports
+Create Date: 2026-07-07
+"""
+from alembic import op
+import sqlalchemy as sa
+
+revision = '071_app_volume_declared_size'
+down_revision = '070_app_ports'
+branch_labels = None
+depends_on = None
+
+
+def upgrade():
+ conn = op.get_bind()
+ inspector = sa.inspect(conn)
+ if 'app_volumes' not in set(inspector.get_table_names()):
+ return
+ cols = {c['name'] for c in inspector.get_columns('app_volumes')}
+ if 'declared_size' not in cols:
+ op.add_column('app_volumes',
+ sa.Column('declared_size', sa.String(length=40),
+ nullable=True))
+
+
+def downgrade():
+ conn = op.get_bind()
+ inspector = sa.inspect(conn)
+ if 'app_volumes' not in set(inspector.get_table_names()):
+ return
+ cols = {c['name'] for c in inspector.get_columns('app_volumes')}
+ if 'declared_size' in cols:
+ op.drop_column('app_volumes', 'declared_size')
diff --git a/backend/migrations/versions/072_app_bootstrap_done.py b/backend/migrations/versions/072_app_bootstrap_done.py
new file mode 100644
index 00000000..c8f2787d
--- /dev/null
+++ b/backend/migrations/versions/072_app_bootstrap_done.py
@@ -0,0 +1,42 @@
+"""One-shot appliance bootstrap flag (Appliance tier, plan 35).
+
+Adds ``applications.bootstrap_done`` (default False) — set once the appliance
+``bootstrap`` step has run for an app, so it is never re-run on subsequent
+deploys.
+
+Idempotent: MigrationService runs _fix_missing_columns() + db.create_all() on
+boot before Alembic, so guard on the live schema.
+
+Revision ID: 072_app_bootstrap_done
+Revises: 071_app_volume_declared_size
+Create Date: 2026-07-07
+"""
+from alembic import op
+import sqlalchemy as sa
+
+revision = '072_app_bootstrap_done'
+down_revision = '071_app_volume_declared_size'
+branch_labels = None
+depends_on = None
+
+
+def upgrade():
+ conn = op.get_bind()
+ inspector = sa.inspect(conn)
+ if 'applications' not in set(inspector.get_table_names()):
+ return
+ cols = {c['name'] for c in inspector.get_columns('applications')}
+ if 'bootstrap_done' not in cols:
+ op.add_column('applications',
+ sa.Column('bootstrap_done', sa.Boolean(), nullable=False,
+ server_default='0'))
+
+
+def downgrade():
+ conn = op.get_bind()
+ inspector = sa.inspect(conn)
+ if 'applications' not in set(inspector.get_table_names()):
+ return
+ cols = {c['name'] for c in inspector.get_columns('applications')}
+ if 'bootstrap_done' in cols:
+ op.drop_column('applications', 'bootstrap_done')
diff --git a/backend/migrations/versions/073_dns_provider_origin_ca_key.py b/backend/migrations/versions/073_dns_provider_origin_ca_key.py
new file mode 100644
index 00000000..ed488c8e
--- /dev/null
+++ b/backend/migrations/versions/073_dns_provider_origin_ca_key.py
@@ -0,0 +1,41 @@
+"""Cloudflare Origin CA private key (plan 36 Origin CA).
+
+Adds ``dns_provider_configs.origin_ca_key`` — the private key the panel
+generated for the CSR when issuing an Origin certificate for this provider's
+zones. Stored so the matching certificate can be installed on the origin.
+
+Idempotent: MigrationService runs _fix_missing_columns() + db.create_all() on
+boot before Alembic, so guard on the live schema.
+
+Revision ID: 073_dns_provider_origin_ca_key
+Revises: 072_app_bootstrap_done
+Create Date: 2026-07-07
+"""
+from alembic import op
+import sqlalchemy as sa
+
+revision = '073_dns_provider_origin_ca_key'
+down_revision = '072_app_bootstrap_done'
+branch_labels = None
+depends_on = None
+
+
+def upgrade():
+ conn = op.get_bind()
+ inspector = sa.inspect(conn)
+ if 'dns_provider_configs' not in set(inspector.get_table_names()):
+ return
+ cols = {c['name'] for c in inspector.get_columns('dns_provider_configs')}
+ if 'origin_ca_key' not in cols:
+ op.add_column('dns_provider_configs',
+ sa.Column('origin_ca_key', sa.Text(), nullable=True))
+
+
+def downgrade():
+ conn = op.get_bind()
+ inspector = sa.inspect(conn)
+ if 'dns_provider_configs' not in set(inspector.get_table_names()):
+ return
+ cols = {c['name'] for c in inspector.get_columns('dns_provider_configs')}
+ if 'origin_ca_key' in cols:
+ op.drop_column('dns_provider_configs', 'origin_ca_key')
diff --git a/backend/migrations/versions/074_cf_ops_changes.py b/backend/migrations/versions/074_cf_ops_changes.py
new file mode 100644
index 00000000..cc0198d7
--- /dev/null
+++ b/backend/migrations/versions/074_cf_ops_changes.py
@@ -0,0 +1,60 @@
+"""Per-zone Cloudflare-ops activity ledger (plan 36 #10).
+
+Adds ``cf_ops_changes`` — the ops-layer sibling of ``dns_changes`` — recording
+every Cloudflare zone-operations write ServerKit makes (settings, DNSSEC, WAF,
+redirect/transform rules, Origin CA, Workers, Tunnels, storage), keyed by
+``provider_zone_id`` for the per-zone Activity tab.
+
+Idempotent: MigrationService runs _fix_missing_columns() + db.create_all() on
+boot before Alembic, so guard on the live schema (the table may already exist).
+
+Revision ID: 074_cf_ops_changes
+Revises: 073_dns_provider_origin_ca_key
+Create Date: 2026-07-07
+"""
+from alembic import op
+import sqlalchemy as sa
+
+revision = '074_cf_ops_changes'
+down_revision = '073_dns_provider_origin_ca_key'
+branch_labels = None
+depends_on = None
+
+
+def upgrade():
+ conn = op.get_bind()
+ inspector = sa.inspect(conn)
+ tables = set(inspector.get_table_names())
+
+ if 'cf_ops_changes' not in tables:
+ op.create_table(
+ 'cf_ops_changes',
+ sa.Column('id', sa.Integer(), nullable=False),
+ sa.Column('dns_provider_config_id', sa.Integer(), nullable=True),
+ sa.Column('provider_zone_id', sa.String(length=128), nullable=True),
+ sa.Column('product', sa.String(length=32), nullable=False),
+ sa.Column('action', sa.String(length=32), nullable=False),
+ sa.Column('target', sa.String(length=256), nullable=True),
+ sa.Column('result', sa.String(length=16), nullable=False,
+ server_default='ok'),
+ sa.Column('error', sa.Text(), nullable=True),
+ sa.Column('user_id', sa.Integer(), nullable=True),
+ sa.Column('created_at', sa.DateTime(), nullable=True),
+ sa.ForeignKeyConstraint(['dns_provider_config_id'],
+ ['dns_provider_configs.id']),
+ sa.ForeignKeyConstraint(['user_id'], ['users.id']),
+ sa.PrimaryKeyConstraint('id'),
+ )
+ op.create_index('ix_cf_ops_changes_dns_provider_config_id',
+ 'cf_ops_changes', ['dns_provider_config_id'])
+ op.create_index('ix_cf_ops_changes_provider_zone_id',
+ 'cf_ops_changes', ['provider_zone_id'])
+ op.create_index('ix_cf_ops_changes_created_at',
+ 'cf_ops_changes', ['created_at'])
+
+
+def downgrade():
+ conn = op.get_bind()
+ inspector = sa.inspect(conn)
+ if 'cf_ops_changes' in set(inspector.get_table_names()):
+ op.drop_table('cf_ops_changes')