diff --git a/.claude/docs/working/ACCESS_LAYER_ENDPOINT_AUDIT.md b/.claude/docs/working/ACCESS_LAYER_ENDPOINT_AUDIT.md
index d13886e..a58435b 100644
--- a/.claude/docs/working/ACCESS_LAYER_ENDPOINT_AUDIT.md
+++ b/.claude/docs/working/ACCESS_LAYER_ENDPOINT_AUDIT.md
@@ -29,6 +29,8 @@ Fortlaufend gemäß `ACCESS_LAYER_AND_GOVERNANCE_PLAN.md` Stufe A–C.
| media_assets | `PATCH /api/media-assets/{id}` | ja | `get_tenant_context` | ja | Copyright, `original_filename`, optional `visibility`/`club_id`; Rechte pro Stufe |
| media_assets | `GET /api/media-assets/{id}/file` | ja | `get_tenant_context_flexible` | ja | aktiv: Bibliotheks-Sichtbarkeit; `trash_soft`/`trash_hidden`: wie Lifecycle-Verwaltung |
| exercises | `POST /api/exercises/{id}/media/from-asset` | ja | `get_tenant_context` | ja | Verknüpfung `exercise_media` → bestehendes `media_asset_id`; Bearbeitungsrecht Übung + Leserecht Archiv |
+| distribution | `GET /api/distribution/v1/*` | Kanal aus Schlüssel | kein Trainer-Tenant | ja, Empfänger der Anbindung | ACCESS_LAYER exempt: Bearer-Distributions-Schlüssel, nicht `X-Auth-Token`. `GET …/exercises/{source_id}/availability` meldet Quelle und Paketstand dieses Kanals |
+| distribution | `POST /api/exercises/{id}/distribution/*`, `/api/distribution/admin/*` | ja | `get_tenant_context` | ja | Privat: Besitzer; Verein: `club_admin` dieses Vereins; global: nur `superadmin`; Verwaltung nur `superadmin` |
| auth | `/api/auth/*` | nein | — | Login/Session | EXEMPT |
| catalogs | Katalog-CRUD | nein (global) | `require_auth` | Admin/Trainer je Endpoint | EXEMPT; bei späterem `club_id` nachziehen |
| skills | `/api/skills*` | nein (global) | `require_auth` | je Endpoint | EXEMPT |
diff --git a/backend/distribution_contract.py b/backend/distribution_contract.py
new file mode 100644
index 0000000..cce746f
--- /dev/null
+++ b/backend/distribution_contract.py
@@ -0,0 +1,627 @@
+"""Vertrag v1: kanonisches Manifest, Ereignisse, Freigaberegeln, Cursor.
+
+Reine Funktionen. Die Datenbankschicht ruft sie auf, die Tests prüfen sie ohne Postgres.
+"""
+from __future__ import annotations
+
+import base64
+import hashlib
+import hmac
+import json
+import os
+import re
+import uuid
+from datetime import datetime, timezone
+from html import unescape
+from typing import Any, Iterable, Optional
+
+PART_ROLES = (
+ "goal",
+ "prerequisites",
+ "preparation",
+ "instructions",
+ "trainer_notes",
+ "equipment",
+ "duration_note",
+)
+ASSET_ROLES = ("demonstration", "worksheet", "illustration")
+ACTIONS = (
+ "store",
+ "render",
+ "stream",
+ "download",
+ "print",
+ "course_display",
+ "commercial_course_use",
+ "adapt",
+ "public_preview",
+ "grant_customer_use",
+)
+REASON_CODES = ("rights", "safety", "privacy", "expired", "editorial_error")
+WITHDRAW_TYPES = ("release.withdrawn", "variant.withdrawn", "asset.withdrawn")
+EVENT_TYPES = ("release.published", "release.retired", *WITHDRAW_TYPES)
+
+_TAG = re.compile(r"<[^>]+>")
+_MEDIA_TOKEN = re.compile(r"\{\{exerciseMedia:(\d+)\}\}")
+_DATA_MEDIA = re.compile(r'data-exercise-media-id=["\'](\d+)["\']', re.I)
+
+LEGAL_HOLD_REASON = {
+ "rights_dispute": "rights",
+ "copyright_complaint": "rights",
+ "consent_withdrawn": "privacy",
+ "privacy_complaint": "privacy",
+ "youth_protection": "safety",
+ "illegal_content": "safety",
+ "other": "safety",
+}
+
+OFFICIAL_WRITE_DENIED = "Globale Übungen dürfen nur von Superadmins bearbeitet werden."
+RATE_LIMIT_PER_MINUTE = 60
+
+
+def distribution_enabled() -> bool:
+ return os.getenv("DISTRIBUTION_ENABLED", "").strip().lower() in ("1", "true", "yes")
+
+
+def cursor_secret() -> str:
+ secret = os.getenv("DISTRIBUTION_CURSOR_SECRET", "").strip()
+ if secret:
+ return secret
+ if os.getenv("ENVIRONMENT", "development").strip().lower() in ("production", "prod"):
+ raise RuntimeError("DISTRIBUTION_CURSOR_SECRET fehlt")
+ return "shinkan-distribution-dev-cursor"
+
+
+def format_utc(dt: datetime) -> str:
+ if dt.tzinfo is None:
+ dt = dt.replace(tzinfo=timezone.utc)
+ return dt.astimezone(timezone.utc).replace(microsecond=0).strftime("%Y-%m-%dT%H:%M:%SZ")
+
+
+def parse_utc(value: str) -> datetime:
+ raw = value.strip()
+ if raw.endswith("Z"):
+ raw = raw[:-1] + "+00:00"
+ parsed = datetime.fromisoformat(raw)
+ if parsed.tzinfo is None:
+ parsed = parsed.replace(tzinfo=timezone.utc)
+ return parsed.astimezone(timezone.utc)
+
+
+def canonical_json(value: Any) -> bytes:
+ return json.dumps(value, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
+
+
+def sha256_bytes(data: bytes) -> str:
+ return hashlib.sha256(data).hexdigest()
+
+
+def _copy_if(source: dict, key: str, required: bool = False, keep_null: bool = False) -> Any:
+ if key not in source:
+ if required:
+ raise ValueError(f"Feld fehlt: {key}")
+ return None
+ value = source[key]
+ if value is None and not keep_null:
+ return None
+ return value
+
+
+def order_manifest(source: dict) -> dict:
+ """Feldreihenfolge des Übergabevertrags. Optionale leere Felder entfallen, null bleibt bei Fristen."""
+ exercise = source["exercise"]
+ ordered_exercise: dict[str, Any] = {"title": exercise["title"]}
+ if exercise.get("summary") is not None:
+ ordered_exercise["summary"] = exercise["summary"]
+ if exercise.get("audience") is not None:
+ ordered_exercise["audience"] = exercise["audience"]
+ ordered_exercise["rights_id"] = exercise["rights_id"]
+ ordered_exercise["parts"] = [
+ {
+ "id": part["id"],
+ "role": part["role"],
+ "text": part["text"],
+ "rights_id": part["rights_id"],
+ }
+ for part in exercise["parts"]
+ ]
+ assets = []
+ for asset in exercise["assets"]:
+ item = {
+ "id": asset["id"],
+ "role": asset["role"],
+ "media_type": asset["media_type"],
+ "size_bytes": asset["size_bytes"],
+ "sha256": asset["sha256"],
+ "rights_id": asset["rights_id"],
+ }
+ if asset.get("label") is not None:
+ item["label"] = asset["label"]
+ assets.append(item)
+ ordered_exercise["assets"] = assets
+ ordered_exercise["common_part_ids"] = list(exercise["common_part_ids"])
+ ordered_exercise["common_asset_ids"] = list(exercise["common_asset_ids"])
+ ordered_exercise["variants"] = [
+ {
+ "id": variant["id"],
+ "label": variant["label"],
+ "part_ids": list(variant["part_ids"]),
+ "asset_ids": list(variant["asset_ids"]),
+ }
+ for variant in exercise["variants"]
+ ]
+ rights = []
+ for right in source["rights"]:
+ item = {
+ "id": right["id"],
+ "evidence_ref": right["evidence_ref"],
+ "actions": list(right["actions"]),
+ "territories": right["territories"],
+ "valid_from": right["valid_from"],
+ "valid_until": right["valid_until"],
+ }
+ if right.get("attribution") is not None:
+ item["attribution"] = right["attribution"]
+ rights.append(item)
+ return {
+ "schema_version": source["schema_version"],
+ "resource_type": source["resource_type"],
+ "release_id": source["release_id"],
+ "source_id": source["source_id"],
+ "revision": source["revision"],
+ "publisher_id": source["publisher_id"],
+ "published_at": source["published_at"],
+ "exercise": ordered_exercise,
+ "rights": rights,
+ }
+
+
+def manifest_bytes(source: dict) -> bytes:
+ return canonical_json(order_manifest(source))
+
+
+def order_event(event: dict) -> dict:
+ ordered = {
+ "event_id": event["event_id"],
+ "type": event["type"],
+ "release_id": event["release_id"],
+ "occurred_at": event["occurred_at"],
+ }
+ if event["type"] == "release.published":
+ ordered["source_id"] = event["source_id"]
+ ordered["revision"] = event["revision"]
+ ordered["manifest_sha256"] = event["manifest_sha256"]
+ elif event["type"] in WITHDRAW_TYPES:
+ if event["type"] != "release.withdrawn":
+ ordered["target_id"] = event["target_id"]
+ ordered["reason_code"] = event["reason_code"]
+ return ordered
+
+
+def encode_cursor(secret: str, recipient_id: str, seq: int) -> str:
+ payload = f"{recipient_id}:{int(seq)}".encode("utf-8")
+ sig = hmac.new(secret.encode("utf-8"), payload, hashlib.sha256).hexdigest()
+ raw = payload + b"." + sig.encode("ascii")
+ return base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=")
+
+
+def decode_cursor(secret: str, recipient_id: str, token: Optional[str]) -> int:
+ if token is None or token == "":
+ return 0
+ pad = "=" * (-len(token) % 4)
+ try:
+ raw = base64.urlsafe_b64decode(token + pad)
+ payload, sig = raw.rsplit(b".", 1)
+ expected = hmac.new(secret.encode("utf-8"), payload, hashlib.sha256).hexdigest().encode("ascii")
+ if not hmac.compare_digest(sig, expected):
+ raise ValueError("sig")
+ rec, seq_raw = payload.decode("utf-8").split(":", 1)
+ if rec != recipient_id:
+ raise ValueError("channel")
+ seq = int(seq_raw)
+ if seq < 0:
+ raise ValueError("seq")
+ return seq
+ except Exception as exc:
+ raise InvalidCursor() from exc
+
+
+class InvalidCursor(Exception):
+ pass
+
+
+def official_write_allowed(visibility: Optional[str], role: Optional[str]) -> bool:
+ if (visibility or "").strip().lower() != "official":
+ return True
+ return (role or "").strip().lower() == "superadmin"
+
+
+def _same_club(left: Any, right: Any) -> bool:
+ try:
+ return left is not None and right is not None and int(left) == int(right)
+ except (TypeError, ValueError):
+ return False
+
+
+def release_denial(
+ *,
+ visibility: Optional[str],
+ role: Optional[str],
+ publisher_kind: str,
+ is_owner: bool,
+ is_club_admin: bool,
+ publisher_club_id: Any = None,
+ exercise_club_id: Any = None,
+) -> Optional[str]:
+ """Freigabe folgt der Zugehörigkeit der Übung, nicht einer gesonderten Zuordnungsliste."""
+ vis = (visibility or "").strip().lower()
+ role_l = (role or "").strip().lower()
+ kind = (publisher_kind or "").strip().lower()
+ if vis == "official":
+ if role_l != "superadmin":
+ return "Globale Übungen dürfen nur von Superadmins freigegeben werden."
+ if kind != "platform":
+ return "Globale Übungen werden nur über den Plattformbestand freigegeben."
+ return None
+ if kind == "platform":
+ return "Der Plattformbestand gibt nur globale Übungen frei."
+ if vis == "private":
+ if not is_owner:
+ return "Private Übungen gibt nur die Person frei, der sie gehören."
+ if kind != "own":
+ return "Private Übungen werden über den eigenen Bestand freigegeben."
+ return None
+ if vis == "club":
+ if not is_club_admin:
+ return "Vereinsübungen gibt ein Vereinsadmin dieses Vereins frei."
+ if kind != "club" or not _same_club(publisher_club_id, exercise_club_id):
+ return "Vereinsübungen werden über den Bestand dieses Vereins freigegeben."
+ return None
+ return "Diese Übung kann so nicht freigegeben werden."
+
+
+def can_withdraw(*, role: Optional[str], denial: Optional[str]) -> bool:
+ if (role or "").strip().lower() == "superadmin":
+ return True
+ return denial is None
+
+
+def package_state(*, fetch_blocked: bool, retired: bool) -> str:
+ if fetch_blocked:
+ return "withdrawn"
+ if retired:
+ return "retired"
+ return "available"
+
+
+def exercise_offerable(source_status: Optional[str], package_states: Iterable[str]) -> tuple[str, bool]:
+ """Die eingefrorene Kopie bleibt abrufbar. Neu anbieten darf der Empfänger sie nur, solange die Quelle approved und ein Paket verfügbar ist."""
+ status = "deleted" if not (source_status or "").strip() else str(source_status).strip().lower()
+ states = list(package_states)
+ return status, status == "approved" and any(item == "available" for item in states)
+
+
+def decide_confirm(stored_release_id: Optional[str], new_release_id: str) -> tuple[str, bool]:
+ """Technische Wiederholung liefert die gespeicherte Paket-ID. Eine neue Bestätigung legt ein Paket an."""
+ if stored_release_id:
+ return stored_release_id, False
+ return new_release_id, True
+
+
+def rate_decision(hits: int, window_age_seconds: float, limit: int = RATE_LIMIT_PER_MINUTE) -> tuple[int, bool]:
+ if window_age_seconds >= 60:
+ return 1, False
+ if hits >= limit:
+ return hits, True
+ return hits + 1, False
+
+
+def plaintext(value: Optional[str]) -> str:
+ text = value or ""
+ text = _MEDIA_TOKEN.sub("", text)
+ text = _DATA_MEDIA.sub("", text)
+ text = _TAG.sub("", text)
+ return unescape(text).strip()
+
+
+def inline_media_ids(value: Optional[str]) -> set[int]:
+ if not value:
+ return set()
+ ids = {int(item) for item in _MEDIA_TOKEN.findall(value)}
+ ids.update(int(item) for item in _DATA_MEDIA.findall(value))
+ return ids
+
+
+def snapshot_hash(exercise: dict, variants: list[dict], media: list[dict]) -> str:
+ body = {
+ "title": exercise.get("title") or "",
+ "summary": exercise.get("summary") or "",
+ "goal": exercise.get("goal") or "",
+ "execution": exercise.get("execution") or "",
+ "preparation": exercise.get("preparation") or "",
+ "trainer_notes": exercise.get("trainer_notes") or "",
+ "equipment": exercise.get("equipment"),
+ "duration_min": exercise.get("duration_min"),
+ "duration_max": exercise.get("duration_max"),
+ "status": exercise.get("status"),
+ "exercise_kind": exercise.get("exercise_kind") or "simple",
+ "variants": [
+ {
+ "id": str(item.get("public_id")),
+ "name": item.get("variant_name") or "",
+ "description": item.get("description") or "",
+ "execution_changes": item.get("execution_changes") or "",
+ "duration_min": item.get("duration_min"),
+ "duration_max": item.get("duration_max"),
+ }
+ for item in variants
+ ],
+ "media": [
+ {
+ "id": str(item.get("public_id")),
+ "sha256": item.get("sha256") or "",
+ "media_type": item.get("media_type") or "",
+ }
+ for item in media
+ ],
+ }
+ return sha256_bytes(canonical_json(body))
+
+
+def _duration_note(exercise: dict) -> Optional[str]:
+ low = exercise.get("duration_min")
+ high = exercise.get("duration_max")
+ if low and high:
+ return f"{low}–{high} Minuten"
+ if low or high:
+ return f"{low or high} Minuten"
+ return None
+
+
+def _equipment_text(exercise: dict) -> Optional[str]:
+ raw = exercise.get("equipment")
+ if isinstance(raw, str):
+ try:
+ raw = json.loads(raw)
+ except json.JSONDecodeError:
+ raw = [raw] if raw.strip() else []
+ if isinstance(raw, list):
+ parts = [str(item).strip() for item in raw if str(item).strip()]
+ return ", ".join(parts) or None
+ return None
+
+
+def default_cut(exercise: dict, variants: list[dict], media: list[dict]) -> dict:
+ parts: list[dict] = []
+
+ def add(key: str, role: str, text: Optional[str]) -> None:
+ cleaned = plaintext(text)
+ if cleaned:
+ parts.append({"key": key, "role": role, "text": cleaned})
+
+ add("field:goal", "goal", exercise.get("goal"))
+ add("field:preparation", "preparation", exercise.get("preparation"))
+ add("field:trainer_notes", "trainer_notes", exercise.get("trainer_notes"))
+ add("field:equipment", "equipment", _equipment_text(exercise))
+ add("field:duration", "duration_note", _duration_note(exercise))
+ common_keys = [part["key"] for part in parts]
+ variant_rows = []
+ if variants:
+ for variant in variants:
+ key = f"variant:{variant['public_id']}:instructions"
+ text = plaintext(exercise.get("execution"))
+ extra = plaintext(variant.get("execution_changes"))
+ combined = "\n".join(piece for piece in (text, extra) if piece)
+ if combined:
+ parts.append({"key": key, "role": "instructions", "text": combined})
+ variant_rows.append(
+ {
+ "key": str(variant["public_id"]),
+ "label": variant.get("variant_name") or "Variante",
+ "part_keys": [key] if combined else [],
+ "media_ids": [],
+ }
+ )
+ else:
+ key = "variant:default:instructions"
+ text = plaintext(exercise.get("execution"))
+ if text:
+ parts.append({"key": key, "role": "instructions", "text": text})
+ variant_rows.append(
+ {
+ "key": "default",
+ "label": "Standard",
+ "part_keys": [key] if text else [],
+ "media_ids": [],
+ }
+ )
+ assets = []
+ for item in media:
+ kind = (item.get("media_type") or "").lower()
+ if kind == "video":
+ role = "demonstration"
+ elif kind in ("document", "pdf"):
+ role = "worksheet"
+ else:
+ role = "illustration"
+ assets.append(
+ {
+ "media_id": str(item["public_id"]),
+ "role": role,
+ "label": item.get("title") or None,
+ }
+ )
+ return {
+ "title": exercise.get("title") or "",
+ "summary": plaintext(exercise.get("summary")) or None,
+ "audience": None,
+ "rights": [],
+ "parts": parts,
+ "assets": assets,
+ "common_part_keys": common_keys,
+ "common_media_ids": [],
+ "variants": variant_rows,
+ }
+
+
+def cut_hash(cut: dict) -> str:
+ return sha256_bytes(canonical_json(cut))
+
+
+def collect_blockers(exercise: dict, variants: list[dict], media: list[dict], cut: dict, now: datetime) -> list[str]:
+ blockers: list[str] = []
+ if (exercise.get("exercise_kind") or "simple") != "simple":
+ blockers.append("Kombinationsübungen können in dieser Fassung nicht herausgegeben werden.")
+ if (exercise.get("status") or "") != "approved":
+ blockers.append("Nur Übungen mit Status approved können freigegeben werden.")
+ texts = " ".join(
+ str(exercise.get(field) or "")
+ for field in ("goal", "execution", "preparation", "trainer_notes", "summary")
+ )
+ selected_media = {str(item.get("media_id")) for item in cut.get("assets") or []}
+ known_media = {str(item.get("public_id")): item for item in media}
+ referenced = inline_media_ids(texts)
+ for media_id in referenced:
+ match = next((item for item in media if int(item.get("id") or 0) == media_id), None)
+ if match is None or str(match.get("public_id")) not in selected_media:
+ blockers.append("Ein Medienanker im Text ist nicht als Medium im Paket enthalten.")
+ break
+ part_keys = [part.get("key") for part in cut.get("parts") or []]
+ if len(part_keys) != len(set(part_keys)):
+ blockers.append("Teilschlüssel sind nicht eindeutig.")
+ if not any(part.get("role") == "goal" and str(part.get("text") or "").strip() for part in cut.get("parts") or []):
+ blockers.append("Das Paket braucht ein Lernziel.")
+ rights = {item.get("id"): item for item in cut.get("rights") or []}
+ if None in rights or "" in rights:
+ blockers.append("Jeder Rechtevermerk braucht eine Kennung.")
+ for right in cut.get("rights") or []:
+ actions = set(right.get("actions") or [])
+ unknown = actions - set(ACTIONS)
+ if unknown:
+ blockers.append("Unbekannte Nutzungsaktion im Rechtevermerk.")
+ if "store" not in actions:
+ blockers.append("Jeder Rechtevermerk muss die Übernahme erlauben.")
+ if not str(right.get("evidence_ref") or "").strip():
+ blockers.append("Jeder Rechtevermerk braucht eine Nachweisreferenz.")
+ try:
+ start = parse_utc(right["valid_from"])
+ except Exception:
+ blockers.append("valid_from ist kein UTC-Zeitpunkt.")
+ continue
+ until_raw = right.get("valid_until")
+ until = None
+ if until_raw is not None:
+ try:
+ until = parse_utc(until_raw)
+ except Exception:
+ blockers.append("valid_until ist kein UTC-Zeitpunkt.")
+ continue
+ if start > now or (until is not None and not (start <= now < until)):
+ blockers.append("Ein Rechtevermerk ist zum Freigabezeitpunkt nicht wirksam.")
+ territories = right.get("territories")
+ if territories is not None:
+ if not isinstance(territories, list) or any(not re.fullmatch(r"[A-Z]{2}", str(code)) for code in territories):
+ blockers.append("territories sind ISO-Ländercodes oder null.")
+ editorial = cut.get("editorial_rights_id")
+ if editorial not in rights:
+ blockers.append("Die redaktionellen Angaben brauchen einen Rechtevermerk.")
+ used_parts: set[str] = set(cut.get("common_part_keys") or [])
+ used_media: set[str] = set(str(item) for item in (cut.get("common_media_ids") or []))
+ variant_keys = []
+ for variant in cut.get("variants") or []:
+ variant_keys.append(variant.get("key"))
+ used_parts.update(variant.get("part_keys") or [])
+ used_media.update(str(item) for item in (variant.get("media_ids") or []))
+ for key in variant.get("part_keys") or []:
+ if key not in part_keys:
+ blockers.append("Eine Variante verweist auf einen unbekannten Teil.")
+ for media_id in variant.get("media_ids") or []:
+ if str(media_id) not in selected_media:
+ blockers.append("Eine Variante verweist auf ein unbekanntes Medium.")
+ for key in cut.get("common_part_keys") or []:
+ if key not in part_keys:
+ blockers.append("Ein gemeinsamer Teil ist unbekannt.")
+ for media_id in cut.get("common_media_ids") or []:
+ if str(media_id) not in selected_media:
+ blockers.append("Ein gemeinsames Medium ist unbekannt.")
+ if len(variant_keys) != len(set(variant_keys)) or not variant_keys:
+ blockers.append("Das Paket braucht mindestens eine Variante.")
+ for part in cut.get("parts") or []:
+ if part.get("role") not in PART_ROLES:
+ blockers.append("Unbekannte Textrolle.")
+ if part.get("key") not in used_parts:
+ blockers.append("Ein Textteil hängt an keiner Variante.")
+ if part.get("rights_id") not in rights:
+ blockers.append("Ein Textteil hat keinen wirksamen Rechtevermerk.")
+ for asset in cut.get("assets") or []:
+ media_id = str(asset.get("media_id"))
+ if media_id not in used_media:
+ blockers.append("Ein Medium hängt an keiner Variante.")
+ if asset.get("role") not in ASSET_ROLES:
+ blockers.append("Unbekannte Medienrolle.")
+ if asset.get("rights_id") not in rights:
+ blockers.append("Ein Medium hat keinen wirksamen Rechtevermerk.")
+ stored = known_media.get(media_id)
+ if stored is None:
+ blockers.append("Ein ausgewähltes Medium gehört nicht zu dieser Übung.")
+ continue
+ if stored.get("legal_hold_active"):
+ blockers.append("Ein ausgewähltes Medium ist gesperrt.")
+ if not stored.get("file_path"):
+ blockers.append("Ein ausgewähltes Medium hat keine gespeicherten Bytes.")
+ if (stored.get("rights_status") or "legacy_unreviewed") in ("legacy_unreviewed", "blocked", ""):
+ blockers.append("Die Upload-Erklärung eines Mediums trägt die Herausgabe nicht.")
+ if variants:
+ known_variant_ids = {str(item.get("public_id")) for item in variants}
+ for variant in cut.get("variants") or []:
+ if variant.get("key") not in known_variant_ids and variant.get("key") != "default":
+ blockers.append("Eine Variante gehört nicht zur Übung.")
+ return list(dict.fromkeys(blockers))
+
+
+def resolved_asset_ids(manifest: dict, variant_id: str) -> set[str]:
+ exercise = manifest["exercise"]
+ variant = next(item for item in exercise["variants"] if item["id"] == variant_id)
+ return set(exercise["common_asset_ids"]) | set(variant["asset_ids"])
+
+
+def package_fetch_blocked(events: Iterable[dict], release_id: str) -> bool:
+ return any(
+ event.get("type") in WITHDRAW_TYPES and event.get("release_id") == release_id
+ for event in events
+ )
+
+
+def retrievable_release_ids(events: Iterable[dict]) -> set[str]:
+ published: set[str] = set()
+ blocked: set[str] = set()
+ for event in events:
+ if event.get("type") == "release.published":
+ published.add(event["release_id"])
+ elif event.get("type") in WITHDRAW_TYPES:
+ blocked.add(event["release_id"])
+ return published - blocked
+
+
+def plan_available(plan: dict, manifest: dict, events: Iterable[dict]) -> bool:
+ release_id = plan["release_id"]
+ variant_id = plan["variant_id"]
+ relevant = [event for event in events if event.get("release_id") == release_id]
+ if any(event.get("type") == "release.withdrawn" for event in relevant):
+ return False
+ if any(event.get("type") == "variant.withdrawn" and event.get("target_id") == variant_id for event in relevant):
+ return False
+ withdrawn_assets = {
+ event["target_id"] for event in relevant if event.get("type") == "asset.withdrawn"
+ }
+ if withdrawn_assets & resolved_asset_ids(manifest, variant_id):
+ return False
+ return True
+
+
+def actions_cover(actions: Iterable[str], required: Iterable[str]) -> bool:
+ return set(required).issubset(set(actions))
+
+
+def new_id() -> str:
+ return str(uuid.uuid4())
diff --git a/backend/distribution_service.py b/backend/distribution_service.py
new file mode 100644
index 0000000..6c6b37a
--- /dev/null
+++ b/backend/distribution_service.py
@@ -0,0 +1,1093 @@
+"""Datenbank und Bytekopien der Distributionsfreigabe."""
+from __future__ import annotations
+
+import os
+import shutil
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Any, Optional
+
+from fastapi import HTTPException
+
+from auth import hash_pin, verify_pin
+from club_tenancy import has_club_role
+from db import r2d
+from distribution_contract import (
+ LEGAL_HOLD_REASON,
+ REASON_CODES,
+ can_withdraw,
+ canonical_json,
+ collect_blockers,
+ cut_hash,
+ decide_confirm,
+ exercise_offerable,
+ package_state,
+ default_cut,
+ distribution_enabled,
+ format_utc,
+ manifest_bytes,
+ new_id,
+ order_event,
+ parse_utc,
+ rate_decision,
+ release_denial,
+ sha256_bytes,
+ snapshot_hash,
+)
+
+_MEDIA_TYPE = {
+ "video": "video/mp4",
+ "image": "image/jpeg",
+ "document": "application/pdf",
+ "pdf": "application/pdf",
+ "sketch": "image/png",
+}
+
+
+def _now() -> datetime:
+ return datetime.now(timezone.utc)
+
+
+def _rows(cur) -> list:
+ rows = cur.fetchall()
+ if not isinstance(rows, list):
+ return []
+ return rows
+
+
+def _one(cur) -> Optional[dict]:
+ row = cur.fetchone()
+ if row is None or not isinstance(row, (dict, tuple)):
+ try:
+ mapped = r2d(row)
+ except Exception:
+ return None
+ return mapped
+ return r2d(row)
+
+
+def distribution_media_root() -> Path:
+ base = os.getenv("MEDIA_ROOT", str(Path(__file__).resolve().parent / "media"))
+ root = Path(base) / "distribution"
+ root.mkdir(parents=True, exist_ok=True)
+ return root
+
+
+def require_enabled() -> None:
+ if not distribution_enabled():
+ raise HTTPException(
+ status_code=403,
+ detail={
+ "code": "distribution_disabled",
+ "message": "Die Distribution ist auf dieser Instanz nicht aktiv.",
+ },
+ )
+
+
+def blocks_exercise_delete(cur, exercise_id: int) -> bool:
+ cur.execute(
+ """
+ SELECT dr.release_id
+ FROM distribution_releases dr
+ JOIN exercises e ON e.public_id = dr.source_id
+ WHERE e.id = %s
+ LIMIT 1
+ """,
+ (exercise_id,),
+ )
+ return len(_rows(cur)) > 0
+
+
+def blocks_media_delete(cur, media_id: int) -> bool:
+ cur.execute(
+ """
+ SELECT a.asset_id
+ FROM distribution_release_assets a
+ JOIN exercise_media em ON em.public_id = a.source_media_public_id
+ WHERE em.id = %s
+ LIMIT 1
+ """,
+ (media_id,),
+ )
+ return len(_rows(cur)) > 0
+
+
+def blocks_variant_delete(cur, variant_id: int) -> bool:
+ cur.execute(
+ """
+ SELECT dr.release_id
+ FROM distribution_releases dr
+ JOIN exercise_variants v ON position(v.public_id::text in dr.manifest_text) > 0
+ WHERE v.id = %s
+ LIMIT 1
+ """,
+ (variant_id,),
+ )
+ return len(_rows(cur)) > 0
+
+
+def _lock_recipient(cur, recipient_id: str) -> None:
+ cur.execute(
+ "SELECT id FROM distribution_recipients WHERE id = %s FOR UPDATE",
+ (str(recipient_id),),
+ )
+ if cur.fetchone() is None:
+ raise HTTPException(status_code=404, detail="Empfänger nicht gefunden")
+
+
+def append_event(cur, recipient_id: str, event: dict) -> int:
+ _lock_recipient(cur, recipient_id)
+ cur.execute(
+ "SELECT COALESCE(MAX(seq), 0) AS seq FROM distribution_events WHERE recipient_id = %s",
+ (str(recipient_id),),
+ )
+ seq = int((_one(cur) or {"seq": 0})["seq"]) + 1
+ ordered = order_event(event)
+ cur.execute(
+ """
+ INSERT INTO distribution_events (event_id, recipient_id, seq, event_type, release_id, occurred_at, body)
+ VALUES (%s, %s, %s, %s, %s, %s, %s::jsonb)
+ """,
+ (
+ ordered["event_id"],
+ str(recipient_id),
+ seq,
+ ordered["type"],
+ ordered["release_id"],
+ parse_utc(ordered["occurred_at"]),
+ canonical_json(ordered).decode("utf-8"),
+ ),
+ )
+ return seq
+
+
+def _mark_blocked(cur, release_id: str) -> None:
+ cur.execute(
+ "UPDATE distribution_releases SET fetch_blocked = true WHERE release_id = %s",
+ (str(release_id),),
+ )
+
+
+def withdraw_assets_for_media_asset(cur, asset_id: int, legal_reason: str) -> None:
+ reason = LEGAL_HOLD_REASON.get(legal_reason, "safety")
+ cur.execute(
+ """
+ SELECT a.release_id, a.asset_id, r.recipient_id
+ FROM distribution_release_assets a
+ JOIN distribution_releases r ON r.release_id = a.release_id
+ WHERE a.source_asset_id = %s
+ """,
+ (asset_id,),
+ )
+ rows = _rows(cur)
+ now = format_utc(_now())
+ for row in rows:
+ item = r2d(row)
+ event = {
+ "event_id": new_id(),
+ "type": "asset.withdrawn",
+ "release_id": str(item["release_id"]),
+ "occurred_at": now,
+ "target_id": str(item["asset_id"]),
+ "reason_code": reason,
+ }
+ append_event(cur, str(item["recipient_id"]), event)
+ _mark_blocked(cur, str(item["release_id"]))
+
+
+def _load_exercise(cur, exercise_id: int) -> dict:
+ cur.execute(
+ """
+ SELECT id, public_id, title, summary, goal, execution, preparation, trainer_notes,
+ equipment, duration_min, duration_max, status, visibility, club_id,
+ exercise_kind, created_by
+ FROM exercises WHERE id = %s
+ """,
+ (exercise_id,),
+ )
+ row = _one(cur)
+ if not row:
+ raise HTTPException(status_code=404, detail="Übung nicht gefunden")
+ return row
+
+
+def _load_variants(cur, exercise_id: int) -> list[dict]:
+ cur.execute(
+ """
+ SELECT id, public_id, variant_name, description, execution_changes, duration_min, duration_max
+ FROM exercise_variants
+ WHERE exercise_id = %s
+ ORDER BY id
+ """,
+ (exercise_id,),
+ )
+ return [r2d(row) for row in _rows(cur)]
+
+
+def _load_media(cur, exercise_id: int) -> list[dict]:
+ cur.execute(
+ """
+ SELECT em.id, em.public_id, em.media_type, em.file_path, em.title, em.media_asset_id,
+ COALESCE(ma.legal_hold_active, false) AS legal_hold_active,
+ COALESCE(ma.rights_status, 'declared') AS rights_status,
+ ma.sha256 AS sha256
+ FROM exercise_media em
+ LEFT JOIN media_assets ma ON ma.id = em.media_asset_id
+ WHERE em.exercise_id = %s
+ ORDER BY em.sort_order NULLS LAST, em.id
+ """,
+ (exercise_id,),
+ )
+ return [r2d(row) for row in _rows(cur)]
+
+
+def _publisher(cur, publisher_id: str) -> dict:
+ cur.execute(
+ "SELECT id, name, kind, club_id, status FROM distribution_publishers WHERE id = %s",
+ (str(publisher_id),),
+ )
+ row = _one(cur)
+ if not row or row.get("status") != "active":
+ raise HTTPException(status_code=403, detail="Herausgeber ist nicht freigeschaltet.")
+ return row
+
+
+def _is_owner(exercise: dict, profile_id: int) -> bool:
+ created = exercise.get("created_by")
+ try:
+ return created is not None and int(created) == int(profile_id)
+ except (TypeError, ValueError):
+ return False
+
+
+def _is_club_admin(cur, exercise: dict, profile_id: int) -> bool:
+ if (exercise.get("visibility") or "").strip().lower() != "club":
+ return False
+ club_id = exercise.get("club_id")
+ if club_id is None:
+ return False
+ try:
+ return has_club_role(cur, int(profile_id), int(club_id), "club_admin")
+ except (TypeError, ValueError):
+ return False
+
+
+def _denial_for(cur, exercise: dict, publisher: dict, profile_id: int, role: str) -> Optional[str]:
+ return release_denial(
+ visibility=exercise.get("visibility"),
+ role=role,
+ publisher_kind=publisher["kind"],
+ is_owner=_is_owner(exercise, profile_id),
+ is_club_admin=_is_club_admin(cur, exercise, profile_id),
+ publisher_club_id=publisher.get("club_id"),
+ exercise_club_id=exercise.get("club_id"),
+ )
+
+
+def _assert_may_release(cur, exercise: dict, publisher: dict, profile_id: int, role: str) -> None:
+ denial = _denial_for(cur, exercise, publisher, profile_id, role)
+ if denial:
+ raise HTTPException(status_code=403, detail=denial)
+
+
+def _relationship_ok(cur, publisher_id: str, recipient_id: str) -> bool:
+ cur.execute(
+ """
+ SELECT 1 AS ok
+ FROM distribution_relationships rel
+ JOIN distribution_recipients rec ON rec.id = rel.recipient_id
+ WHERE rel.publisher_id = %s AND rel.recipient_id = %s
+ AND rel.status = 'active' AND rec.status = 'active'
+ """,
+ (str(publisher_id), str(recipient_id)),
+ )
+ return _one(cur) is not None
+
+
+def _part_id(cur, source_id: str, part_key: str) -> str:
+ cur.execute(
+ """
+ SELECT part_id FROM distribution_part_identities
+ WHERE source_id = %s AND part_key = %s
+ """,
+ (str(source_id), part_key),
+ )
+ row = _one(cur)
+ if row:
+ return str(row["part_id"])
+ part_id = new_id()
+ cur.execute(
+ """
+ INSERT INTO distribution_part_identities (source_id, part_key, part_id)
+ VALUES (%s, %s, %s)
+ """,
+ (str(source_id), part_key, part_id),
+ )
+ return part_id
+
+
+def _variant_id(cur, source_id: str, variant_key: str, public_id: Optional[str]) -> str:
+ if public_id:
+ return str(public_id)
+ return _part_id(cur, source_id, f"variant-id:{variant_key}")
+
+
+def _revision_for(cur, source_id: str, snap: str) -> int:
+ cur.execute(
+ """
+ SELECT revision FROM distribution_source_revisions
+ WHERE source_id = %s AND snapshot_hash = %s
+ """,
+ (str(source_id), snap),
+ )
+ row = _one(cur)
+ if row:
+ return int(row["revision"])
+ cur.execute(
+ "SELECT COALESCE(MAX(revision), 0) AS revision FROM distribution_source_revisions WHERE source_id = %s",
+ (str(source_id),),
+ )
+ revision = int((_one(cur) or {"revision": 0})["revision"]) + 1
+ cur.execute(
+ """
+ INSERT INTO distribution_source_revisions (source_id, revision, snapshot_hash)
+ VALUES (%s, %s, %s)
+ """,
+ (str(source_id), revision, snap),
+ )
+ return revision
+
+
+def hashlib_file(path: Path) -> tuple[str, int]:
+ import hashlib
+
+ hasher = hashlib.sha256()
+ size = 0
+ with path.open("rb") as handle:
+ for chunk in iter(lambda: handle.read(1024 * 1024), b""):
+ hasher.update(chunk)
+ size += len(chunk)
+ return hasher.hexdigest(), size
+
+
+def overview(cur, exercise_id: int, profile_id: int, role: str) -> dict:
+ exercise = _load_exercise(cur, exercise_id)
+ cur.execute(
+ """
+ SELECT dr.release_id, dr.revision, dr.published_at, dr.fetch_blocked, dr.recipient_id,
+ rec.name AS recipient_name
+ FROM distribution_releases dr
+ JOIN distribution_recipients rec ON rec.id = dr.recipient_id
+ JOIN exercises e ON e.public_id = dr.source_id
+ WHERE e.id = %s
+ ORDER BY dr.published_at
+ """,
+ (exercise_id,),
+ )
+ releases = []
+ for row in _rows(cur):
+ item = r2d(row)
+ releases.append(
+ {
+ "release_id": str(item["release_id"]),
+ "revision": item["revision"],
+ "published_at": format_utc(item["published_at"]) if not isinstance(item["published_at"], str) else item["published_at"],
+ "fetch_blocked": bool(item["fetch_blocked"]),
+ "recipient_id": str(item["recipient_id"]),
+ "recipient_name": item["recipient_name"],
+ }
+ )
+ cur.execute(
+ """
+ SELECT p.id, p.name, p.kind, p.club_id
+ FROM distribution_publishers p
+ WHERE p.status = 'active'
+ ORDER BY p.name
+ """
+ )
+ publishers = []
+ for row in _rows(cur):
+ item = r2d(row)
+ if _denial_for(cur, exercise, item, profile_id, role):
+ continue
+ publishers.append(
+ {"id": str(item["id"]), "name": item["name"], "kind": item["kind"], "club_id": item["club_id"]}
+ )
+ release_block = None
+ if not publishers:
+ release_block = _denial_for(
+ cur,
+ exercise,
+ {
+ "kind": {"official": "platform", "club": "club"}.get(
+ (exercise.get("visibility") or "").strip().lower(), "own"
+ ),
+ "club_id": exercise.get("club_id"),
+ },
+ profile_id,
+ role,
+ ) or "Für diesen Bestand ist noch kein Herausgeber eingerichtet."
+ return {
+ "enabled": distribution_enabled(),
+ "visibility": exercise.get("visibility"),
+ "may_release": release_block is None,
+ "release_block": release_block,
+ "releases": releases,
+ "publishers": publishers,
+ "profile_id": profile_id,
+ "role": role,
+ }
+
+
+def create_draft(cur, exercise_id: int, publisher_id: str, recipient_id: str, profile_id: int, role: str, cut: Optional[dict]) -> dict:
+ require_enabled()
+ exercise = _load_exercise(cur, exercise_id)
+ variants = _load_variants(cur, exercise_id)
+ media = _load_media(cur, exercise_id)
+ publisher = _publisher(cur, publisher_id)
+ _assert_may_release(cur, exercise, publisher, profile_id, role)
+ if not _relationship_ok(cur, publisher_id, recipient_id):
+ raise HTTPException(status_code=403, detail="Für diesen Empfänger besteht keine zugelassene Beziehung.")
+ payload = cut if cut is not None else default_cut(exercise, variants, media)
+ blockers = collect_blockers(exercise, variants, media, payload, _now())
+ draft_id = new_id()
+ snap = snapshot_hash(exercise, variants, media)
+ cur.execute(
+ """
+ INSERT INTO distribution_drafts (
+ id, exercise_id, publisher_id, recipient_id, prepared_by, cut, preview_hash
+ ) VALUES (%s, %s, %s, %s, %s, %s::jsonb, %s)
+ """,
+ (draft_id, exercise_id, str(publisher_id), str(recipient_id), profile_id, canonical_json(payload).decode("utf-8"), snap),
+ )
+ return {"draft_id": draft_id, "cut": payload, "blockers": blockers, "preview_hash": snap}
+
+
+def update_draft(cur, exercise_id: int, draft_id: str, cut: dict, profile_id: int, role: str) -> dict:
+ require_enabled()
+ exercise = _load_exercise(cur, exercise_id)
+ variants = _load_variants(cur, exercise_id)
+ media = _load_media(cur, exercise_id)
+ cur.execute(
+ "SELECT id, publisher_id, release_id FROM distribution_drafts WHERE id = %s AND exercise_id = %s FOR UPDATE",
+ (str(draft_id), exercise_id),
+ )
+ draft = _one(cur)
+ if not draft:
+ raise HTTPException(status_code=404, detail="Entwurf nicht gefunden")
+ if draft.get("release_id"):
+ raise HTTPException(status_code=409, detail="Dieser Entwurf ist bereits bestätigt.")
+ _assert_may_release(cur, exercise, _publisher(cur, str(draft["publisher_id"])), profile_id, role)
+ snap = snapshot_hash(exercise, variants, media)
+ cur.execute(
+ """
+ UPDATE distribution_drafts SET cut = %s::jsonb, preview_hash = %s WHERE id = %s
+ """,
+ (canonical_json(cut).decode("utf-8"), snap, str(draft_id)),
+ )
+ return {"draft_id": str(draft_id), "cut": cut, "blockers": collect_blockers(exercise, variants, media, cut, _now()), "preview_hash": snap}
+
+
+def _load_cut(value) -> dict:
+ if isinstance(value, str):
+ import json
+ return json.loads(value)
+ return dict(value)
+
+
+def confirm_draft(cur, exercise_id: int, draft_id: str, profile_id: int, role: str) -> dict:
+ require_enabled()
+ cur.execute("SELECT id FROM exercises WHERE id = %s FOR UPDATE", (exercise_id,))
+ if cur.fetchone() is None:
+ raise HTTPException(status_code=404, detail="Übung nicht gefunden")
+ cur.execute(
+ """
+ SELECT id, publisher_id, recipient_id, cut, preview_hash, release_id
+ FROM distribution_drafts
+ WHERE id = %s AND exercise_id = %s
+ FOR UPDATE
+ """,
+ (str(draft_id), exercise_id),
+ )
+ draft = _one(cur)
+ if not draft:
+ raise HTTPException(status_code=404, detail="Entwurf nicht gefunden")
+ exercise = _load_exercise(cur, exercise_id)
+ publisher = _publisher(cur, str(draft["publisher_id"]))
+ _assert_may_release(cur, exercise, publisher, profile_id, role)
+ release_id, created = decide_confirm(
+ str(draft["release_id"]) if draft.get("release_id") else None,
+ new_id(),
+ )
+ if not created:
+ cur.execute(
+ "SELECT manifest_sha256 FROM distribution_releases WHERE release_id = %s",
+ (release_id,),
+ )
+ stored = _one(cur) or {}
+ return {"release_id": release_id, "replayed": True, "manifest_sha256": stored.get("manifest_sha256")}
+
+ variants = _load_variants(cur, exercise_id)
+ media = _load_media(cur, exercise_id)
+ snap = snapshot_hash(exercise, variants, media)
+ if snap != draft["preview_hash"]:
+ raise HTTPException(
+ status_code=409,
+ detail="Die Übung wurde seit der Vorschau geändert. Bitte die Vorschau neu erstellen.",
+ )
+ cut = _load_cut(draft["cut"])
+ blockers = collect_blockers(exercise, variants, media, cut, _now())
+ if blockers:
+ raise HTTPException(status_code=400, detail={"code": "release_blocked", "blockers": blockers})
+ source_id = str(exercise["public_id"])
+ revision = _revision_for(cur, source_id, snap)
+ published_at = format_utc(_now())
+ part_ids = {part["key"]: _part_id(cur, source_id, part["key"]) for part in cut["parts"]}
+ variant_ids = {}
+ known_variants = {str(item["public_id"]): str(item["public_id"]) for item in variants}
+ for variant in cut["variants"]:
+ variant_ids[variant["key"]] = known_variants.get(variant["key"]) or _variant_id(
+ cur, source_id, variant["key"], None
+ )
+ media_by_public = {str(item["public_id"]): item for item in media}
+ copied: list[Path] = []
+ asset_rows = []
+ try:
+ for asset in cut["assets"]:
+ stored = media_by_public[str(asset["media_id"])]
+ source = Path(stored["file_path"])
+ if not source.is_file():
+ raise HTTPException(status_code=400, detail="Mediendatei fehlt auf dem Speicher.")
+ digest, size = hashlib_file(source)
+ asset_id = str(stored["public_id"])
+ target = distribution_media_root() / release_id / asset_id
+ target.parent.mkdir(parents=True, exist_ok=True)
+ shutil.copyfile(source, target)
+ copied.append(target)
+ asset_rows.append(
+ {
+ "id": asset_id,
+ "role": asset["role"],
+ "media_type": _MEDIA_TYPE.get((stored.get("media_type") or "").lower(), "application/octet-stream"),
+ "size_bytes": size,
+ "sha256": digest,
+ "rights_id": asset["rights_id"],
+ "label": asset.get("label"),
+ "source_media_public_id": asset_id,
+ "source_asset_id": stored.get("media_asset_id"),
+ "path": str(target),
+ }
+ )
+ manifest = {
+ "schema_version": 1,
+ "resource_type": "exercise",
+ "release_id": release_id,
+ "source_id": source_id,
+ "revision": revision,
+ "publisher_id": str(publisher["id"]),
+ "published_at": published_at,
+ "exercise": {
+ "title": cut["title"],
+ "summary": cut.get("summary"),
+ "audience": cut.get("audience"),
+ "rights_id": cut["editorial_rights_id"],
+ "parts": [
+ {
+ "id": part_ids[part["key"]],
+ "role": part["role"],
+ "text": part["text"],
+ "rights_id": part["rights_id"],
+ }
+ for part in cut["parts"]
+ ],
+ "assets": [
+ {
+ "id": row["id"],
+ "role": row["role"],
+ "media_type": row["media_type"],
+ "size_bytes": row["size_bytes"],
+ "sha256": row["sha256"],
+ "rights_id": row["rights_id"],
+ "label": row["label"],
+ }
+ for row in asset_rows
+ ],
+ "common_part_ids": [part_ids[key] for key in cut.get("common_part_keys") or []],
+ "common_asset_ids": [str(item) for item in cut.get("common_media_ids") or []],
+ "variants": [
+ {
+ "id": variant_ids[variant["key"]],
+ "label": variant["label"],
+ "part_ids": [part_ids[key] for key in variant.get("part_keys") or []],
+ "asset_ids": [str(item) for item in variant.get("media_ids") or []],
+ }
+ for variant in cut["variants"]
+ ],
+ },
+ "rights": [
+ {
+ "id": right["id"],
+ "evidence_ref": right["evidence_ref"],
+ "actions": right["actions"],
+ "territories": right.get("territories"),
+ "valid_from": right["valid_from"],
+ "valid_until": right.get("valid_until"),
+ "attribution": right.get("attribution"),
+ }
+ for right in cut["rights"]
+ ],
+ }
+ body = manifest_bytes(manifest)
+ digest = sha256_bytes(body)
+ cur.execute(
+ """
+ INSERT INTO distribution_releases (
+ release_id, recipient_id, publisher_id, source_id, revision, cut_hash,
+ manifest_text, manifest_sha256, published_at, fetch_blocked, confirmed_by
+ ) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, false, %s)
+ """,
+ (
+ release_id,
+ str(draft["recipient_id"]),
+ str(publisher["id"]),
+ source_id,
+ revision,
+ cut_hash(cut),
+ body.decode("utf-8"),
+ digest,
+ parse_utc(published_at),
+ profile_id,
+ ),
+ )
+ for row in asset_rows:
+ cur.execute(
+ """
+ INSERT INTO distribution_release_assets (
+ release_id, asset_id, sha256, size_bytes, media_type, storage_path,
+ source_media_public_id, source_asset_id
+ ) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
+ """,
+ (
+ release_id,
+ row["id"],
+ row["sha256"],
+ row["size_bytes"],
+ row["media_type"],
+ row["path"],
+ row["source_media_public_id"],
+ row["source_asset_id"],
+ ),
+ )
+ for right in cut["rights"]:
+ note = right.get("note")
+ if note:
+ cur.execute(
+ """
+ INSERT INTO distribution_evidence (id, publisher_id, note, created_by)
+ VALUES (%s, %s, %s, %s)
+ ON CONFLICT (id) DO NOTHING
+ """,
+ (right["evidence_ref"], str(publisher["id"]), note, profile_id),
+ )
+ append_event(
+ cur,
+ str(draft["recipient_id"]),
+ {
+ "event_id": new_id(),
+ "type": "release.published",
+ "release_id": release_id,
+ "occurred_at": published_at,
+ "source_id": source_id,
+ "revision": revision,
+ "manifest_sha256": digest,
+ },
+ )
+ cur.execute(
+ "UPDATE distribution_drafts SET release_id = %s, confirmed_at = NOW() WHERE id = %s",
+ (release_id, str(draft_id)),
+ )
+ return {"release_id": release_id, "replayed": False, "manifest_sha256": digest}
+ except Exception:
+ for path in copied:
+ path.unlink(missing_ok=True)
+ raise
+
+
+def _release_row(cur, release_id: str) -> dict:
+ cur.execute(
+ """
+ SELECT release_id, recipient_id, publisher_id, source_id, fetch_blocked, manifest_text
+ FROM distribution_releases WHERE release_id = %s
+ """,
+ (str(release_id),),
+ )
+ row = _one(cur)
+ if not row:
+ raise HTTPException(status_code=404, detail="Paket nicht gefunden")
+ return row
+
+
+def _assert_withdraw(cur, release: dict, profile_id: int, role: str) -> None:
+ require_enabled()
+ publisher = _publisher(cur, str(release["publisher_id"]))
+ cur.execute(
+ """
+ SELECT id, public_id, visibility, club_id, created_by
+ FROM exercises WHERE public_id = %s
+ """,
+ (str(release["source_id"]),),
+ )
+ exercise = _one(cur)
+ denial = (
+ "Paket ohne zugehörige Übung."
+ if not exercise
+ else _denial_for(cur, exercise, publisher, profile_id, role)
+ )
+ if not can_withdraw(role=role, denial=denial):
+ raise HTTPException(status_code=403, detail=denial or "Keine Befugnis für diesen Rückzug.")
+
+
+def retire_release(cur, release_id: str, profile_id: int, role: str) -> dict:
+ release = _release_row(cur, release_id)
+ _assert_withdraw(cur, release, profile_id, role)
+ cur.execute(
+ """
+ SELECT 1 AS ok FROM distribution_events
+ WHERE release_id = %s AND event_type = 'release.retired'
+ """,
+ (str(release_id),),
+ )
+ if _one(cur):
+ return {"release_id": str(release_id), "replayed": True}
+ append_event(
+ cur,
+ str(release["recipient_id"]),
+ {
+ "event_id": new_id(),
+ "type": "release.retired",
+ "release_id": str(release_id),
+ "occurred_at": format_utc(_now()),
+ },
+ )
+ return {"release_id": str(release_id), "replayed": False}
+
+
+def withdraw_release(cur, release_id: str, reason_code: str, profile_id: int, role: str, kind: str, target_id: Optional[str]) -> dict:
+ if reason_code not in REASON_CODES:
+ raise HTTPException(status_code=400, detail="Unbekannte Grundklasse.")
+ release = _release_row(cur, release_id)
+ _assert_withdraw(cur, release, profile_id, role)
+ event_type = {
+ "release": "release.withdrawn",
+ "variant": "variant.withdrawn",
+ "asset": "asset.withdrawn",
+ }[kind]
+ if kind != "release" and not target_id:
+ raise HTTPException(status_code=400, detail="Ziel fehlt.")
+ event = {
+ "event_id": new_id(),
+ "type": event_type,
+ "release_id": str(release_id),
+ "occurred_at": format_utc(_now()),
+ "reason_code": reason_code,
+ }
+ if target_id:
+ event["target_id"] = str(target_id)
+ append_event(cur, str(release["recipient_id"]), event)
+ _mark_blocked(cur, str(release_id))
+ return {"release_id": str(release_id), "type": event_type}
+
+
+def enforce_expiry(cur, release: dict, now: Optional[datetime] = None) -> None:
+ if release.get("fetch_blocked"):
+ return
+ import json
+
+ manifest = json.loads(release["manifest_text"])
+ moment = now or _now()
+ expired = set()
+ for right in manifest.get("rights") or []:
+ until = right.get("valid_until")
+ if until and parse_utc(until) <= moment:
+ expired.add(right["id"])
+ if not expired:
+ return
+ exercise = manifest["exercise"]
+ events = []
+ if exercise.get("rights_id") in expired:
+ events.append({"type": "release.withdrawn"})
+ else:
+ for asset in exercise.get("assets") or []:
+ if asset.get("rights_id") in expired:
+ events.append({"type": "asset.withdrawn", "target_id": asset["id"]})
+ if not events:
+ events.append({"type": "release.withdrawn"})
+ stamp = format_utc(moment)
+ for event in events:
+ payload = {
+ "event_id": new_id(),
+ "type": event["type"],
+ "release_id": str(release["release_id"]),
+ "occurred_at": stamp,
+ "reason_code": "expired",
+ }
+ if event.get("target_id"):
+ payload["target_id"] = event["target_id"]
+ append_event(cur, str(release["recipient_id"]), payload)
+ _mark_blocked(cur, str(release["release_id"]))
+ release["fetch_blocked"] = True
+
+
+def backlog_count(cur) -> int:
+ cur.execute(
+ "SELECT manifest_text, fetch_blocked FROM distribution_releases WHERE fetch_blocked = false"
+ )
+ import json
+
+ count = 0
+ moment = _now()
+ for row in _rows(cur):
+ item = r2d(row)
+ manifest = json.loads(item["manifest_text"])
+ for right in manifest.get("rights") or []:
+ until = right.get("valid_until")
+ if until and parse_utc(until) <= moment:
+ count += 1
+ break
+ return count
+
+
+def issue_key(cur, binding_id: str, expires_at: Optional[str]) -> dict:
+ cur.execute(
+ "SELECT id, status, recipient_id FROM distribution_bindings WHERE id = %s",
+ (str(binding_id),),
+ )
+ binding = _one(cur)
+ if not binding or binding.get("status") != "active":
+ raise HTTPException(status_code=404, detail="Anbindung nicht gefunden")
+ import secrets
+
+ prefix = secrets.token_hex(6)
+ secret = secrets.token_urlsafe(32)
+ token = f"shk.{prefix}.{secret}"
+ cur.execute(
+ """
+ INSERT INTO distribution_keys (id, binding_id, key_prefix, secret_hash, expires_at)
+ VALUES (%s, %s, %s, %s, %s)
+ """,
+ (new_id(), str(binding_id), prefix, hash_pin(token), parse_utc(expires_at) if expires_at else None),
+ )
+ return {"token": token, "prefix": prefix, "expires_at": expires_at}
+
+
+def resolve_bearer(cur, token: str) -> dict:
+ if not token or not token.startswith("shk.") or token.count(".") < 2:
+ raise HTTPException(status_code=401, detail={"code": "invalid_key", "message": "Schlüssel ungültig."})
+ prefix = token.split(".", 2)[1]
+ cur.execute(
+ """
+ SELECT k.secret_hash, k.expires_at, k.revoked_at, b.id AS binding_id, b.status AS binding_status,
+ b.recipient_id, r.status AS recipient_status
+ FROM distribution_keys k
+ JOIN distribution_bindings b ON b.id = k.binding_id
+ JOIN distribution_recipients r ON r.id = b.recipient_id
+ WHERE k.key_prefix = %s
+ """,
+ (prefix,),
+ )
+ row = _one(cur)
+ if not row or row.get("revoked_at") is not None or not verify_pin(token, row["secret_hash"]):
+ raise HTTPException(status_code=401, detail={"code": "invalid_key", "message": "Schlüssel ungültig."})
+ expires = row.get("expires_at")
+ if expires is not None:
+ exp = expires if isinstance(expires, datetime) else parse_utc(str(expires))
+ if exp <= _now():
+ raise HTTPException(status_code=401, detail={"code": "invalid_key", "message": "Schlüssel abgelaufen."})
+ if row.get("binding_status") != "active" or row.get("recipient_status") != "active":
+ raise HTTPException(status_code=403, detail={"code": "binding_suspended", "message": "Anbindung ohne Abrufumfang."})
+ allowed, blocked = touch_rate(cur, str(row["binding_id"]))
+ if blocked:
+ raise HTTPException(
+ status_code=429,
+ detail={"code": "rate_limited", "message": "Abrufgrenze erreicht."},
+ headers={"Retry-After": "60", "Cache-Control": "private, no-store"},
+ )
+ return {"binding_id": str(row["binding_id"]), "recipient_id": str(row["recipient_id"]), "hits": allowed}
+
+
+def touch_rate(cur, binding_id: str) -> tuple[int, bool]:
+ cur.execute(
+ "SELECT window_start, hits FROM distribution_rate_windows WHERE binding_id = %s FOR UPDATE",
+ (binding_id,),
+ )
+ row = _one(cur)
+ now = _now()
+ if row is None:
+ cur.execute(
+ """
+ INSERT INTO distribution_rate_windows (binding_id, window_start, hits)
+ VALUES (%s, %s, 1)
+ """,
+ (binding_id, now),
+ )
+ return 1, False
+ started = row["window_start"]
+ if not isinstance(started, datetime):
+ started = parse_utc(str(started))
+ hits, blocked = rate_decision(int(row["hits"]), (now - started).total_seconds())
+ if (now - started).total_seconds() >= 60:
+ cur.execute(
+ "UPDATE distribution_rate_windows SET window_start = %s, hits = %s WHERE binding_id = %s",
+ (now, hits, binding_id),
+ )
+ else:
+ cur.execute(
+ "UPDATE distribution_rate_windows SET hits = %s WHERE binding_id = %s",
+ (hits, binding_id),
+ )
+ return hits, blocked
+
+
+def list_changes(cur, recipient_id: str, cursor_seq: int, limit: int) -> dict:
+ cur.execute(
+ """
+ SELECT seq, body FROM distribution_events
+ WHERE recipient_id = %s AND seq > %s
+ ORDER BY seq
+ LIMIT %s
+ """,
+ (str(recipient_id), cursor_seq, limit + 1),
+ )
+ rows = _rows(cur)
+ page = rows[:limit]
+ import json
+
+ events = []
+ last_seq = cursor_seq
+ for row in page:
+ item = r2d(row)
+ body = item["body"]
+ if isinstance(body, str):
+ body = json.loads(body)
+ events.append(order_event(body))
+ last_seq = int(item["seq"])
+ from distribution_contract import cursor_secret, encode_cursor
+
+ return {
+ "events": events,
+ "next_cursor": encode_cursor(cursor_secret(), recipient_id, last_seq),
+ "has_more": len(rows) > limit,
+ }
+
+
+def load_availability(cur, recipient_id: str, source_id: str) -> dict:
+ import json
+ import uuid
+
+ try:
+ uuid.UUID(str(source_id))
+ except ValueError:
+ raise HTTPException(status_code=404, detail={"code": "not_found", "message": "Übung nicht gefunden."})
+ cur.execute(
+ """
+ SELECT release_id, revision, fetch_blocked, manifest_text, publisher_id, recipient_id
+ FROM distribution_releases
+ WHERE source_id = %s AND recipient_id = %s
+ ORDER BY revision, published_at
+ """,
+ (str(source_id), str(recipient_id)),
+ )
+ rows = [r2d(row) for row in _rows(cur)]
+ if not rows:
+ raise HTTPException(
+ status_code=404,
+ detail={"code": "not_found", "message": "Für diesen Empfänger liegt keine Freigabe dieser Übung vor."},
+ )
+ cur.execute("SELECT status FROM exercises WHERE public_id = %s", (str(source_id),))
+ source = _one(cur)
+ releases = []
+ for row in rows:
+ enforce_expiry(cur, row)
+ cur.execute(
+ """
+ SELECT event_type, body
+ FROM distribution_events
+ WHERE release_id = %s
+ AND event_type IN ('release.retired', 'release.withdrawn', 'variant.withdrawn', 'asset.withdrawn')
+ ORDER BY seq DESC
+ """,
+ (str(row["release_id"]),),
+ )
+ retired = False
+ reason = None
+ for event in _rows(cur):
+ item = r2d(event)
+ if item["event_type"] == "release.retired":
+ retired = True
+ continue
+ if reason is None:
+ body = item["body"]
+ if isinstance(body, str):
+ body = json.loads(body)
+ reason = (body or {}).get("reason_code")
+ state = package_state(fetch_blocked=bool(row.get("fetch_blocked")), retired=retired)
+ releases.append(
+ {
+ "release_id": str(row["release_id"]),
+ "revision": row["revision"],
+ "package": state,
+ "fetchable": state != "withdrawn",
+ "reason_code": reason if state == "withdrawn" else None,
+ }
+ )
+ status, offerable = exercise_offerable(
+ source.get("status") if source else None,
+ [item["package"] for item in releases],
+ )
+ return {
+ "source_id": str(source_id),
+ "source_status": status,
+ "offerable": offerable,
+ "releases": releases,
+ }
+
+
+def load_manifest(cur, recipient_id: str, release_id: str) -> bytes:
+ cur.execute(
+ """
+ SELECT release_id, recipient_id, publisher_id, fetch_blocked, manifest_text
+ FROM distribution_releases WHERE release_id = %s
+ """,
+ (str(release_id),),
+ )
+ row = _one(cur)
+ if not row or str(row["recipient_id"]) != str(recipient_id):
+ raise HTTPException(status_code=404, detail={"code": "not_found", "message": "Paket nicht gefunden."})
+ enforce_expiry(cur, row)
+ if row.get("fetch_blocked"):
+ raise HTTPException(status_code=410, detail={"code": "withdrawn", "message": "Paket zurückgezogen."})
+ return row["manifest_text"].encode("utf-8")
+
+
+def load_asset(cur, recipient_id: str, release_id: str, asset_id: str) -> tuple[Path, str]:
+ cur.execute(
+ """
+ SELECT r.recipient_id, r.fetch_blocked, r.manifest_text, r.release_id, r.publisher_id,
+ a.storage_path, a.media_type, a.sha256
+ FROM distribution_releases r
+ JOIN distribution_release_assets a ON a.release_id = r.release_id
+ WHERE r.release_id = %s AND a.asset_id = %s
+ """,
+ (str(release_id), str(asset_id)),
+ )
+ row = _one(cur)
+ if not row or str(row["recipient_id"]) != str(recipient_id):
+ raise HTTPException(status_code=404, detail={"code": "not_found", "message": "Medium nicht gefunden."})
+ enforce_expiry(cur, row)
+ if row.get("fetch_blocked"):
+ raise HTTPException(status_code=410, detail={"code": "withdrawn", "message": "Medium zurückgezogen."})
+ path = Path(row["storage_path"])
+ digest, _size = hashlib_file(path)
+ if digest != row["sha256"]:
+ raise HTTPException(status_code=500, detail={"code": "integrity", "message": "Medienprüfsumme stimmt nicht."})
+ return path, row["media_type"]
diff --git a/backend/main.py b/backend/main.py
index 8ab8407..617a6b5 100644
--- a/backend/main.py
+++ b/backend/main.py
@@ -243,7 +243,7 @@ def read_root():
return out
# Register routers
-from routers import auth, profiles, exercises, exercise_progression_graphs, clubs, club_memberships, club_join_requests, club_creation_requests, admin_users, admin_user_content, admin_rights, me_entitlements, platform_media_storage, media_assets, skills, skill_profiles, training_planning, planning_exercise_suggest, dashboard, training_modules, training_framework_programs, catalogs, catalog_prompt_slots, maturity_models, matrix_stack_bundle, matrix_editor, import_wiki, import_wiki_admin, legal_documents, content_reports, ai_prompts_admin, ai_skill_retrieval_admin, exercise_enrichment_admin, openrouter_admin
+from routers import auth, profiles, exercises, exercise_progression_graphs, clubs, club_memberships, club_join_requests, club_creation_requests, admin_users, admin_user_content, admin_rights, me_entitlements, platform_media_storage, media_assets, skills, skill_profiles, training_planning, planning_exercise_suggest, dashboard, training_modules, training_framework_programs, catalogs, catalog_prompt_slots, maturity_models, matrix_stack_bundle, matrix_editor, import_wiki, import_wiki_admin, legal_documents, content_reports, ai_prompts_admin, ai_skill_retrieval_admin, exercise_enrichment_admin, openrouter_admin, distribution
app.include_router(auth.router)
app.include_router(profiles.router)
@@ -281,6 +281,8 @@ app.include_router(ai_prompts_admin.router)
app.include_router(openrouter_admin.router)
app.include_router(ai_skill_retrieval_admin.router)
app.include_router(exercise_enrichment_admin.router)
+app.include_router(distribution.router)
+app.include_router(distribution.editorial)
# Lokale Übungs-Medien: standardmäßig nur über geschützten API-Pfad
# GET /api/exercises/{id}/media/{mid}/file (?ssetoken = kurzlebiges Medien-Token, kein Sitzungstoken).
diff --git a/backend/media_legal_hold.py b/backend/media_legal_hold.py
index 04fce0c..4e62127 100644
--- a/backend/media_legal_hold.py
+++ b/backend/media_legal_hold.py
@@ -134,6 +134,10 @@ def set_legal_hold(
updated_row = cur.fetchone()
updated = r2d(updated_row)
+ from distribution_service import withdraw_assets_for_media_asset
+
+ withdraw_assets_for_media_asset(cur, asset_id, reason_code)
+
write_audit_log_entry(
cur,
asset_id=asset_id,
diff --git a/backend/migrations/099_distribution.sql b/backend/migrations/099_distribution.sql
new file mode 100644
index 0000000..e783162
--- /dev/null
+++ b/backend/migrations/099_distribution.sql
@@ -0,0 +1,191 @@
+-- Distribution v1: eingefrorene Übungspakete für Empfängerkanäle.
+-- Produktiver Abruf bleibt über DISTRIBUTION_ENABLED aus, bis die Testinstanz ihn einschaltet.
+
+ALTER TABLE exercises
+ ADD COLUMN IF NOT EXISTS public_id UUID;
+
+UPDATE exercises SET public_id = gen_random_uuid() WHERE public_id IS NULL;
+
+ALTER TABLE exercises
+ ALTER COLUMN public_id SET DEFAULT gen_random_uuid();
+
+ALTER TABLE exercises
+ ALTER COLUMN public_id SET NOT NULL;
+
+CREATE UNIQUE INDEX IF NOT EXISTS uq_exercises_public_id ON exercises (public_id);
+
+ALTER TABLE exercise_variants
+ ADD COLUMN IF NOT EXISTS public_id UUID;
+
+UPDATE exercise_variants SET public_id = gen_random_uuid() WHERE public_id IS NULL;
+
+ALTER TABLE exercise_variants
+ ALTER COLUMN public_id SET DEFAULT gen_random_uuid();
+
+ALTER TABLE exercise_variants
+ ALTER COLUMN public_id SET NOT NULL;
+
+CREATE UNIQUE INDEX IF NOT EXISTS uq_exercise_variants_public_id ON exercise_variants (public_id);
+
+ALTER TABLE exercise_media
+ ADD COLUMN IF NOT EXISTS public_id UUID;
+
+UPDATE exercise_media SET public_id = gen_random_uuid() WHERE public_id IS NULL;
+
+ALTER TABLE exercise_media
+ ALTER COLUMN public_id SET DEFAULT gen_random_uuid();
+
+ALTER TABLE exercise_media
+ ALTER COLUMN public_id SET NOT NULL;
+
+CREATE UNIQUE INDEX IF NOT EXISTS uq_exercise_media_public_id ON exercise_media (public_id);
+
+CREATE TABLE IF NOT EXISTS distribution_publishers (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ name TEXT NOT NULL,
+ kind TEXT NOT NULL CHECK (kind IN ('platform', 'own', 'club')),
+ club_id INT REFERENCES clubs (id),
+ status TEXT NOT NULL DEFAULT 'active' CHECK (status IN ('active', 'suspended')),
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+ CONSTRAINT distribution_publishers_kind_club CHECK (
+ (kind = 'club' AND club_id IS NOT NULL)
+ OR (kind <> 'club' AND club_id IS NULL)
+ )
+);
+
+CREATE UNIQUE INDEX IF NOT EXISTS uq_distribution_platform_publisher
+ ON distribution_publishers (kind)
+ WHERE kind = 'platform';
+
+CREATE TABLE IF NOT EXISTS distribution_recipients (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ name TEXT NOT NULL,
+ status TEXT NOT NULL DEFAULT 'active' CHECK (status IN ('active', 'suspended')),
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
+);
+
+CREATE TABLE IF NOT EXISTS distribution_relationships (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ publisher_id UUID NOT NULL REFERENCES distribution_publishers (id),
+ recipient_id UUID NOT NULL REFERENCES distribution_recipients (id),
+ status TEXT NOT NULL DEFAULT 'active' CHECK (status IN ('active', 'suspended')),
+ UNIQUE (publisher_id, recipient_id)
+);
+
+CREATE TABLE IF NOT EXISTS distribution_bindings (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ recipient_id UUID NOT NULL REFERENCES distribution_recipients (id),
+ name TEXT NOT NULL,
+ status TEXT NOT NULL DEFAULT 'active' CHECK (status IN ('active', 'suspended')),
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
+);
+
+CREATE TABLE IF NOT EXISTS distribution_keys (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ binding_id UUID NOT NULL REFERENCES distribution_bindings (id),
+ key_prefix TEXT NOT NULL UNIQUE,
+ secret_hash TEXT NOT NULL,
+ expires_at TIMESTAMPTZ,
+ revoked_at TIMESTAMPTZ,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
+);
+
+CREATE TABLE IF NOT EXISTS distribution_releasers (
+ publisher_id UUID NOT NULL REFERENCES distribution_publishers (id),
+ profile_id INT NOT NULL REFERENCES profiles (id),
+ PRIMARY KEY (publisher_id, profile_id)
+);
+
+CREATE TABLE IF NOT EXISTS distribution_publisher_exercises (
+ publisher_id UUID NOT NULL REFERENCES distribution_publishers (id),
+ exercise_id INT NOT NULL REFERENCES exercises (id),
+ PRIMARY KEY (publisher_id, exercise_id)
+);
+
+CREATE TABLE IF NOT EXISTS distribution_part_identities (
+ source_id UUID NOT NULL,
+ part_key TEXT NOT NULL,
+ part_id UUID NOT NULL,
+ PRIMARY KEY (source_id, part_key)
+);
+
+CREATE TABLE IF NOT EXISTS distribution_source_revisions (
+ source_id UUID NOT NULL,
+ revision INT NOT NULL CHECK (revision > 0),
+ snapshot_hash TEXT NOT NULL,
+ PRIMARY KEY (source_id, revision),
+ UNIQUE (source_id, snapshot_hash)
+);
+
+CREATE TABLE IF NOT EXISTS distribution_drafts (
+ id UUID PRIMARY KEY,
+ exercise_id INT NOT NULL REFERENCES exercises (id),
+ publisher_id UUID NOT NULL REFERENCES distribution_publishers (id),
+ recipient_id UUID NOT NULL REFERENCES distribution_recipients (id),
+ prepared_by INT NOT NULL REFERENCES profiles (id),
+ cut JSONB NOT NULL,
+ preview_hash TEXT NOT NULL,
+ release_id UUID,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+ confirmed_at TIMESTAMPTZ
+);
+
+CREATE TABLE IF NOT EXISTS distribution_releases (
+ release_id UUID PRIMARY KEY,
+ recipient_id UUID NOT NULL REFERENCES distribution_recipients (id),
+ publisher_id UUID NOT NULL REFERENCES distribution_publishers (id),
+ source_id UUID NOT NULL,
+ revision INT NOT NULL,
+ cut_hash TEXT NOT NULL,
+ manifest_text TEXT NOT NULL,
+ manifest_sha256 TEXT NOT NULL,
+ published_at TIMESTAMPTZ NOT NULL,
+ fetch_blocked BOOLEAN NOT NULL DEFAULT FALSE,
+ confirmed_by INT REFERENCES profiles (id)
+);
+
+CREATE INDEX IF NOT EXISTS idx_distribution_releases_source ON distribution_releases (source_id);
+CREATE INDEX IF NOT EXISTS idx_distribution_releases_recipient ON distribution_releases (recipient_id);
+
+CREATE TABLE IF NOT EXISTS distribution_release_assets (
+ release_id UUID NOT NULL REFERENCES distribution_releases (release_id),
+ asset_id UUID NOT NULL,
+ sha256 TEXT NOT NULL,
+ size_bytes INT NOT NULL,
+ media_type TEXT NOT NULL,
+ storage_path TEXT NOT NULL,
+ source_media_public_id UUID,
+ source_asset_id INT,
+ PRIMARY KEY (release_id, asset_id)
+);
+
+CREATE INDEX IF NOT EXISTS idx_distribution_release_assets_source
+ ON distribution_release_assets (source_asset_id);
+
+CREATE TABLE IF NOT EXISTS distribution_events (
+ event_id UUID PRIMARY KEY,
+ recipient_id UUID NOT NULL REFERENCES distribution_recipients (id),
+ seq BIGINT NOT NULL,
+ event_type TEXT NOT NULL,
+ release_id UUID NOT NULL,
+ occurred_at TIMESTAMPTZ NOT NULL,
+ body JSONB NOT NULL,
+ UNIQUE (recipient_id, seq)
+);
+
+CREATE INDEX IF NOT EXISTS idx_distribution_events_feed
+ ON distribution_events (recipient_id, seq);
+
+CREATE TABLE IF NOT EXISTS distribution_evidence (
+ id TEXT PRIMARY KEY,
+ publisher_id UUID NOT NULL REFERENCES distribution_publishers (id),
+ note TEXT NOT NULL,
+ created_by INT NOT NULL REFERENCES profiles (id),
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
+);
+
+CREATE TABLE IF NOT EXISTS distribution_rate_windows (
+ binding_id UUID PRIMARY KEY REFERENCES distribution_bindings (id),
+ window_start TIMESTAMPTZ NOT NULL,
+ hits INT NOT NULL
+);
diff --git a/backend/routers/distribution.py b/backend/routers/distribution.py
new file mode 100644
index 0000000..2dc97fc
--- /dev/null
+++ b/backend/routers/distribution.py
@@ -0,0 +1,460 @@
+"""Distributionsfreigabe: Maschinenabruf und Redaktion.
+
+Maschinenabruf authentifiziert allein über den Distributions-Schlüssel.
+# ACCESS_LAYER exempt: kein Trainer-Mandant; Kanal kommt aus der Anbindung.
+Die Redaktions- und Verwaltungsrouten nutzen TenantContext.
+"""
+from __future__ import annotations
+
+from typing import Optional
+
+from fastapi import APIRouter, Depends, Header, HTTPException, Query
+from fastapi.responses import FileResponse, Response
+from pydantic import BaseModel, Field
+
+from club_tenancy import is_superadmin
+from db import get_cursor, get_db
+from distribution_contract import (
+ InvalidCursor,
+ cursor_secret,
+ decode_cursor,
+ distribution_enabled,
+)
+from distribution_service import (
+ backlog_count,
+ confirm_draft,
+ create_draft,
+ issue_key,
+ list_changes,
+ load_asset,
+ load_availability,
+ load_manifest,
+ overview,
+ resolve_bearer,
+ retire_release,
+ update_draft,
+ withdraw_release,
+)
+from tenant_context import TenantContext, get_tenant_context
+
+router = APIRouter(prefix="/api/distribution/v1", tags=["distribution"])
+editorial = APIRouter(tags=["distribution-editorial"])
+
+NO_STORE = {"Cache-Control": "private, no-store"}
+
+
+def _machine(authorization: Optional[str]):
+ if not distribution_enabled():
+ raise HTTPException(status_code=404, detail="Nicht gefunden", headers=NO_STORE)
+ if not authorization or not authorization.lower().startswith("bearer "):
+ raise HTTPException(
+ status_code=401,
+ detail={"code": "invalid_key", "message": "Schlüssel ungültig."},
+ headers=NO_STORE,
+ )
+ token = authorization.split(" ", 1)[1].strip()
+ held: Optional[HTTPException] = None
+ binding = None
+ with get_db() as conn:
+ cur = get_cursor(conn)
+ try:
+ binding = resolve_bearer(cur, token)
+ except HTTPException as exc:
+ held = exc
+ if held is not None:
+ held.headers = {**(held.headers or {}), **NO_STORE}
+ raise held
+ return binding
+
+
+def _superadmin(tenant: TenantContext) -> None:
+ if not is_superadmin(tenant.global_role):
+ raise HTTPException(status_code=403, detail="Nur Superadmins dürfen die Distribution verwalten.")
+
+
+class PublisherBody(BaseModel):
+ name: str = Field(min_length=1, max_length=200)
+ kind: str
+ club_id: Optional[int] = None
+
+
+class RecipientBody(BaseModel):
+ name: str = Field(min_length=1, max_length=200)
+
+
+class RelationshipBody(BaseModel):
+ publisher_id: str
+ recipient_id: str
+
+
+class BindingBody(BaseModel):
+ recipient_id: str
+ name: str = Field(min_length=1, max_length=200)
+
+
+class KeyBody(BaseModel):
+ expires_at: Optional[str] = None
+
+
+class ProfileBody(BaseModel):
+ profile_id: int
+
+
+class ExerciseAssignBody(BaseModel):
+ exercise_id: int
+
+
+class SuspendBody(BaseModel):
+ kind: str
+ id: str
+
+
+class DraftBody(BaseModel):
+ publisher_id: str
+ recipient_id: str
+ cut: Optional[dict] = None
+
+
+class CutBody(BaseModel):
+ cut: dict
+
+
+class ReasonBody(BaseModel):
+ reason_code: str
+
+
+@router.get("/changes")
+def get_changes(
+ cursor: Optional[str] = None,
+ limit: Optional[int] = Query(default=None),
+ authorization: Optional[str] = Header(default=None),
+):
+ binding = _machine(authorization)
+ if limit is None:
+ limit = 50
+ elif limit < 1 or limit > 100:
+ raise HTTPException(status_code=400, detail={"code": "invalid_limit", "message": "limit ist 1 bis 100."}, headers=NO_STORE)
+ try:
+ seq = decode_cursor(cursor_secret(), binding["recipient_id"], cursor)
+ except InvalidCursor:
+ raise HTTPException(
+ status_code=400,
+ detail={"code": "invalid_cursor", "message": "Cursor ungültig."},
+ headers=NO_STORE,
+ )
+ with get_db() as conn:
+ cur = get_cursor(conn)
+ payload = list_changes(cur, binding["recipient_id"], seq, limit)
+ return Response(
+ content=__import__("json").dumps(payload, ensure_ascii=False, separators=(",", ":")),
+ media_type="application/json",
+ headers=NO_STORE,
+ )
+
+
+@router.get("/exercises/{source_id}/availability")
+def get_availability(source_id: str, authorization: Optional[str] = Header(default=None)):
+ binding = _machine(authorization)
+ held: Optional[HTTPException] = None
+ payload = None
+ with get_db() as conn:
+ cur = get_cursor(conn)
+ try:
+ payload = load_availability(cur, binding["recipient_id"], source_id)
+ except HTTPException as exc:
+ held = exc
+ if held is not None:
+ held.headers = {**(held.headers or {}), **NO_STORE}
+ raise held
+ return Response(
+ content=__import__("json").dumps(payload, ensure_ascii=False, separators=(",", ":")),
+ media_type="application/json",
+ headers=NO_STORE,
+ )
+
+
+@router.get("/releases/{release_id}")
+def get_release(release_id: str, authorization: Optional[str] = Header(default=None)):
+ binding = _machine(authorization)
+ held: Optional[HTTPException] = None
+ body = b""
+ with get_db() as conn:
+ cur = get_cursor(conn)
+ try:
+ body = load_manifest(cur, binding["recipient_id"], release_id)
+ except HTTPException as exc:
+ held = exc
+ if held is not None:
+ held.headers = {**(held.headers or {}), **NO_STORE}
+ raise held
+ return Response(content=body, media_type="application/json", headers=NO_STORE)
+
+
+@router.get("/releases/{release_id}/assets/{asset_id}")
+def get_asset(release_id: str, asset_id: str, authorization: Optional[str] = Header(default=None)):
+ binding = _machine(authorization)
+ held: Optional[HTTPException] = None
+ path = None
+ media_type = "application/octet-stream"
+ with get_db() as conn:
+ cur = get_cursor(conn)
+ try:
+ path, media_type = load_asset(cur, binding["recipient_id"], release_id, asset_id)
+ except HTTPException as exc:
+ held = exc
+ if held is not None:
+ held.headers = {**(held.headers or {}), **NO_STORE}
+ raise held
+ return FileResponse(path, media_type=media_type, headers=NO_STORE)
+
+
+@editorial.get("/api/exercises/{exercise_id}/distribution")
+def exercise_distribution(exercise_id: int, tenant: TenantContext = Depends(get_tenant_context)):
+ with get_db() as conn:
+ cur = get_cursor(conn)
+ return overview(cur, exercise_id, tenant.profile_id, tenant.global_role or "")
+
+
+@editorial.post("/api/exercises/{exercise_id}/distribution/drafts")
+def post_draft(exercise_id: int, body: DraftBody, tenant: TenantContext = Depends(get_tenant_context)):
+ with get_db() as conn:
+ cur = get_cursor(conn)
+ from routers.exercises import _assert_can_edit_exercise
+
+ _assert_can_edit_exercise(cur, exercise_id, tenant)
+ result = create_draft(
+ cur,
+ exercise_id,
+ body.publisher_id,
+ body.recipient_id,
+ tenant.profile_id,
+ tenant.global_role or "",
+ body.cut,
+ )
+ conn.commit()
+ return result
+
+
+@editorial.put("/api/exercises/{exercise_id}/distribution/drafts/{draft_id}")
+def put_draft(exercise_id: int, draft_id: str, body: CutBody, tenant: TenantContext = Depends(get_tenant_context)):
+ with get_db() as conn:
+ cur = get_cursor(conn)
+ from routers.exercises import _assert_can_edit_exercise
+
+ _assert_can_edit_exercise(cur, exercise_id, tenant)
+ result = update_draft(
+ cur, exercise_id, draft_id, body.cut, tenant.profile_id, tenant.global_role or ""
+ )
+ conn.commit()
+ return result
+
+
+@editorial.post("/api/exercises/{exercise_id}/distribution/drafts/{draft_id}/confirm")
+def post_confirm(exercise_id: int, draft_id: str, tenant: TenantContext = Depends(get_tenant_context)):
+ with get_db() as conn:
+ cur = get_cursor(conn)
+ result = confirm_draft(cur, exercise_id, draft_id, tenant.profile_id, tenant.global_role or "")
+ conn.commit()
+ return result
+
+
+@editorial.post("/api/distribution/releases/{release_id}/retire")
+def post_retire(release_id: str, tenant: TenantContext = Depends(get_tenant_context)):
+ with get_db() as conn:
+ cur = get_cursor(conn)
+ result = retire_release(cur, release_id, tenant.profile_id, tenant.global_role or "")
+ conn.commit()
+ return result
+
+
+@editorial.post("/api/distribution/releases/{release_id}/withdraw")
+def post_withdraw(release_id: str, body: ReasonBody, tenant: TenantContext = Depends(get_tenant_context)):
+ with get_db() as conn:
+ cur = get_cursor(conn)
+ result = withdraw_release(cur, release_id, body.reason_code, tenant.profile_id, tenant.global_role or "", "release", None)
+ conn.commit()
+ return result
+
+
+@editorial.post("/api/distribution/releases/{release_id}/variants/{variant_id}/withdraw")
+def post_withdraw_variant(
+ release_id: str,
+ variant_id: str,
+ body: ReasonBody,
+ tenant: TenantContext = Depends(get_tenant_context),
+):
+ with get_db() as conn:
+ cur = get_cursor(conn)
+ result = withdraw_release(
+ cur, release_id, body.reason_code, tenant.profile_id, tenant.global_role or "", "variant", variant_id
+ )
+ conn.commit()
+ return result
+
+
+@editorial.post("/api/distribution/releases/{release_id}/assets/{asset_id}/withdraw")
+def post_withdraw_asset(
+ release_id: str,
+ asset_id: str,
+ body: ReasonBody,
+ tenant: TenantContext = Depends(get_tenant_context),
+):
+ with get_db() as conn:
+ cur = get_cursor(conn)
+ result = withdraw_release(
+ cur, release_id, body.reason_code, tenant.profile_id, tenant.global_role or "", "asset", asset_id
+ )
+ conn.commit()
+ return result
+
+
+@editorial.post("/api/distribution/admin/publishers")
+def post_publisher(body: PublisherBody, tenant: TenantContext = Depends(get_tenant_context)):
+ _superadmin(tenant)
+ if body.kind not in ("platform", "own", "club"):
+ raise HTTPException(status_code=400, detail="kind ist platform, own oder club.")
+ with get_db() as conn:
+ cur = get_cursor(conn)
+ cur.execute(
+ """
+ INSERT INTO distribution_publishers (name, kind, club_id)
+ VALUES (%s, %s, %s)
+ RETURNING id
+ """,
+ (body.name, body.kind, body.club_id),
+ )
+ row = cur.fetchone()
+ conn.commit()
+ return {"id": str(row["id"])}
+
+
+@editorial.post("/api/distribution/admin/recipients")
+def post_recipient(body: RecipientBody, tenant: TenantContext = Depends(get_tenant_context)):
+ _superadmin(tenant)
+ with get_db() as conn:
+ cur = get_cursor(conn)
+ cur.execute(
+ "INSERT INTO distribution_recipients (name) VALUES (%s) RETURNING id",
+ (body.name,),
+ )
+ row = cur.fetchone()
+ conn.commit()
+ return {"id": str(row["id"])}
+
+
+@editorial.post("/api/distribution/admin/relationships")
+def post_relationship(body: RelationshipBody, tenant: TenantContext = Depends(get_tenant_context)):
+ _superadmin(tenant)
+ with get_db() as conn:
+ cur = get_cursor(conn)
+ cur.execute(
+ """
+ INSERT INTO distribution_relationships (publisher_id, recipient_id)
+ VALUES (%s, %s)
+ RETURNING id
+ """,
+ (body.publisher_id, body.recipient_id),
+ )
+ row = cur.fetchone()
+ conn.commit()
+ return {"id": str(row["id"])}
+
+
+@editorial.post("/api/distribution/admin/bindings")
+def post_binding(body: BindingBody, tenant: TenantContext = Depends(get_tenant_context)):
+ _superadmin(tenant)
+ with get_db() as conn:
+ cur = get_cursor(conn)
+ cur.execute(
+ """
+ INSERT INTO distribution_bindings (recipient_id, name)
+ VALUES (%s, %s)
+ RETURNING id
+ """,
+ (body.recipient_id, body.name),
+ )
+ row = cur.fetchone()
+ conn.commit()
+ return {"id": str(row["id"])}
+
+
+@editorial.post("/api/distribution/admin/bindings/{binding_id}/keys")
+def post_key(binding_id: str, body: KeyBody, tenant: TenantContext = Depends(get_tenant_context)):
+ _superadmin(tenant)
+ with get_db() as conn:
+ cur = get_cursor(conn)
+ result = issue_key(cur, binding_id, body.expires_at)
+ conn.commit()
+ return result
+
+
+@editorial.post("/api/distribution/admin/keys/{key_prefix}/revoke")
+def post_revoke(key_prefix: str, tenant: TenantContext = Depends(get_tenant_context)):
+ _superadmin(tenant)
+ with get_db() as conn:
+ cur = get_cursor(conn)
+ cur.execute(
+ "UPDATE distribution_keys SET revoked_at = NOW() WHERE key_prefix = %s AND revoked_at IS NULL",
+ (key_prefix,),
+ )
+ conn.commit()
+ return {"ok": True}
+
+
+@editorial.post("/api/distribution/admin/publishers/{publisher_id}/releasers")
+def post_releaser(publisher_id: str, body: ProfileBody, tenant: TenantContext = Depends(get_tenant_context)):
+ _superadmin(tenant)
+ with get_db() as conn:
+ cur = get_cursor(conn)
+ cur.execute(
+ """
+ INSERT INTO distribution_releasers (publisher_id, profile_id)
+ VALUES (%s, %s)
+ ON CONFLICT DO NOTHING
+ """,
+ (publisher_id, body.profile_id),
+ )
+ conn.commit()
+ return {"ok": True}
+
+
+@editorial.post("/api/distribution/admin/publishers/{publisher_id}/exercises")
+def post_assign(publisher_id: str, body: ExerciseAssignBody, tenant: TenantContext = Depends(get_tenant_context)):
+ _superadmin(tenant)
+ with get_db() as conn:
+ cur = get_cursor(conn)
+ cur.execute(
+ """
+ INSERT INTO distribution_publisher_exercises (publisher_id, exercise_id)
+ VALUES (%s, %s)
+ ON CONFLICT DO NOTHING
+ """,
+ (publisher_id, body.exercise_id),
+ )
+ conn.commit()
+ return {"ok": True}
+
+
+@editorial.post("/api/distribution/admin/suspend")
+def post_suspend(body: SuspendBody, tenant: TenantContext = Depends(get_tenant_context)):
+ _superadmin(tenant)
+ table = {
+ "publisher": "distribution_publishers",
+ "recipient": "distribution_recipients",
+ "binding": "distribution_bindings",
+ }.get(body.kind)
+ if table is None:
+ raise HTTPException(status_code=400, detail="kind ist publisher, recipient oder binding.")
+ with get_db() as conn:
+ cur = get_cursor(conn)
+ cur.execute(f"UPDATE {table} SET status = 'suspended' WHERE id = %s", (body.id,))
+ conn.commit()
+ return {"ok": True}
+
+
+@editorial.get("/api/distribution/admin/backlog")
+def get_backlog(tenant: TenantContext = Depends(get_tenant_context)):
+ _superadmin(tenant)
+ with get_db() as conn:
+ cur = get_cursor(conn)
+ return {"count": backlog_count(cur)}
diff --git a/backend/routers/exercises.py b/backend/routers/exercises.py
index 0df30ee..7778789 100644
--- a/backend/routers/exercises.py
+++ b/backend/routers/exercises.py
@@ -29,6 +29,7 @@ from club_tenancy import (
club_admin_shares_club_with_creator,
has_club_role,
is_platform_admin,
+ is_superadmin,
library_content_visible_to_profile,
)
from tenant_context import TenantContext, get_tenant_context, get_tenant_context_flexible, library_content_visibility_sql
@@ -39,6 +40,8 @@ from ai_prompt_context import ExerciseFormAiFocusRow, ExerciseFormAiPromptContex
from ai_prompt_job import run_exercise_form_ai_suggestion
from account_lifecycle import assert_min_account_state
from capabilities import probe_capability
+from distribution_contract import OFFICIAL_WRITE_DENIED, official_write_allowed
+from distribution_service import blocks_exercise_delete, blocks_media_delete, blocks_variant_delete
from club_features import (
consume_club_feature_with_usage,
merge_feature_usage_into_response,
@@ -563,11 +566,13 @@ def _assert_can_edit_exercise(cur, exercise_id: int, tenant: TenantContext) -> N
owner = rd.get("created_by")
if owner is not None:
owner = int(owner)
+ ex_vis = (rd.get("visibility") or "private").strip().lower()
+ if not official_write_allowed(ex_vis, role):
+ raise HTTPException(status_code=403, detail=OFFICIAL_WRITE_DENIED)
if owner == profile_id:
return
if is_platform_admin(role):
return
- ex_vis = (rd.get("visibility") or "private").strip().lower()
ex_cid_raw = rd.get("club_id")
ex_cid = int(ex_cid_raw) if ex_cid_raw is not None else None
if ex_vis == "club" and ex_cid is not None and can_plan_in_club(cur, profile_id, ex_cid, role):
@@ -1458,9 +1463,13 @@ def _exercise_delete_usage_message(counts: dict) -> str:
def _assert_can_delete_exercise(cur, tenant: TenantContext, row: dict) -> None:
pid = tenant.profile_id
role = tenant.global_role
+ vis = str(row.get("visibility") or "private").strip().lower()
+ if vis == "official":
+ if not is_superadmin(role):
+ raise HTTPException(status_code=403, detail=OFFICIAL_WRITE_DENIED)
+ return
if is_platform_admin(role):
return
- vis = str(row.get("visibility") or "private").strip().lower()
cid = row.get("club_id")
creator = row.get("created_by")
try:
@@ -1468,11 +1477,6 @@ def _assert_can_delete_exercise(cur, tenant: TenantContext, row: dict) -> None:
except (TypeError, ValueError):
creator_int = None
- if vis == "official":
- raise HTTPException(
- status_code=403,
- detail="Globale Übungen dürfen nur von Plattform-Admins gelöscht werden.",
- )
if vis == "club":
try:
ex_club = int(cid) if cid is not None else None
@@ -1598,6 +1602,9 @@ def bulk_patch_exercises_metadata(
owner = int(owner)
ex_vis = (rowd.get("visibility") or "private").strip().lower()
+ if not official_write_allowed(ex_vis, role):
+ failed.append({"id": ex_id, "detail": OFFICIAL_WRITE_DENIED})
+ continue
ex_cid_raw = rowd.get("club_id")
ex_cid = int(ex_cid_raw) if ex_cid_raw is not None else None
@@ -2833,6 +2840,11 @@ def delete_exercise(
usage_msg = _exercise_delete_usage_message(counts)
if usage_msg:
raise HTTPException(status_code=409, detail=usage_msg)
+ if blocks_exercise_delete(cur, exercise_id):
+ raise HTTPException(
+ status_code=409,
+ detail="Die Übung hat eine externe Freigabe und kann nicht gelöscht werden.",
+ )
cur.execute("DELETE FROM exercises WHERE id = %s", (exercise_id,))
conn.commit()
@@ -3040,6 +3052,11 @@ def delete_exercise_variant(
cur = get_cursor(conn)
_assert_can_edit_exercise(cur, exercise_id, tenant)
assert_exercise_not_combination(cur, exercise_id)
+ if blocks_variant_delete(cur, variant_id):
+ raise HTTPException(
+ status_code=409,
+ detail="Die Variante ist Teil einer externen Freigabe und kann nicht gelöscht werden.",
+ )
_fetch_variant_row(cur, exercise_id, variant_id)
cur.execute(
@@ -3840,6 +3857,11 @@ def delete_exercise_media(
row = cur.fetchone()
if not row:
raise HTTPException(status_code=404, detail="Medium nicht gefunden")
+ if blocks_media_delete(cur, media_id):
+ raise HTTPException(
+ status_code=409,
+ detail="Das Medium ist Teil einer externen Freigabe und kann nicht gelöst werden.",
+ )
rec = r2d(row)
media_asset_id = rec.get("media_asset_id")
if media_asset_id:
diff --git a/backend/tests/test_distribution_contract.py b/backend/tests/test_distribution_contract.py
new file mode 100644
index 0000000..a71cb96
--- /dev/null
+++ b/backend/tests/test_distribution_contract.py
@@ -0,0 +1,259 @@
+"""Vertrag v1, Referenzfall, Rollen und Bestätigung nach Rückzug."""
+from __future__ import annotations
+
+import inspect
+import json
+import os
+from pathlib import Path
+from unittest.mock import MagicMock, patch
+
+import pytest
+from fastapi import HTTPException
+from fastapi.testclient import TestClient
+
+os.environ.setdefault("SKIP_DB_MIGRATE", "1")
+
+from auth import require_auth
+from distribution_service import _lock_recipient
+from distribution_contract import (
+ InvalidCursor,
+ actions_cover,
+ cursor_secret,
+ decide_confirm,
+ decode_cursor,
+ encode_cursor,
+ exercise_offerable,
+ package_state,
+ manifest_bytes,
+ official_write_allowed,
+ plan_available,
+ rate_decision,
+ release_denial,
+ retrievable_release_ids,
+ sha256_bytes,
+)
+from main import app
+from routers.exercises import _assert_can_edit_exercise
+from tenant_context import TenantContext, get_tenant_context
+
+FIXTURE = json.loads(
+ (Path(__file__).resolve().parents[2] / "docs" / "architecture" / "distribution" / "Shinkan_Lara_Felix_Referenzfall_v1.json").read_text(
+ encoding="utf-8"
+ )
+)
+
+
+def test_fixture_manifest_hashes_match_contract_order() -> None:
+ for release in FIXTURE["releases"].values():
+ body = manifest_bytes(release["manifest"])
+ assert sha256_bytes(body) == release["manifest_sha256"]
+ assert not body.endswith(b"\n")
+
+
+def test_reference_case_retrieval_and_plan_effect() -> None:
+ lara_events = FIXTURE["channels"]["lara_felix"]["events"]
+ second_events = FIXTURE["channels"]["zweiter_verein"]["events"]
+ assert retrievable_release_ids(lara_events) == set(FIXTURE["expected"]["lara_felix_can_retrieve_after_withdrawal"])
+ assert retrievable_release_ids(second_events) == set(FIXTURE["expected"]["zweiter_verein_can_retrieve"])
+ manifests = {item["manifest"]["release_id"]: item["manifest"] for item in FIXTURE["releases"].values()}
+ blocked = []
+ available = []
+ for name, plan in FIXTURE["plans"].items():
+ if plan_available(plan, manifests[plan["release_id"]], lara_events):
+ available.append(name)
+ else:
+ blocked.append(name)
+ assert set(blocked) == set(FIXTURE["expected"]["blocked_plans_after_withdrawal"])
+ assert set(available) == set(FIXTURE["expected"]["available_plans_after_withdrawal"])
+ film_actions = FIXTURE["releases"]["vereinsfassung_1"]["manifest"]["rights"][1]["actions"]
+ assert actions_cover(film_actions, ["stream", "course_display", "commercial_course_use"]) is FIXTURE["expected"]["course_film_allowed"]
+ assert ("download" in film_actions) is FIXTURE["expected"]["film_download_allowed"]
+
+
+def test_replay_keeps_release_id_and_explicit_reconfirm_mints_a_new_one() -> None:
+ drafts: dict[str, str] = {}
+ releases: dict[str, dict] = {}
+ events: list[tuple[str, str]] = []
+
+ def confirm(draft_id: str, revision: int, cut: str) -> tuple[str, bool]:
+ release_id, created = decide_confirm(drafts.get(draft_id), f"rel-{len(releases) + 1}")
+ if created:
+ drafts[draft_id] = release_id
+ releases[release_id] = {"withdrawn": False, "revision": revision, "cut": cut}
+ events.append(("published", release_id))
+ return release_id, created
+
+ first, created = confirm("draft-1", 1, "same-cut")
+ again, replayed = confirm("draft-1", 1, "same-cut")
+ assert first == again
+ assert created is True
+ assert replayed is False
+ assert events == [("published", first)]
+
+ releases[first]["withdrawn"] = True
+ second, created_again = confirm("draft-2", 1, "same-cut")
+ assert created_again is True
+ assert second != first
+ assert releases[first]["withdrawn"] is True
+ assert releases[second]["revision"] == 1
+ assert releases[second]["cut"] == "same-cut"
+ assert [kind for kind, _ in events] == ["published", "published"]
+
+
+def test_availability_keeps_the_copy_and_stops_new_offers() -> None:
+ assert package_state(fetch_blocked=False, retired=False) == "available"
+ assert package_state(fetch_blocked=False, retired=True) == "retired"
+ assert package_state(fetch_blocked=True, retired=True) == "withdrawn"
+ status, offerable = exercise_offerable("approved", ["available"])
+ assert status == "approved" and offerable is True
+ status, offerable = exercise_offerable("archived", ["available"])
+ assert status == "archived" and offerable is False
+ status, offerable = exercise_offerable(None, ["withdrawn"])
+ assert status == "deleted" and offerable is False
+ status, offerable = exercise_offerable("approved", ["retired", "withdrawn"])
+ assert offerable is False
+
+
+def test_cursor_is_bound_to_recipient() -> None:
+ secret = cursor_secret()
+ token = encode_cursor(secret, "recipient-a", 4)
+ assert decode_cursor(secret, "recipient-a", token) == 4
+ assert decode_cursor(secret, "recipient-a", None) == 0
+ with pytest.raises(InvalidCursor):
+ decode_cursor(secret, "recipient-b", token)
+
+
+def test_rate_window_blocks_at_sixty() -> None:
+ hits, blocked = rate_decision(59, 10)
+ assert hits == 60 and blocked is False
+ hits, blocked = rate_decision(60, 10)
+ assert blocked is True
+ hits, blocked = rate_decision(60, 61)
+ assert hits == 1 and blocked is False
+
+
+def test_official_release_and_edit_roles() -> None:
+ assert official_write_allowed("official", "superadmin") is True
+ assert official_write_allowed("official", "admin") is False
+ assert official_write_allowed("official", "club_admin") is False
+ assert official_write_allowed("club", "admin") is True
+ assert release_denial(
+ visibility="official",
+ role="admin",
+ publisher_kind="platform",
+ is_owner=True,
+ is_club_admin=False,
+ )
+ assert release_denial(
+ visibility="official",
+ role="superadmin",
+ publisher_kind="platform",
+ is_owner=False,
+ is_club_admin=False,
+ ) is None
+ assert release_denial(
+ visibility="private",
+ role="trainer",
+ publisher_kind="own",
+ is_owner=True,
+ is_club_admin=False,
+ ) is None
+ assert release_denial(
+ visibility="private",
+ role="admin",
+ publisher_kind="own",
+ is_owner=False,
+ is_club_admin=False,
+ )
+ assert release_denial(
+ visibility="club",
+ role="trainer",
+ publisher_kind="club",
+ is_owner=True,
+ is_club_admin=False,
+ publisher_club_id=4,
+ exercise_club_id=4,
+ )
+ assert release_denial(
+ visibility="club",
+ role="trainer",
+ publisher_kind="club",
+ is_owner=False,
+ is_club_admin=True,
+ publisher_club_id=4,
+ exercise_club_id=4,
+ ) is None
+ assert release_denial(
+ visibility="club",
+ role="trainer",
+ publisher_kind="club",
+ is_owner=False,
+ is_club_admin=True,
+ publisher_club_id=9,
+ exercise_club_id=4,
+ )
+
+
+def _tenant(role: str, profile_id: int = 7) -> TenantContext:
+ return TenantContext(
+ profile_id=profile_id,
+ global_role=role,
+ effective_club_id=None,
+ club_ids=frozenset(),
+ memberships=[],
+ )
+
+
+def test_assert_edit_rejects_admin_and_club_role_for_official() -> None:
+ cur = MagicMock()
+ cur.fetchone.return_value = {"created_by": 7, "visibility": "official", "club_id": None}
+ for role in ("admin", "trainer", "club_admin"):
+ with pytest.raises(HTTPException) as caught:
+ _assert_can_edit_exercise(cur, 3, _tenant(role))
+ assert caught.value.status_code == 403
+ _assert_can_edit_exercise(cur, 3, _tenant("superadmin", profile_id=1))
+
+
+@pytest.fixture
+def client() -> TestClient:
+ return TestClient(app)
+
+
+def test_distribution_read_is_hidden_while_disabled(client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.delenv("DISTRIBUTION_ENABLED", raising=False)
+ response = client.get("/api/distribution/v1/changes", headers={"Authorization": "Bearer shk.abc.def"})
+ assert response.status_code == 404
+ assert response.headers.get("cache-control") == "private, no-store"
+
+
+def test_channel_sequence_is_locked() -> None:
+ assert "FOR UPDATE" in inspect.getsource(_lock_recipient)
+
+
+def test_variant_and_media_routes_reject_admin_on_official(client: TestClient) -> None:
+ app.dependency_overrides[require_auth] = lambda: {"profile_id": 4, "role": "admin"}
+ app.dependency_overrides[get_tenant_context] = lambda: _tenant("admin", 4)
+ mock_cur = MagicMock()
+ mock_cur.fetchone.return_value = {"created_by": 4, "visibility": "official", "club_id": None}
+ mock_cm = MagicMock()
+ mock_cm.__enter__.return_value = MagicMock()
+ mock_cm.__exit__.return_value = False
+ try:
+ with patch("routers.exercises.get_db", return_value=mock_cm), patch(
+ "routers.exercises.get_cursor", return_value=mock_cur
+ ):
+ variant = client.post(
+ "/api/exercises/9/variants",
+ headers={"X-Auth-Token": "t"},
+ json={"variant_name": "Kartenweg"},
+ )
+ media = client.post(
+ "/api/exercises/9/media/from-asset",
+ headers={"X-Auth-Token": "t"},
+ json={"media_asset_id": 3},
+ )
+ assert variant.status_code == 403
+ assert media.status_code == 403
+ finally:
+ app.dependency_overrides.pop(require_auth, None)
+ app.dependency_overrides.pop(get_tenant_context, None)
diff --git a/backend/version.py b/backend/version.py
index bb8e470..3bb3871 100644
--- a/backend/version.py
+++ b/backend/version.py
@@ -1,8 +1,8 @@
# Shinkan Jinkendo Version Information
-APP_VERSION = "0.8.250"
+APP_VERSION = "0.8.252"
BUILD_DATE = "2026-11-23"
-DB_SCHEMA_VERSION = "20261123098"
+DB_SCHEMA_VERSION = "20261123099"
MODULE_VERSIONS = {
"legal_documents": "1.4.0", # Admin: Live-Vorschau pro Abschnitt + modale Vollvorschau (Editor + Dokumentenliste)
@@ -38,7 +38,8 @@ MODULE_VERSIONS = {
"skills": "0.1.1", # DB 065 karate_relevance + relevance_level; CRUD unterstützt Felder
"skill_profiles": "1.0.0", # Phase 3: gewichtetes Fähigkeiten-Profil + skill-discovery/suggestions
"methods": "0.1.0",
- "exercises": "2.37.2", # Upload-MIME nur aus Magic Bytes; PDF als Anhang; Rich-Text-Allowlist beim Speichern
+ "exercises": "2.38.0", # Globale Übungen schreibt und gibt nur superadmin frei
+ "distribution": "1.1.0", # Freigabe folgt der Übung: Besitzer, Vereinsadmin, Superadmin für global
"planning_exercise_suggest": "0.23.8", # Progressionsgraph: Katalog-Kontext (Fokus/Stil/TT/ZG) im Match-Profil
"training_units": "0.4.0", # POST .../publish-to-framework: Ablauf aus geplanter Einheit → Rahmen-Slot-Blueprint
"training_programs": "0.1.0",
@@ -54,6 +55,21 @@ MODULE_VERSIONS = {
}
CHANGELOG = [
+ {
+ "version": "0.8.252",
+ "date": "2026-11-23",
+ "changes": [
+ "Externe Freigabe folgt der Übung: private Übungen gibt der Besitzer frei, Vereinsübungen der Vereinsadmin, globale Übungen nur ein Superadmin.",
+ "Empfänger fragen die Verfügbarkeit einer freigegebenen Übung ab. Archiv und Löschung der Quelle beenden neue Angebote, die eingefrorene Kopie bleibt bis zum Rückzug abrufbar.",
+ ],
+ },
+ {
+ "version": "0.8.251",
+ "date": "2026-11-23",
+ "changes": [
+ "Eingefrorene Übungsfassungen können für einen Empfängerkanal freigegeben und per Distributions-Schlüssel abgerufen werden. Globale Übungen bearbeitet und gibt nur ein Superadmin frei. Die Distribution bleibt aus, bis DISTRIBUTION_ENABLED gesetzt ist.",
+ ],
+ },
{
"version": "0.8.250",
"date": "2026-11-23",
diff --git a/docker-compose.dev-env.yml b/docker-compose.dev-env.yml
index b24d4d3..bd2b27c 100644
--- a/docker-compose.dev-env.yml
+++ b/docker-compose.dev-env.yml
@@ -38,6 +38,7 @@ services:
APP_URL: "${APP_URL:-https://dev.shinkan.jinkendo.de}"
ALLOWED_ORIGINS: "${ALLOWED_ORIGINS:-https://dev.shinkan.jinkendo.de,http://192.168.2.49:3098}"
ENVIRONMENT: "${ENVIRONMENT:-development}"
+ DISTRIBUTION_ENABLED: "${DISTRIBUTION_ENABLED:-1}"
AUTO_ADMIN_FIRST_USER: "${AUTO_ADMIN_FIRST_USER:-false}"
REQUIRE_ADMIN_TOTP: "${REQUIRE_ADMIN_TOTP:-false}"
# M5: Hard-Block Vereins-Kontingente (Default aus — in .env auf 1 setzen zum Testen)
diff --git a/docs/architecture/distribution/Shinkan_Lara_Felix_Referenzfall_v1.json b/docs/architecture/distribution/Shinkan_Lara_Felix_Referenzfall_v1.json
new file mode 100644
index 0000000..51820e8
--- /dev/null
+++ b/docs/architecture/distribution/Shinkan_Lara_Felix_Referenzfall_v1.json
@@ -0,0 +1,493 @@
+{
+ "fixture_version": 1,
+ "note": "Synthetische Inhalte ohne produktive Rechte. Die Medienbytes dienen der Testung von Groesse und Hash. Sie sind keine abspielbare Filmdatei.",
+ "manifest_serialization": "UTF-8, JSON ohne Leerraum, Reihenfolge der Felder aus manifest, kein abschliessender Zeilenumbruch",
+ "channels": {
+ "lara_felix": {
+ "recipient_id": "caa20000-0000-4000-8000-0000000001f5",
+ "events": [
+ {
+ "event_id": "caa20000-0000-4000-8000-000000000258",
+ "type": "release.published",
+ "release_id": "caa20000-0000-4000-8000-0000000000c9",
+ "occurred_at": "2026-11-23T09:01:00Z",
+ "source_id": "caa20000-0000-4000-8000-00000000000a",
+ "revision": 1,
+ "manifest_sha256": "fcebc8c4db56328a55dc7f350e705822cef19f02392f26625274e68c0abc239c"
+ },
+ {
+ "event_id": "caa20000-0000-4000-8000-000000000259",
+ "type": "release.published",
+ "release_id": "caa20000-0000-4000-8000-0000000000ca",
+ "occurred_at": "2026-11-23T09:02:00Z",
+ "source_id": "caa20000-0000-4000-8000-00000000000b",
+ "revision": 1,
+ "manifest_sha256": "7dad43afb3077fb2d9fb3aa490bb91daf53f175c06575d648411021d352a1744"
+ },
+ {
+ "event_id": "caa20000-0000-4000-8000-00000000025a",
+ "type": "release.published",
+ "release_id": "caa20000-0000-4000-8000-0000000000cb",
+ "occurred_at": "2026-11-23T09:03:00Z",
+ "source_id": "caa20000-0000-4000-8000-00000000000a",
+ "revision": 2,
+ "manifest_sha256": "f0c8051cee6feb0e6399f1bc5681e0ef1ecd640c1cbe6b634c5df1c1b1df9ed0"
+ },
+ {
+ "event_id": "caa20000-0000-4000-8000-00000000025b",
+ "type": "release.retired",
+ "release_id": "caa20000-0000-4000-8000-0000000000c9",
+ "occurred_at": "2026-11-23T09:04:00Z"
+ },
+ {
+ "event_id": "caa20000-0000-4000-8000-00000000025c",
+ "type": "asset.withdrawn",
+ "release_id": "caa20000-0000-4000-8000-0000000000c9",
+ "occurred_at": "2026-11-23T09:05:00Z",
+ "target_id": "caa20000-0000-4000-8000-00000000012c",
+ "reason_code": "rights"
+ },
+ {
+ "event_id": "caa20000-0000-4000-8000-00000000025d",
+ "type": "asset.withdrawn",
+ "release_id": "caa20000-0000-4000-8000-0000000000cb",
+ "occurred_at": "2026-11-23T09:05:00Z",
+ "target_id": "caa20000-0000-4000-8000-00000000012c",
+ "reason_code": "rights"
+ }
+ ]
+ },
+ "zweiter_verein": {
+ "recipient_id": "caa20000-0000-4000-8000-0000000001f6",
+ "events": [
+ {
+ "event_id": "caa20000-0000-4000-8000-0000000002bc",
+ "type": "release.published",
+ "release_id": "caa20000-0000-4000-8000-0000000000cc",
+ "occurred_at": "2026-11-23T09:03:00Z",
+ "source_id": "caa20000-0000-4000-8000-00000000000c",
+ "revision": 1,
+ "manifest_sha256": "3e34007864d308ac1cf6b555bb7fd00dd6962fb6f396eca16492ace0fec59603"
+ }
+ ]
+ }
+ },
+ "releases": {
+ "vereinsfassung_1": {
+ "channel": "lara_felix",
+ "manifest_sha256": "fcebc8c4db56328a55dc7f350e705822cef19f02392f26625274e68c0abc239c",
+ "manifest": {
+ "schema_version": 1,
+ "resource_type": "exercise",
+ "release_id": "caa20000-0000-4000-8000-0000000000c9",
+ "source_id": "caa20000-0000-4000-8000-00000000000a",
+ "revision": 1,
+ "publisher_id": "caa20000-0000-4000-8000-00000000177a",
+ "published_at": "2026-11-23T09:01:00Z",
+ "exercise": {
+ "title": "Raum und Wege wahrnehmen",
+ "audience": "Kursleitungen",
+ "rights_id": "caa20000-0000-4000-8000-000000000191",
+ "parts": [
+ {
+ "id": "caa20000-0000-4000-8000-000000000065",
+ "role": "goal",
+ "text": "Die Gruppe nimmt freie Wege im Raum wahr.",
+ "rights_id": "caa20000-0000-4000-8000-000000000191"
+ },
+ {
+ "id": "caa20000-0000-4000-8000-000000000066",
+ "role": "instructions",
+ "text": "Die Kursleitung legt Karten aus und bespricht die freien Wege.",
+ "rights_id": "caa20000-0000-4000-8000-000000000191"
+ },
+ {
+ "id": "caa20000-0000-4000-8000-000000000067",
+ "role": "trainer_notes",
+ "text": "Vorab genug Platz vorsehen.",
+ "rights_id": "caa20000-0000-4000-8000-000000000191"
+ },
+ {
+ "id": "caa20000-0000-4000-8000-000000000068",
+ "role": "instructions",
+ "text": "Den kurzen Film ansehen und danach die gezeigten Wege vergleichen.",
+ "rights_id": "caa20000-0000-4000-8000-000000000191"
+ }
+ ],
+ "assets": [
+ {
+ "id": "caa20000-0000-4000-8000-00000000012c",
+ "role": "demonstration",
+ "media_type": "video/mp4",
+ "size_bytes": 32,
+ "sha256": "0fb807ef5ec44b003f181dfa9ce317becbcfd5755ebf91a57702d2024df2b915",
+ "rights_id": "caa20000-0000-4000-8000-000000000192",
+ "label": "Demonstrationsfilm"
+ }
+ ],
+ "common_part_ids": [
+ "caa20000-0000-4000-8000-000000000065",
+ "caa20000-0000-4000-8000-000000000067"
+ ],
+ "common_asset_ids": [],
+ "variants": [
+ {
+ "id": "caa20000-0000-4000-8000-00000000006b",
+ "label": "Kartenvariante",
+ "part_ids": [
+ "caa20000-0000-4000-8000-000000000066"
+ ],
+ "asset_ids": []
+ },
+ {
+ "id": "caa20000-0000-4000-8000-00000000006c",
+ "label": "Filmvariante",
+ "part_ids": [
+ "caa20000-0000-4000-8000-000000000068"
+ ],
+ "asset_ids": [
+ "caa20000-0000-4000-8000-00000000012c"
+ ]
+ }
+ ]
+ },
+ "rights": [
+ {
+ "id": "caa20000-0000-4000-8000-000000000191",
+ "evidence_ref": "test-textrechte",
+ "actions": [
+ "store",
+ "render",
+ "grant_customer_use",
+ "commercial_course_use"
+ ],
+ "territories": [
+ "DE"
+ ],
+ "valid_from": "2026-11-23T09:00:00Z",
+ "valid_until": null
+ },
+ {
+ "id": "caa20000-0000-4000-8000-000000000192",
+ "evidence_ref": "test-filmrechte",
+ "actions": [
+ "store",
+ "stream",
+ "course_display",
+ "grant_customer_use",
+ "commercial_course_use"
+ ],
+ "territories": [
+ "DE"
+ ],
+ "valid_from": "2026-11-23T09:00:00Z",
+ "valid_until": null
+ }
+ ]
+ },
+ "synthetic_asset_base64_by_id": {
+ "caa20000-0000-4000-8000-00000000012c": "U2hpbmthbiBkaXN0cmlidXRpb24gZml4dHVyZSB2MQo="
+ }
+ },
+ "eigener_bestand": {
+ "channel": "lara_felix",
+ "manifest_sha256": "7dad43afb3077fb2d9fb3aa490bb91daf53f175c06575d648411021d352a1744",
+ "manifest": {
+ "schema_version": 1,
+ "resource_type": "exercise",
+ "release_id": "caa20000-0000-4000-8000-0000000000ca",
+ "source_id": "caa20000-0000-4000-8000-00000000000b",
+ "revision": 1,
+ "publisher_id": "caa20000-0000-4000-8000-00000000177b",
+ "published_at": "2026-11-23T09:02:00Z",
+ "exercise": {
+ "title": "Aufmerksam im Raum ankommen",
+ "audience": "Kursleitungen",
+ "rights_id": "caa20000-0000-4000-8000-000000000191",
+ "parts": [
+ {
+ "id": "caa20000-0000-4000-8000-00000000006f",
+ "role": "goal",
+ "text": "Die Gruppe nimmt freie Wege im Raum wahr.",
+ "rights_id": "caa20000-0000-4000-8000-000000000191"
+ },
+ {
+ "id": "caa20000-0000-4000-8000-000000000070",
+ "role": "instructions",
+ "text": "Die Kursleitung legt Karten aus und bespricht die freien Wege.",
+ "rights_id": "caa20000-0000-4000-8000-000000000191"
+ },
+ {
+ "id": "caa20000-0000-4000-8000-000000000071",
+ "role": "trainer_notes",
+ "text": "Vorab genug Platz vorsehen.",
+ "rights_id": "caa20000-0000-4000-8000-000000000191"
+ }
+ ],
+ "assets": [],
+ "common_part_ids": [
+ "caa20000-0000-4000-8000-00000000006f",
+ "caa20000-0000-4000-8000-000000000071"
+ ],
+ "common_asset_ids": [],
+ "variants": [
+ {
+ "id": "caa20000-0000-4000-8000-000000000075",
+ "label": "Kartenvariante",
+ "part_ids": [
+ "caa20000-0000-4000-8000-000000000070"
+ ],
+ "asset_ids": []
+ }
+ ]
+ },
+ "rights": [
+ {
+ "id": "caa20000-0000-4000-8000-000000000191",
+ "evidence_ref": "test-textrechte",
+ "actions": [
+ "store",
+ "render",
+ "grant_customer_use",
+ "commercial_course_use"
+ ],
+ "territories": [
+ "DE"
+ ],
+ "valid_from": "2026-11-23T09:00:00Z",
+ "valid_until": null
+ }
+ ]
+ },
+ "synthetic_asset_base64_by_id": {}
+ },
+ "vereinsfassung_2": {
+ "channel": "lara_felix",
+ "manifest_sha256": "f0c8051cee6feb0e6399f1bc5681e0ef1ecd640c1cbe6b634c5df1c1b1df9ed0",
+ "manifest": {
+ "schema_version": 1,
+ "resource_type": "exercise",
+ "release_id": "caa20000-0000-4000-8000-0000000000cb",
+ "source_id": "caa20000-0000-4000-8000-00000000000a",
+ "revision": 2,
+ "publisher_id": "caa20000-0000-4000-8000-00000000177a",
+ "published_at": "2026-11-23T09:03:00Z",
+ "exercise": {
+ "title": "Raum und Wege wahrnehmen",
+ "audience": "Kursleitungen",
+ "rights_id": "caa20000-0000-4000-8000-000000000191",
+ "parts": [
+ {
+ "id": "caa20000-0000-4000-8000-000000000065",
+ "role": "goal",
+ "text": "Die Gruppe nimmt freie Wege im Raum wahr.",
+ "rights_id": "caa20000-0000-4000-8000-000000000191"
+ },
+ {
+ "id": "caa20000-0000-4000-8000-000000000066",
+ "role": "instructions",
+ "text": "Die Kursleitung legt Karten aus und bespricht die freien Wege.",
+ "rights_id": "caa20000-0000-4000-8000-000000000191"
+ },
+ {
+ "id": "caa20000-0000-4000-8000-000000000067",
+ "role": "trainer_notes",
+ "text": "Vorab genug Platz vorsehen und die Laufwege gemeinsam prüfen.",
+ "rights_id": "caa20000-0000-4000-8000-000000000191"
+ },
+ {
+ "id": "caa20000-0000-4000-8000-000000000068",
+ "role": "instructions",
+ "text": "Den kurzen Film ansehen und danach die gezeigten Wege vergleichen.",
+ "rights_id": "caa20000-0000-4000-8000-000000000191"
+ }
+ ],
+ "assets": [
+ {
+ "id": "caa20000-0000-4000-8000-00000000012c",
+ "role": "demonstration",
+ "media_type": "video/mp4",
+ "size_bytes": 32,
+ "sha256": "0fb807ef5ec44b003f181dfa9ce317becbcfd5755ebf91a57702d2024df2b915",
+ "rights_id": "caa20000-0000-4000-8000-000000000192",
+ "label": "Demonstrationsfilm"
+ }
+ ],
+ "common_part_ids": [
+ "caa20000-0000-4000-8000-000000000065",
+ "caa20000-0000-4000-8000-000000000067"
+ ],
+ "common_asset_ids": [],
+ "variants": [
+ {
+ "id": "caa20000-0000-4000-8000-00000000006b",
+ "label": "Kartenvariante",
+ "part_ids": [
+ "caa20000-0000-4000-8000-000000000066"
+ ],
+ "asset_ids": []
+ },
+ {
+ "id": "caa20000-0000-4000-8000-00000000006c",
+ "label": "Filmvariante",
+ "part_ids": [
+ "caa20000-0000-4000-8000-000000000068"
+ ],
+ "asset_ids": [
+ "caa20000-0000-4000-8000-00000000012c"
+ ]
+ }
+ ]
+ },
+ "rights": [
+ {
+ "id": "caa20000-0000-4000-8000-000000000191",
+ "evidence_ref": "test-textrechte",
+ "actions": [
+ "store",
+ "render",
+ "grant_customer_use",
+ "commercial_course_use"
+ ],
+ "territories": [
+ "DE"
+ ],
+ "valid_from": "2026-11-23T09:00:00Z",
+ "valid_until": null
+ },
+ {
+ "id": "caa20000-0000-4000-8000-000000000192",
+ "evidence_ref": "test-filmrechte",
+ "actions": [
+ "store",
+ "stream",
+ "course_display",
+ "grant_customer_use",
+ "commercial_course_use"
+ ],
+ "territories": [
+ "DE"
+ ],
+ "valid_from": "2026-11-23T09:00:00Z",
+ "valid_until": null
+ }
+ ]
+ },
+ "synthetic_asset_base64_by_id": {
+ "caa20000-0000-4000-8000-00000000012c": "U2hpbmthbiBkaXN0cmlidXRpb24gZml4dHVyZSB2MQo="
+ }
+ },
+ "zweiter_verein": {
+ "channel": "zweiter_verein",
+ "manifest_sha256": "3e34007864d308ac1cf6b555bb7fd00dd6962fb6f396eca16492ace0fec59603",
+ "manifest": {
+ "schema_version": 1,
+ "resource_type": "exercise",
+ "release_id": "caa20000-0000-4000-8000-0000000000cc",
+ "source_id": "caa20000-0000-4000-8000-00000000000c",
+ "revision": 1,
+ "publisher_id": "caa20000-0000-4000-8000-00000000177c",
+ "published_at": "2026-11-23T09:03:00Z",
+ "exercise": {
+ "title": "Gemeinsam den Raum erkunden",
+ "audience": "Kursleitungen",
+ "rights_id": "caa20000-0000-4000-8000-000000000191",
+ "parts": [
+ {
+ "id": "caa20000-0000-4000-8000-000000000079",
+ "role": "goal",
+ "text": "Die Gruppe nimmt freie Wege im Raum wahr.",
+ "rights_id": "caa20000-0000-4000-8000-000000000191"
+ },
+ {
+ "id": "caa20000-0000-4000-8000-00000000007a",
+ "role": "instructions",
+ "text": "Die Kursleitung legt Karten aus und bespricht die freien Wege.",
+ "rights_id": "caa20000-0000-4000-8000-000000000191"
+ },
+ {
+ "id": "caa20000-0000-4000-8000-00000000007b",
+ "role": "trainer_notes",
+ "text": "Vorab genug Platz vorsehen.",
+ "rights_id": "caa20000-0000-4000-8000-000000000191"
+ }
+ ],
+ "assets": [],
+ "common_part_ids": [
+ "caa20000-0000-4000-8000-000000000079",
+ "caa20000-0000-4000-8000-00000000007b"
+ ],
+ "common_asset_ids": [],
+ "variants": [
+ {
+ "id": "caa20000-0000-4000-8000-00000000007f",
+ "label": "Kartenvariante",
+ "part_ids": [
+ "caa20000-0000-4000-8000-00000000007a"
+ ],
+ "asset_ids": []
+ }
+ ]
+ },
+ "rights": [
+ {
+ "id": "caa20000-0000-4000-8000-000000000191",
+ "evidence_ref": "test-textrechte",
+ "actions": [
+ "store",
+ "render",
+ "grant_customer_use",
+ "commercial_course_use"
+ ],
+ "territories": [
+ "DE"
+ ],
+ "valid_from": "2026-11-23T09:00:00Z",
+ "valid_until": null
+ }
+ ]
+ },
+ "synthetic_asset_base64_by_id": {}
+ }
+ },
+ "plans": {
+ "plan_a_mit_film": {
+ "release_id": "caa20000-0000-4000-8000-0000000000c9",
+ "variant_id": "caa20000-0000-4000-8000-00000000006c"
+ },
+ "plan_b_mit_karten": {
+ "release_id": "caa20000-0000-4000-8000-0000000000c9",
+ "variant_id": "caa20000-0000-4000-8000-00000000006b"
+ },
+ "plan_c_mit_film_neuere_fassung": {
+ "release_id": "caa20000-0000-4000-8000-0000000000cb",
+ "variant_id": "caa20000-0000-4000-8000-00000000006c"
+ },
+ "plan_d_eigener_bestand": {
+ "release_id": "caa20000-0000-4000-8000-0000000000ca",
+ "variant_id": "caa20000-0000-4000-8000-000000000075"
+ }
+ },
+ "expected": {
+ "plan_binding_after_revision": {
+ "release_id": "caa20000-0000-4000-8000-0000000000c9",
+ "variant_id": "caa20000-0000-4000-8000-00000000006c"
+ },
+ "blocked_plans_after_withdrawal": [
+ "plan_a_mit_film",
+ "plan_c_mit_film_neuere_fassung"
+ ],
+ "available_plans_after_withdrawal": [
+ "plan_b_mit_karten",
+ "plan_d_eigener_bestand"
+ ],
+ "lara_felix_can_retrieve_after_withdrawal": [
+ "caa20000-0000-4000-8000-0000000000ca"
+ ],
+ "zweiter_verein_can_retrieve": [
+ "caa20000-0000-4000-8000-0000000000cc"
+ ],
+ "course_film_allowed": true,
+ "film_download_allowed": false
+ }
+}
diff --git a/docs/architecture/distribution/Shinkan_Lara_Felix_Uebergabevertrag_v1.md b/docs/architecture/distribution/Shinkan_Lara_Felix_Uebergabevertrag_v1.md
new file mode 100644
index 0000000..097e835
--- /dev/null
+++ b/docs/architecture/distribution/Shinkan_Lara_Felix_Uebergabevertrag_v1.md
@@ -0,0 +1,70 @@
+# Übergabevertrag für Übungsfassungen aus Shinkan · Version 1.0
+
+**23.11.2026 · Spezifikationsstand für die Beauftragung auf der Testinstanz**
+
+Shinkan führt die importierten Übungsoriginale. Es gibt ausgewählte Fassungen pro Empfänger frei. Lara & Felix übernimmt sie als lokale Übungsfassungen und bindet sie in seine Trainingspläne und Artikel-Stände ein. Die Veröffentlichung für Kundinnen und Kunden, die Lizenzprüfung und die Auslieferung liegen bei Lara & Felix. Planeditor, Angebotsmodell und dauerhafte Pflege eigener Lara-&-Felix-Übungsoriginale können gesondert entschieden werden. Die Freigabe des Produktivbetriebs erfordert beiderseitige Abnahme und belegte Nutzungsrechte.
+
+## 1. Identität, Herausgabe und Fassung
+
+| Begriff | Bedeutung im Vertrag |
+|---|---|
+| Herausgeber | Verantwortet eine Freigabe aus dem eigenen oder gemeinsam gepflegten Vereinsbestand. Der Empfänger erhält eine opaque UUID und gegebenenfalls die vereinbarte öffentliche Namensnennung. |
+| Empfänger und Anbindung | Ein Empfänger hat einen eigenen Lieferkanal. Eine Maschinenanbindung ist an einen Kanal gebunden, mit einem separat widerrufbaren Schlüssel. Mehrere Herausgeber können für denselben Empfänger freigeben, sofern jede Herausgeber-Empfänger-Beziehung autorisiert ist. |
+| `source_id` | Stabile öffentliche Übungs-UUID in Shinkan. Sie bleibt bei redaktionellen Änderungen und einem autorisierten Wechsel des Verantwortlichen erhalten. |
+| `revision` | Positive Ganzzahl je `source_id` für den eingefrorenen fachlichen Stand. Dasselbe unveränderte Quellabbild kann für mehrere Kanäle verwendet werden. Redaktionelle Änderungen an einer Arbeitsfassung verändern einen eingefrorenen Stand nicht. |
+| `release_id` | UUID des unveränderlichen Lieferpakets für einen Empfänger. Ein erneuter Zuschnitt von Auswahl oder Rechten führt zu einem neuen Paket, auch wenn die Quellrevision gleich bleibt. Mehrere Pakete derselben Revision erhalten im Änderungsverlauf eine eindeutige Reihenfolge. |
+
+Lara & Felix ordnet `source_id` einer stabilen lokalen Übung zu und `release_id` einem lokalen übernommenen Stand. Der Schlüssel hierfür umfasst das konfigurierte Quellsystem beziehungsweise die Quellinstanz. Die Prüfsumme dient der Integritätsprüfung. Gleiche Bytes mit unterschiedlicher Freigabe können einen unterschiedlichen Nutzungsumfang haben. Technische Schlüssel, Zugangsdaten, Vereinslisten, Profile, Gruppen, interne IDs und vertrauliche Nachweise sind von der Ausgabe ausgeschlossen. Die interne Shinkan-Sichtbarkeit regelt weiterhin die Nutzung im Trainerbereich.
+
+## 2. Das unveränderliche Paket
+
+`GET /api/distribution/v1/releases/{release_id}` liefert folgende Struktur als UTF-8-JSON. Zeiten im Vertrag verwenden UTC im Format `YYYY-MM-DDTHH:mm:ssZ`. Die angegebenen Objektfelder sind erforderlich, sofern sie hier als optional oder nullfähig beschrieben werden.
+
+| Feld | Inhalt |
+|---|---|
+| `schema_version`, `resource_type` | Ganzzahl `1`, Zeichenkette `exercise`. Ein neuer fachlicher Ressourcentyp benötigt eine eigene Vereinbarung. |
+| `release_id`, `source_id`, `revision`, `publisher_id`, `published_at` | Kennungen und Zeitpunkt gemäß Abschnitt 1. |
+| `exercise` | `title`, optionale `summary`, optionales `audience` und `rights_id` für diese redaktionellen Angaben. Dazu `parts`, `assets`, `common_part_ids`, `common_asset_ids` und `variants`. `parts` enthält mindestens einen Eintrag für das Lernziel. Jede Variante kann nach Auflösung eine Durchführung anzeigen. |
+| `parts[]` | `id` als UUID, `role`, `text` als Klartext und `rights_id`. Rollen in v1 sind `goal`, `prerequisites`, `preparation`, `instructions`, `trainer_notes`, `equipment` und `duration_note`. Trainerhinweise behalten eine eigene Rolle für die spätere Rechteprüfung in Lara & Felix. |
+| `assets[]` | `id` als UUID, `role`, `media_type`, `size_bytes`, `sha256`, `rights_id` und optionales `label`. Rollen in v1 sind `demonstration`, `worksheet` und `illustration`. SHA-256 steht als 64-stellige kleingeschriebene Hex-Zeichenkette. |
+| `common_part_ids`, `common_asset_ids` | Geordnete Referenzen auf die Bestandteile, die jede Variante nutzt. |
+| `variants[]` | `id` als UUID, `label`, `part_ids` und `asset_ids` als geordnete zusätzliche Referenzen. Eine Übung ohne redaktionelle Alternativen erhält eine Standardvariante. Eine wiederverwendete Varianten-UUID bezeichnet dieselbe fachliche Variante über Fassungen hinweg. |
+| `rights[]` | `id` als UUID, `evidence_ref` als opaque Nachweisreferenz, `actions`, `territories`, `valid_from`, `valid_until` und optional `attribution`. `territories` ist eine Liste von ISO-Ländercodes oder explizit `null` für räumlich unbeschränkt. `valid_until` ist exklusiv oder explizit `null` für unbefristet. |
+
+Für `actions` gelten `store`, `render`, `stream`, `download`, `print`, `course_display`, `commercial_course_use`, `adapt`, `public_preview` und `grant_customer_use`. `store` erlaubt die Übernahme durch den Empfänger, `render` die Anzeige eines Textes oder Bildes und `grant_customer_use` die Einräumung des abgedeckten Nutzungsumfangs an Endkunden. Die übrigen Aktionen begrenzen die jeweilige Nutzung. Kombinationen werden gemeinsam geprüft. Für kommerzielle Vorführung sind zum Beispiel neben `course_display` auch `commercial_course_use` und, bei gestreamtem Material, `stream` erforderlich. Lara & Felix prüft zusätzlich das eigene Rechteprofil. Auflagen außerhalb des Schemas müssen vor Veröffentlichung operationalisiert werden. [§ 31 UrhG](https://www.gesetze-im-internet.de/urhg/__31.html)
+
+Alle IDs innerhalb ihrer Listen sind eindeutig. Alle Referenzen müssen im selben Paket aufgehen. Jeder übermittelte Teil und jedes Medium gehört zu mindestens einer freigegebenen Variante und verweist auf einen wirksamen Rechtevermerk, der die Übernahme abdeckt. Variantenbeschriftungen sind vom Rechtevermerk der redaktionellen Angaben abgedeckt. Zum Freigabezeitpunkt muss die vorgesehene Nutzung möglich sein. Die exportierte Fassung v1 verwendet Klartext und separate Medienreferenzen. Sind Inline-Medien oder die Anordnung für das Verständnis wesentlich, prüft die Redaktion die aufbereitete Exportfassung und ihre Medien vor Freigabe. Unaufgelöste Anker, fremde URLs im Medienmanifest und nicht exportierbare Kombinationsabhängigkeiten sperren die Freigabe.
+
+Shinkan speichert den exakten JSON-Body und veröffentlicht seinen SHA-256 als `manifest_sha256` im Änderungsverlauf. Gehasht werden die UTF-8-Bytes des gespeicherten JSON-Bodys vor HTTP-Komprimierung. Der Empfänger hasht die empfangenen dekomprimierten Bytes vor dem Parsen. Für Medien werden die unveränderten Originalbytes geprüft. Setzt eine neue Paketfassung Teile neu zusammen, entsteht ein eigener Manifest-Hash. Der Status der Freigabe steht im Änderungsverlauf und verändert die gespeicherten Paketbytes nicht.
+
+## 3. Schnittstelle und Änderungsverlauf
+
+Die drei Lesezugriffe laufen serverseitig über TLS unter `/api/distribution/v1` mit `Authorization: Bearer Die Distribution ist auf dieser Instanz nicht aktiv. Bearbeitung und Planung bleiben davon unberührt.
+ Private Übungen gibt die Person frei, der sie gehören. Vereinsübungen gibt ein Vereinsadmin dieses Vereins frei.
+ Globale Übungen gibt nur ein Superadmin frei.
+ {overview.release_block} Keine blockierenden Punkte. {error}Externe Freigabe
+ {!overview.enabled ? (
+
+ {overview.publishers.map((publisher) => (
+
+ ) : null}
+
+
+
+
+ {draft.blockers.map((item) => (
+
+ ) : (
+
+ {(draft.cut?.parts || []).map((part) => (
+
+ Freigegebene Fassungen
+
+
+ {overview.releases.map((release) => (
+
+ >
+ ) : null}
+ {error ?