From 2558239bfdfb54cda98e973c34473bb620a39446 Mon Sep 17 00:00:00 2001 From: Lars Date: Fri, 16 Oct 2026 22:09:08 +0200 Subject: [PATCH] Stelle den ersten nutzbaren Ablauf zum Organisieren und Nachverfolgen bereit. Anmeldung, Datenraeume, Akten, Vorgaenge, gemeinsame Notizen, Dateien, manuelle Paperless-Referenzen, Aufgaben und unabhaengige Fristen laufen damit in der Entwicklungsumgebung. Co-authored-by: Cursor --- AGENTS.md | 7 + README.md | 13 +- backend/.dockerignore | 5 + backend/Dockerfile | 6 +- backend/app/__init__.py | 1 + backend/app/access/__init__.py | 1 + backend/app/access/policy.py | 763 ++++++++ backend/app/api/__init__.py | 1 + backend/app/api/deps.py | 97 + backend/app/api/routes.py | 1193 ++++++++++++ backend/app/api/schemas.py | 203 ++ backend/app/auth/__init__.py | 1 + backend/app/auth/accounts.py | 78 + backend/app/auth/security.py | 74 + backend/app/cli.py | 44 + backend/app/content/__init__.py | 1 + backend/app/content/documents.py | 25 + backend/app/core/__init__.py | 1 + backend/app/core/errors.py | 71 + backend/app/core/settings.py | 47 + backend/app/core/timeutil.py | 23 + backend/app/db/__init__.py | 1 + backend/app/db/migrate.py | 90 + backend/app/db/pool.py | 19 + backend/app/entrypoint.py | 18 + backend/app/main.py | 119 ++ backend/app/media/__init__.py | 1 + backend/app/media/storage.py | 71 + backend/app/ops.py | 784 ++++++++ backend/app/present.py | 490 +++++ backend/app/seed.py | 211 ++ backend/main.py | 43 +- .../20261016T210000Z_foundation.sql | 356 ++++ backend/requirements-dev.txt | 3 + backend/requirements.txt | 6 +- docker-compose.dev-env.yml | 7 +- docker-compose.yml | 7 +- docs/DEPLOYMENT.md | 2 + docs/MVP_ANNAHMEN.md | 12 + docs/architecture/TSUMUGU_TECHNICAL_SPEC.md | 2 +- frontend/.dockerignore | 2 + frontend/Dockerfile | 13 +- frontend/index.html | 24 +- frontend/nginx.conf | 21 +- frontend/package-lock.json | 1735 +++++++++++++++++ frontend/package.json | 19 + frontend/src/App.jsx | 85 + frontend/src/api.js | 101 + frontend/src/main.jsx | 13 + frontend/src/pages/Cases.jsx | 395 ++++ frontend/src/pages/Login.jsx | 82 + frontend/src/pages/Matters.jsx | 343 ++++ frontend/src/pages/Overview.jsx | 119 ++ frontend/src/pages/Rooms.jsx | 87 + frontend/src/pages/Search.jsx | 68 + frontend/src/pages/Shell.jsx | 66 + frontend/src/pages/widgets.jsx | 339 ++++ frontend/src/session.js | 3 + frontend/src/styles.css | 113 ++ frontend/vite.config.js | 13 + 60 files changed, 8467 insertions(+), 71 deletions(-) create mode 100644 AGENTS.md create mode 100644 backend/.dockerignore create mode 100644 backend/app/__init__.py create mode 100644 backend/app/access/__init__.py create mode 100644 backend/app/access/policy.py create mode 100644 backend/app/api/__init__.py create mode 100644 backend/app/api/deps.py create mode 100644 backend/app/api/routes.py create mode 100644 backend/app/api/schemas.py create mode 100644 backend/app/auth/__init__.py create mode 100644 backend/app/auth/accounts.py create mode 100644 backend/app/auth/security.py create mode 100644 backend/app/cli.py create mode 100644 backend/app/content/__init__.py create mode 100644 backend/app/content/documents.py create mode 100644 backend/app/core/__init__.py create mode 100644 backend/app/core/errors.py create mode 100644 backend/app/core/settings.py create mode 100644 backend/app/core/timeutil.py create mode 100644 backend/app/db/__init__.py create mode 100644 backend/app/db/migrate.py create mode 100644 backend/app/db/pool.py create mode 100644 backend/app/entrypoint.py create mode 100644 backend/app/main.py create mode 100644 backend/app/media/__init__.py create mode 100644 backend/app/media/storage.py create mode 100644 backend/app/ops.py create mode 100644 backend/app/present.py create mode 100644 backend/app/seed.py create mode 100644 backend/migrations/20261016T210000Z_foundation.sql create mode 100644 backend/requirements-dev.txt create mode 100644 docs/MVP_ANNAHMEN.md create mode 100644 frontend/.dockerignore create mode 100644 frontend/package-lock.json create mode 100644 frontend/package.json create mode 100644 frontend/src/App.jsx create mode 100644 frontend/src/api.js create mode 100644 frontend/src/main.jsx create mode 100644 frontend/src/pages/Cases.jsx create mode 100644 frontend/src/pages/Login.jsx create mode 100644 frontend/src/pages/Matters.jsx create mode 100644 frontend/src/pages/Overview.jsx create mode 100644 frontend/src/pages/Rooms.jsx create mode 100644 frontend/src/pages/Search.jsx create mode 100644 frontend/src/pages/Shell.jsx create mode 100644 frontend/src/pages/widgets.jsx create mode 100644 frontend/src/session.js create mode 100644 frontend/src/styles.css create mode 100644 frontend/vite.config.js diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..5eeaf40 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,7 @@ +# Tsumugu + +Fachlich führend ist `docs/product/TSUMUGU_PRODUCT_SPEC.md`. Der technische Entwurf ist `docs/architecture/TSUMUGU_TECHNICAL_SPEC.md`. Vorläufige Rechte- und Löschregeln der ersten Lieferung stehen in `docs/MVP_ANNAHMEN.md` und sind keine endgültigen Produktentscheidungen. + +Deployment und Ports: `docs/DEPLOYMENT.md`. Gearbeitet wird auf `develop`. Ein Push dorthin startet das Development-Deploy auf dem Raspberry Pi. Production entsteht nur durch einen Merge nach `main`. + +Die Anwendung bleibt produktlokal: FastAPI, PostgreSQL, React. Keine gemeinsame Fachdatenbank mit anderen Jinkendo-Anwendungen. Finanzfunktionen, Paperless-Abgleich, KI und externer Anwaltszugang gehören nicht in diese Lieferung. diff --git a/README.md b/README.md index a2a804c..c38523e 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,9 @@ Remote: `http://192.168.2.144:3000/Lars/tsumugu.git` ## Stand -Das Repository enthält das Deploy-Gerüst. Ein Push auf `develop` baut und startet Development, ein Merge von `develop` nach `main` die Produktion. Der Gitea-Runner auf dem Raspberry Pi (`192.168.2.49`) übernimmt Build und Deploy. +Die erste benutzbare Lieferung organisiert und verfolgt: Anmeldung, Datenräume, Akten und Vorgänge, Notizen, Dateien, manuelle Paperless-Referenzen, Chronologie, Aufgaben und unabhängige Fristen. Finanzfunktionen, automatische Paperless-Synchronisation, KI und externer Anwaltszugang folgen später. + +Ein Push auf `develop` baut und startet Development, ein Merge von `develop` nach `main` die Produktion. Der Gitea-Runner auf dem Raspberry Pi (`192.168.2.49`) übernimmt Build und Deploy. Beim Start führt das Backend die Migrationen aus. In Development legt es synthetische Beispieldaten an, in Production nicht. | | Development | Production | |---|---|---| @@ -17,4 +19,11 @@ Das Repository enthält das Deploy-Gerüst. Ein Push auf `develop` baut und star Details, Ports und der Synology-Reverse-Proxy: `docs/DEPLOYMENT.md`. -Backend und Frontend sind bewusst schmal: `/api/health` prüft Postgres, das Frontend reicht `/api/` an das Backend durch. Die Anwendung selbst ist noch nicht begonnen. +Development ist nach dem Deploy unter https://dev.tsumugu.jinkendo.de oder http://192.168.2.49:3094 erreichbar. Die Beispielkonten stehen auf der Anmeldeseite: + +| | E-Mail | Passwort | +|---|---|---| +| Ada Beispiel | ada@example.test | Beispiel-Ada-2026 | +| Ben Beispiel | ben@example.test | Beispiel-Ben-2026 | + +Ada führt den Mietstreit Musterstraße. Ben darf diesen Kontext bearbeiten und sieht die private Verhandlungsstrategie nicht. Vorläufige Rechte- und Löschannahmen: `docs/MVP_ANNAHMEN.md`. `/api/health` prüft weiterhin nur, ob die Anwendung und die Datenbank antworten. diff --git a/backend/.dockerignore b/backend/.dockerignore new file mode 100644 index 0000000..853f620 --- /dev/null +++ b/backend/.dockerignore @@ -0,0 +1,5 @@ +__pycache__ +.pytest_cache +.venv +data +*.pyc diff --git a/backend/Dockerfile b/backend/Dockerfile index 18ed63f..e9339d8 100644 --- a/backend/Dockerfile +++ b/backend/Dockerfile @@ -2,11 +2,15 @@ FROM python:3.12-slim WORKDIR /app +ENV PYTHONDONTWRITEBYTECODE=1 + COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt COPY main.py . +COPY app ./app +COPY migrations ./migrations EXPOSE 8000 -CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"] +CMD ["python", "-m", "app.entrypoint"] diff --git a/backend/app/__init__.py b/backend/app/__init__.py new file mode 100644 index 0000000..d486c71 --- /dev/null +++ b/backend/app/__init__.py @@ -0,0 +1 @@ +"""Tsumugu application package.""" diff --git a/backend/app/access/__init__.py b/backend/app/access/__init__.py new file mode 100644 index 0000000..2569485 --- /dev/null +++ b/backend/app/access/__init__.py @@ -0,0 +1 @@ +"""Data rooms and the case-based access policy.""" diff --git a/backend/app/access/policy.py b/backend/app/access/policy.py new file mode 100644 index 0000000..dff0794 --- /dev/null +++ b/backend/app/access/policy.py @@ -0,0 +1,763 @@ +"""Context rights for the first delivery. + +Provisional MVP assumptions, not final product decisions, live in docs/MVP_ANNAHMEN.md. +The action context is the only rights path used here. A case link inherits that case's +rights. Cross-links do not. Exceptions apply only in the context they name. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Any +from uuid import UUID + +from app.core.errors import conflict, forbidden, not_found, unprocessable + +SHARED_NOTICE = "Diese Änderung betrifft den gemeinsamen Inhalt der Notiz." + + +@dataclass(frozen=True) +class Rights: + read: bool = False + edit: bool = False + share: bool = False + delete: bool = False + + @classmethod + def full(cls) -> Rights: + return cls(True, True, True, True) + + @classmethod + def from_row(cls, row: dict | None) -> Rights: + if row is None: + return cls() + return cls(bool(row["can_read"]), bool(row["can_edit"]), bool(row["can_share"]), bool(row["can_delete"])) + + def without(self, blocked: Rights) -> Rights: + return Rights( + self.read and not blocked.read, + self.edit and not blocked.edit, + self.share and not blocked.share, + self.delete and not blocked.delete, + ) + + def allows(self, need: str) -> bool: + return bool(getattr(self, need)) + + def as_dict(self) -> dict[str, bool]: + return {"read": self.read, "edit": self.edit, "share": self.share, "delete": self.delete} + + +@dataclass(frozen=True) +class Ctx: + kind: str + id: UUID + + def as_dict(self) -> dict[str, str]: + return {"kind": self.kind, "id": str(self.id)} + + +def parse_context(payload: dict | None, *, required: bool = False) -> Ctx | None: + if not payload: + if required: + raise unprocessable("Der Handlungskontext fehlt.") + return None + kind = payload.get("kind") + raw = payload.get("id") + if kind not in ("case", "matter") or not raw: + raise unprocessable("Der Handlungskontext ist ungültig.") + try: + return Ctx(kind, UUID(str(raw))) + except ValueError as exc: + raise unprocessable("Der Handlungskontext ist ungültig.") from exc + + +def parse_query_context(kind: str | None, raw: str | None) -> Ctx | None: + if kind is None and raw is None: + return None + return parse_context({"kind": kind, "id": raw}, required=True) + + +def audit( + conn, + actor_id: UUID | None, + scope_id: UUID | None, + action: str, + resource_kind: str, + resource_id: UUID, + context: Ctx | None = None, + occurred_on=None, +) -> None: + conn.execute( + """ + INSERT INTO domain_events ( + actor_subject_id, scope_id, action, resource_kind, resource_id, + context_kind, context_id, occurred_on + ) + VALUES (%s, %s, %s, %s, %s, %s, %s, %s) + """, + ( + actor_id, + scope_id, + action, + resource_kind, + resource_id, + context.kind if context else None, + context.id if context else None, + occurred_on, + ), + ) + + +def bump_version(conn, table: str, row_id: UUID, expected: int) -> int: + if table not in {"cases", "matters", "elements", "tasks", "deadlines"}: + raise RuntimeError("unsupported version table") + row = conn.execute( + f"UPDATE {table} SET version = version + 1, updated_at = now() " + f"WHERE id = %s AND version = %s AND deleted_at IS NULL RETURNING version", + (row_id, expected), + ).fetchone() + if row is None: + current = conn.execute( + f"SELECT version, deleted_at FROM {table} WHERE id = %s", + (row_id,), + ).fetchone() + if current is None or current["deleted_at"] is not None: + raise not_found() + raise conflict() + return int(row["version"]) + + +def _get(conn, table: str, row_id: UUID) -> dict | None: + if table not in {"cases", "matters", "elements", "tasks", "deadlines", "data_rooms"}: + raise RuntimeError("unsupported lookup") + return conn.execute(f"SELECT * FROM {table} WHERE id = %s", (row_id,)).fetchone() + + +def get_case(conn, case_id: UUID) -> dict | None: + row = _get(conn, "cases", case_id) + if row is None or row["deleted_at"] is not None: + return None + return row + + +def get_matter(conn, matter_id: UUID) -> dict | None: + row = _get(conn, "matters", matter_id) + if row is None or row["deleted_at"] is not None: + return None + return row + + +def get_element(conn, element_id: UUID) -> dict | None: + row = _get(conn, "elements", element_id) + if row is None or row["deleted_at"] is not None: + return None + return row + + +def get_task(conn, task_id: UUID) -> dict | None: + row = _get(conn, "tasks", task_id) + if row is None or row["deleted_at"] is not None: + return None + return row + + +def get_deadline(conn, deadline_id: UUID) -> dict | None: + row = _get(conn, "deadlines", deadline_id) + if row is None or row["deleted_at"] is not None: + return None + return row + + +def _direct_grant(conn, actor: UUID, kind: str, resource_id: UUID) -> Rights: + row = conn.execute( + """ + SELECT can_read, can_edit, can_share, can_delete + FROM access_grants + WHERE NOT is_exception + AND grantee_subject_id = %s + AND resource_kind = %s + AND resource_id = %s + AND context_kind IS NULL + """, + (actor, kind, resource_id), + ).fetchone() + return Rights.from_row(row) + + +def _exceptions(conn, actor: UUID, kind: str, resource_id: UUID, context: Ctx | None) -> Rights: + rows = conn.execute( + """ + SELECT can_read, can_edit, can_share, can_delete + FROM access_grants + WHERE is_exception + AND resource_kind = %s + AND resource_id = %s + AND context_kind IS NOT DISTINCT FROM %s + AND context_id IS NOT DISTINCT FROM %s + AND (grantee_subject_id IS NULL OR grantee_subject_id = %s) + """, + ( + kind, + resource_id, + context.kind if context else None, + context.id if context else None, + actor, + ), + ).fetchall() + blocked = Rights() + for row in rows: + blocked = Rights( + blocked.read or row["can_read"], + blocked.edit or row["can_edit"], + blocked.share or row["can_share"], + blocked.delete or row["can_delete"], + ) + return blocked + + +def case_rights(conn, actor: UUID, case: dict) -> Rights: + if case["parent_case_id"] is not None and case["rights_mode"] == "inherit_parent": + parent = get_case(conn, case["parent_case_id"]) + base = case_rights(conn, actor, parent) if parent else Rights() + elif case["owner_subject_id"] == actor: + base = Rights.full() + else: + base = _direct_grant(conn, actor, "case", case["id"]) + return base.without(_exceptions(conn, actor, "case", case["id"], None)) + + +def _linked(conn, matter_id: UUID, case_id: UUID) -> bool: + row = conn.execute( + "SELECT 1 FROM matter_case_links WHERE matter_id = %s AND case_id = %s", + (matter_id, case_id), + ).fetchone() + return row is not None + + +def matter_rights(conn, actor: UUID, matter: dict, context: Ctx | None) -> Rights: + if context is None: + base = Rights.full() if matter["owner_subject_id"] == actor else _direct_grant(conn, actor, "matter", matter["id"]) + return base.without(_exceptions(conn, actor, "matter", matter["id"], None)) + + if context.kind == "case": + anchor_id = matter["id"] + if not _linked(conn, matter["id"], context.id) and matter["parent_matter_id"] is not None: + if _linked(conn, matter["parent_matter_id"], context.id): + anchor_id = matter["parent_matter_id"] + else: + return Rights() + elif not _linked(conn, matter["id"], context.id): + return Rights() + case = get_case(conn, context.id) + if case is None: + return Rights() + base = case_rights(conn, actor, case) + if anchor_id != matter["id"]: + parent = get_matter(conn, anchor_id) + if parent is None: + return Rights() + base = matter_rights(conn, actor, parent, context) + return base.without(_exceptions(conn, actor, "matter", matter["id"], context)) + + if context.kind == "matter": + if matter["parent_matter_id"] != context.id: + return Rights() + parent = get_matter(conn, context.id) + if parent is None: + return Rights() + base = matter_rights(conn, actor, parent, None) + return base.without(_exceptions(conn, actor, "matter", matter["id"], context)) + return Rights() + + +def _bindings(conn, element_id: UUID) -> list[dict]: + return conn.execute( + "SELECT * FROM bindings WHERE element_id = %s ORDER BY position, created_at", + (element_id,), + ).fetchall() + + +def _blocked(conn, case_id: UUID, element_id: UUID) -> bool: + row = conn.execute( + """ + SELECT 1 + FROM case_link_blocks b + JOIN matter_case_links l ON l.id = b.link_id + WHERE l.case_id = %s AND b.element_id = %s + """, + (case_id, element_id), + ).fetchone() + return row is not None + + +def _matter_reaches_case(conn, matter_id: UUID, case_id: UUID) -> bool: + matter = get_matter(conn, matter_id) + if matter is None: + return False + if _linked(conn, matter_id, case_id): + return True + return bool(matter["parent_matter_id"] and _linked(conn, matter["parent_matter_id"], case_id)) + + +def element_rights(conn, actor: UUID, element: dict, context: Ctx | None) -> Rights: + if context is None: + base = ( + Rights.full() + if element["owner_subject_id"] == actor + else _direct_grant(conn, actor, "element", element["id"]) + ) + return base.without(_exceptions(conn, actor, "element", element["id"], None)) + + bindings = _bindings(conn, element["id"]) + if context.kind == "case": + on_case = any(item["context_kind"] == "case" and item["context_id"] == context.id for item in bindings) + via_matter = [ + item + for item in bindings + if item["context_kind"] == "matter" and _matter_reaches_case(conn, item["context_id"], context.id) + ] + if not on_case and not via_matter: + return Rights() + if not on_case and _blocked(conn, context.id, element["id"]): + return Rights() + case = get_case(conn, context.id) + if case is None: + return Rights() + base = case_rights(conn, actor, case) + return base.without(_exceptions(conn, actor, "element", element["id"], context)) + + if context.kind == "matter": + matter = get_matter(conn, context.id) + if matter is None: + return Rights() + hosted = any( + item["context_kind"] == "matter" + and (item["context_id"] == context.id or _child_of(conn, item["context_id"], context.id)) + for item in bindings + ) + if not hosted: + return Rights() + base = matter_rights(conn, actor, matter, None) + return base.without(_exceptions(conn, actor, "element", element["id"], context)) + return Rights() + + +def _child_of(conn, matter_id: UUID, parent_id: UUID) -> bool: + matter = get_matter(conn, matter_id) + return bool(matter and matter["parent_matter_id"] == parent_id) + + +def element_rights_via_case_or_direct(conn, actor: UUID, element: dict, context: Ctx | None) -> Rights: + """Rights for an element bound to a matter when the caller names a case path. + + A matter context uses direct matter rights. A case context uses that case only. + """ + if context is None: + return element_rights(conn, actor, element, None) + if context.kind == "matter": + return element_rights(conn, actor, element, context) + return element_rights(conn, actor, element, context) + + +def task_rights(conn, actor: UUID, task: dict, context: Ctx | None) -> Rights: + if task["assignee_subject_id"] == actor and context is None: + granted = _direct_grant(conn, actor, "task", task["id"]) + base = Rights(read=True, edit=granted.edit, share=False, delete=False) + if task["owner_subject_id"] == actor: + base = Rights.full() + return base.without(_exceptions(conn, actor, "task", task["id"], None)) + if context is None: + base = Rights.full() if task["owner_subject_id"] == actor else _direct_grant(conn, actor, "task", task["id"]) + return base.without(_exceptions(conn, actor, "task", task["id"], None)) + if task["matter_id"] is None: + return Rights() + matter = get_matter(conn, task["matter_id"]) + if matter is None: + return Rights() + if context.kind == "matter" and context.id == task["matter_id"]: + base = matter_rights(conn, actor, matter, None) + elif context.kind == "case": + base = matter_rights(conn, actor, matter, context) + elif context.kind == "matter" and matter["parent_matter_id"] == context.id: + base = matter_rights(conn, actor, matter, context) + else: + return Rights() + return base.without(_exceptions(conn, actor, "task", task["id"], context)) + + +def deadline_rights(conn, actor: UUID, deadline: dict, context: Ctx | None) -> Rights: + if deadline["assignee_subject_id"] == actor and context is None: + base = Rights(read=True, edit=False, share=False, delete=False) + if deadline["owner_subject_id"] == actor: + base = Rights.full() + return base.without(_exceptions(conn, actor, "deadline", deadline["id"], None)) + if context is None: + base = ( + Rights.full() + if deadline["owner_subject_id"] == actor + else _direct_grant(conn, actor, "deadline", deadline["id"]) + ) + return base.without(_exceptions(conn, actor, "deadline", deadline["id"], None)) + if deadline["matter_id"] is None: + return Rights() + matter = get_matter(conn, deadline["matter_id"]) + if matter is None: + return Rights() + if context.kind == "matter" and context.id == deadline["matter_id"]: + base = matter_rights(conn, actor, matter, None) + elif context.kind == "case": + base = matter_rights(conn, actor, matter, context) + else: + return Rights() + return base.without(_exceptions(conn, actor, "deadline", deadline["id"], context)) + + +def require_case(conn, actor: UUID, case_id: UUID, need: str) -> tuple[dict, Rights]: + case = get_case(conn, case_id) + if case is None: + raise not_found() + rights = case_rights(conn, actor, case) + _require(rights, need) + return case, rights + + +def require_matter(conn, actor: UUID, matter_id: UUID, context: Ctx | None, need: str) -> tuple[dict, Rights]: + matter = get_matter(conn, matter_id) + if matter is None: + raise not_found() + rights = matter_rights(conn, actor, matter, context) + _require(rights, need) + return matter, rights + + +def require_element(conn, actor: UUID, element_id: UUID, context: Ctx | None, need: str) -> tuple[dict, Rights]: + element = get_element(conn, element_id) + if element is None: + raise not_found() + rights = element_rights(conn, actor, element, context) + _require(rights, need) + return element, rights + + +def _require(rights: Rights, need: str) -> None: + if not rights.read: + raise not_found() + if need != "read" and not rights.allows(need): + raise forbidden() + + +def can_change_status(actor: UUID, row: dict, rights: Rights, assignee_key: str = "assignee_subject_id") -> bool: + if rights.edit or row["owner_subject_id"] == actor: + return True + return row[assignee_key] == actor and rights.read + + +def readable_matter_contexts(conn, actor: UUID, matter: dict) -> list[dict]: + found: list[dict] = [] + direct = matter_rights(conn, actor, matter, None) + if direct.read: + found.append({"kind": "matter", "id": str(matter["id"]), "title": matter["title"], "rights": direct.as_dict()}) + links = conn.execute( + """ + SELECT l.case_id, c.title + FROM matter_case_links l + JOIN cases c ON c.id = l.case_id + WHERE l.matter_id = %s AND c.deleted_at IS NULL + """, + (matter["id"],), + ).fetchall() + if matter["parent_matter_id"] is not None: + links = list(links) + list( + conn.execute( + """ + SELECT l.case_id, c.title + FROM matter_case_links l + JOIN cases c ON c.id = l.case_id + WHERE l.matter_id = %s AND c.deleted_at IS NULL + """, + (matter["parent_matter_id"],), + ).fetchall() + ) + seen: set[UUID] = set() + for link in links: + if link["case_id"] in seen: + continue + seen.add(link["case_id"]) + rights = matter_rights(conn, actor, matter, Ctx("case", link["case_id"])) + if rights.read: + found.append( + { + "kind": "case", + "id": str(link["case_id"]), + "title": link["title"], + "rights": rights.as_dict(), + } + ) + return found + + +def list_cases(conn, actor: UUID) -> list[dict]: + rows = conn.execute( + """ + SELECT c.* + FROM cases c + WHERE c.deleted_at IS NULL + AND ( + c.owner_subject_id = %(actor)s + OR EXISTS ( + SELECT 1 FROM access_grants g + WHERE g.resource_kind = 'case' AND g.resource_id = c.id + AND g.grantee_subject_id = %(actor)s AND NOT g.is_exception AND g.can_read + AND g.context_id IS NULL + ) + OR ( + c.rights_mode = 'inherit_parent' AND c.parent_case_id IS NOT NULL AND EXISTS ( + SELECT 1 FROM cases p + WHERE p.id = c.parent_case_id AND p.deleted_at IS NULL + AND ( + p.owner_subject_id = %(actor)s + OR EXISTS ( + SELECT 1 FROM access_grants g + WHERE g.resource_kind = 'case' AND g.resource_id = p.id + AND g.grantee_subject_id = %(actor)s AND NOT g.is_exception + AND g.can_read AND g.context_id IS NULL + ) + ) + ) + ) + ) + ORDER BY c.updated_at DESC, c.id DESC + """, + {"actor": actor}, + ).fetchall() + visible = [] + for row in rows: + rights = case_rights(conn, actor, row) + if rights.read: + visible.append((row, rights)) + return visible + + +def list_matters(conn, actor: UUID) -> list[tuple[dict, list[dict]]]: + rows = conn.execute( + """ + SELECT m.* + FROM matters m + WHERE m.deleted_at IS NULL + AND ( + m.owner_subject_id = %(actor)s + OR EXISTS ( + SELECT 1 FROM access_grants g + WHERE g.resource_kind = 'matter' AND g.resource_id = m.id + AND g.grantee_subject_id = %(actor)s AND NOT g.is_exception AND g.can_read + AND g.context_id IS NULL + ) + OR EXISTS ( + SELECT 1 FROM matter_case_links l + JOIN cases c ON c.id = l.case_id AND c.deleted_at IS NULL + WHERE l.matter_id = m.id + AND ( + c.owner_subject_id = %(actor)s + OR EXISTS ( + SELECT 1 FROM access_grants g + WHERE g.resource_kind = 'case' AND g.resource_id = c.id + AND g.grantee_subject_id = %(actor)s AND NOT g.is_exception + AND g.can_read AND g.context_id IS NULL + ) + ) + ) + ) + ORDER BY m.updated_at DESC, m.id DESC + """, + {"actor": actor}, + ).fetchall() + visible = [] + for row in rows: + contexts = readable_matter_contexts(conn, actor, row) + if contexts: + visible.append((row, contexts)) + return visible + + +def assert_scope_can_host(conn, scope_id: UUID) -> dict: + room = _get(conn, "data_rooms", scope_id) + if room is None or room["status"] != "active": + raise forbidden("Der gewählte Datenraum ist nicht verfügbar.") + return room + + +def same_home(row: dict, scope_id: UUID) -> None: + if row["home_scope_id"] != scope_id: + raise unprocessable( + "Unterakten, Teilvorgänge und Kapitel bleiben im Datenraum ihres Behälters. " + "Wähle diesen Datenraum, wenn du dort Mitglied bist, oder lege einen Querverweis an." + ) + + +def account_by_email(conn, email: str) -> dict | None: + return conn.execute( + "SELECT id, email, display_name, status FROM auth_accounts WHERE email = %s", + (email.strip().lower(),), + ).fetchone() + + +def display_name(conn, account_id: UUID | None) -> str | None: + if account_id is None: + return None + row = conn.execute("SELECT display_name FROM auth_accounts WHERE id = %s", (account_id,)).fetchone() + return row["display_name"] if row else None + + +def room_name(conn, room_id: UUID) -> str | None: + row = conn.execute("SELECT name FROM data_rooms WHERE id = %s", (room_id,)).fetchone() + return row["name"] if row else None + + +def visible_bindings_for_element(conn, actor: UUID, element: dict) -> list[dict]: + """Names and counts only bindings the actor can actually read.""" + result = [] + for binding in _bindings(conn, element["id"]): + if binding["context_kind"] == "case": + context = Ctx("case", binding["context_id"]) + rights = element_rights(conn, actor, element, context) + if not rights.read: + continue + case = get_case(conn, binding["context_id"]) + if case is None: + continue + title = case["title"] + else: + matter = get_matter(conn, binding["context_id"]) + if matter is None: + continue + contexts = readable_matter_contexts(conn, actor, matter) + if not contexts: + continue + direct = element_rights(conn, actor, element, Ctx("matter", matter["id"])) + via_cases = [] + for item in contexts: + if item["kind"] != "case": + continue + case_rights_now = element_rights(conn, actor, element, Ctx("case", UUID(item["id"]))) + if case_rights_now.read: + via_cases.append(item) + if not direct.read and not via_cases: + continue + title = matter["title"] + context = Ctx("matter", matter["id"]) + result.append( + { + "id": str(binding["id"]), + "context_kind": binding["context_kind"], + "context_id": str(binding["context_id"]), + "context_title": title, + } + ) + return result + + +def chapter_for(conn, chapter_id: UUID | None, kind: str, container_id: UUID) -> None: + if chapter_id is None: + return + column = "case_id" if kind == "case" else "matter_id" + row = conn.execute( + f"SELECT id FROM chapters WHERE id = %s AND {column} = %s", + (chapter_id, container_id), + ).fetchone() + if row is None: + raise unprocessable("Das Kapitel gehört nicht zu diesem Kontext.") + + +def next_position(conn, kind: str, container_id: UUID) -> int: + row = conn.execute( + "SELECT COALESCE(MAX(position), 0) + 1 AS pos FROM bindings WHERE context_kind = %s AND context_id = %s", + (kind, container_id), + ).fetchone() + return int(row["pos"]) + + +def insert_binding(conn, element_id: UUID, kind: str, container_id: UUID, chapter_id: UUID | None, actor: UUID) -> dict: + existing = conn.execute( + """ + SELECT id FROM bindings + WHERE element_id = %s AND context_kind = %s AND context_id = %s + """, + (element_id, kind, container_id), + ).fetchone() + if existing is not None: + raise unprocessable("Die Notiz ist in diesem Kontext bereits eingebunden.") + chapter_for(conn, chapter_id, kind, container_id) + row = conn.execute( + """ + INSERT INTO bindings (element_id, context_kind, context_id, chapter_id, position, created_by) + VALUES (%s, %s, %s, %s, %s, %s) + RETURNING * + """, + (element_id, kind, container_id, chapter_id, next_position(conn, kind, container_id), actor), + ).fetchone() + return row + + +def block_unsharable_matter_elements(conn, actor: UUID, link_id: UUID, matter: dict) -> None: + """Contents the linking actor cannot share stay invisible in that case. No titles are stored.""" + matter_ids = [matter["id"]] + children = conn.execute( + "SELECT id FROM matters WHERE parent_matter_id = %s AND deleted_at IS NULL", + (matter["id"],), + ).fetchall() + matter_ids.extend(item["id"] for item in children) + for matter_id in matter_ids: + bindings = conn.execute( + "SELECT element_id FROM bindings WHERE context_kind = 'matter' AND context_id = %s", + (matter_id,), + ).fetchall() + container = get_matter(conn, matter_id) + if container is None: + continue + for binding in bindings: + element = get_element(conn, binding["element_id"]) + if element is None: + continue + rights = element_rights(conn, actor, element, Ctx("matter", matter_id)) + if matter_id != matter["id"]: + parent_rights = element_rights(conn, actor, element, Ctx("matter", matter["id"])) + if parent_rights.share: + rights = parent_rights + if rights.share: + continue + conn.execute( + "INSERT INTO case_link_blocks (link_id, element_id) VALUES (%s, %s) ON CONFLICT DO NOTHING", + (link_id, element["id"]), + ) + + +def matter_title_if_readable(conn, actor: UUID, matter_id: UUID | None) -> str | None: + if matter_id is None: + return None + matter = get_matter(conn, matter_id) + if matter is None: + return None + if readable_matter_contexts(conn, actor, matter): + return matter["title"] + return None + + +def ensure_member_or_personal(conn, account_id: UUID, kind: str, scope_id: UUID) -> dict: + room = assert_scope_can_host(conn, scope_id) + if kind == "personal": + if room["kind"] != "personal" or room["id"] != account_id: + raise forbidden("Der persönliche Datenraum gehört zu einem anderen Konto.") + return room + if kind != "organization" or room["kind"] != "organization": + raise forbidden("Dieser Datenraum kann nicht gewählt werden.") + membership = conn.execute( + """ + SELECT role FROM room_memberships + WHERE room_id = %s AND subject_id = %s AND status = 'active' + """, + (scope_id, account_id), + ).fetchone() + if membership is None: + raise forbidden("Du bist in diesem Datenraum nicht Mitglied.") + return room diff --git a/backend/app/api/__init__.py b/backend/app/api/__init__.py new file mode 100644 index 0000000..36ad2dc --- /dev/null +++ b/backend/app/api/__init__.py @@ -0,0 +1 @@ +"""HTTP adapters. Authorization stays in the domain services.""" diff --git a/backend/app/api/deps.py b/backend/app/api/deps.py new file mode 100644 index 0000000..dbf6482 --- /dev/null +++ b/backend/app/api/deps.py @@ -0,0 +1,97 @@ +"""Request scope: one transaction, a session principal, and no client-supplied identity.""" + +from __future__ import annotations + +from dataclasses import dataclass +from pathlib import Path +from uuid import UUID + +from fastapi import Depends, Request +from psycopg import Connection + +from app.access.policy import ensure_member_or_personal +from app.auth.security import hash_secret, read_session_token +from app.core.errors import forbidden, unauthorized +from app.core.timeutil import utcnow + + +@dataclass(frozen=True) +class Principal: + account_id: UUID + email: str + display_name: str + session_id: UUID + scope_kind: str + scope_id: UUID + scope_name: str + epoch: int + + +def get_conn(request: Request): + pool = request.app.state.pool + with pool.connection() as conn: + try: + conn.execute("SET TIME ZONE 'UTC'") + yield conn + conn.commit() + for path in getattr(request.state, "delete_after_commit", []): + Path(path).unlink(missing_ok=True) + except Exception: + conn.rollback() + for path in getattr(request.state, "cleanup_files", []): + Path(path).unlink(missing_ok=True) + raise + + +def _session_row(conn: Connection, request: Request) -> dict: + token = read_session_token(request) + if not token: + raise unauthorized() + row = conn.execute( + """ + SELECT s.id, s.account_id, s.csrf_token, s.scope_kind, s.scope_id, s.epoch, + s.expires_at, s.revoked_at, a.email, a.display_name, a.status AS account_status + FROM auth_sessions s + JOIN auth_accounts a ON a.id = s.account_id + WHERE s.secret_hash = %s + """, + (hash_secret(token),), + ).fetchone() + if row is None or row["revoked_at"] is not None or row["expires_at"] <= utcnow(): + raise unauthorized() + if row["account_status"] != "active": + raise unauthorized() + if request.method not in {"GET", "HEAD", "OPTIONS"}: + sent = request.headers.get("x-csrf-token") or "" + if not sent or sent != row["csrf_token"]: + raise forbidden("Die Anfrage konnte der Sitzung nicht zugeordnet werden.") + return row + + +def get_session(request: Request, conn: Connection = Depends(get_conn)) -> dict: + return _session_row(conn, request) + + +def get_principal(request: Request, conn: Connection = Depends(get_conn)) -> Principal: + row = _session_row(conn, request) + kind = request.headers.get("x-scope-kind") + raw_scope = request.headers.get("x-scope-id") + if not kind or not raw_scope: + raise forbidden("Der Datenraum ist nicht gewählt.") + try: + scope_id = UUID(raw_scope) + except ValueError as exc: + raise forbidden("Der Datenraum ist nicht gewählt.") from exc + if kind != row["scope_kind"] or scope_id != row["scope_id"]: + raise forbidden("Der gewählte Datenraum entspricht nicht mehr der Sitzung.") + room = ensure_member_or_personal(conn, row["account_id"], kind, scope_id) + return Principal( + account_id=row["account_id"], + email=row["email"], + display_name=row["display_name"], + session_id=row["id"], + scope_kind=kind, + scope_id=scope_id, + scope_name=room["name"], + epoch=row["epoch"], + ) diff --git a/backend/app/api/routes.py b/backend/app/api/routes.py new file mode 100644 index 0000000..01c9131 --- /dev/null +++ b/backend/app/api/routes.py @@ -0,0 +1,1193 @@ +"""HTTP routes for the first usable delivery.""" + +from __future__ import annotations + +from datetime import date, datetime, timedelta, timezone +from uuid import UUID + +from fastapi import APIRouter, Depends, File, Form, Request, Response, UploadFile +from fastapi.responses import JSONResponse +from psycopg import Connection + +from app.access.policy import ( + Ctx, + account_by_email, + case_rights, + deadline_rights, + element_rights, + get_case, + get_deadline, + get_element, + get_matter, + get_task, + list_cases, + list_matters, + matter_rights, + parse_context, + parse_query_context, + require_case, + require_matter, + task_rights, +) +from app.api.deps import Principal, get_conn, get_principal, get_session +from app.api.schemas import ( + AcceptInviteIn, + AnnotationIn, + AssigneeIn, + BindingIn, + CaseIn, + CaseLinkIn, + CasePatch, + ChapterIn, + CrossLinkIn, + DeadlineIn, + DeadlinePatch, + DeleteElementIn, + ExceptionIn, + ExternalIn, + FulfillIn, + GrantIn, + InvitationIn, + LoginIn, + MatterIn, + MatterPatch, + MemberIn, + NoteIn, + NotePatch, + RoomIn, + ScopeIn, + TaskDeadlineIn, + TaskIn, + TaskPatch, +) +from app.auth.accounts import create_account, list_rooms, normalize_email, start_session +from app.auth.security import ( + clear_session_cookie, + hash_secret, + new_secret, + session_expiry, + set_session_cookie, + verify_password, +) +from app.core.errors import Problem, forbidden, not_found, too_many, unprocessable +from app.core.timeutil import utcnow +from app.media.storage import content_disposition, read_bytes +from app.media.storage import asset_path +from app.ops import ( + add_annotation, + assign_task, + bind_element, + create_case, + create_chapter, + create_cross_link, + create_deadline, + create_external, + create_file, + create_matter, + create_note, + create_task, + delete_cross_link, + delete_element, + detach_binding, + fulfill_deadline, + grant_access, + link_matter_to_case, + link_task_deadline, + patch_case, + patch_deadline, + patch_matter, + patch_task, + revoke_grant, + set_exception, + unlink_matter_case, + update_note, +) +from app.present import ( + LABELS, + binding_payload, + case_detail, + case_summary, + deadline_payload, + matter_detail, + matter_summary, + note_update_payload, + task_payload, +) +from app.seed import demo_public + +router = APIRouter() +_login_attempts: dict[str, list[datetime]] = {} + + +def _created(path: str, payload: dict) -> JSONResponse: + return JSONResponse(status_code=201, content=payload, headers={"Location": path}) + + +def _ctx_model(value) -> Ctx | None: + return None if value is None else Ctx(value.kind, value.id) + + +def _session_body(conn, account_id: UUID, scope_kind: str, scope_id: UUID, csrf: str, epoch: int) -> dict: + account = conn.execute( + "SELECT id, email, display_name FROM auth_accounts WHERE id = %s", + (account_id,), + ).fetchone() + room = conn.execute("SELECT id, kind, name FROM data_rooms WHERE id = %s", (scope_id,)).fetchone() + return { + "account": { + "id": str(account["id"]), + "email": account["email"], + "display_name": account["display_name"], + }, + "scope": {"kind": scope_kind, "id": str(room["id"]), "name": room["name"]}, + "rooms": list_rooms(conn, account_id), + "csrf_token": csrf, + "epoch": epoch, + } + + +def _limit_login(key: str) -> None: + now = utcnow() + window = [item for item in _login_attempts.get(key, []) if now - item < timedelta(minutes=10)] + if len(window) >= 8: + _login_attempts[key] = window + raise too_many() + window.append(now) + _login_attempts[key] = window + + +@router.post("/api/v1/auth/login") +def login(body: LoginIn, request: Request, conn: Connection = Depends(get_conn)): + email = normalize_email(body.email) + _limit_login(f"{request.client.host if request.client else 'local'}:{email}") + account = conn.execute( + "SELECT * FROM auth_accounts WHERE email = %s", + (email,), + ).fetchone() + if account is None or account["status"] != "active" or not verify_password(body.password, account["password_hash"]): + raise Problem(401, "Anmeldung fehlgeschlagen", "E-Mail oder Passwort ist nicht richtig.", "unauthorized") + settings = request.app.state.settings + token, csrf = start_session(conn, settings, account["id"]) + payload = _session_body(conn, account["id"], "personal", account["id"], csrf, 1) + response = JSONResponse(payload) + set_session_cookie(response, request, settings, token) + return response + + +@router.post("/api/v1/auth/logout", status_code=204) +def logout(request: Request, session: dict = Depends(get_session), conn: Connection = Depends(get_conn)): + conn.execute("UPDATE auth_sessions SET revoked_at = now() WHERE id = %s", (session["id"],)) + response = Response(status_code=204) + clear_session_cookie(response, request, request.app.state.settings) + return response + + +@router.get("/api/v1/auth/session") +def session_view(session: dict = Depends(get_session), conn: Connection = Depends(get_conn)): + return _session_body( + conn, + session["account_id"], + session["scope_kind"], + session["scope_id"], + session["csrf_token"], + session["epoch"], + ) + + +@router.post("/api/v1/auth/session/scope") +def choose_scope( + body: ScopeIn, + request: Request, + session: dict = Depends(get_session), + conn: Connection = Depends(get_conn), +): + from app.access.policy import ensure_member_or_personal + + room = ensure_member_or_personal(conn, session["account_id"], body.kind, body.id) + row = conn.execute( + """ + UPDATE auth_sessions + SET scope_kind = %s, scope_id = %s, epoch = epoch + 1 + WHERE id = %s + RETURNING epoch, csrf_token + """, + (body.kind, room["id"], session["id"]), + ).fetchone() + return _session_body(conn, session["account_id"], body.kind, room["id"], row["csrf_token"], row["epoch"]) + + +@router.get("/api/v1/auth/demo") +def demo(request: Request): + return demo_public(request.app.state.settings) + + +@router.post("/api/v1/invitations") +def invite( + body: InvitationIn, + principal: Principal = Depends(get_principal), + conn: Connection = Depends(get_conn), +): + room = conn.execute("SELECT * FROM data_rooms WHERE id = %s", (body.room_id,)).fetchone() + if room is None or room["kind"] != "organization": + raise not_found() + membership = conn.execute( + """ + SELECT role FROM room_memberships + WHERE room_id = %s AND subject_id = %s AND status = 'active' + """, + (room["id"], principal.account_id), + ).fetchone() + if membership is None or membership["role"] != "manager": + raise forbidden() + email = normalize_email(body.email) + if account_by_email(conn, email): + raise unprocessable("Es gibt bereits ein Konto. Füge die Person als Mitglied hinzu.") + token = new_secret() + row = conn.execute( + """ + INSERT INTO auth_invitations (email, room_id, token_hash, invited_by, expires_at) + VALUES (%s, %s, %s, %s, %s) + RETURNING id, expires_at + """, + (email, room["id"], hash_secret(token), principal.account_id, utcnow() + timedelta(days=7)), + ).fetchone() + return _created( + f"/api/v1/invitations/{row['id']}", + {"id": str(row["id"]), "email": email, "expires_at": row["expires_at"].isoformat(), "token": token}, + ) + + +@router.post("/api/v1/invitations/{invitation_id}/accept") +def accept_invite( + invitation_id: UUID, + body: AcceptInviteIn, + request: Request, + conn: Connection = Depends(get_conn), +): + row = conn.execute("SELECT * FROM auth_invitations WHERE id = %s", (invitation_id,)).fetchone() + if row is None or row["accepted_at"] is not None or row["expires_at"] <= utcnow(): + raise not_found() + if row["token_hash"] != hash_secret(body.token): + raise not_found() + account = create_account(conn, row["email"], body.display_name, body.password) + conn.execute( + """ + INSERT INTO room_memberships (room_id, subject_id, role) + VALUES (%s, %s, 'member') + """, + (row["room_id"], account["id"]), + ) + conn.execute("UPDATE auth_invitations SET accepted_at = now() WHERE id = %s", (invitation_id,)) + settings = request.app.state.settings + token, csrf = start_session(conn, settings, account["id"]) + payload = _session_body(conn, account["id"], "personal", account["id"], csrf, 1) + response = JSONResponse(status_code=201, content=payload) + set_session_cookie(response, request, settings, token) + return response + + +@router.get("/api/v1/rooms") +def rooms(principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)): + return {"items": list_rooms(conn, principal.account_id), "next_cursor": None} + + +@router.post("/api/v1/rooms") +def create_room(body: RoomIn, principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)): + from uuid import uuid4 + + room_id = uuid4() + conn.execute( + """ + INSERT INTO data_rooms (id, kind, name, created_by) + VALUES (%s, 'organization', %s, %s) + """, + (room_id, body.name.strip(), principal.account_id), + ) + conn.execute( + """ + INSERT INTO room_memberships (room_id, subject_id, role) + VALUES (%s, %s, 'manager') + """, + (room_id, principal.account_id), + ) + return _created(f"/api/v1/rooms/{room_id}", {"id": str(room_id), "kind": "organization", "name": body.name.strip()}) + + +@router.get("/api/v1/rooms/{room_id}/members") +def members(room_id: UUID, principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)): + _require_manager(conn, principal, room_id) + rows = conn.execute( + """ + SELECT m.subject_id, m.role, a.email, a.display_name + FROM room_memberships m + JOIN auth_accounts a ON a.id = m.subject_id + WHERE m.room_id = %s AND m.status = 'active' + ORDER BY a.display_name, a.id + """, + (room_id,), + ).fetchall() + return { + "items": [ + { + "subject_id": str(row["subject_id"]), + "email": row["email"], + "display_name": row["display_name"], + "role": row["role"], + } + for row in rows + ] + } + + +@router.post("/api/v1/rooms/{room_id}/members") +def add_member( + room_id: UUID, + body: MemberIn, + principal: Principal = Depends(get_principal), + conn: Connection = Depends(get_conn), +): + _require_manager(conn, principal, room_id) + account = account_by_email(conn, body.email) + if account is None or account["status"] != "active": + raise not_found() + conn.execute( + """ + INSERT INTO room_memberships (room_id, subject_id, role, status) + VALUES (%s, %s, %s, 'active') + ON CONFLICT (room_id, subject_id) DO UPDATE SET role = EXCLUDED.role, status = 'active' + """, + (room_id, account["id"], body.role), + ) + return {"subject_id": str(account["id"]), "role": body.role} + + +@router.delete("/api/v1/rooms/{room_id}/members/{subject_id}", status_code=204) +def remove_member( + room_id: UUID, + subject_id: UUID, + principal: Principal = Depends(get_principal), + conn: Connection = Depends(get_conn), +): + _require_manager(conn, principal, room_id) + if subject_id == principal.account_id: + managers = conn.execute( + """ + SELECT count(*) AS n FROM room_memberships + WHERE room_id = %s AND role = 'manager' AND status = 'active' + """, + (room_id,), + ).fetchone() + if managers["n"] <= 1: + raise unprocessable("Der letzte Verwalter kann den Datenraum nicht verlassen.") + conn.execute( + """ + UPDATE room_memberships SET status = 'removed' + WHERE room_id = %s AND subject_id = %s + """, + (room_id, subject_id), + ) + return Response(status_code=204) + + +def _require_manager(conn, principal: Principal, room_id: UUID) -> None: + membership = conn.execute( + """ + SELECT role FROM room_memberships + WHERE room_id = %s AND subject_id = %s AND status = 'active' + """, + (room_id, principal.account_id), + ).fetchone() + room = conn.execute("SELECT kind FROM data_rooms WHERE id = %s", (room_id,)).fetchone() + if room is None or room["kind"] != "organization" or membership is None or membership["role"] != "manager": + raise forbidden() + + +@router.get("/api/v1/principals") +def find_principal(email: str, principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)): + account = account_by_email(conn, email) + if account is None or account["status"] != "active": + raise not_found() + return {"id": str(account["id"]), "email": account["email"], "display_name": account["display_name"]} + + +@router.get("/api/v1/cases") +def cases(principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)): + items = [case_summary(case, rights) for case, rights in list_cases(conn, principal.account_id)] + return {"items": items, "next_cursor": None} + + +@router.post("/api/v1/cases") +def post_case(body: CaseIn, principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)): + case = create_case(conn, principal.account_id, principal.scope_id, body.title, body.parent_case_id, body.rights_mode) + rights = case_rights(conn, principal.account_id, case) + return _created(f"/api/v1/cases/{case['id']}", case_summary(case, rights)) + + +@router.get("/api/v1/cases/{case_id}") +def get_one_case(case_id: UUID, principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)): + case, rights = require_case(conn, principal.account_id, case_id, "read") + return case_detail(conn, principal.account_id, case, rights) + + +@router.patch("/api/v1/cases/{case_id}") +def patch_one_case( + case_id: UUID, + body: CasePatch, + principal: Principal = Depends(get_principal), + conn: Connection = Depends(get_conn), +): + case = patch_case(conn, principal.account_id, case_id, body.expected_version, body.title, body.status) + rights = case_rights(conn, principal.account_id, case) + return case_summary(case, rights) + + +@router.post("/api/v1/cases/{case_id}/chapters") +def post_case_chapter( + case_id: UUID, + body: ChapterIn, + principal: Principal = Depends(get_principal), + conn: Connection = Depends(get_conn), +): + row = create_chapter(conn, principal.account_id, "case", case_id, body.title, body.position, None) + return _created(f"/api/v1/cases/{case_id}/chapters/{row['id']}", {"id": str(row["id"]), "title": row["title"], "position": row["position"]}) + + +@router.post("/api/v1/cases/{case_id}/grants") +def post_case_grant( + case_id: UUID, + body: GrantIn, + principal: Principal = Depends(get_principal), + conn: Connection = Depends(get_conn), +): + account = account_by_email(conn, body.email) + if account is None: + raise not_found() + grant = grant_access( + conn, principal.account_id, "case", case_id, account["id"], body.can_read, body.can_edit, body.can_share, None + ) + return _created(f"/api/v1/grants/{grant['id']}", {"id": str(grant["id"])}) + + +@router.get("/api/v1/matters") +def matters(principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)): + items = [matter_summary(conn, principal.account_id, matter) for matter, _contexts in list_matters(conn, principal.account_id)] + return {"items": items, "next_cursor": None} + + +@router.post("/api/v1/matters") +def post_matter(body: MatterIn, principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)): + matter = create_matter( + conn, principal.account_id, principal.scope_id, body.title, body.parent_matter_id, _ctx_model(body.context) + ) + return _created(f"/api/v1/matters/{matter['id']}", matter_summary(conn, principal.account_id, matter)) + + +@router.get("/api/v1/matters/{matter_id}") +def get_one_matter( + matter_id: UUID, + context_kind: str | None = None, + context_id: str | None = None, + principal: Principal = Depends(get_principal), + conn: Connection = Depends(get_conn), +): + context = parse_query_context(context_kind, context_id) + matter, rights = require_matter(conn, principal.account_id, matter_id, context, "read") + return matter_detail(conn, principal.account_id, matter, rights, context) + + +@router.patch("/api/v1/matters/{matter_id}") +def patch_one_matter( + matter_id: UUID, + body: MatterPatch, + principal: Principal = Depends(get_principal), + conn: Connection = Depends(get_conn), +): + matter = patch_matter( + conn, principal.account_id, matter_id, body.expected_version, body.title, body.status, _ctx_model(body.context) + ) + return matter_summary(conn, principal.account_id, matter) + + +@router.post("/api/v1/matters/{matter_id}/chapters") +def post_matter_chapter( + matter_id: UUID, + body: ChapterIn, + context_kind: str | None = None, + context_id: str | None = None, + principal: Principal = Depends(get_principal), + conn: Connection = Depends(get_conn), +): + context = parse_query_context(context_kind, context_id) + row = create_chapter(conn, principal.account_id, "matter", matter_id, body.title, body.position, context) + return _created( + f"/api/v1/matters/{matter_id}/chapters/{row['id']}", + {"id": str(row["id"]), "title": row["title"], "position": row["position"]}, + ) + + +@router.post("/api/v1/matters/{matter_id}/case-links") +def post_case_link( + matter_id: UUID, + body: CaseLinkIn, + principal: Principal = Depends(get_principal), + conn: Connection = Depends(get_conn), +): + link = link_matter_to_case(conn, principal.account_id, matter_id, body.case_id, _ctx_model(body.context)) + return _created(f"/api/v1/matter-case-links/{link['id']}", {"id": str(link["id"]), "case_id": str(body.case_id)}) + + +@router.delete("/api/v1/matter-case-links/{link_id}", status_code=204) +def delete_case_link(link_id: UUID, principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)): + unlink_matter_case(conn, principal.account_id, link_id) + return Response(status_code=204) + + +@router.post("/api/v1/matters/{matter_id}/cross-links") +def post_cross_link( + matter_id: UUID, + body: CrossLinkIn, + principal: Principal = Depends(get_principal), + conn: Connection = Depends(get_conn), +): + row = create_cross_link( + conn, + principal.account_id, + matter_id, + body.target_matter_id, + _ctx_model(body.source_context), + Ctx(body.target_context.kind, body.target_context.id), + ) + return _created(f"/api/v1/matter-cross-links/{row['id']}", {"id": str(row["id"])}) + + +@router.delete("/api/v1/matter-cross-links/{link_id}", status_code=204) +def remove_cross_link( + link_id: UUID, + context_kind: str | None = None, + context_id: str | None = None, + principal: Principal = Depends(get_principal), + conn: Connection = Depends(get_conn), +): + delete_cross_link(conn, principal.account_id, link_id, parse_query_context(context_kind, context_id)) + return Response(status_code=204) + + +@router.post("/api/v1/matters/{matter_id}/grants") +def post_matter_grant( + matter_id: UUID, + body: GrantIn, + principal: Principal = Depends(get_principal), + conn: Connection = Depends(get_conn), +): + account = account_by_email(conn, body.email) + if account is None: + raise not_found() + grant = grant_access( + conn, principal.account_id, "matter", matter_id, account["id"], body.can_read, body.can_edit, body.can_share, None + ) + return _created(f"/api/v1/grants/{grant['id']}", {"id": str(grant["id"])}) + + +@router.delete("/api/v1/grants/{grant_id}", status_code=204) +def delete_grant(grant_id: UUID, principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)): + revoke_grant(conn, principal.account_id, grant_id) + return Response(status_code=204) + + +@router.put("/api/v1/exceptions") +def put_exception(body: ExceptionIn, principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)): + set_exception( + conn, + principal.account_id, + body.resource_kind, + body.resource_id, + Ctx(body.context.kind, body.context.id), + body.remove_read, + body.remove_edit, + body.remove_share, + ) + return {"ok": True} + + +@router.post("/api/v1/notes") +def post_note(body: NoteIn, principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)): + created = create_note( + conn, + principal.account_id, + principal.scope_id, + body.title, + body.document.model_dump(), + Ctx(body.context.kind, body.context.id), + _ctx_model(body.placement), + body.chapter_id, + ) + element = created["element"] + return _created( + f"/api/v1/notes/{element['id']}", + note_update_payload(conn, principal.account_id, element, created["document"]), + ) + + +@router.patch("/api/v1/notes/{element_id}") +def patch_note( + element_id: UUID, + body: NotePatch, + principal: Principal = Depends(get_principal), + conn: Connection = Depends(get_conn), +): + updated = update_note( + conn, + principal.account_id, + element_id, + body.expected_version, + body.document.model_dump(), + _ctx_model(body.context), + ) + return note_update_payload(conn, principal.account_id, updated["element"], updated["document"]) + + +@router.post("/api/v1/bindings") +def post_binding(body: BindingIn, principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)): + binding = bind_element( + conn, + principal.account_id, + body.element_id, + Ctx(body.source_context.kind, body.source_context.id), + Ctx(body.target.kind, body.target.id), + _ctx_model(body.target_context), + body.chapter_id, + ) + return _created(f"/api/v1/bindings/{binding['id']}", {"id": str(binding["id"])}) + + +@router.delete("/api/v1/bindings/{binding_id}", status_code=204) +def delete_binding( + binding_id: UUID, + context_kind: str | None = None, + context_id: str | None = None, + principal: Principal = Depends(get_principal), + conn: Connection = Depends(get_conn), +): + detach_binding(conn, principal.account_id, binding_id, parse_query_context(context_kind, context_id)) + return Response(status_code=204) + + +@router.post("/api/v1/bindings/{binding_id}/annotations") +def post_annotation( + binding_id: UUID, + body: AnnotationIn, + context_kind: str | None = None, + context_id: str | None = None, + principal: Principal = Depends(get_principal), + conn: Connection = Depends(get_conn), +): + row = add_annotation( + conn, principal.account_id, binding_id, body.body, parse_query_context(context_kind, context_id) + ) + return _created(f"/api/v1/bindings/{binding_id}/annotations/{row['id']}", {"id": str(row["id"]), "body": row["body"]}) + + +@router.post("/api/v1/external-refs") +def post_external(body: ExternalIn, principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)): + element = create_external( + conn, + principal.account_id, + principal.scope_id, + body.title, + body.source, + body.external_id, + Ctx(body.context.kind, body.context.id), + _ctx_model(body.placement), + body.chapter_id, + body.dates.document_on, + body.dates.sent_on, + body.dates.received_on, + ) + return _created(f"/api/v1/elements/{element['id']}", {"id": str(element["id"]), "title": element["title"]}) + + +@router.post("/api/v1/files") +def post_file( + request: Request, + title: str = Form(), + context_kind: str = Form(), + context_id: UUID = Form(), + upload: UploadFile = File(), + placement_kind: str | None = Form(default=None), + placement_id: UUID | None = Form(default=None), + chapter_id: UUID | None = Form(default=None), + document_on: str | None = Form(default=None), + sent_on: str | None = Form(default=None), + received_on: str | None = Form(default=None), + principal: Principal = Depends(get_principal), + conn: Connection = Depends(get_conn), +): + settings = request.app.state.settings + cleaned_title = title.strip() + if not cleaned_title or len(cleaned_title) > 200: + raise unprocessable("Der Titel fehlt oder ist zu lang.") + data = upload.file.read(settings.upload_max_bytes + 1) + context = parse_context({"kind": context_kind, "id": str(context_id)}, required=True) + placement = None + if placement_kind or placement_id: + placement = parse_context({"kind": placement_kind, "id": str(placement_id)}, required=True) + request.state.cleanup_files = [] + element = create_file( + conn, + principal.account_id, + principal.scope_id, + cleaned_title, + upload.filename or "datei", + data, + context, + placement, + chapter_id, + _parse_date(document_on), + _parse_date(sent_on), + _parse_date(received_on), + settings.media_root, + settings.upload_max_bytes, + request.state.cleanup_files, + ) + return _created(f"/api/v1/elements/{element['id']}", {"id": str(element["id"]), "title": element["title"]}) + + +@router.get("/api/v1/files/{element_id}/content") +def download_file( + element_id: UUID, + request: Request, + context_kind: str | None = None, + context_id: str | None = None, + principal: Principal = Depends(get_principal), + conn: Connection = Depends(get_conn), +): + context = parse_query_context(context_kind, context_id) + element = get_element(conn, element_id) + if element is None or element["kind"] != "file": + raise not_found() + rights = element_rights(conn, principal.account_id, element, context) + if not rights.read: + raise not_found() + asset = conn.execute( + "SELECT id, original_filename, content_type, status FROM media_assets WHERE element_id = %s", + (element_id,), + ).fetchone() + if asset is None or asset["status"] != "active": + raise not_found() + payload = read_bytes(asset_path(request.app.state.settings.media_root, asset["id"])) + return Response( + content=payload, + media_type=asset["content_type"], + headers={ + "Content-Disposition": content_disposition(asset["original_filename"]), + "X-Content-Type-Options": "nosniff", + "Cache-Control": "private, no-store", + }, + ) + + +@router.post("/api/v1/elements/{element_id}/delete", status_code=204) +def destroy_element( + element_id: UUID, + body: DeleteElementIn, + request: Request, + principal: Principal = Depends(get_principal), + conn: Connection = Depends(get_conn), +): + request.state.delete_after_commit = [] + delete_element( + conn, + principal.account_id, + element_id, + body.expected_version, + request.app.state.settings.media_root, + request.state.delete_after_commit, + ) + return Response(status_code=204) + + +@router.get("/api/v1/elements") +def elements(principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)): + rows = conn.execute( + """ + SELECT * FROM elements + WHERE owner_subject_id = %s AND deleted_at IS NULL + AND NOT EXISTS (SELECT 1 FROM bindings b WHERE b.element_id = elements.id) + ORDER BY updated_at DESC, id DESC + LIMIT 100 + """, + (principal.account_id,), + ).fetchall() + return { + "items": [{"id": str(row["id"]), "kind": row["kind"], "title": row["title"], "version": row["version"]} for row in rows], + "next_cursor": None, + } + + +@router.post("/api/v1/tasks") +def post_task(body: TaskIn, principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)): + task = create_task( + conn, principal.account_id, principal.scope_id, body.title, body.due_on, body.matter_id, _ctx_model(body.context) + ) + rights = task_rights(conn, principal.account_id, task, _ctx_model(body.context)) + return _created(f"/api/v1/tasks/{task['id']}", task_payload(conn, principal.account_id, task, rights)) + + +@router.patch("/api/v1/tasks/{task_id}") +def patch_one_task( + task_id: UUID, + body: TaskPatch, + principal: Principal = Depends(get_principal), + conn: Connection = Depends(get_conn), +): + task = patch_task( + conn, + principal.account_id, + task_id, + body.expected_version, + body.title, + body.due_on, + body.clear_due_on, + body.status, + _ctx_model(body.context), + ) + rights = task_rights(conn, principal.account_id, task, _ctx_model(body.context)) + return task_payload(conn, principal.account_id, task, rights) + + +@router.post("/api/v1/tasks/{task_id}/assignee") +def post_assignee( + task_id: UUID, + body: AssigneeIn, + principal: Principal = Depends(get_principal), + conn: Connection = Depends(get_conn), +): + assignee = None + if body.email: + account = account_by_email(conn, body.email) + if account is None: + raise not_found() + assignee = account["id"] + task = assign_task(conn, principal.account_id, task_id, assignee, _ctx_model(body.context)) + rights = task_rights(conn, principal.account_id, task, _ctx_model(body.context)) + return task_payload(conn, principal.account_id, task, rights) + + +@router.post("/api/v1/tasks/{task_id}/deadline-links", status_code=204) +def post_task_deadline( + task_id: UUID, + body: TaskDeadlineIn, + principal: Principal = Depends(get_principal), + conn: Connection = Depends(get_conn), +): + link_task_deadline(conn, principal.account_id, task_id, body.deadline_id, _ctx_model(body.context)) + return Response(status_code=204) + + +@router.post("/api/v1/deadlines") +def post_deadline(body: DeadlineIn, principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)): + deadline = create_deadline( + conn, principal.account_id, principal.scope_id, body.title, body.due_on, body.matter_id, _ctx_model(body.context) + ) + return _created(f"/api/v1/deadlines/{deadline['id']}", deadline_payload(conn, principal.account_id, deadline)) + + +@router.patch("/api/v1/deadlines/{deadline_id}") +def patch_one_deadline( + deadline_id: UUID, + body: DeadlinePatch, + principal: Principal = Depends(get_principal), + conn: Connection = Depends(get_conn), +): + deadline = patch_deadline( + conn, principal.account_id, deadline_id, body.expected_version, body.title, body.due_on, _ctx_model(body.context) + ) + return deadline_payload(conn, principal.account_id, deadline) + + +@router.post("/api/v1/deadlines/{deadline_id}/fulfill") +def post_fulfill( + deadline_id: UUID, + body: FulfillIn, + principal: Principal = Depends(get_principal), + conn: Connection = Depends(get_conn), +): + deadline = fulfill_deadline(conn, principal.account_id, deadline_id, body.expected_version, _ctx_model(body.context)) + return deadline_payload(conn, principal.account_id, deadline) + + +@router.get("/api/v1/views/open-tasks") +def open_tasks(principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)): + rows = conn.execute( + """ + SELECT * FROM tasks + WHERE deleted_at IS NULL AND task_status = 'open' + ORDER BY due_on NULLS LAST, created_at, id + LIMIT 200 + """ + ).fetchall() + items = [] + for task in rows: + if _task_visible(conn, principal.account_id, task): + items.append(task_payload(conn, principal.account_id, task)) + return {"items": items, "next_cursor": None} + + +@router.get("/api/v1/views/open-deadlines") +def open_deadlines(principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)): + rows = conn.execute( + """ + SELECT * FROM deadlines + WHERE deleted_at IS NULL AND deadline_status = 'open' + ORDER BY due_on, created_at, id + LIMIT 200 + """ + ).fetchall() + items = [] + for deadline in rows: + if _deadline_visible(conn, principal.account_id, deadline): + items.append(deadline_payload(conn, principal.account_id, deadline)) + return {"items": items, "next_cursor": None} + + +@router.get("/api/v1/placement-targets") +def placement_targets(principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)): + items = [] + for case, rights in list_cases(conn, principal.account_id): + if rights.edit: + items.append({"kind": "case", "id": str(case["id"]), "title": case["title"]}) + for matter, contexts in list_matters(conn, principal.account_id): + editable = [item for item in contexts if item["rights"]["edit"]] + if editable: + items.append( + { + "kind": "matter", + "id": str(matter["id"]), + "title": matter["title"], + "contexts": [ + { + "kind": "direct" if item["kind"] == "matter" else item["kind"], + "id": item["id"], + "title": item["title"], + } + for item in editable + ], + } + ) + return {"items": items} + + +@router.get("/api/v1/search") +def search(q: str, principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)): + term = q.strip() + if len(term) < 2: + raise unprocessable("Bitte mindestens zwei Zeichen suchen.") + pattern = "%" + term.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_") + "%" + items = [] + for case, rights in list_cases(conn, principal.account_id): + if rights.read and term.casefold() in case["title"].casefold(): + items.append({"kind": "case", "id": str(case["id"]), "title": case["title"], "contexts": []}) + for matter, contexts in list_matters(conn, principal.account_id): + if term.casefold() in matter["title"].casefold(): + items.append( + { + "kind": "matter", + "id": str(matter["id"]), + "title": matter["title"], + "contexts": [ + {"kind": "direct" if item["kind"] == "matter" else item["kind"], "id": item["id"], "title": item["title"]} + for item in contexts + ], + } + ) + elements = conn.execute( + """ + SELECT e.* + FROM elements e + LEFT JOIN note_bodies n ON n.element_id = e.id + WHERE e.deleted_at IS NULL + AND (e.title ILIKE %s ESCAPE '\\' OR COALESCE(n.document_json::text, '') ILIKE %s ESCAPE '\\') + ORDER BY e.updated_at DESC + LIMIT 100 + """, + (pattern, pattern), + ).fetchall() + for element in elements: + from app.access.policy import visible_bindings_for_element + + bindings = visible_bindings_for_element(conn, principal.account_id, element) + owner = element["owner_subject_id"] == principal.account_id + if not bindings and not owner: + continue + if not bindings and owner: + direct = element_rights(conn, principal.account_id, element, None) + if not direct.read: + continue + items.append( + { + "kind": element["kind"], + "id": str(element["id"]), + "title": element["title"], + "contexts": [ + {"kind": item["context_kind"], "id": item["context_id"], "title": item["context_title"]} + for item in bindings + ], + } + ) + return {"items": items[:50], "next_cursor": None} + + +@router.get("/api/v1/cases/{case_id}/chronology") +def case_chronology(case_id: UUID, principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)): + case, _rights = require_case(conn, principal.account_id, case_id, "read") + page = Ctx("case", case["id"]) + rows = conn.execute( + """ + SELECT * + FROM domain_events + WHERE (resource_kind = 'case' AND resource_id = %(case)s) + OR (context_kind = 'case' AND context_id = %(case)s) + OR resource_id IN (SELECT matter_id FROM matter_case_links WHERE case_id = %(case)s) + OR resource_id IN ( + SELECT element_id FROM bindings WHERE context_kind = 'case' AND context_id = %(case)s + UNION + SELECT b.element_id + FROM bindings b + JOIN matter_case_links l ON b.context_kind = 'matter' AND b.context_id = l.matter_id + WHERE l.case_id = %(case)s + ) + ORDER BY COALESCE(occurred_on, occurred_at::date), occurred_at, id + """, + {"case": case_id}, + ).fetchall() + return {"items": _visible_events(conn, principal.account_id, rows, page)} + + +@router.get("/api/v1/matters/{matter_id}/chronology") +def matter_chronology( + matter_id: UUID, + context_kind: str | None = None, + context_id: str | None = None, + principal: Principal = Depends(get_principal), + conn: Connection = Depends(get_conn), +): + context = parse_query_context(context_kind, context_id) + matter, _rights = require_matter(conn, principal.account_id, matter_id, context, "read") + page = context or Ctx("matter", matter["id"]) + rows = conn.execute( + """ + SELECT * + FROM domain_events + WHERE resource_id = %(matter)s + OR (context_kind = 'matter' AND context_id = %(matter)s) + OR resource_id IN ( + SELECT element_id FROM bindings WHERE context_kind = 'matter' AND context_id = %(matter)s + ) + OR resource_id IN ( + SELECT id FROM tasks WHERE matter_id = %(matter)s + UNION + SELECT id FROM deadlines WHERE matter_id = %(matter)s + ) + ORDER BY COALESCE(occurred_on, occurred_at::date), occurred_at, id + """, + {"matter": matter_id}, + ).fetchall() + return {"items": _visible_events(conn, principal.account_id, rows, page)} + + +def _parse_date(value: str | None) -> date | None: + if value is None or value == "": + return None + try: + return date.fromisoformat(value) + except ValueError as exc: + raise unprocessable("Ein Datum ist ungültig.") from exc + + +def _task_visible(conn, actor: UUID, task: dict) -> bool: + if task_rights(conn, actor, task, None).read: + return True + matter = get_matter(conn, task["matter_id"]) if task["matter_id"] else None + if matter is None: + return False + return any(task_rights(conn, actor, task, Ctx(item["kind"], UUID(item["id"]))).read for item in _case_contexts(conn, actor, matter)) + + +def _deadline_visible(conn, actor: UUID, deadline: dict) -> bool: + if deadline_rights(conn, actor, deadline, None).read: + return True + matter = get_matter(conn, deadline["matter_id"]) if deadline["matter_id"] else None + if matter is None: + return False + return any( + deadline_rights(conn, actor, deadline, Ctx(item["kind"], UUID(item["id"]))).read + for item in _case_contexts(conn, actor, matter) + ) + + +def _case_contexts(conn, actor, matter) -> list[dict]: + from app.access.policy import readable_matter_contexts + + return [item for item in readable_matter_contexts(conn, actor, matter) if item["kind"] == "case"] + + +def _visible_events(conn, actor: UUID, rows: list[dict], page: Ctx) -> list[dict]: + items = [] + for event in rows: + title = _event_title(conn, actor, event, page) + if title is None: + continue + items.append( + { + "id": str(event["id"]), + "action": event["action"], + "label": LABELS.get(event["action"], "Ereignis"), + "title": title, + "occurred_on": event["occurred_on"].isoformat() if event["occurred_on"] else None, + "occurred_at": event["occurred_at"].astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), + "resource_kind": event["resource_kind"], + "resource_id": str(event["resource_id"]), + } + ) + return items + + +def _event_title(conn, actor: UUID, event: dict, page: Ctx) -> str | None: + kind = event["resource_kind"] + resource_id = event["resource_id"] + if kind == "case": + case = get_case(conn, resource_id) + if case is None or not case_rights(conn, actor, case).read: + return None + return case["title"] + if kind == "matter": + matter = get_matter(conn, resource_id) + if matter is None: + return None + context = page if page.kind == "case" else None + if not matter_rights(conn, actor, matter, context).read and not matter_rights(conn, actor, matter, None).read: + return None + if page.kind == "case" and not matter_rights(conn, actor, matter, page).read: + return None + return matter["title"] + if kind == "element": + element = get_element(conn, resource_id) + if element is None or not element_rights(conn, actor, element, page).read: + return None + return element["title"] + if kind == "task": + task = get_task(conn, resource_id) + if task is None or not task_rights(conn, actor, task, None if page.kind == "matter" else page).read: + if task is None or not task_rights(conn, actor, task, page).read: + return None + return task["title"] if task else None + if kind == "deadline": + deadline = get_deadline(conn, resource_id) + if deadline is None: + return None + direct = deadline_rights(conn, actor, deadline, None) + via = deadline_rights(conn, actor, deadline, page) + if not direct.read and not via.read: + return None + return deadline["title"] + return None diff --git a/backend/app/api/schemas.py b/backend/app/api/schemas.py new file mode 100644 index 0000000..d6330c2 --- /dev/null +++ b/backend/app/api/schemas.py @@ -0,0 +1,203 @@ +"""Request bodies. Unknown fields are rejected.""" + +from __future__ import annotations + +from datetime import date +from typing import Annotated, Literal +from uuid import UUID + +from pydantic import BaseModel, ConfigDict, Field + +Email = Annotated[str, Field(min_length=3, max_length=320, pattern=r"^[^@\s]+@[^@\s]+\.[^@\s]+$")] + + +class APIModel(BaseModel): + model_config = ConfigDict(extra="forbid") + + +class LoginIn(APIModel): + email: Email + password: str = Field(min_length=1, max_length=200) + + +class ScopeIn(APIModel): + kind: Literal["personal", "organization"] + id: UUID + + +class AcceptInviteIn(APIModel): + token: str = Field(min_length=20, max_length=200) + display_name: str = Field(min_length=1, max_length=120) + password: str = Field(min_length=10, max_length=200) + + +class InvitationIn(APIModel): + email: Email + room_id: UUID + + +class RoomIn(APIModel): + name: str = Field(min_length=1, max_length=160) + + +class MemberIn(APIModel): + email: Email + role: Literal["member", "manager"] + + +class ContextIn(APIModel): + kind: Literal["case", "matter"] + id: UUID + + +class CaseIn(APIModel): + title: str = Field(min_length=1, max_length=200) + parent_case_id: UUID | None = None + rights_mode: Literal["inherit_parent", "explicit"] = "inherit_parent" + + +class CasePatch(APIModel): + expected_version: int = Field(ge=1) + title: str | None = Field(default=None, min_length=1, max_length=200) + status: Literal["open", "closed"] | None = None + + +class ChapterIn(APIModel): + title: str = Field(min_length=1, max_length=200) + position: int | None = Field(default=None, ge=0, le=10000) + + +class MatterIn(APIModel): + title: str = Field(min_length=1, max_length=200) + parent_matter_id: UUID | None = None + context: ContextIn | None = None + + +class MatterPatch(APIModel): + expected_version: int = Field(ge=1) + title: str | None = Field(default=None, min_length=1, max_length=200) + status: Literal["open", "closed"] | None = None + context: ContextIn | None = None + + +class CaseLinkIn(APIModel): + case_id: UUID + context: ContextIn | None = None + + +class CrossLinkIn(APIModel): + target_matter_id: UUID + target_context: ContextIn + source_context: ContextIn | None = None + + +class GrantIn(APIModel): + email: Email + can_read: bool = True + can_edit: bool = False + can_share: bool = False + + +class ExceptionIn(APIModel): + resource_kind: Literal["element", "matter", "task", "deadline"] + resource_id: UUID + context: ContextIn + remove_read: bool = False + remove_edit: bool = False + remove_share: bool = False + + +class DocumentIn(APIModel): + version: Literal[1] = 1 + blocks: list[dict] + + +class NoteIn(APIModel): + title: str = Field(min_length=1, max_length=200) + document: DocumentIn + context: ContextIn + placement: ContextIn | None = None + chapter_id: UUID | None = None + + +class NotePatch(APIModel): + expected_version: int = Field(ge=1) + document: DocumentIn + context: ContextIn | None = None + + +class BindingIn(APIModel): + element_id: UUID + source_context: ContextIn + target: ContextIn + target_context: ContextIn | None = None + chapter_id: UUID | None = None + + +class AnnotationIn(APIModel): + body: str = Field(min_length=1, max_length=4000) + + +class DatesIn(APIModel): + document_on: date | None = None + sent_on: date | None = None + received_on: date | None = None + + +class ExternalIn(APIModel): + title: str = Field(min_length=1, max_length=200) + source: Literal["paperless", "url"] + external_id: str = Field(min_length=1, max_length=200) + context: ContextIn + placement: ContextIn | None = None + chapter_id: UUID | None = None + dates: DatesIn = DatesIn() + + +class DeleteElementIn(APIModel): + expected_version: int = Field(ge=1) + + +class TaskIn(APIModel): + title: str = Field(min_length=1, max_length=200) + due_on: date | None = None + matter_id: UUID | None = None + context: ContextIn | None = None + + +class TaskPatch(APIModel): + expected_version: int = Field(ge=1) + title: str | None = Field(default=None, min_length=1, max_length=200) + due_on: date | None = None + clear_due_on: bool = False + status: Literal["open", "done"] | None = None + context: ContextIn | None = None + + +class AssigneeIn(APIModel): + email: str | None = None + context: ContextIn | None = None + + +class DeadlineIn(APIModel): + title: str = Field(min_length=1, max_length=200) + due_on: date + matter_id: UUID | None = None + context: ContextIn | None = None + + +class DeadlinePatch(APIModel): + expected_version: int = Field(ge=1) + title: str | None = Field(default=None, min_length=1, max_length=200) + due_on: date | None = None + context: ContextIn | None = None + + +class FulfillIn(APIModel): + expected_version: int = Field(ge=1) + context: ContextIn | None = None + + +class TaskDeadlineIn(APIModel): + deadline_id: UUID + context: ContextIn | None = None diff --git a/backend/app/auth/__init__.py b/backend/app/auth/__init__.py new file mode 100644 index 0000000..1674b43 --- /dev/null +++ b/backend/app/auth/__init__.py @@ -0,0 +1 @@ +"""Accounts, sessions and cookies.""" diff --git a/backend/app/auth/accounts.py b/backend/app/auth/accounts.py new file mode 100644 index 0000000..d333306 --- /dev/null +++ b/backend/app/auth/accounts.py @@ -0,0 +1,78 @@ +"""Accounts, personal rooms and sessions.""" + +from __future__ import annotations + +from uuid import UUID, uuid4 + +from app.auth.security import hash_password, hash_secret, new_secret, session_expiry +from app.core.errors import unprocessable +from app.core.settings import Settings + + +def normalize_email(email: str) -> str: + return email.strip().lower() + + +def create_account(conn, email: str, display_name: str, password: str) -> dict: + email = normalize_email(email) + display_name = display_name.strip() + if conn.execute("SELECT 1 FROM auth_accounts WHERE email = %s", (email,)).fetchone(): + raise unprocessable("Für diese E-Mail gibt es bereits ein Konto.") + account_id = uuid4() + password_hash = hash_password(password) + conn.execute( + """ + INSERT INTO auth_accounts (id, email, display_name, password_hash) + VALUES (%s, %s, %s, %s) + """, + (account_id, email, display_name, password_hash), + ) + conn.execute( + """ + INSERT INTO data_rooms (id, kind, name, created_by) + VALUES (%s, 'personal', 'Persönlicher Raum', %s) + """, + (account_id, account_id), + ) + return conn.execute( + "SELECT id, email, display_name FROM auth_accounts WHERE id = %s", + (account_id,), + ).fetchone() + + +def start_session(conn, settings: Settings, account_id: UUID) -> tuple[str, str]: + token = new_secret() + csrf = new_secret() + conn.execute( + """ + INSERT INTO auth_sessions ( + account_id, secret_hash, csrf_token, scope_kind, scope_id, expires_at + ) + VALUES (%s, %s, %s, 'personal', %s, %s) + """, + (account_id, hash_secret(token), csrf, account_id, session_expiry(settings)), + ) + return token, csrf + + +def list_rooms(conn, account_id: UUID) -> list[dict]: + personal = conn.execute( + "SELECT id, kind, name FROM data_rooms WHERE id = %s AND kind = 'personal'", + (account_id,), + ).fetchone() + rooms = [] + if personal is not None: + rooms.append({"id": str(personal["id"]), "kind": personal["kind"], "name": personal["name"], "role": "owner"}) + shared = conn.execute( + """ + SELECT r.id, r.kind, r.name, m.role + FROM room_memberships m + JOIN data_rooms r ON r.id = m.room_id + WHERE m.subject_id = %s AND m.status = 'active' AND r.status = 'active' AND r.kind = 'organization' + ORDER BY r.name, r.id + """, + (account_id,), + ).fetchall() + for room in shared: + rooms.append({"id": str(room["id"]), "kind": room["kind"], "name": room["name"], "role": room["role"]}) + return rooms diff --git a/backend/app/auth/security.py b/backend/app/auth/security.py new file mode 100644 index 0000000..c0a30be --- /dev/null +++ b/backend/app/auth/security.py @@ -0,0 +1,74 @@ +"""Password hashing, session cookies and CSRF.""" + +from __future__ import annotations + +import hashlib +import secrets +from datetime import timedelta + +import bcrypt +from fastapi import Request, Response + +from app.core.settings import Settings +from app.core.timeutil import utcnow + +HOST_COOKIE = "__Host-jinkendo-session" +PLAIN_COOKIE = "jinkendo-session" + + +def hash_password(password: str) -> str: + return bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt(rounds=12)).decode("utf-8") + + +def verify_password(password: str, password_hash: str) -> bool: + try: + return bcrypt.checkpw(password.encode("utf-8"), password_hash.encode("utf-8")) + except ValueError: + return False + + +def new_secret() -> str: + return secrets.token_urlsafe(32) + + +def hash_secret(secret: str) -> str: + return hashlib.sha256(secret.encode("utf-8")).hexdigest() + + +def cookie_name_and_secure(request: Request, settings: Settings) -> tuple[str, bool]: + # __Host- cookies require Secure. Production is only published behind HTTPS. + # Development also serves the documented plain HTTP LAN addresses, which cannot store them. + if settings.tsumugu_env == "production": + return HOST_COOKIE, True + forwarded = request.headers.get("x-forwarded-proto", request.url.scheme) + if forwarded == "https": + return HOST_COOKIE, True + return PLAIN_COOKIE, False + + +def read_session_token(request: Request) -> str | None: + return request.cookies.get(HOST_COOKIE) or request.cookies.get(PLAIN_COOKIE) + + +def set_session_cookie(response: Response, request: Request, settings: Settings, token: str) -> None: + name, secure = cookie_name_and_secure(request, settings) + response.set_cookie( + key=name, + value=token, + httponly=True, + secure=secure, + samesite="lax", + path="/", + max_age=settings.session_ttl_hours * 3600, + ) + + +def clear_session_cookie(response: Response, request: Request, settings: Settings) -> None: + name, secure = cookie_name_and_secure(request, settings) + response.delete_cookie(key=name, path="/", secure=secure, httponly=True, samesite="lax") + if name != PLAIN_COOKIE: + response.delete_cookie(key=PLAIN_COOKIE, path="/", httponly=True, samesite="lax") + + +def session_expiry(settings: Settings): + return utcnow() + timedelta(hours=settings.session_ttl_hours) diff --git a/backend/app/cli.py b/backend/app/cli.py new file mode 100644 index 0000000..1fe9d1e --- /dev/null +++ b/backend/app/cli.py @@ -0,0 +1,44 @@ +"""Operator commands: migrate, seed demo data, create the first account.""" + +from __future__ import annotations + +import argparse + +from app.auth.accounts import create_account +from app.core.settings import get_settings +from app.db.migrate import migrate +from app.seed import seed_demo + +import psycopg +from psycopg.rows import dict_row + + +def main() -> None: + parser = argparse.ArgumentParser(prog="tsumugu") + sub = parser.add_subparsers(dest="command", required=True) + sub.add_parser("migrate") + sub.add_parser("seed-demo") + create = sub.add_parser("create-account") + create.add_argument("--email", required=True) + create.add_argument("--name", required=True) + create.add_argument("--password", required=True) + args = parser.parse_args() + settings = get_settings() + if args.command == "migrate": + applied = migrate(settings) + print("applied" if applied else "up to date") + return + if args.command == "seed-demo": + created = seed_demo(settings) + print("seeded" if created else "unchanged") + return + if len(args.password) < 10: + raise SystemExit("password must be at least 10 characters") + with psycopg.connect(settings.dsn(), row_factory=dict_row) as conn: + account = create_account(conn, args.email, args.name, args.password) + conn.commit() + print(account["id"]) + + +if __name__ == "__main__": + main() diff --git a/backend/app/content/__init__.py b/backend/app/content/__init__.py new file mode 100644 index 0000000..3ba5923 --- /dev/null +++ b/backend/app/content/__init__.py @@ -0,0 +1 @@ +"""Notes, bindings, files and external references.""" diff --git a/backend/app/content/documents.py b/backend/app/content/documents.py new file mode 100644 index 0000000..e30d524 --- /dev/null +++ b/backend/app/content/documents.py @@ -0,0 +1,25 @@ +"""Bounded note documents. Only paragraph text is stored.""" + +from __future__ import annotations + +from app.core.errors import unprocessable + + +def clean_document(document: dict) -> dict: + blocks = document.get("blocks") + if not isinstance(blocks, list) or len(blocks) > 400: + raise unprocessable("Die Notiz hat kein gültiges Dokument.") + clean = [] + for block in blocks: + if not isinstance(block, dict) or set(block) - {"type", "text"}: + raise unprocessable("Die Notiz enthält einen nicht unterstützten Block.") + if block.get("type") != "paragraph" or not isinstance(block.get("text"), str): + raise unprocessable("Die Notiz enthält einen nicht unterstützten Block.") + if len(block["text"]) > 20000: + raise unprocessable("Ein Absatz ist zu lang.") + clean.append({"type": "paragraph", "text": block["text"]}) + return {"version": 1, "blocks": clean} + + +def document_text(document: dict) -> str: + return "\n".join(block["text"] for block in document.get("blocks", [])) diff --git a/backend/app/core/__init__.py b/backend/app/core/__init__.py new file mode 100644 index 0000000..ebe0959 --- /dev/null +++ b/backend/app/core/__init__.py @@ -0,0 +1 @@ +"""Core settings, errors and request helpers.""" diff --git a/backend/app/core/errors.py b/backend/app/core/errors.py new file mode 100644 index 0000000..ce16081 --- /dev/null +++ b/backend/app/core/errors.py @@ -0,0 +1,71 @@ +"""RFC 9457 problem responses. Hidden objects use the same 404 as missing ones.""" + +from __future__ import annotations + +from fastapi import Request +from fastapi.responses import JSONResponse + + +class Problem(Exception): + def __init__(self, status: int, title: str, detail: str, code: str) -> None: + super().__init__(detail) + self.status = status + self.title = title + self.detail = detail + self.code = code + + def body(self, instance: str) -> dict: + return { + "type": "about:blank", + "title": self.title, + "status": self.status, + "detail": self.detail, + "instance": instance, + "code": self.code, + } + + +def unauthorized() -> Problem: + return Problem(401, "Anmeldung erforderlich", "Die Sitzung fehlt oder ist abgelaufen.", "unauthorized") + + +def forbidden(detail: str = "Diese Aktion ist im gewählten Kontext nicht erlaubt.") -> Problem: + return Problem(403, "Keine Berechtigung", detail, "forbidden") + + +def not_found() -> Problem: + return Problem(404, "Nicht gefunden", "Der Eintrag ist nicht vorhanden.", "not_found") + + +def conflict() -> Problem: + return Problem( + 409, + "Versionskonflikt", + "Der Stand hat sich geändert. Bitte neu laden.", + "conflict", + ) + + +def unprocessable(detail: str) -> Problem: + return Problem(422, "Eingabe ungültig", detail, "unprocessable") + + +def too_many() -> Problem: + return Problem(429, "Zu viele Versuche", "Bitte kurz warten und es erneut versuchen.", "too_many_requests") + + +def storage_unavailable() -> Problem: + return Problem( + 503, + "Speicher nicht verfügbar", + "Die Datei kann gerade nicht gelesen oder geschrieben werden.", + "storage_unavailable", + ) + + +def problem_response(problem: Problem, request: Request) -> JSONResponse: + return JSONResponse( + status_code=problem.status, + content=problem.body(request.url.path), + media_type="application/problem+json", + ) diff --git a/backend/app/core/settings.py b/backend/app/core/settings.py new file mode 100644 index 0000000..f08008a --- /dev/null +++ b/backend/app/core/settings.py @@ -0,0 +1,47 @@ +"""Process settings. Unknown environments refuse to start.""" + +from __future__ import annotations + +from functools import lru_cache +from typing import Literal + +from pydantic import field_validator +from pydantic_settings import BaseSettings, SettingsConfigDict + + +class Settings(BaseSettings): + model_config = SettingsConfigDict(extra="ignore") + + tsumugu_env: Literal["development", "production"] + db_host: str = "localhost" + db_port: int = 5432 + db_name: str + db_user: str + db_password: str + db_runtime_user: str = "tsumugu_runtime" + app_url: str = "http://localhost:5173" + allowed_origins: str = "http://localhost:5173,http://localhost:3094" + media_root: str = "data/media" + seed_demo: bool = False + session_ttl_hours: int = 336 + upload_max_bytes: int = 20 * 1024 * 1024 + + @field_validator("allowed_origins") + @classmethod + def strip_origins(cls, value: str) -> str: + return value.strip() + + @property + def origin_set(self) -> set[str]: + return {item.strip() for item in self.allowed_origins.split(",") if item.strip()} + + def dsn(self, user: str | None = None) -> str: + return ( + f"host={self.db_host} port={self.db_port} dbname={self.db_name} " + f"user={user or self.db_user} password={self.db_password} connect_timeout=5" + ) + + +@lru_cache +def get_settings() -> Settings: + return Settings() diff --git a/backend/app/core/timeutil.py b/backend/app/core/timeutil.py new file mode 100644 index 0000000..a5a254f --- /dev/null +++ b/backend/app/core/timeutil.py @@ -0,0 +1,23 @@ +"""UTC formatting for API values.""" + +from __future__ import annotations + +from datetime import date, datetime, timezone + + +def utcnow() -> datetime: + return datetime.now(timezone.utc) + + +def dump_dt(value: datetime | None) -> str | None: + if value is None: + return None + if value.tzinfo is None: + value = value.replace(tzinfo=timezone.utc) + return value.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") + + +def dump_date(value: date | None) -> str | None: + if value is None: + return None + return value.isoformat() diff --git a/backend/app/db/__init__.py b/backend/app/db/__init__.py new file mode 100644 index 0000000..f87718e --- /dev/null +++ b/backend/app/db/__init__.py @@ -0,0 +1 @@ +"""Database pool and migrations.""" diff --git a/backend/app/db/migrate.py b/backend/app/db/migrate.py new file mode 100644 index 0000000..a2ff974 --- /dev/null +++ b/backend/app/db/migrate.py @@ -0,0 +1,90 @@ +"""SQL migrations with a checksum ledger, then a runtime role without DDL.""" + +from __future__ import annotations + +import hashlib +from pathlib import Path + +import psycopg +from psycopg import ClientCursor, sql + +from app.core.settings import Settings, get_settings + +MIGRATIONS = Path(__file__).resolve().parent.parent.parent / "migrations" + + +def _checksum(path: Path) -> str: + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def migrate(settings: Settings | None = None) -> list[str]: + settings = settings or get_settings() + applied: list[str] = [] + with psycopg.connect(settings.dsn(), autocommit=True, cursor_factory=ClientCursor) as conn: + conn.execute( + """ + CREATE TABLE IF NOT EXISTS schema_migrations ( + version text PRIMARY KEY, + checksum text NOT NULL, + applied_at timestamptz NOT NULL DEFAULT now() + ) + """ + ) + for path in sorted(MIGRATIONS.glob("*.sql")): + version = path.name + checksum = _checksum(path) + row = conn.execute( + "SELECT checksum FROM schema_migrations WHERE version = %s", + (version,), + ).fetchone() + if row is not None: + if row[0] != checksum: + raise RuntimeError(f"checksum mismatch for migration {version}") + continue + with conn.transaction(): + conn.execute(path.read_text(encoding="utf-8")) + conn.execute( + "INSERT INTO schema_migrations (version, checksum) VALUES (%s, %s)", + (version, checksum), + ) + applied.append(version) + _ensure_runtime_role(conn, settings) + return applied + + +def _ensure_runtime_role(conn: psycopg.Connection, settings: Settings) -> None: + role = sql.Identifier(settings.db_runtime_user) + database = sql.Identifier(settings.db_name) + owner = sql.Identifier(settings.db_user) + password = sql.Literal(settings.db_password) + exists = conn.execute( + "SELECT 1 FROM pg_roles WHERE rolname = %s", + (settings.db_runtime_user,), + ).fetchone() + if exists is None: + conn.execute( + sql.SQL( + "CREATE ROLE {} LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT PASSWORD {}" + ).format(role, password) + ) + else: + conn.execute( + sql.SQL( + "ALTER ROLE {} WITH LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT PASSWORD {}" + ).format(role, password) + ) + conn.execute(sql.SQL("GRANT CONNECT ON DATABASE {} TO {}").format(database, role)) + conn.execute(sql.SQL("GRANT USAGE ON SCHEMA public TO {}").format(role)) + conn.execute(sql.SQL("REVOKE CREATE ON SCHEMA public FROM {}").format(role)) + conn.execute( + sql.SQL( + "GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO {}" + ).format(role) + ) + conn.execute(sql.SQL("REVOKE ALL ON TABLE schema_migrations FROM {}").format(role)) + conn.execute( + sql.SQL( + "ALTER DEFAULT PRIVILEGES FOR ROLE {} IN SCHEMA public " + "GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO {}" + ).format(owner, role) + ) diff --git a/backend/app/db/pool.py b/backend/app/db/pool.py new file mode 100644 index 0000000..7c11a4f --- /dev/null +++ b/backend/app/db/pool.py @@ -0,0 +1,19 @@ +"""Runtime connection pool. Importing the app does not open it.""" + +from __future__ import annotations + +from psycopg.rows import dict_row +from psycopg_pool import ConnectionPool + +from app.core.settings import Settings + + +def open_pool(settings: Settings) -> ConnectionPool: + return ConnectionPool( + conninfo=settings.dsn(settings.db_runtime_user), + kwargs={"row_factory": dict_row}, + min_size=1, + max_size=10, + open=True, + timeout=10, + ) diff --git a/backend/app/entrypoint.py b/backend/app/entrypoint.py new file mode 100644 index 0000000..fb6a895 --- /dev/null +++ b/backend/app/entrypoint.py @@ -0,0 +1,18 @@ +"""Migrate, optionally seed development data, then serve.""" + +from __future__ import annotations + +import os + +from app.db.migrate import migrate +from app.seed import seed_demo + + +def main() -> None: + migrate() + seed_demo() + os.execvp("uvicorn", ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]) + + +if __name__ == "__main__": + main() diff --git a/backend/app/main.py b/backend/app/main.py new file mode 100644 index 0000000..5c9788e --- /dev/null +++ b/backend/app/main.py @@ -0,0 +1,119 @@ +"""Application factory. Importing this module does not open a database connection.""" + +from __future__ import annotations + +import logging +from contextlib import asynccontextmanager + +from fastapi import FastAPI, Request +from fastapi.exceptions import RequestValidationError +from fastapi.responses import JSONResponse + +from app.api.routes import router +from app.core.errors import Problem, problem_response +from app.core.settings import get_settings +from app.db.pool import open_pool + +logger = logging.getLogger("tsumugu") + + +def _database_ok(app: FastAPI) -> bool: + pool = getattr(app.state, "pool", None) + if pool is None: + return False + try: + with pool.connection() as conn: + conn.execute("SELECT 1") + conn.rollback() + return True + except Exception: + logger.warning("database check failed") + return False + + +def create_app() -> FastAPI: + settings = get_settings() + logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s %(message)s") + + @asynccontextmanager + async def lifespan(app: FastAPI): + app.state.pool = open_pool(settings) + try: + yield + finally: + app.state.pool.close() + + app = FastAPI(title="Tsumugu", docs_url=None, redoc_url=None, openapi_url=None, lifespan=lifespan) + app.state.settings = settings + + @app.middleware("http") + async def origin_guard(request: Request, call_next): + if request.method not in {"GET", "HEAD", "OPTIONS"} and request.url.path.startswith("/api/"): + origin = request.headers.get("origin") + if origin not in settings.origin_set: + problem = Problem(403, "Keine Berechtigung", "Der Ursprung der Anfrage ist nicht erlaubt.", "forbidden") + return problem_response(problem, request) + response = await call_next(request) + logger.info("%s %s -> %s", request.method, request.url.path, response.status_code) + return response + + @app.exception_handler(Problem) + async def handle_problem(request: Request, exc: Problem): + return problem_response(exc, request) + + @app.exception_handler(RequestValidationError) + async def handle_validation(request: Request, exc: RequestValidationError): + return JSONResponse( + status_code=422, + content={ + "type": "about:blank", + "title": "Eingabe ungültig", + "status": 422, + "detail": "Die Eingabe ist unvollständig oder ungültig.", + "instance": request.url.path, + "code": "unprocessable", + }, + media_type="application/problem+json", + ) + + @app.exception_handler(Exception) + async def handle_unexpected(request: Request, exc: Exception): + logger.exception("unhandled error") + return JSONResponse( + status_code=500, + content={ + "type": "about:blank", + "title": "Unerwarteter Fehler", + "status": 500, + "detail": "Die Aktion konnte nicht abgeschlossen werden.", + "instance": request.url.path, + "code": "internal", + }, + media_type="application/problem+json", + ) + + @app.get("/api/health") + def api_health(): + ok = _database_ok(app) + return JSONResponse( + status_code=200 if ok else 503, + content={"status": "ok" if ok else "degraded", "app": "tsumugu"}, + ) + + @app.get("/health/live") + def health_live(): + return {"status": "ok", "app": "tsumugu"} + + @app.get("/health/ready") + def health_ready(): + ok = _database_ok(app) + return JSONResponse( + status_code=200 if ok else 503, + content={"status": "ok" if ok else "degraded", "app": "tsumugu"}, + ) + + app.include_router(router) + return app + + +app = create_app() diff --git a/backend/app/media/__init__.py b/backend/app/media/__init__.py new file mode 100644 index 0000000..4ed08e7 --- /dev/null +++ b/backend/app/media/__init__.py @@ -0,0 +1 @@ +"""Private file storage. Paths are server-generated.""" diff --git a/backend/app/media/storage.py b/backend/app/media/storage.py new file mode 100644 index 0000000..5002fcb --- /dev/null +++ b/backend/app/media/storage.py @@ -0,0 +1,71 @@ +"""Sniff uploads and keep client names out of the storage path.""" + +from __future__ import annotations + +import hashlib +from pathlib import Path +from uuid import UUID + +from app.core.errors import storage_unavailable, unprocessable + +ALLOWED = { + "application/pdf": "pdf", + "image/png": "png", + "image/jpeg": "jpg", + "image/webp": "webp", +} + + +def sniff(data: bytes) -> str: + if data.startswith(b"%PDF"): + return "application/pdf" + if data.startswith(b"\x89PNG\r\n\x1a\n"): + return "image/png" + if data.startswith(b"\xff\xd8\xff"): + return "image/jpeg" + if len(data) >= 12 and data[:4] == b"RIFF" and data[8:12] == b"WEBP": + return "image/webp" + raise unprocessable("Erlaubt sind PDF, PNG, JPEG und WebP.") + + +def asset_path(media_root: str, asset_id: UUID) -> Path: + root = Path(media_root).resolve() + root.mkdir(parents=True, exist_ok=True) + target = (root / str(asset_id)).resolve() + if target.parent != root: + raise unprocessable("Ungültiger Speicherpfad.") + return target + + +def write_bytes(path: Path, data: bytes) -> None: + try: + path.write_bytes(data) + except OSError as exc: + raise storage_unavailable() from exc + + +def read_bytes(path: Path) -> bytes: + try: + if not path.is_file(): + raise storage_unavailable() + return path.read_bytes() + except OSError as exc: + raise storage_unavailable() from exc + + +def sha256(data: bytes) -> str: + return hashlib.sha256(data).hexdigest() + + +def display_filename(name: str) -> str: + cleaned = [] + for char in name.replace("\\", "/").split("/")[-1]: + if char.isprintable() and char not in {'"', "\r", "\n", ":"}: + cleaned.append(char) + text = "".join(cleaned).strip() or "datei" + return text[:240] + + +def content_disposition(filename: str) -> str: + safe = display_filename(filename).replace('"', "") + return f'attachment; filename="{safe}"' diff --git a/backend/app/ops.py b/backend/app/ops.py new file mode 100644 index 0000000..e1e0dd6 --- /dev/null +++ b/backend/app/ops.py @@ -0,0 +1,784 @@ +"""Use-cases for organisation, content and tracking. One transaction is the caller's.""" + +from __future__ import annotations + +from datetime import date +from pathlib import Path +from uuid import UUID, uuid4 + +from psycopg.types.json import Json + +from app.access.policy import ( + Ctx, + Rights, + audit, + block_unsharable_matter_elements, + bump_version, + can_change_status, + case_rights, + chapter_for, + deadline_rights, + display_name, + element_rights, + get_case, + get_deadline, + get_element, + get_matter, + get_task, + insert_binding, + matter_rights, + require_case, + require_element, + require_matter, + task_rights, +) +from app.content.documents import clean_document +from app.core.errors import forbidden, not_found, unprocessable +from app.core.timeutil import utcnow +from app.media.storage import asset_path, display_filename, sha256, sniff, write_bytes + + +def _ctx(value) -> Ctx | None: + if value is None: + return None + if isinstance(value, Ctx): + return value + return Ctx(value.kind, value.id) + + +def require_container_edit(conn, actor: UUID, target: Ctx, rights_context: Ctx | None) -> None: + if target.kind == "case": + if rights_context is not None and (rights_context.kind != "case" or rights_context.id != target.id): + raise unprocessable("Der Handlungskontext passt nicht zur Akte.") + require_case(conn, actor, target.id, "edit") + return + if rights_context is None or (rights_context.kind == "matter" and rights_context.id == target.id): + require_matter(conn, actor, target.id, None, "edit") + return + require_matter(conn, actor, target.id, rights_context, "edit") + + +def _placement(context: Ctx, placement: Ctx | None) -> tuple[Ctx, Ctx]: + target = placement or context + rights_context = None if placement is None and context.kind == "matter" else context + if placement is None and context.kind == "matter": + return target, None + if placement is not None and placement.kind == "matter" and context.kind == "case": + return placement, context + if placement is not None and placement == context: + return target, None if context.kind == "matter" else context + return target, context if context.kind == "case" or placement is not None else None + + +def create_case(conn, actor: UUID, scope_id: UUID, title: str, parent_case_id: UUID | None, rights_mode: str) -> dict: + title = title.strip() + if parent_case_id is None: + row = conn.execute( + """ + INSERT INTO cases ( + home_scope_id, owner_subject_id, created_by, title, rights_mode + ) + VALUES (%s, %s, %s, %s, 'explicit') + RETURNING * + """, + (scope_id, actor, actor, title), + ).fetchone() + else: + parent, _rights = require_case(conn, actor, parent_case_id, "edit") + if parent["parent_case_id"] is not None: + raise unprocessable("Im ersten Schnitt hat eine Unterakte keine weitere Unterakte.") + if rights_mode not in {"inherit_parent", "explicit"}: + raise unprocessable("Die Rechteart der Unterakte ist ungültig.") + row = conn.execute( + """ + INSERT INTO cases ( + home_scope_id, owner_subject_id, created_by, title, parent_case_id, rights_mode + ) + VALUES (%s, %s, %s, %s, %s, %s) + RETURNING * + """, + (parent["home_scope_id"], actor, actor, title, parent["id"], rights_mode), + ).fetchone() + audit(conn, actor, row["home_scope_id"], "case_created", "case", row["id"]) + return row + + +def patch_case(conn, actor: UUID, case_id: UUID, expected: int, title: str | None, status: str | None) -> dict: + case, rights = require_case(conn, actor, case_id, "edit") + if title is None and status is None: + raise unprocessable("Es fehlt eine Änderung.") + if not rights.edit: + raise forbidden() + version = bump_version(conn, "cases", case_id, expected) + if title is not None: + conn.execute("UPDATE cases SET title = %s WHERE id = %s", (title.strip(), case_id)) + if status is not None: + conn.execute("UPDATE cases SET record_status = %s WHERE id = %s", (status, case_id)) + updated = get_case(conn, case_id) + updated["version"] = version + return updated + + +def create_chapter(conn, actor: UUID, kind: str, container_id: UUID, title: str, position: int | None, context: Ctx | None) -> dict: + if kind == "case": + container, _rights = require_case(conn, actor, container_id, "edit") + else: + container, _rights = require_matter(conn, actor, container_id, context, "edit") + if position is None: + column = "case_id" if kind == "case" else "matter_id" + current = conn.execute( + f"SELECT COALESCE(MAX(position), -1) + 1 AS pos FROM chapters WHERE {column} = %s", + (container_id,), + ).fetchone() + position = int(current["pos"]) + if kind == "case": + row = conn.execute( + """ + INSERT INTO chapters (home_scope_id, case_id, title, position) + VALUES (%s, %s, %s, %s) RETURNING * + """, + (container["home_scope_id"], container_id, title.strip(), position), + ).fetchone() + else: + row = conn.execute( + """ + INSERT INTO chapters (home_scope_id, matter_id, title, position) + VALUES (%s, %s, %s, %s) RETURNING * + """, + (container["home_scope_id"], container_id, title.strip(), position), + ).fetchone() + audit(conn, actor, container["home_scope_id"], "chapter_created", kind, container_id, context) + return row + + +def create_matter(conn, actor: UUID, scope_id: UUID, title: str, parent_matter_id: UUID | None, context: Ctx | None) -> dict: + title = title.strip() + if parent_matter_id is None: + row = conn.execute( + """ + INSERT INTO matters (home_scope_id, owner_subject_id, created_by, title) + VALUES (%s, %s, %s, %s) RETURNING * + """, + (scope_id, actor, actor, title), + ).fetchone() + else: + parent, _rights = require_matter(conn, actor, parent_matter_id, context, "edit") + if parent["parent_matter_id"] is not None: + raise unprocessable("Im ersten Schnitt hat ein Teilvorgang keinen weiteren Teilvorgang.") + row = conn.execute( + """ + INSERT INTO matters ( + home_scope_id, owner_subject_id, created_by, title, parent_matter_id + ) + VALUES (%s, %s, %s, %s, %s) RETURNING * + """, + (parent["home_scope_id"], actor, actor, title, parent["id"]), + ).fetchone() + audit(conn, actor, row["home_scope_id"], "matter_created", "matter", row["id"], context) + return row + + +def patch_matter(conn, actor: UUID, matter_id: UUID, expected: int, title: str | None, status: str | None, context: Ctx | None) -> dict: + if title is None and status is None: + raise unprocessable("Es fehlt eine Änderung.") + _matter, _rights = require_matter(conn, actor, matter_id, context, "edit") + bump_version(conn, "matters", matter_id, expected) + if title is not None: + conn.execute("UPDATE matters SET title = %s WHERE id = %s", (title.strip(), matter_id)) + if status is not None: + conn.execute("UPDATE matters SET record_status = %s WHERE id = %s", (status, matter_id)) + return get_matter(conn, matter_id) + + +def link_matter_to_case(conn, actor: UUID, matter_id: UUID, case_id: UUID, matter_context: Ctx | None) -> dict: + matter, matter_right = require_matter(conn, actor, matter_id, matter_context, "share") + case, _case_right = require_case(conn, actor, case_id, "edit") + if not matter_right.share: + raise forbidden() + try: + link = conn.execute( + """ + INSERT INTO matter_case_links (matter_id, case_id, created_by) + VALUES (%s, %s, %s) RETURNING * + """, + (matter["id"], case["id"], actor), + ).fetchone() + except Exception as exc: + if exc.__class__.__name__ == "UniqueViolation": + raise unprocessable("Der Vorgang ist dieser Akte bereits zugeordnet.") from exc + raise + block_unsharable_matter_elements(conn, actor, link["id"], matter) + audit(conn, actor, case["home_scope_id"], "matter_linked", "matter", matter["id"], Ctx("case", case["id"])) + return link + + +def unlink_matter_case(conn, actor: UUID, link_id: UUID) -> None: + link = conn.execute("SELECT * FROM matter_case_links WHERE id = %s", (link_id,)).fetchone() + if link is None: + raise not_found() + matter_direct = matter_rights(conn, actor, get_matter(conn, link["matter_id"]), None) + case_right = case_rights(conn, actor, get_case(conn, link["case_id"])) + if not case_right.read and not matter_direct.read: + raise not_found() + if not case_right.edit and not matter_direct.share: + raise forbidden() + conn.execute("DELETE FROM matter_case_links WHERE id = %s", (link_id,)) + audit(conn, actor, None, "matter_unlinked", "matter", link["matter_id"], Ctx("case", link["case_id"])) + + +def create_cross_link(conn, actor: UUID, source_id: UUID, target_id: UUID, source_context: Ctx | None, target_context: Ctx) -> dict: + if source_id == target_id: + raise unprocessable("Ein Vorgang kann nicht auf sich selbst verweisen.") + source, _rights = require_matter(conn, actor, source_id, source_context, "edit") + target, target_rights = require_matter(conn, actor, target_id, target_context, "read") + if not target_rights.read: + raise not_found() + try: + row = conn.execute( + """ + INSERT INTO matter_cross_links (from_matter_id, to_matter_id, created_by) + VALUES (%s, %s, %s) RETURNING * + """, + (source["id"], target["id"], actor), + ).fetchone() + except Exception as exc: + if exc.__class__.__name__ == "UniqueViolation": + raise unprocessable("Dieser Querverweis besteht bereits.") from exc + raise + audit(conn, actor, source["home_scope_id"], "cross_linked", "matter", source["id"], source_context) + return row + + +def delete_cross_link(conn, actor: UUID, link_id: UUID, source_context: Ctx | None) -> None: + link = conn.execute("SELECT * FROM matter_cross_links WHERE id = %s", (link_id,)).fetchone() + if link is None: + raise not_found() + require_matter(conn, actor, link["from_matter_id"], source_context, "edit") + conn.execute("DELETE FROM matter_cross_links WHERE id = %s", (link_id,)) + + +def _actor_rights_for(conn, actor: UUID, kind: str, resource_id: UUID, context: Ctx | None) -> Rights: + if kind == "case": + _row, rights = require_case(conn, actor, resource_id, "read") + return rights + if kind == "matter": + _row, rights = require_matter(conn, actor, resource_id, context, "read") + return rights + if kind == "element": + _row, rights = require_element(conn, actor, resource_id, context, "read") + return rights + if kind == "task": + task = get_task(conn, resource_id) + if task is None: + raise not_found() + rights = task_rights(conn, actor, task, context) + if not rights.read: + raise not_found() + return rights + deadline = get_deadline(conn, resource_id) + if deadline is None: + raise not_found() + rights = deadline_rights(conn, actor, deadline, context) + if not rights.read: + raise not_found() + return rights + + +def grant_access(conn, actor: UUID, kind: str, resource_id: UUID, grantee_id: UUID, can_read: bool, can_edit: bool, can_share: bool, context: Ctx | None) -> dict: + if grantee_id == actor: + raise unprocessable("Die eigene Berechtigung wird nicht als Freigabe gespeichert.") + if not can_read: + raise unprocessable("Eine Freigabe braucht mindestens Lesen.") + if kind == "case": + resource = get_case(conn, resource_id) + rights = case_rights(conn, actor, resource) if resource else Rights() + elif kind == "matter": + resource = get_matter(conn, resource_id) + rights = matter_rights(conn, actor, resource, context) if resource else Rights() + else: + raise unprocessable("Freigaben werden an der Akte oder am Vorgang erteilt.") + if resource is None or not rights.read: + raise not_found() + owner = resource["owner_subject_id"] == actor + if not owner and not rights.share: + raise forbidden() + if can_edit and not (owner or rights.edit): + raise forbidden() + if can_share and not (owner or rights.share): + raise forbidden() + account = conn.execute( + "SELECT id FROM auth_accounts WHERE id = %s AND status = 'active'", + (grantee_id,), + ).fetchone() + if account is None: + raise not_found() + existing = conn.execute( + """ + SELECT id FROM access_grants + WHERE NOT is_exception AND grantee_subject_id = %s + AND resource_kind = %s AND resource_id = %s AND context_kind IS NULL + """, + (grantee_id, kind, resource_id), + ).fetchone() + if existing is None: + row = conn.execute( + """ + INSERT INTO access_grants ( + grantee_subject_id, resource_kind, resource_id, + can_read, can_edit, can_share, can_delete, is_exception, created_by + ) + VALUES (%s, %s, %s, %s, %s, %s, false, false, %s) + RETURNING * + """, + (grantee_id, kind, resource_id, can_read, can_edit, can_share, actor), + ).fetchone() + else: + row = conn.execute( + """ + UPDATE access_grants + SET can_read = %s, can_edit = %s, can_share = %s + WHERE id = %s + RETURNING * + """, + (can_read, can_edit, can_share, existing["id"]), + ).fetchone() + audit(conn, actor, resource["home_scope_id"], "grant_created", kind, resource_id, context) + return row + + +def revoke_grant(conn, actor: UUID, grant_id: UUID) -> None: + grant = conn.execute("SELECT * FROM access_grants WHERE id = %s AND NOT is_exception", (grant_id,)).fetchone() + if grant is None: + raise not_found() + kind = grant["resource_kind"] + if kind == "case": + resource = get_case(conn, grant["resource_id"]) + rights = case_rights(conn, actor, resource) if resource else Rights() + elif kind == "matter": + resource = get_matter(conn, grant["resource_id"]) + rights = matter_rights(conn, actor, resource, None) if resource else Rights() + elif kind == "task": + resource = get_task(conn, grant["resource_id"]) + rights = task_rights(conn, actor, resource, None) if resource else Rights() + elif kind == "deadline": + resource = get_deadline(conn, grant["resource_id"]) + rights = deadline_rights(conn, actor, resource, None) if resource else Rights() + else: + resource = get_element(conn, grant["resource_id"]) + rights = element_rights(conn, actor, resource, None) if resource else Rights() + if resource is None or not rights.read: + raise not_found() + if resource["owner_subject_id"] != actor and not rights.share: + raise forbidden() + conn.execute("DELETE FROM access_grants WHERE id = %s", (grant_id,)) + audit(conn, actor, resource["home_scope_id"], "grant_revoked", kind, grant["resource_id"]) + + +def set_exception(conn, actor: UUID, kind: str, resource_id: UUID, context: Ctx, remove_read: bool, remove_edit: bool, remove_share: bool) -> None: + if kind == "element": + resource = get_element(conn, resource_id) + elif kind == "matter": + resource = get_matter(conn, resource_id) + elif kind == "task": + resource = get_task(conn, resource_id) + else: + resource = get_deadline(conn, resource_id) + if resource is None: + raise not_found() + if resource["owner_subject_id"] != actor: + raise forbidden() + conn.execute( + """ + DELETE FROM access_grants + WHERE is_exception AND grantee_subject_id IS NULL + AND resource_kind = %s AND resource_id = %s + AND context_kind = %s AND context_id = %s + """, + (kind, resource_id, context.kind, context.id), + ) + if remove_read or remove_edit or remove_share: + conn.execute( + """ + INSERT INTO access_grants ( + grantee_subject_id, resource_kind, resource_id, context_kind, context_id, + can_read, can_edit, can_share, can_delete, is_exception, created_by + ) + VALUES (NULL, %s, %s, %s, %s, %s, %s, %s, false, true, %s) + """, + (kind, resource_id, context.kind, context.id, remove_read, remove_edit, remove_share, actor), + ) + + +def _new_element(conn, actor: UUID, scope_id: UUID, title: str, kind: str) -> dict: + return conn.execute( + """ + INSERT INTO elements (home_scope_id, owner_subject_id, created_by, title, kind) + VALUES (%s, %s, %s, %s, %s) RETURNING * + """, + (scope_id, actor, actor, title.strip(), kind), + ).fetchone() + + +def record_dates(conn, actor: UUID, scope_id: UUID, element_id: UUID, context: Ctx, document_on: date | None, sent_on: date | None, received_on: date | None) -> None: + conn.execute( + """ + INSERT INTO correspondence_dates (element_id, document_on, sent_on, received_on) + VALUES (%s, %s, %s, %s) + ON CONFLICT (element_id) DO UPDATE + SET document_on = EXCLUDED.document_on, + sent_on = EXCLUDED.sent_on, + received_on = EXCLUDED.received_on + """, + (element_id, document_on, sent_on, received_on), + ) + if document_on is not None: + audit(conn, actor, scope_id, "correspondence_document", "element", element_id, context, document_on) + if sent_on is not None: + audit(conn, actor, scope_id, "correspondence_sent", "element", element_id, context, sent_on) + if received_on is not None: + audit(conn, actor, scope_id, "correspondence_received", "element", element_id, context, received_on) + audit(conn, actor, scope_id, "correspondence_recorded", "element", element_id, context) + + +def create_note(conn, actor: UUID, scope_id: UUID, title: str, document: dict, context: Ctx, placement: Ctx | None, chapter_id: UUID | None) -> dict: + document = clean_document(document) + target, rights_context = _placement(context, placement) + require_container_edit(conn, actor, target, rights_context) + element = _new_element(conn, actor, scope_id, title, "note") + conn.execute( + "INSERT INTO note_bodies (element_id, document_json, version) VALUES (%s, %s, 1)", + (element["id"], Json(document)), + ) + binding = insert_binding(conn, element["id"], target.kind, target.id, chapter_id, actor) + audit(conn, actor, scope_id, "note_created", "element", element["id"], rights_context or target) + return {"element": element, "binding": binding, "document": document} + + +def update_note(conn, actor: UUID, element_id: UUID, expected: int, document: dict, context: Ctx | None) -> dict: + document = clean_document(document) + element, rights = require_element(conn, actor, element_id, context, "edit") + if element["kind"] != "note": + raise not_found() + if not rights.edit: + raise forbidden() + version = bump_version(conn, "elements", element_id, expected) + conn.execute( + "UPDATE note_bodies SET document_json = %s, version = %s, updated_at = now() WHERE element_id = %s", + (Json(document), version, element_id), + ) + audit(conn, actor, element["home_scope_id"], "note_updated", "element", element_id, context) + element = get_element(conn, element_id) + return {"element": element, "document": document} + + +def bind_element(conn, actor: UUID, element_id: UUID, source: Ctx, target: Ctx, target_context: Ctx | None, chapter_id: UUID | None) -> dict: + _element, source_rights = require_element(conn, actor, element_id, source, "share") + if not source_rights.share: + raise forbidden() + require_container_edit(conn, actor, target, target_context) + binding = insert_binding(conn, element_id, target.kind, target.id, chapter_id, actor) + audit(conn, actor, None, "binding_created", "element", element_id, target_context or target) + return binding + + +def detach_binding(conn, actor: UUID, binding_id: UUID, context: Ctx | None) -> None: + binding = conn.execute("SELECT * FROM bindings WHERE id = %s", (binding_id,)).fetchone() + if binding is None: + raise not_found() + element = get_element(conn, binding["element_id"]) + if element is None: + raise not_found() + action_context = context or Ctx(binding["context_kind"], binding["context_id"]) + _element, rights = require_element(conn, actor, element["id"], action_context, "edit") + if binding["context_kind"] != action_context.kind and not ( + action_context.kind == "case" and binding["context_kind"] == "matter" + ): + raise not_found() + if not rights.edit: + raise forbidden() + conn.execute("DELETE FROM bindings WHERE id = %s", (binding_id,)) + audit(conn, actor, element["home_scope_id"], "binding_removed", "element", element["id"], action_context) + + +def add_annotation(conn, actor: UUID, binding_id: UUID, body: str, context: Ctx | None) -> dict: + binding = conn.execute("SELECT * FROM bindings WHERE id = %s", (binding_id,)).fetchone() + if binding is None: + raise not_found() + element = get_element(conn, binding["element_id"]) + if element is None: + raise not_found() + action_context = context or Ctx(binding["context_kind"], binding["context_id"]) + _element, rights = require_element(conn, actor, element["id"], action_context, "edit") + if not rights.edit: + raise forbidden() + if binding["context_id"] != action_context.id and not ( + action_context.kind == "case" and binding["context_kind"] == "matter" + ): + raise not_found() + row = conn.execute( + """ + INSERT INTO context_annotations (binding_id, body, author_subject_id) + VALUES (%s, %s, %s) RETURNING * + """, + (binding_id, body.strip(), actor), + ).fetchone() + audit(conn, actor, element["home_scope_id"], "annotation_created", "element", element["id"], action_context) + return row + + +def create_external(conn, actor: UUID, scope_id: UUID, title: str, source: str, external_id: str, context: Ctx, placement: Ctx | None, chapter_id: UUID | None, document_on, sent_on, received_on) -> dict: + target, rights_context = _placement(context, placement) + require_container_edit(conn, actor, target, rights_context) + element = _new_element(conn, actor, scope_id, title, "external_ref") + conn.execute( + "INSERT INTO external_references (element_id, source, external_id) VALUES (%s, %s, %s)", + (element["id"], source, external_id.strip()), + ) + binding = insert_binding(conn, element["id"], target.kind, target.id, chapter_id, actor) + record_dates(conn, actor, scope_id, element["id"], rights_context or target, document_on, sent_on, received_on) + audit(conn, actor, scope_id, "external_ref_added", "element", element["id"], rights_context or target) + return element | {"binding_id": binding["id"]} + + +def create_file(conn, actor: UUID, scope_id: UUID, title: str, filename: str, data: bytes, context: Ctx, placement: Ctx | None, chapter_id: UUID | None, document_on, sent_on, received_on, media_root: str, max_bytes: int, rollback_files: list[Path]) -> dict: + if not data or len(data) > max_bytes: + raise unprocessable("Die Datei ist leer oder zu groß.") + content_type = sniff(data) + target, rights_context = _placement(context, placement) + require_container_edit(conn, actor, target, rights_context) + element = _new_element(conn, actor, scope_id, title, "file") + asset_id = uuid4() + path = asset_path(media_root, asset_id) + write_bytes(path, data) + rollback_files.append(path) + conn.execute( + """ + INSERT INTO media_assets ( + id, element_id, owner_subject_id, home_scope_id, original_filename, + content_type, byte_size, sha256, status + ) + VALUES (%s, %s, %s, %s, %s, %s, %s, %s, 'active') + """, + ( + asset_id, + element["id"], + actor, + scope_id, + display_filename(filename), + content_type, + len(data), + sha256(data), + ), + ) + conn.execute( + """ + INSERT INTO media_operations (element_id, asset_id, phase, status) + VALUES (%s, %s, 'active', 'committed') + """, + (element["id"], asset_id), + ) + binding = insert_binding(conn, element["id"], target.kind, target.id, chapter_id, actor) + record_dates(conn, actor, scope_id, element["id"], rights_context or target, document_on, sent_on, received_on) + audit(conn, actor, scope_id, "file_added", "element", element["id"], rights_context or target) + return element | {"binding_id": binding["id"], "asset_id": asset_id} + + +def delete_element(conn, actor: UUID, element_id: UUID, expected: int, media_root: str, delete_after: list[Path]) -> None: + element = get_element(conn, element_id) + if element is None or element["owner_subject_id"] != actor: + raise not_found() + bump_version(conn, "elements", element_id, expected) + asset = conn.execute("SELECT * FROM media_assets WHERE element_id = %s", (element_id,)).fetchone() + conn.execute("DELETE FROM bindings WHERE element_id = %s", (element_id,)) + conn.execute( + "UPDATE elements SET deleted_at = now(), updated_at = now() WHERE id = %s", + (element_id,), + ) + if asset is not None and asset["status"] == "active": + conn.execute("UPDATE media_assets SET status = 'purging' WHERE id = %s", (asset["id"],)) + delete_after.append(asset_path(media_root, asset["id"])) + conn.execute("UPDATE media_assets SET status = 'purged' WHERE id = %s", (asset["id"],)) + audit(conn, actor, element["home_scope_id"], "element_deleted", "element", element_id) + + +def create_task(conn, actor: UUID, scope_id: UUID, title: str, due_on: date | None, matter_id: UUID | None, context: Ctx | None) -> dict: + if matter_id is not None: + require_matter(conn, actor, matter_id, context, "edit") + row = conn.execute( + """ + INSERT INTO tasks ( + home_scope_id, owner_subject_id, created_by, title, matter_id, due_on + ) + VALUES (%s, %s, %s, %s, %s, %s) RETURNING * + """, + (scope_id, actor, actor, title.strip(), matter_id, due_on), + ).fetchone() + audit(conn, actor, scope_id, "task_created", "task", row["id"], context) + return row + + +def patch_task(conn, actor: UUID, task_id: UUID, expected: int, title: str | None, due_on: date | None, clear_due: bool, status: str | None, context: Ctx | None) -> dict: + task = get_task(conn, task_id) + if task is None: + raise not_found() + rights = task_rights(conn, actor, task, context) + if not rights.read: + raise not_found() + structural = title is not None or due_on is not None or clear_due + if structural and not rights.edit: + raise forbidden() + if status is not None and not can_change_status(actor, task, rights): + raise forbidden() + if title is None and due_on is None and not clear_due and status is None: + raise unprocessable("Es fehlt eine Änderung.") + bump_version(conn, "tasks", task_id, expected) + if title is not None: + conn.execute("UPDATE tasks SET title = %s WHERE id = %s", (title.strip(), task_id)) + if clear_due: + conn.execute("UPDATE tasks SET due_on = NULL WHERE id = %s", (task_id,)) + elif due_on is not None: + conn.execute("UPDATE tasks SET due_on = %s WHERE id = %s", (due_on, task_id)) + if status is not None: + conn.execute("UPDATE tasks SET task_status = %s WHERE id = %s", (status, task_id)) + audit( + conn, + actor, + task["home_scope_id"], + "task_done" if status == "done" else "task_reopened", + "task", + task_id, + context, + ) + return get_task(conn, task_id) + + +def assign_task(conn, actor: UUID, task_id: UUID, assignee_id: UUID | None, context: Ctx | None) -> dict: + task = get_task(conn, task_id) + if task is None: + raise not_found() + rights = task_rights(conn, actor, task, context) + if not rights.read: + raise not_found() + if task["owner_subject_id"] != actor and not rights.share: + raise forbidden() + if assignee_id is not None: + account = conn.execute( + "SELECT id FROM auth_accounts WHERE id = %s AND status = 'active'", + (assignee_id,), + ).fetchone() + if account is None: + raise not_found() + existing = conn.execute( + """ + SELECT * FROM access_grants + WHERE NOT is_exception AND grantee_subject_id = %s + AND resource_kind = 'task' AND resource_id = %s AND context_kind IS NULL + """, + (assignee_id, task_id), + ).fetchone() + if existing is None: + conn.execute( + """ + INSERT INTO access_grants ( + grantee_subject_id, resource_kind, resource_id, + can_read, can_edit, can_share, can_delete, is_exception, created_by + ) + VALUES (%s, 'task', %s, true, false, false, false, false, %s) + """, + (assignee_id, task_id, actor), + ) + elif not existing["can_read"]: + conn.execute("UPDATE access_grants SET can_read = true WHERE id = %s", (existing["id"],)) + elif task["assignee_subject_id"] is not None: + conn.execute( + """ + DELETE FROM access_grants + WHERE NOT is_exception AND grantee_subject_id = %s + AND resource_kind = 'task' AND resource_id = %s + AND context_kind IS NULL AND can_read AND NOT can_edit AND NOT can_share AND NOT can_delete + """, + (task["assignee_subject_id"], task_id), + ) + conn.execute( + "UPDATE tasks SET assignee_subject_id = %s, updated_at = now() WHERE id = %s", + (assignee_id, task_id), + ) + return get_task(conn, task_id) + + +def create_deadline(conn, actor: UUID, scope_id: UUID, title: str, due_on: date, matter_id: UUID | None, context: Ctx | None) -> dict: + if matter_id is not None: + require_matter(conn, actor, matter_id, context, "edit") + row = conn.execute( + """ + INSERT INTO deadlines ( + home_scope_id, owner_subject_id, created_by, title, matter_id, due_on + ) + VALUES (%s, %s, %s, %s, %s, %s) RETURNING * + """, + (scope_id, actor, actor, title.strip(), matter_id, due_on), + ).fetchone() + audit(conn, actor, scope_id, "deadline_created", "deadline", row["id"], context) + return row + + +def patch_deadline(conn, actor: UUID, deadline_id: UUID, expected: int, title: str | None, due_on: date | None, context: Ctx | None) -> dict: + deadline = get_deadline(conn, deadline_id) + if deadline is None: + raise not_found() + rights = deadline_rights(conn, actor, deadline, context) + if not rights.read: + raise not_found() + if not rights.edit: + raise forbidden() + if title is None and due_on is None: + raise unprocessable("Es fehlt eine Änderung.") + bump_version(conn, "deadlines", deadline_id, expected) + if title is not None: + conn.execute("UPDATE deadlines SET title = %s WHERE id = %s", (title.strip(), deadline_id)) + if due_on is not None: + conn.execute("UPDATE deadlines SET due_on = %s WHERE id = %s", (due_on, deadline_id)) + return get_deadline(conn, deadline_id) + + +def fulfill_deadline(conn, actor: UUID, deadline_id: UUID, expected: int, context: Ctx | None) -> dict: + deadline = get_deadline(conn, deadline_id) + if deadline is None: + raise not_found() + rights = deadline_rights(conn, actor, deadline, context) + if not rights.read: + raise not_found() + if not can_change_status(actor, deadline, rights): + raise forbidden() + bump_version(conn, "deadlines", deadline_id, expected) + conn.execute( + """ + UPDATE deadlines + SET deadline_status = 'fulfilled', fulfilled_at = %s, updated_at = now() + WHERE id = %s + """, + (utcnow(), deadline_id), + ) + audit(conn, actor, deadline["home_scope_id"], "deadline_fulfilled", "deadline", deadline_id, context) + return get_deadline(conn, deadline_id) + + +def link_task_deadline(conn, actor: UUID, task_id: UUID, deadline_id: UUID, context: Ctx | None) -> None: + task = get_task(conn, task_id) + deadline = get_deadline(conn, deadline_id) + if task is None or deadline is None: + raise not_found() + task_right = task_rights(conn, actor, task, context) + deadline_right = deadline_rights(conn, actor, deadline, context) + if not task_right.read or not deadline_right.read: + raise not_found() + if not task_right.edit: + raise forbidden() + conn.execute( + """ + INSERT INTO task_deadline_links (task_id, deadline_id, created_by) + VALUES (%s, %s, %s) + ON CONFLICT DO NOTHING + """, + (task_id, deadline_id, actor), + ) diff --git a/backend/app/present.py b/backend/app/present.py new file mode 100644 index 0000000..23cff0a --- /dev/null +++ b/backend/app/present.py @@ -0,0 +1,490 @@ +"""Response shapes. Hidden objects are omitted, not counted and not titled.""" + +from __future__ import annotations + +from uuid import UUID + +from app.access.policy import ( + Ctx, + case_rights, + deadline_rights, + display_name, + element_rights, + get_case, + get_element, + get_matter, + matter_rights, + matter_title_if_readable, + readable_matter_contexts, + room_name, + task_rights, + visible_bindings_for_element, +) +from app.access.policy import SHARED_NOTICE +from app.core.timeutil import dump_date, dump_dt + + +def rights_dict(rights) -> dict: + return rights.as_dict() + + +def _chapters(conn, kind: str, container_id: UUID) -> list[dict]: + column = "case_id" if kind == "case" else "matter_id" + rows = conn.execute( + f"SELECT id, title, position FROM chapters WHERE {column} = %s ORDER BY position, created_at", + (container_id,), + ).fetchall() + return [{"id": str(row["id"]), "title": row["title"], "position": row["position"]} for row in rows] + + +def _annotations(conn, binding_id: UUID) -> list[dict]: + rows = conn.execute( + """ + SELECT a.id, a.body, a.created_at, p.display_name + FROM context_annotations a + JOIN auth_accounts p ON p.id = a.author_subject_id + WHERE a.binding_id = %s + ORDER BY a.created_at, a.id + """, + (binding_id,), + ).fetchall() + return [ + { + "id": str(row["id"]), + "body": row["body"], + "author_display_name": row["display_name"], + "created_at": dump_dt(row["created_at"]), + } + for row in rows + ] + + +def _dates(conn, element: dict) -> dict: + row = conn.execute( + "SELECT document_on, sent_on, received_on FROM correspondence_dates WHERE element_id = %s", + (element["id"],), + ).fetchone() + return { + "document_on": dump_date(row["document_on"]) if row else None, + "sent_on": dump_date(row["sent_on"]) if row else None, + "received_on": dump_date(row["received_on"]) if row else None, + "recorded_at": dump_dt(element["created_at"]), + } + + +def _element_body(conn, element: dict) -> dict: + payload = { + "id": str(element["id"]), + "kind": element["kind"], + "title": element["title"], + "version": element["version"], + "owner_subject_id": str(element["owner_subject_id"]), + "dates": _dates(conn, element), + } + if element["kind"] == "note": + body = conn.execute( + "SELECT document_json FROM note_bodies WHERE element_id = %s", + (element["id"],), + ).fetchone() + payload["document"] = body["document_json"] if body else {"version": 1, "blocks": []} + elif element["kind"] == "file": + asset = conn.execute( + """ + SELECT original_filename, content_type, byte_size, status + FROM media_assets WHERE element_id = %s + """, + (element["id"],), + ).fetchone() + if asset is not None: + payload["file"] = { + "filename": asset["original_filename"], + "content_type": asset["content_type"], + "byte_size": asset["byte_size"], + "status": asset["status"], + } + elif element["kind"] == "external_ref": + ref = conn.execute( + "SELECT source, external_id FROM external_references WHERE element_id = %s", + (element["id"],), + ).fetchone() + if ref is not None: + payload["external"] = {"source": ref["source"], "external_id": ref["external_id"]} + return payload + + +def _exception(conn, kind: str, resource_id: UUID, context: Ctx | None) -> dict | None: + if context is None: + return None + row = conn.execute( + """ + SELECT can_read, can_edit, can_share + FROM access_grants + WHERE is_exception AND grantee_subject_id IS NULL + AND resource_kind = %s AND resource_id = %s + AND context_kind = %s AND context_id = %s + """, + (kind, resource_id, context.kind, context.id), + ).fetchone() + if row is None: + return {"remove_read": False, "remove_edit": False, "remove_share": False} + return {"remove_read": row["can_read"], "remove_edit": row["can_edit"], "remove_share": row["can_share"]} + + +def binding_payload(conn, actor: UUID, binding: dict, context: Ctx) -> dict | None: + element = get_element(conn, binding["element_id"]) + if element is None: + return None + rights = element_rights(conn, actor, element, context) + if not rights.read: + return None + payload = { + "id": str(binding["id"]), + "position": binding["position"], + "chapter_id": str(binding["chapter_id"]) if binding["chapter_id"] else None, + "rights": rights.as_dict(), + "annotations": _annotations(conn, binding["id"]), + "element": _element_body(conn, element), + } + if element["owner_subject_id"] == actor: + payload["exception"] = _exception(conn, "element", element["id"], context) + return payload + + +def _grants(conn, kind: str, resource_id: UUID) -> list[dict]: + rows = conn.execute( + """ + SELECT g.id, g.grantee_subject_id, g.can_read, g.can_edit, g.can_share, a.email, a.display_name + FROM access_grants g + JOIN auth_accounts a ON a.id = g.grantee_subject_id + WHERE NOT g.is_exception AND g.resource_kind = %s AND g.resource_id = %s AND g.context_kind IS NULL + ORDER BY a.display_name, g.id + """, + (kind, resource_id), + ).fetchall() + return [ + { + "id": str(row["id"]), + "grantee_subject_id": str(row["grantee_subject_id"]), + "email": row["email"], + "display_name": row["display_name"], + "can_read": row["can_read"], + "can_edit": row["can_edit"], + "can_share": row["can_share"], + } + for row in rows + ] + + +def case_summary(case: dict, rights) -> dict: + return { + "id": str(case["id"]), + "title": case["title"], + "status": case["record_status"], + "version": case["version"], + "rights_mode": case["rights_mode"], + "parent_case_id": str(case["parent_case_id"]) if case["parent_case_id"] else None, + "home_scope_id": str(case["home_scope_id"]), + "rights": rights.as_dict(), + } + + +def case_detail(conn, actor: UUID, case: dict, rights) -> dict: + payload = case_summary(case, rights) + payload["home_scope_name"] = room_name(conn, case["home_scope_id"]) + payload["is_owner"] = case["owner_subject_id"] == actor + payload["chapters"] = _chapters(conn, "case", case["id"]) + subcases = [] + for row in conn.execute( + """ + SELECT * FROM cases + WHERE parent_case_id = %s AND deleted_at IS NULL + ORDER BY title, id + """, + (case["id"],), + ).fetchall(): + child_rights = case_rights(conn, actor, row) + if child_rights.read: + subcases.append(case_summary(row, child_rights)) + payload["subcases"] = subcases + matters = [] + for link in conn.execute( + """ + SELECT l.id AS link_id, m.* + FROM matter_case_links l + JOIN matters m ON m.id = l.matter_id + WHERE l.case_id = %s AND m.deleted_at IS NULL + ORDER BY m.title, m.id + """, + (case["id"],), + ).fetchall(): + matter_right = matter_rights(conn, actor, link, Ctx("case", case["id"])) + if not matter_right.read: + continue + matters.append( + { + "id": str(link["id"]), + "link_id": str(link["link_id"]), + "title": link["title"], + "status": link["record_status"], + } + ) + payload["matters"] = matters + context = Ctx("case", case["id"]) + bindings = [] + for binding in conn.execute( + """ + SELECT * FROM bindings + WHERE context_kind = 'case' AND context_id = %s + ORDER BY position, created_at + """, + (case["id"],), + ).fetchall(): + item = binding_payload(conn, actor, binding, context) + if item is not None: + bindings.append(item) + payload["bindings"] = bindings + if rights.share or case["owner_subject_id"] == actor: + payload["grants"] = _grants(conn, "case", case["id"]) + return payload + + +def matter_contexts(conn, actor: UUID, matter: dict) -> list[dict]: + contexts = [] + for item in readable_matter_contexts(conn, actor, matter): + kind = "direct" if item["kind"] == "matter" and item["id"] == str(matter["id"]) else item["kind"] + contexts.append({"kind": kind, "id": item["id"], "title": item["title"]}) + return contexts + + +def matter_summary(conn, actor: UUID, matter: dict) -> dict: + return { + "id": str(matter["id"]), + "title": matter["title"], + "status": matter["record_status"], + "version": matter["version"], + "parent_matter_id": str(matter["parent_matter_id"]) if matter["parent_matter_id"] else None, + "home_scope_id": str(matter["home_scope_id"]), + "contexts": matter_contexts(conn, actor, matter), + } + + +def _page_context(matter_id: UUID, context: Ctx | None) -> Ctx: + if context is None: + return Ctx("matter", matter_id) + return context + + +def matter_detail(conn, actor: UUID, matter: dict, rights, context: Ctx | None) -> dict: + page = _page_context(matter["id"], context) + payload = { + "id": str(matter["id"]), + "title": matter["title"], + "status": matter["record_status"], + "version": matter["version"], + "parent_matter_id": str(matter["parent_matter_id"]) if matter["parent_matter_id"] else None, + "home_scope_id": str(matter["home_scope_id"]), + "home_scope_name": room_name(conn, matter["home_scope_id"]), + "is_owner": matter["owner_subject_id"] == actor, + "rights": rights.as_dict(), + "context": None if context is None else context.as_dict(), + "chapters": _chapters(conn, "matter", matter["id"]), + } + submatters = [] + for child in conn.execute( + "SELECT * FROM matters WHERE parent_matter_id = %s AND deleted_at IS NULL ORDER BY title, id", + (matter["id"],), + ).fetchall(): + child_rights = matter_rights(conn, actor, child, page) + if child_rights.read: + submatters.append({"id": str(child["id"]), "title": child["title"], "status": child["record_status"]}) + payload["submatters"] = submatters + case_links = [] + for link in conn.execute( + """ + SELECT l.id, l.case_id, c.title + FROM matter_case_links l + JOIN cases c ON c.id = l.case_id AND c.deleted_at IS NULL + WHERE l.matter_id = %s + ORDER BY c.title, c.id + """, + (matter["id"],), + ).fetchall(): + linked_case = get_case(conn, link["case_id"]) + if linked_case is not None and case_rights(conn, actor, linked_case).read: + case_links.append({"id": str(link["id"]), "case_id": str(link["case_id"]), "title": link["title"]}) + payload["case_links"] = case_links + crosses = [] + for link in conn.execute( + """ + SELECT l.id, l.to_matter_id + FROM matter_cross_links l + WHERE l.from_matter_id = %s + """, + (matter["id"],), + ).fetchall(): + title = matter_title_if_readable(conn, actor, link["to_matter_id"]) + if title is not None: + crosses.append({"id": str(link["id"]), "matter_id": str(link["to_matter_id"]), "title": title}) + payload["cross_links"] = crosses + bindings = [] + for binding in conn.execute( + """ + SELECT * FROM bindings + WHERE context_kind = 'matter' AND context_id = %s + ORDER BY position, created_at + """, + (matter["id"],), + ).fetchall(): + item = binding_payload(conn, actor, binding, page) + if item is not None: + bindings.append(item) + payload["bindings"] = bindings + payload["tasks"] = [] + for task in conn.execute( + """ + SELECT * FROM tasks + WHERE matter_id = %s AND deleted_at IS NULL + ORDER BY due_on NULLS LAST, created_at + """, + (matter["id"],), + ).fetchall(): + task_right = task_rights(conn, actor, task, context) + if task_right.read: + payload["tasks"].append(task_payload(conn, actor, task, task_right)) + payload["deadlines"] = [] + visible_deadlines = set() + for deadline in conn.execute( + """ + SELECT * FROM deadlines + WHERE matter_id = %s AND deleted_at IS NULL + ORDER BY due_on, created_at + """, + (matter["id"],), + ).fetchall(): + deadline_right = deadline_rights(conn, actor, deadline, context) + if deadline_right.read: + payload["deadlines"].append(deadline_payload(conn, actor, deadline)) + visible_deadlines.add(deadline["id"]) + visible_tasks = {UUID(item["id"]) for item in payload["tasks"]} + links = [] + if visible_tasks and visible_deadlines: + for link in conn.execute( + "SELECT task_id, deadline_id FROM task_deadline_links WHERE task_id = ANY(%s::uuid[])", + (list(visible_tasks),), + ).fetchall(): + if link["deadline_id"] in visible_deadlines: + links.append({"task_id": str(link["task_id"]), "deadline_id": str(link["deadline_id"])}) + payload["task_deadline_links"] = links + if rights.share or matter["owner_subject_id"] == actor: + payload["grants"] = _grants(conn, "matter", matter["id"]) + if matter["owner_subject_id"] == actor: + payload["exception"] = _exception(conn, "matter", matter["id"], context) + return payload + + +def task_payload(conn, actor: UUID, task: dict, rights=None) -> dict: + payload = { + "id": str(task["id"]), + "title": task["title"], + "status": task["task_status"], + "version": task["version"], + "due_on": dump_date(task["due_on"]), + "assignee_display_name": display_name(conn, task["assignee_subject_id"]), + } + if rights is not None: + payload["rights"] = rights.as_dict() + title = matter_title_if_readable(conn, actor, task["matter_id"]) + if title is not None and task["matter_id"] is not None: + payload["matter_id"] = str(task["matter_id"]) + payload["matter_title"] = title + action = _task_action_context(conn, actor, task) + if action is not None: + payload["action_context"] = action + return payload + + +def _task_action_context(conn, actor: UUID, task: dict) -> dict | None: + direct = task_rights(conn, actor, task, None) + if direct.read and (direct.edit or task["owner_subject_id"] == actor or task["assignee_subject_id"] == actor): + return None + if task["matter_id"] is None: + return None + matter = get_matter(conn, task["matter_id"]) + if matter is None: + return None + for item in readable_matter_contexts(conn, actor, matter): + if item["kind"] != "case": + continue + rights = task_rights(conn, actor, task, Ctx("case", UUID(item["id"]))) + if rights.edit or (rights.read and task["assignee_subject_id"] == actor): + return {"kind": "case", "id": item["id"]} + return None + + +def deadline_payload(conn, actor: UUID, deadline: dict) -> dict: + payload = { + "id": str(deadline["id"]), + "title": deadline["title"], + "status": deadline["deadline_status"], + "version": deadline["version"], + "due_on": dump_date(deadline["due_on"]), + "fulfilled_at": dump_dt(deadline["fulfilled_at"]), + "assignee_display_name": display_name(conn, deadline["assignee_subject_id"]), + } + title = matter_title_if_readable(conn, actor, deadline["matter_id"]) + if title is not None and deadline["matter_id"] is not None: + payload["matter_id"] = str(deadline["matter_id"]) + payload["matter_title"] = title + direct = deadline_rights(conn, actor, deadline, None) + if not (direct.read and (direct.edit or deadline["owner_subject_id"] == actor or deadline["assignee_subject_id"] == actor)): + if deadline["matter_id"] is not None: + matter = get_matter(conn, deadline["matter_id"]) + if matter is not None: + for item in readable_matter_contexts(conn, actor, matter): + if item["kind"] != "case": + continue + rights = deadline_rights(conn, actor, deadline, Ctx("case", UUID(item["id"]))) + if rights.edit or (rights.read and deadline["assignee_subject_id"] == actor): + payload["action_context"] = {"kind": "case", "id": item["id"]} + break + return payload + + +def note_update_payload(conn, actor: UUID, element: dict, document: dict) -> dict: + return { + "id": str(element["id"]), + "title": element["title"], + "version": element["version"], + "document": document, + "visible_bindings": visible_bindings_for_element(conn, actor, element), + "notice": SHARED_NOTICE, + } + + +LABELS = { + "case_created": "Akte angelegt", + "matter_created": "Vorgang angelegt", + "matter_linked": "Vorgang einer Akte zugeordnet", + "matter_unlinked": "Aktenzuordnung gelöst", + "cross_linked": "Querverweis erfasst", + "note_created": "Notiz angelegt", + "note_updated": "Gemeinsamer Notizinhalt geändert", + "annotation_created": "Kontextbezogene Anmerkung erfasst", + "file_added": "Datei hinzugefügt", + "external_ref_added": "Externe Referenz erfasst", + "binding_created": "Einbindung ergänzt", + "binding_removed": "Einbindung entfernt", + "element_deleted": "Element gelöscht", + "task_created": "Aufgabe angelegt", + "task_done": "Aufgabe erledigt", + "task_reopened": "Aufgabe wieder geöffnet", + "deadline_created": "Frist erfasst", + "deadline_fulfilled": "Frist erfüllt", + "grant_created": "Freigabe erteilt", + "grant_revoked": "Freigabe entzogen", + "correspondence_document": "Dokumentdatum", + "correspondence_sent": "Versand", + "correspondence_received": "Zugang", + "correspondence_recorded": "Erfassung", + "chapter_created": "Kapitel angelegt", +} diff --git a/backend/app/seed.py b/backend/app/seed.py new file mode 100644 index 0000000..99b2fd7 --- /dev/null +++ b/backend/app/seed.py @@ -0,0 +1,211 @@ +"""Synthetic development accounts and a rental matter. Never runs in production.""" + +from __future__ import annotations + +from datetime import date +from pathlib import Path + +import psycopg +from psycopg.rows import dict_row + +from app.access.policy import Ctx +from app.auth.accounts import create_account +from app.core.errors import not_found +from app.core.settings import Settings, get_settings +from app.ops import ( + add_annotation, + assign_task, + bind_element, + create_case, + create_chapter, + create_deadline, + create_external, + create_file, + create_matter, + create_note, + create_task, + grant_access, + link_matter_to_case, + link_task_deadline, +) + +ADA_EMAIL = "ada@example.test" +BEN_EMAIL = "ben@example.test" +ADA_PASSWORD = "Beispiel-Ada-2026" +BEN_PASSWORD = "Beispiel-Ben-2026" + +SAMPLE_PDF = b"""%PDF-1.1 +1 0 obj<>endobj +2 0 obj<>endobj +3 0 obj<>endobj +4 0 obj<>stream +BT /F1 12 Tf 40 90 Td (Mietschreiben Beispiel) Tj ET +endstream +endobj +trailer<> +%%EOF +""" + + +def demo_public(settings: Settings) -> dict: + if settings.tsumugu_env != "development" or not settings.seed_demo: + raise not_found() + return { + "accounts": [ + {"email": ADA_EMAIL, "password": ADA_PASSWORD, "display_name": "Ada Beispiel"}, + {"email": BEN_EMAIL, "password": BEN_PASSWORD, "display_name": "Ben Beispiel"}, + ] + } + + +def seed_demo(settings: Settings | None = None) -> bool: + settings = settings or get_settings() + if settings.tsumugu_env != "development" or not settings.seed_demo: + return False + cleanup: list[Path] = [] + with psycopg.connect(settings.dsn(), row_factory=dict_row) as conn: + try: + if conn.execute("SELECT 1 FROM auth_accounts WHERE email = %s", (ADA_EMAIL,)).fetchone(): + return False + ada = create_account(conn, ADA_EMAIL, "Ada Beispiel", ADA_PASSWORD) + ben = create_account(conn, BEN_EMAIL, "Ben Beispiel", BEN_PASSWORD) + room = conn.execute( + """ + INSERT INTO data_rooms (id, kind, name, created_by) + VALUES (gen_random_uuid(), 'organization', 'Haushalt Musterstraße', %s) + RETURNING id + """, + (ada["id"],), + ).fetchone() + conn.execute( + "INSERT INTO room_memberships (room_id, subject_id, role) VALUES (%s, %s, 'manager'), (%s, %s, 'member')", + (room["id"], ada["id"], room["id"], ben["id"]), + ) + private_case = create_case(conn, ada["id"], ada["id"], "Persönliche Verhandlungsstrategie", None, "explicit") + shared_case = create_case(conn, ada["id"], ada["id"], "Mietstreit Musterstraße 12", None, "explicit") + grant_access(conn, ada["id"], "case", shared_case["id"], ben["id"], True, True, False, None) + strategy = create_matter(conn, ada["id"], ada["id"], "Interne Verhandlungsstrategie", None, None) + moisture = create_matter(conn, ada["id"], ada["id"], "Mängelanzeige Feuchtigkeit", None, None) + link_matter_to_case(conn, ada["id"], moisture["id"], shared_case["id"], None) + link_matter_to_case(conn, ada["id"], strategy["id"], private_case["id"], None) + note = create_note( + conn, + ada["id"], + ada["id"], + "Gespräch mit der Hausverwaltung", + { + "version": 1, + "blocks": [ + { + "type": "paragraph", + "text": ( + "Am 1. Oktober die Feuchtigkeit im Schlafzimmer angezeigt. " + "Die Verwaltung will bis Ende November antworten." + ), + } + ], + }, + Ctx("case", shared_case["id"]), + None, + None, + ) + matter_binding = bind_element( + conn, + ada["id"], + note["element"]["id"], + Ctx("case", shared_case["id"]), + Ctx("matter", moisture["id"]), + None, + None, + ) + add_annotation( + conn, + ada["id"], + note["binding"]["id"], + "Nur in der Akte: Original im blauen Ordner.", + Ctx("case", shared_case["id"]), + ) + add_annotation( + conn, + ada["id"], + matter_binding["id"], + "Nur in diesem Vorgang: Zeugin Frau Keller erinnern.", + Ctx("matter", moisture["id"]), + ) + create_note( + conn, + ada["id"], + ada["id"], + "Nicht weitergeben", + { + "version": 1, + "blocks": [ + { + "type": "paragraph", + "text": "Vergleich nur anbieten, wenn die Gegenseite zuerst einen Betrag nennt.", + } + ], + }, + Ctx("case", private_case["id"]), + None, + None, + ) + chapter = create_chapter(conn, ada["id"], "matter", moisture["id"], "Schriftwechsel", 0, None) + create_file( + conn, + ada["id"], + ada["id"], + "Schreiben an die Hausverwaltung", + "Schreiben-Hausverwaltung.pdf", + SAMPLE_PDF, + Ctx("matter", moisture["id"]), + None, + chapter["id"], + date(2026, 10, 1), + date(2026, 10, 2), + None, + settings.media_root, + settings.upload_max_bytes, + cleanup, + ) + create_external( + conn, + ada["id"], + ada["id"], + "Antwort der Hausverwaltung", + "paperless", + "4821", + Ctx("matter", moisture["id"]), + None, + chapter["id"], + date(2026, 10, 8), + None, + date(2026, 10, 10), + ) + task = create_task( + conn, + ada["id"], + ada["id"], + "Unterlagen für die Antwort zusammenstellen", + date(2026, 11, 25), + moisture["id"], + None, + ) + assign_task(conn, ada["id"], task["id"], ben["id"], None) + deadline = create_deadline( + conn, + ada["id"], + ada["id"], + "Antwort an die Gegenseite", + date(2026, 11, 30), + moisture["id"], + None, + ) + link_task_deadline(conn, ada["id"], task["id"], deadline["id"], None) + conn.commit() + return True + except Exception: + conn.rollback() + for path in cleanup: + path.unlink(missing_ok=True) + raise diff --git a/backend/main.py b/backend/main.py index bb188a6..ac4b385 100644 --- a/backend/main.py +++ b/backend/main.py @@ -1,42 +1,5 @@ -"""Tsumugu — schmales Startgerüst, damit der Pi-Deploy einen Health-Check hat.""" +"""Uvicorn entry: `uvicorn main:app`.""" -from __future__ import annotations +from app.main import app -import os - -import psycopg2 -from fastapi import FastAPI -from fastapi.responses import JSONResponse - -app = FastAPI(title="Tsumugu", docs_url=None, redoc_url=None) - - -def _database_status() -> str: - try: - connection = psycopg2.connect( - host=os.environ.get("DB_HOST", "postgres"), - port=os.environ.get("DB_PORT", "5432"), - dbname=os.environ.get("DB_NAME", "tsumugu"), - user=os.environ.get("DB_USER", "tsumugu"), - password=os.environ.get("DB_PASSWORD", ""), - connect_timeout=3, - ) - connection.close() - except Exception: - return "error" - return "ok" - - -@app.get("/api/health") -def api_health(): - database = _database_status() - status = "ok" if database == "ok" else "degraded" - return JSONResponse( - status_code=200 if database == "ok" else 503, - content={ - "status": status, - "app": "tsumugu", - "env": os.environ.get("TSUMUGU_ENV", "development"), - "db": database, - }, - ) +__all__ = ["app"] diff --git a/backend/migrations/20261016T210000Z_foundation.sql b/backend/migrations/20261016T210000Z_foundation.sql new file mode 100644 index 0000000..bbfe4a4 --- /dev/null +++ b/backend/migrations/20261016T210000Z_foundation.sql @@ -0,0 +1,356 @@ +-- Erster Fachschnitt: Identität, Struktur, Inhalte, Nachverfolgung, eigene Dateien. +-- Finanz-, Zusammenstellungs- und Paperless-Abgleichstabellen gehören nicht in diese Lieferung. + +CREATE TABLE auth_accounts ( + id uuid PRIMARY KEY, + email text NOT NULL UNIQUE, + display_name text NOT NULL, + password_hash text NOT NULL, + status text NOT NULL DEFAULT 'active', + created_at timestamptz NOT NULL DEFAULT now(), + CONSTRAINT auth_accounts_status CHECK (status IN ('active', 'disabled')), + CONSTRAINT auth_accounts_email_len CHECK (char_length(email) <= 320), + CONSTRAINT auth_accounts_name_len CHECK (char_length(display_name) BETWEEN 1 AND 120) +); + +CREATE TABLE data_rooms ( + id uuid PRIMARY KEY, + kind text NOT NULL, + name text NOT NULL, + status text NOT NULL DEFAULT 'active', + created_by uuid NOT NULL REFERENCES auth_accounts (id), + created_at timestamptz NOT NULL DEFAULT now(), + CONSTRAINT data_rooms_kind CHECK (kind IN ('personal', 'organization')), + CONSTRAINT data_rooms_status CHECK (status IN ('active', 'archived')), + CONSTRAINT data_rooms_name_len CHECK (char_length(name) BETWEEN 1 AND 160) +); + +CREATE TABLE auth_sessions ( + id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + account_id uuid NOT NULL REFERENCES auth_accounts (id), + secret_hash text NOT NULL UNIQUE, + csrf_token text NOT NULL, + scope_kind text NOT NULL, + scope_id uuid NOT NULL REFERENCES data_rooms (id), + epoch integer NOT NULL DEFAULT 1, + expires_at timestamptz NOT NULL, + revoked_at timestamptz, + created_at timestamptz NOT NULL DEFAULT now(), + CONSTRAINT auth_sessions_scope_kind CHECK (scope_kind IN ('personal', 'organization')) +); + +CREATE INDEX auth_sessions_account ON auth_sessions (account_id); + +CREATE TABLE auth_invitations ( + id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + email text NOT NULL, + room_id uuid NOT NULL REFERENCES data_rooms (id), + token_hash text NOT NULL UNIQUE, + invited_by uuid NOT NULL REFERENCES auth_accounts (id), + expires_at timestamptz NOT NULL, + accepted_at timestamptz, + created_at timestamptz NOT NULL DEFAULT now() +); + +CREATE TABLE room_memberships ( + room_id uuid NOT NULL REFERENCES data_rooms (id), + subject_id uuid NOT NULL REFERENCES auth_accounts (id), + role text NOT NULL, + status text NOT NULL DEFAULT 'active', + created_at timestamptz NOT NULL DEFAULT now(), + PRIMARY KEY (room_id, subject_id), + CONSTRAINT room_memberships_role CHECK (role IN ('member', 'manager')), + CONSTRAINT room_memberships_status CHECK (status IN ('active', 'removed')) +); + +CREATE TABLE cases ( + id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + home_scope_id uuid NOT NULL REFERENCES data_rooms (id), + owner_subject_id uuid NOT NULL REFERENCES auth_accounts (id), + created_by uuid NOT NULL REFERENCES auth_accounts (id), + version integer NOT NULL DEFAULT 1, + title text NOT NULL, + parent_case_id uuid, + rights_mode text NOT NULL DEFAULT 'explicit', + record_status text NOT NULL DEFAULT 'open', + created_at timestamptz NOT NULL DEFAULT now(), + updated_at timestamptz NOT NULL DEFAULT now(), + deleted_at timestamptz, + CONSTRAINT cases_title_len CHECK (char_length(title) BETWEEN 1 AND 200), + CONSTRAINT cases_rights_mode CHECK (rights_mode IN ('inherit_parent', 'explicit')), + CONSTRAINT cases_status CHECK (record_status IN ('open', 'closed')), + CONSTRAINT cases_root_explicit CHECK ( + (parent_case_id IS NULL AND rights_mode = 'explicit') + OR parent_case_id IS NOT NULL + ), + UNIQUE (id, home_scope_id) +); + +ALTER TABLE cases + ADD CONSTRAINT cases_parent_same_scope + FOREIGN KEY (parent_case_id, home_scope_id) REFERENCES cases (id, home_scope_id); + +CREATE INDEX cases_owner ON cases (owner_subject_id) WHERE deleted_at IS NULL; +CREATE INDEX cases_home ON cases (home_scope_id) WHERE deleted_at IS NULL; + +CREATE TABLE matters ( + id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + home_scope_id uuid NOT NULL REFERENCES data_rooms (id), + owner_subject_id uuid NOT NULL REFERENCES auth_accounts (id), + created_by uuid NOT NULL REFERENCES auth_accounts (id), + version integer NOT NULL DEFAULT 1, + title text NOT NULL, + parent_matter_id uuid, + record_status text NOT NULL DEFAULT 'open', + created_at timestamptz NOT NULL DEFAULT now(), + updated_at timestamptz NOT NULL DEFAULT now(), + deleted_at timestamptz, + CONSTRAINT matters_title_len CHECK (char_length(title) BETWEEN 1 AND 200), + CONSTRAINT matters_status CHECK (record_status IN ('open', 'closed')), + UNIQUE (id, home_scope_id) +); + +ALTER TABLE matters + ADD CONSTRAINT matters_parent_same_scope + FOREIGN KEY (parent_matter_id, home_scope_id) REFERENCES matters (id, home_scope_id); + +CREATE INDEX matters_owner ON matters (owner_subject_id) WHERE deleted_at IS NULL; + +CREATE TABLE chapters ( + id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + home_scope_id uuid NOT NULL REFERENCES data_rooms (id), + case_id uuid, + matter_id uuid, + title text NOT NULL, + position integer NOT NULL DEFAULT 0, + created_at timestamptz NOT NULL DEFAULT now(), + CONSTRAINT chapters_title_len CHECK (char_length(title) BETWEEN 1 AND 200), + CONSTRAINT chapters_one_container CHECK ((case_id IS NULL) <> (matter_id IS NULL)) +); + +ALTER TABLE chapters + ADD CONSTRAINT chapters_case_same_scope + FOREIGN KEY (case_id, home_scope_id) REFERENCES cases (id, home_scope_id); + +ALTER TABLE chapters + ADD CONSTRAINT chapters_matter_same_scope + FOREIGN KEY (matter_id, home_scope_id) REFERENCES matters (id, home_scope_id); + +CREATE TABLE matter_case_links ( + id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + matter_id uuid NOT NULL REFERENCES matters (id), + case_id uuid NOT NULL REFERENCES cases (id), + created_by uuid NOT NULL REFERENCES auth_accounts (id), + created_at timestamptz NOT NULL DEFAULT now(), + UNIQUE (matter_id, case_id) +); + +CREATE INDEX matter_case_links_case ON matter_case_links (case_id); + +CREATE TABLE case_link_blocks ( + link_id uuid NOT NULL REFERENCES matter_case_links (id) ON DELETE CASCADE, + element_id uuid NOT NULL, + PRIMARY KEY (link_id, element_id) +); + +CREATE TABLE matter_cross_links ( + id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + from_matter_id uuid NOT NULL REFERENCES matters (id), + to_matter_id uuid NOT NULL REFERENCES matters (id), + created_by uuid NOT NULL REFERENCES auth_accounts (id), + created_at timestamptz NOT NULL DEFAULT now(), + UNIQUE (from_matter_id, to_matter_id), + CONSTRAINT matter_cross_links_distinct CHECK (from_matter_id <> to_matter_id) +); + +CREATE TABLE elements ( + id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + home_scope_id uuid NOT NULL REFERENCES data_rooms (id), + owner_subject_id uuid NOT NULL REFERENCES auth_accounts (id), + created_by uuid NOT NULL REFERENCES auth_accounts (id), + version integer NOT NULL DEFAULT 1, + title text NOT NULL, + kind text NOT NULL, + created_at timestamptz NOT NULL DEFAULT now(), + updated_at timestamptz NOT NULL DEFAULT now(), + deleted_at timestamptz, + CONSTRAINT elements_title_len CHECK (char_length(title) BETWEEN 1 AND 200), + CONSTRAINT elements_kind CHECK (kind IN ('note', 'file', 'external_ref')), + UNIQUE (id, home_scope_id) +); + +CREATE INDEX elements_owner ON elements (owner_subject_id) WHERE deleted_at IS NULL; + +CREATE TABLE note_bodies ( + element_id uuid PRIMARY KEY REFERENCES elements (id), + document_json jsonb NOT NULL, + version integer NOT NULL DEFAULT 1, + updated_at timestamptz NOT NULL DEFAULT now() +); + +CREATE TABLE correspondence_dates ( + element_id uuid PRIMARY KEY REFERENCES elements (id), + document_on date, + sent_on date, + received_on date +); + +CREATE TABLE external_references ( + element_id uuid PRIMARY KEY REFERENCES elements (id), + source text NOT NULL, + external_id text NOT NULL, + CONSTRAINT external_references_source CHECK (source IN ('paperless', 'url')), + CONSTRAINT external_references_id_len CHECK (char_length(external_id) BETWEEN 1 AND 200) +); + +CREATE TABLE bindings ( + id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + element_id uuid NOT NULL REFERENCES elements (id), + context_kind text NOT NULL, + context_id uuid NOT NULL, + chapter_id uuid REFERENCES chapters (id), + position integer NOT NULL DEFAULT 0, + created_by uuid NOT NULL REFERENCES auth_accounts (id), + created_at timestamptz NOT NULL DEFAULT now(), + UNIQUE (element_id, context_kind, context_id), + CONSTRAINT bindings_context_kind CHECK (context_kind IN ('case', 'matter')) +); + +CREATE INDEX bindings_context ON bindings (context_kind, context_id); + +CREATE TABLE context_annotations ( + id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + binding_id uuid NOT NULL REFERENCES bindings (id) ON DELETE CASCADE, + body text NOT NULL, + author_subject_id uuid NOT NULL REFERENCES auth_accounts (id), + created_at timestamptz NOT NULL DEFAULT now(), + updated_at timestamptz NOT NULL DEFAULT now(), + CONSTRAINT context_annotations_body CHECK (char_length(body) BETWEEN 1 AND 4000) +); + +CREATE TABLE access_grants ( + id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + grantee_subject_id uuid REFERENCES auth_accounts (id), + resource_kind text NOT NULL, + resource_id uuid NOT NULL, + context_kind text, + context_id uuid, + can_read boolean NOT NULL DEFAULT false, + can_edit boolean NOT NULL DEFAULT false, + can_share boolean NOT NULL DEFAULT false, + can_delete boolean NOT NULL DEFAULT false, + is_exception boolean NOT NULL DEFAULT false, + created_by uuid NOT NULL REFERENCES auth_accounts (id), + created_at timestamptz NOT NULL DEFAULT now(), + CONSTRAINT access_grants_kind CHECK (resource_kind IN ('case', 'matter', 'element', 'task', 'deadline')), + CONSTRAINT access_grants_context_pair CHECK ((context_kind IS NULL) = (context_id IS NULL)), + CONSTRAINT access_grants_context_kind CHECK (context_kind IS NULL OR context_kind IN ('case', 'matter')), + CONSTRAINT access_grants_grantee CHECK (is_exception OR grantee_subject_id IS NOT NULL), + CONSTRAINT access_grants_exception_flag CHECK ( + NOT is_exception OR can_read OR can_edit OR can_share OR can_delete + ) +); + +CREATE UNIQUE INDEX access_grants_identity ON access_grants ( + resource_kind, + resource_id, + COALESCE(grantee_subject_id, '00000000-0000-0000-0000-000000000000'::uuid), + COALESCE(context_kind, ''), + COALESCE(context_id, '00000000-0000-0000-0000-000000000000'::uuid), + is_exception +); + +CREATE INDEX access_grants_grantee ON access_grants (grantee_subject_id); +CREATE INDEX access_grants_resource ON access_grants (resource_kind, resource_id); + +CREATE TABLE tasks ( + id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + home_scope_id uuid NOT NULL REFERENCES data_rooms (id), + owner_subject_id uuid NOT NULL REFERENCES auth_accounts (id), + created_by uuid NOT NULL REFERENCES auth_accounts (id), + version integer NOT NULL DEFAULT 1, + title text NOT NULL, + matter_id uuid REFERENCES matters (id), + assignee_subject_id uuid REFERENCES auth_accounts (id), + due_on date, + task_status text NOT NULL DEFAULT 'open', + created_at timestamptz NOT NULL DEFAULT now(), + updated_at timestamptz NOT NULL DEFAULT now(), + deleted_at timestamptz, + CONSTRAINT tasks_title_len CHECK (char_length(title) BETWEEN 1 AND 200), + CONSTRAINT tasks_status CHECK (task_status IN ('open', 'done')) +); + +CREATE INDEX tasks_open ON tasks (task_status) WHERE deleted_at IS NULL; + +CREATE TABLE deadlines ( + id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + home_scope_id uuid NOT NULL REFERENCES data_rooms (id), + owner_subject_id uuid NOT NULL REFERENCES auth_accounts (id), + created_by uuid NOT NULL REFERENCES auth_accounts (id), + version integer NOT NULL DEFAULT 1, + title text NOT NULL, + matter_id uuid REFERENCES matters (id), + element_id uuid REFERENCES elements (id), + assignee_subject_id uuid REFERENCES auth_accounts (id), + due_on date NOT NULL, + deadline_status text NOT NULL DEFAULT 'open', + fulfilled_at timestamptz, + created_at timestamptz NOT NULL DEFAULT now(), + updated_at timestamptz NOT NULL DEFAULT now(), + deleted_at timestamptz, + CONSTRAINT deadlines_title_len CHECK (char_length(title) BETWEEN 1 AND 200), + CONSTRAINT deadlines_status CHECK (deadline_status IN ('open', 'fulfilled')) +); + +CREATE INDEX deadlines_open ON deadlines (deadline_status) WHERE deleted_at IS NULL; + +CREATE TABLE task_deadline_links ( + task_id uuid NOT NULL REFERENCES tasks (id), + deadline_id uuid NOT NULL REFERENCES deadlines (id), + created_by uuid NOT NULL REFERENCES auth_accounts (id), + created_at timestamptz NOT NULL DEFAULT now(), + PRIMARY KEY (task_id, deadline_id) +); + +CREATE TABLE media_assets ( + id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + element_id uuid NOT NULL UNIQUE REFERENCES elements (id), + owner_subject_id uuid NOT NULL REFERENCES auth_accounts (id), + home_scope_id uuid NOT NULL REFERENCES data_rooms (id), + original_filename text NOT NULL, + content_type text NOT NULL, + byte_size bigint NOT NULL, + sha256 text NOT NULL, + revision integer NOT NULL DEFAULT 1, + status text NOT NULL DEFAULT 'active', + created_at timestamptz NOT NULL DEFAULT now(), + CONSTRAINT media_assets_status CHECK (status IN ('active', 'purging', 'purged')), + CONSTRAINT media_assets_filename CHECK (char_length(original_filename) BETWEEN 1 AND 240) +); + +CREATE TABLE media_operations ( + id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + element_id uuid, + asset_id uuid, + phase text NOT NULL, + status text NOT NULL, + created_at timestamptz NOT NULL DEFAULT now() +); + +CREATE TABLE domain_events ( + id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + actor_subject_id uuid REFERENCES auth_accounts (id), + scope_id uuid, + action text NOT NULL, + resource_kind text NOT NULL, + resource_id uuid NOT NULL, + context_kind text, + context_id uuid, + occurred_on date, + occurred_at timestamptz NOT NULL DEFAULT now(), + result text NOT NULL DEFAULT 'ok' +); + +CREATE INDEX domain_events_resource ON domain_events (resource_kind, resource_id); +CREATE INDEX domain_events_context ON domain_events (context_kind, context_id); diff --git a/backend/requirements-dev.txt b/backend/requirements-dev.txt new file mode 100644 index 0000000..a575cbd --- /dev/null +++ b/backend/requirements-dev.txt @@ -0,0 +1,3 @@ +-r requirements.txt +pytest==8.3.4 +httpx==0.28.1 diff --git a/backend/requirements.txt b/backend/requirements.txt index 6a3f316..55637c5 100644 --- a/backend/requirements.txt +++ b/backend/requirements.txt @@ -1,3 +1,7 @@ fastapi==0.115.6 uvicorn[standard]==0.34.0 -psycopg2-binary==2.9.10 +psycopg[binary]==3.2.3 +psycopg-pool==3.2.4 +bcrypt==4.2.1 +pydantic-settings==2.6.1 +python-multipart==0.0.18 diff --git a/docker-compose.dev-env.yml b/docker-compose.dev-env.yml index 774f9e4..fe950ac 100644 --- a/docker-compose.dev-env.yml +++ b/docker-compose.dev-env.yml @@ -32,8 +32,12 @@ services: DB_PASSWORD: "${DB_PASSWORD:-dev_password_change_me}" APP_URL: "${APP_URL:-https://dev.tsumugu.jinkendo.de}" ALLOWED_ORIGINS: "${ALLOWED_ORIGINS:-https://dev.tsumugu.jinkendo.de,http://192.168.2.49:3094,http://localhost:3094}" + MEDIA_ROOT: /data/media + SEED_DEMO: "${SEED_DEMO:-true}" + volumes: + - dev-tsumugu-media:/data/media ports: - - "${TSUMUGU_BACKEND_PORT:-8094}:8000" + - "127.0.0.1:${TSUMUGU_BACKEND_PORT:-8094}:8000" depends_on: postgres: condition: service_healthy @@ -68,6 +72,7 @@ services: volumes: dev-tsumugu-db-data: + dev-tsumugu-media: networks: dev-tsumugu-network: diff --git a/docker-compose.yml b/docker-compose.yml index 5455b86..74492dd 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -34,8 +34,12 @@ services: DB_PASSWORD: "${DB_PASSWORD:?set DB_PASSWORD in .env}" APP_URL: "${APP_URL:-https://tsumugu.jinkendo.de}" ALLOWED_ORIGINS: "${ALLOWED_ORIGINS:-https://tsumugu.jinkendo.de}" + MEDIA_ROOT: /data/media + SEED_DEMO: "${SEED_DEMO:-false}" + volumes: + - tsumugu-media:/data/media ports: - - "${TSUMUGU_BACKEND_PORT:-8007}:8000" + - "127.0.0.1:${TSUMUGU_BACKEND_PORT:-8007}:8000" depends_on: postgres: condition: service_healthy @@ -71,6 +75,7 @@ services: volumes: tsumugu-db-data: + tsumugu-media: networks: tsumugu-network: diff --git a/docs/DEPLOYMENT.md b/docs/DEPLOYMENT.md index 25cf61e..bd302f0 100644 --- a/docs/DEPLOYMENT.md +++ b/docs/DEPLOYMENT.md @@ -35,6 +35,8 @@ Gearbeitet wird auf `develop`. Production entsteht nur durch einen Merge-Commit Fehlt beim ersten Lauf die Host-`.env`, legt der Workflow sie an. Development bekommt die dokumentierten Dev-Defaults. Production bekommt ein zufälliges `DB_PASSWORD`, das nur in `/home/lars/docker/tsumugu/.env` steht und nicht ins Log geschrieben wird. Spätere Läufe überschreiben eine vorhandene `.env` nicht. `git reset --hard` lässt die Datei liegen, weil sie nicht im Repo ist. +Der Backend-Container migriert beim Start und bedient danach den API-Prozess. Der Host-Port des Backends bleibt an `127.0.0.1` gebunden; von außen ist nur das Frontend erreichbar, das `/api/` im Compose-Netz weiterreicht. Eigene Dateien liegen im Volume `dev-tsumugu-media` bzw. `tsumugu-media`. Development setzt `SEED_DEMO` standardmäßig und legt dabei nur synthetische Konten an. Production lässt das aus. Eine schon vorhandene Host-`.env` muss `SEED_DEMO` nicht enthalten. + --- ## Erreichbarkeit von außen diff --git a/docs/MVP_ANNAHMEN.md b/docs/MVP_ANNAHMEN.md new file mode 100644 index 0000000..697cb65 --- /dev/null +++ b/docs/MVP_ANNAHMEN.md @@ -0,0 +1,12 @@ +# Vorläufige MVP-Annahmen + +Diese Regeln sind die Arbeitsgrundlage der ersten Lieferung. Sie sind keine endgültigen Produktentscheidungen und lassen sich später ändern, ohne das Datenmodell umzubauen. + +1. **Widersprüchliche Rechte.** Es gilt nur der Kontext der Aktion. Ein Schreibschutz in Akte A sperrt die Bearbeitung in Kontext B nicht. Rechte werden nicht über unsichtbare Kontexte vereinigt. +2. **Neue Einbindung.** Weitere Sicht entsteht nur mit Weitergaberecht am Element und Bearbeitungsrecht am Ziel. Bearbeiten allein gibt niemandem neuen Zugriff. +3. **Einbindung und Löschen.** „Aus diesem Kontext entfernen“ löscht die Einbindung und ihre Anmerkungen. Das Element bleibt bei der Eigentümerin oder dem Eigentümer, auch ohne Einbindung. „Überall löschen“ darf nur diese Person. Paperless-Originale werden nicht gelöscht. +4. **Aktenvererbung.** Die Zuordnung eines Vorgangs gibt die Rechte dieser Akte an den Vorgang und an Inhalte ohne ausdrückliche Ausnahme weiter. Was die zuordnende Person nicht weitergeben darf, bleibt in diesem Aktenkontext unsichtbar, ohne Titel und ohne Anzahl. Querverweise vererben nichts. Die Ownership bleibt unverändert. + +Der gewählte Datenraum legt fest, wo neue Objekte entstehen. Er ist nicht selbst der Rechtepfad. Eine gültige Sitzung muss einen Datenraum gewählt haben; der Server prüft danach den mitgeschickten Handlungskontext. + +Technische Anpassung: Das Session-Cookie heißt in Production `__Host-jinkendo-session` und ist `Secure`. Development nutzt diesen Namen nur bei HTTPS. Über die dokumentierten HTTP-Adressen im LAN heißt es `jinkendo-session`, weil ein `__Host-`-Cookie dort nicht gespeichert werden kann. diff --git a/docs/architecture/TSUMUGU_TECHNICAL_SPEC.md b/docs/architecture/TSUMUGU_TECHNICAL_SPEC.md index c2abef0..bf8f052 100644 --- a/docs/architecture/TSUMUGU_TECHNICAL_SPEC.md +++ b/docs/architecture/TSUMUGU_TECHNICAL_SPEC.md @@ -1,6 +1,6 @@ # Tsumugu – Technische MVP-Spezifikation -**Stand:** 16.10.2026 · **Fassung:** 0.3 · **Status:** Erster fachlicher Lieferumfang bestätigt; technische Ausgestaltung und offene Produktregeln bleiben Vorschläge. Keine Implementierung, keine Migration, kein Testnachweis. +**Stand:** 16.10.2026 · **Fassung:** 0.3 · **Status:** Erster fachlicher Lieferumfang ist als Anwendung umgesetzt. Offene Rechte- und Löschregeln bleiben vorläufig und stehen in [MVP_ANNAHMEN.md](../MVP_ANNAHMEN.md). Diese Datei bleibt der technische Entwurf, nicht der Nachweis eines Produktionstests. **Fachliche Grundlage:** [TSUMUGU_PRODUCT_SPEC.md](../product/TSUMUGU_PRODUCT_SPEC.md), Arbeitsstand 0.25 einschließlich Lieferentscheidung F-05a. Die historische [Recovery-Baseline](../product/Tsumugu_Product_Recovery_Baseline_v0.1.md) bleibt unverändert; wo das Interview eine Recovery-Aussage präzisiert hat, gilt die Fachspec. diff --git a/frontend/.dockerignore b/frontend/.dockerignore new file mode 100644 index 0000000..f06235c --- /dev/null +++ b/frontend/.dockerignore @@ -0,0 +1,2 @@ +node_modules +dist diff --git a/frontend/Dockerfile b/frontend/Dockerfile index 636b17a..984d96e 100644 --- a/frontend/Dockerfile +++ b/frontend/Dockerfile @@ -1,7 +1,18 @@ +FROM node:22-alpine AS build + +WORKDIR /src + +COPY package.json package-lock.json ./ +RUN npm ci + +COPY index.html vite.config.js ./ +COPY src ./src +RUN npm run build + FROM nginx:alpine COPY nginx.conf /etc/nginx/conf.d/default.conf -COPY index.html /usr/share/nginx/html/index.html +COPY --from=build /src/dist /usr/share/nginx/html EXPOSE 80 diff --git a/frontend/index.html b/frontend/index.html index 4ab495c..bd38bd2 100644 --- a/frontend/index.html +++ b/frontend/index.html @@ -4,29 +4,9 @@ Tsumugu - -
-

Tsumugu

-

Das Deploy-Gerüst der Jinkendo-Familie läuft. Die Anwendung selbst folgt.

-
+
+ diff --git a/frontend/nginx.conf b/frontend/nginx.conf index 3d05006..6a2bef8 100644 --- a/frontend/nginx.conf +++ b/frontend/nginx.conf @@ -3,6 +3,14 @@ server { server_name localhost; root /usr/share/nginx/html; index index.html; + server_tokens off; + client_max_body_size 21m; + + add_header Content-Security-Policy "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' blob:; connect-src 'self'; frame-ancestors 'none'; base-uri 'self'; form-action 'self'" always; + add_header X-Content-Type-Options "nosniff" always; + add_header X-Frame-Options "DENY" always; + add_header Referrer-Policy "no-referrer" always; + add_header Permissions-Policy "camera=(), microphone=(), geolocation=()" always; resolver 127.0.0.11 valid=10s ipv6=off; @@ -13,10 +21,21 @@ server { proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; - proxy_set_header X-Forwarded-Proto $scheme; + proxy_set_header X-Forwarded-Proto $http_x_forwarded_proto; proxy_read_timeout 600s; } + location ^~ /health/ { + set $docker_backend_svc backend; + proxy_pass http://$docker_backend_svc:8000$request_uri; + proxy_http_version 1.1; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $http_x_forwarded_proto; + proxy_read_timeout 30s; + } + location / { try_files $uri $uri/ /index.html; } diff --git a/frontend/package-lock.json b/frontend/package-lock.json new file mode 100644 index 0000000..aaf7d35 --- /dev/null +++ b/frontend/package-lock.json @@ -0,0 +1,1735 @@ +{ + "name": "tsumugu-frontend", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "tsumugu-frontend", + "dependencies": { + "react": "18.3.1", + "react-dom": "18.3.1", + "react-router-dom": "6.28.1" + }, + "devDependencies": { + "@vitejs/plugin-react": "4.3.4", + "vite": "5.4.11" + } + }, + "node_modules/@babel/code-frame": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.7.tgz", + "integrity": "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-validator-identifier": "^7.29.7", + "js-tokens": "^4.0.0", + "picocolors": "^1.1.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/compat-data": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.29.7.tgz", + "integrity": "sha512-locTkQyKvwIEgBzVrn8693ebc97F2U8ZHjbXwDXJ5Fn2TCpNwTlKcaKLkdHop5c/icOFE7qt7Q9JC5hnKNa6Gg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/core": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.29.7.tgz", + "integrity": "sha512-RgHBCvtjbOK2gXSNBNIkNoEc9qoVEtau3hj8gEqKQuL3HZAibKarWFEI3Lfm6EYKkLalOh8eSrj9b+ch9H/VBA==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "@babel/code-frame": "^7.29.7", + "@babel/generator": "^7.29.7", + "@babel/helper-compilation-targets": "^7.29.7", + "@babel/helper-module-transforms": "^7.29.7", + "@babel/helpers": "^7.29.7", + "@babel/parser": "^7.29.7", + "@babel/template": "^7.29.7", + "@babel/traverse": "^7.29.7", + "@babel/types": "^7.29.7", + "@jridgewell/remapping": "^2.3.5", + "convert-source-map": "^2.0.0", + "debug": "^4.1.0", + "gensync": "^1.0.0-beta.2", + "json5": "^2.2.3", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/babel" + } + }, + "node_modules/@babel/generator": { + "version": "7.29.8", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.29.8.tgz", + "integrity": "sha512-gZbepsdh3WDtgZKWL+vTPh71LSBrm/Y4/QDZBVCcYfmeTEEuoOYwlSy+G1StfJg+/Zy550u/3TATbm7qDbbMtg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.29.8", + "@babel/types": "^7.29.8", + "@jridgewell/gen-mapping": "^0.3.12", + "@jridgewell/trace-mapping": "^0.3.28", + "jsesc": "^3.0.2" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-compilation-targets": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.29.7.tgz", + "integrity": "sha512-wem6WaBj4NaVYVdNhLPPVacES6ZJ+KBBfSkTMD3YZxbP3rm3Di85tJU5ljaUNhaOynt+Aj0xruhYuzQBt8n71g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/compat-data": "^7.29.7", + "@babel/helper-validator-option": "^7.29.7", + "browserslist": "^4.24.0", + "lru-cache": "^5.1.1", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-globals": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-globals/-/helper-globals-7.29.7.tgz", + "integrity": "sha512-3nQVUAtvkKH9zahfWgw96Jc/uFOmjACE1kQz82E2lqWmHBgjzbNlsC22nuQTfahmWeQtTq5nQ/4Nnd2A1wj4zA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-module-imports": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.29.7.tgz", + "integrity": "sha512-ejHwrQQYcm9xnTivShn2IDOlIzInN34AXskvq9QicvCtEzq1Vzclu/tKF8Jq1Cg8JG2GL6/EmjgsCT7lXepE3g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/traverse": "^7.29.7", + "@babel/types": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-module-transforms": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.29.7.tgz", + "integrity": "sha512-UPUVSyXbOh627KiCIGQSgwWzGeBKLkaJ9PJEdrngIwMSzxLR4jS4+f1f1jb7VzBbg8nFLaYotvVPFCTqdrmTAg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-module-imports": "^7.29.7", + "@babel/helper-validator-identifier": "^7.29.7", + "@babel/traverse": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/helper-plugin-utils": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.29.7.tgz", + "integrity": "sha512-G7sHYigPY17oO5SYWnfD/0MTBwVR781S/JI643e/JhUYgVgWE/61SoW3NH9KWUKyKq5LVh3npif99Wkt6j86Jw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-string-parser": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.7.tgz", + "integrity": "sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-identifier": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz", + "integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-option": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.29.7.tgz", + "integrity": "sha512-N9ZErrD+yW5geCDtBqnOoxmR8+tNKiGuxKlDpuJxfsqpa2dFcexaziGAE/qoHLiDDreVNMupxGmSoNlyvsA3gw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helpers": { + "version": "7.29.10", + "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.29.10.tgz", + "integrity": "sha512-EMCx3AGZ3WfAl6ht7AyQoPm2Lh+BGYEMdc4Q6Hf7uSCDOZFuLq44qNwL+iaim8VlyYhRAo4X43+weadK8ZB4Yg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/template": "^7.29.7", + "@babel/types": "^7.29.8" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/parser": { + "version": "7.29.9", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.9.tgz", + "integrity": "sha512-CjXrNHTnvqBVqHgdBysY3vk2T8tpJHb5/RMeHJBTyVa9xgugCB0CJTx/3oO8RV2QRQP391RWpB7D6hLjm8V9uA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.29.8" + }, + "bin": { + "parser": "bin/babel-parser.js" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@babel/plugin-transform-react-jsx-self": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx-self/-/plugin-transform-react-jsx-self-7.29.7.tgz", + "integrity": "sha512-TL0hMc9xzy86VD31nUiwzd5otRAcyEPcsegCxolO0PvcXuH1v0kECe/UIznYFihpkvU5wg/jk4v0TTEFfm53fw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-react-jsx-source": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx-source/-/plugin-transform-react-jsx-source-7.29.7.tgz", + "integrity": "sha512-06IyK09H3wi4cGbhDBwp5gUGo0IKtnYa8tyTiephirPCK6fbobVGiXMMI5zLQ4aKEYP3wZ3ArU44o+8KMrSG/Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/template": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.29.7.tgz", + "integrity": "sha512-puq+Gf35oI24FeN11LkoUQFqv9uwNeWpxXZi/Ji3rRIoKAzKnxRaZ+Gkj0vKS9ZCiTESfng1N9LyOyXvo+m+Gg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.29.7", + "@babel/parser": "^7.29.7", + "@babel/types": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/traverse": { + "version": "7.29.10", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.29.10.tgz", + "integrity": "sha512-B3lYAs2nkKskbgQ1nfy8Ma9ao9Q1rntTAQHrzzyDuj+TSO+X3le6PfWwqDvodsb+OumE10eMFfuMCTQSQ5iuIQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.29.7", + "@babel/generator": "^7.29.8", + "@babel/helper-globals": "^7.29.7", + "@babel/parser": "^7.29.9", + "@babel/template": "^7.29.7", + "@babel/types": "^7.29.8", + "debug": "^4.3.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/types": { + "version": "7.29.8", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.8.tgz", + "integrity": "sha512-Vj1jF3cPfxg7OAfoI7QnVKLoILlm2JF9pnVHrX8qx7AHMiYWT+NDAA7jChlNgRS4WTLc/fD1lXLmPixluj+3Gg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-string-parser": "^7.29.7", + "@babel/helper-validator-identifier": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.21.5.tgz", + "integrity": "sha512-1SDgH6ZSPTlggy1yI6+Dbkiz8xzpHJEVAlF/AM1tHPLsf5STom9rwtjE4hKAF20FfXXNTFqEYXyJNWh1GiZedQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.21.5.tgz", + "integrity": "sha512-vCPvzSjpPHEi1siZdlvAlsPxXl7WbOVUBBAowWug4rJHb68Ox8KualB+1ocNvT5fjv6wpkX6o/iEpbDrf68zcg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.21.5.tgz", + "integrity": "sha512-c0uX9VAUBQ7dTDCjq+wdyGLowMdtR/GoC2U5IYk/7D1H1JYC0qseD7+11iMP2mRLN9RcCMRcjC4YMclCzGwS/A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.21.5.tgz", + "integrity": "sha512-D7aPRUUNHRBwHxzxRvp856rjUHRFW1SdQATKXH2hqA0kAZb1hKmi02OpYRacl0TxIGz/ZmXWlbZgjwWYaCakTA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.21.5.tgz", + "integrity": "sha512-DwqXqZyuk5AiWWf3UfLiRDJ5EDd49zg6O9wclZ7kUMv2WRFr4HKjXp/5t8JZ11QbQfUS6/cRCKGwYhtNAY88kQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.21.5.tgz", + "integrity": "sha512-se/JjF8NlmKVG4kNIuyWMV/22ZaerB+qaSi5MdrXtd6R08kvs2qCN4C09miupktDitvh8jRFflwGFBQcxZRjbw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.21.5.tgz", + "integrity": "sha512-5JcRxxRDUJLX8JXp/wcBCy3pENnCgBR9bN6JsY4OmhfUtIHe3ZW0mawA7+RDAcMLrMIZaf03NlQiX9DGyB8h4g==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.21.5.tgz", + "integrity": "sha512-J95kNBj1zkbMXtHVH29bBriQygMXqoVQOQYA+ISs0/2l3T9/kj42ow2mpqerRBxDJnmkUDCaQT/dfNXWX/ZZCQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.21.5.tgz", + "integrity": "sha512-bPb5AHZtbeNGjCKVZ9UGqGwo8EUu4cLq68E95A53KlxAPRmUyYv2D6F0uUI65XisGOL1hBP5mTronbgo+0bFcA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.21.5.tgz", + "integrity": "sha512-ibKvmyYzKsBeX8d8I7MH/TMfWDXBF3db4qM6sy+7re0YXya+K1cem3on9XgdT2EQGMu4hQyZhan7TeQ8XkGp4Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.21.5.tgz", + "integrity": "sha512-YvjXDqLRqPDl2dvRODYmmhz4rPeVKYvppfGYKSNGdyZkA01046pLWyRKKI3ax8fbJoK5QbxblURkwK/MWY18Tg==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.21.5.tgz", + "integrity": "sha512-uHf1BmMG8qEvzdrzAqg2SIG/02+4/DHB6a9Kbya0XDvwDEKCoC8ZRWI5JJvNdUjtciBGFQ5PuBlpEOXQj+JQSg==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.21.5.tgz", + "integrity": "sha512-IajOmO+KJK23bj52dFSNCMsz1QP1DqM6cwLUv3W1QwyxkyIWecfafnI555fvSGqEKwjMXVLokcV5ygHW5b3Jbg==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.21.5.tgz", + "integrity": "sha512-1hHV/Z4OEfMwpLO8rp7CvlhBDnjsC3CttJXIhBi+5Aj5r+MBvy4egg7wCbe//hSsT+RvDAG7s81tAvpL2XAE4w==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.21.5.tgz", + "integrity": "sha512-2HdXDMd9GMgTGrPWnJzP2ALSokE/0O5HhTUvWIbD3YdjME8JwvSCnNGBnTThKGEB91OZhzrJ4qIIxk/SBmyDDA==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.21.5.tgz", + "integrity": "sha512-zus5sxzqBJD3eXxwvjN1yQkRepANgxE9lgOW2qLnmr8ikMTphkjgXu1HR01K4FJg8h1kEEDAqDcZQtbrRnB41A==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.21.5.tgz", + "integrity": "sha512-1rYdTpyv03iycF1+BhzrzQJCdOuAOtaqHTWJZCWvijKD2N5Xu0TtVC8/+1faWqcP9iBCWOmjmhoH94dH82BxPQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.21.5.tgz", + "integrity": "sha512-Woi2MXzXjMULccIwMnLciyZH4nCIMpWQAs049KEeMvOcNADVxo0UBIQPfSmxB3CWKedngg7sWZdLvLczpe0tLg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.21.5.tgz", + "integrity": "sha512-HLNNw99xsvx12lFBUwoT8EVCsSvRNDVxNpjZ7bPn947b8gJPzeHWyNVhFsaerc0n3TsbOINvRP2byTZ5LKezow==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.21.5.tgz", + "integrity": "sha512-6+gjmFpfy0BHU5Tpptkuh8+uw3mnrvgs+dSPQXQOv3ekbordwnzTVEb4qnIvQcYXq6gzkyTnoZ9dZG+D4garKg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.21.5.tgz", + "integrity": "sha512-Z0gOTd75VvXqyq7nsl93zwahcTROgqvuAcYDUr+vOv8uHhNSKROyU961kgtCD1e95IqPKSQKH7tBTslnS3tA8A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.21.5.tgz", + "integrity": "sha512-SWXFF1CL2RVNMaVs+BBClwtfZSvDgtL//G/smwAc5oVK/UPu2Gu9tIaRgFmYFFKrmg3SyAjSrElf0TiJ1v8fYA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.21.5.tgz", + "integrity": "sha512-tQd/1efJuzPC6rCFwEvLtci/xNFcTZknmXs98FYDfGE4wP9ClFV98nyKrzJKVPMhdDnjzLhdUyMX4PsQAPjwIw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@jridgewell/gen-mapping": { + "version": "0.3.13", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", + "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.0", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/remapping": { + "version": "2.3.5", + "resolved": "https://registry.npmjs.org/@jridgewell/remapping/-/remapping-2.3.5.tgz", + "integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.5", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", + "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", + "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@napi-rs/lzma-linux-x64-gnu": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/@napi-rs/lzma-linux-x64-gnu/-/lzma-linux-x64-gnu-1.5.1.tgz", + "integrity": "sha512-oTXEIha4SsuXdTA4Iyskj0kpdx2yVXdhd75c2v3xGrHFfVMsbhTPZU/nMPL4sWKo4pBHm3aucLaqGlF696dTyQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^22.20 || ^24.12 || >=25" + } + }, + "node_modules/@remix-run/router": { + "version": "1.21.0", + "resolved": "https://registry.npmjs.org/@remix-run/router/-/router-1.21.0.tgz", + "integrity": "sha512-xfSkCAchbdG5PnbrKqFWwia4Bi61nH+wm8wLEqfHDyp7Y3dZzgqS2itV8i4gAq9pC2HsTpwyBC6Ds8VHZ96JlA==", + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@rollup/rollup-android-arm-eabi": { + "version": "4.64.7", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.64.7.tgz", + "integrity": "sha512-GFF2tHk0NqYVObrK0+/ps/LEXsV/v2q6Lyiy7mZr+Ej24fpQScvqK2ziz9NHeEQYnKWKym38Ml7dZbPtC9tuAw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-android-arm64": { + "version": "4.64.7", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.64.7.tgz", + "integrity": "sha512-BOymcXJFYYXqluDidj6sLelNjXruC3u1BqVxLn2OPCXH9xaPSOTH+MS4uychsGI1NU7tJoiv9KvqijDHFe+hhQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-darwin-arm64": { + "version": "4.64.7", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.64.7.tgz", + "integrity": "sha512-jgVpGweIbls2H5jfBB70tnX52abMd5pJr3xmtoDILx6JdmGl+Un+tMb9R+MbHPVB46tTBpY8emtn7M71SnQhEQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-darwin-x64": { + "version": "4.64.7", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.64.7.tgz", + "integrity": "sha512-AVMpt94mrXH7WjyWKmd9nT4RC5yM0AN3Lt6A89xVIsuLDi3dDX6dxMytLbW36FlppY9JsoqUoS3LUUpUrYxiMQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-freebsd-arm64": { + "version": "4.64.7", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.64.7.tgz", + "integrity": "sha512-Nje29c/MyajxRNFGU05oyeTDS6SWdMg/wWMSlZSBTBju5BKz2NVc0kFiFSQGzRELNiB+CBk/ZvAVsWsENgjGag==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-freebsd-x64": { + "version": "4.64.7", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.64.7.tgz", + "integrity": "sha512-xxgN5/kMzCNz/NYJ4t49B0/WS6InNlWv6xvgwUQqNnWM9WJMMwMUGWrAxdNEgYWdHL0sMnuh8I87StGrIMTA+w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-linux-arm-gnueabihf": { + "version": "4.64.7", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.64.7.tgz", + "integrity": "sha512-5U/9gVn/X657I8+NHoHO9Wnfyd0lEXwqbslobRoB9TC8SwYzOitcIr6TLE7531Q/NWs3L4mb+YOGzlf3vHIeYw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm-musleabihf": { + "version": "4.64.7", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.64.7.tgz", + "integrity": "sha512-hcDS0a/Y8ggM3dcOfzH7UpSaogCViWTtNDSl0EXpWIj8g8/r86ITqptjil2hayTXS0Umzb+Yt3mjgpQVFVf2+A==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-gnu": { + "version": "4.64.7", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.64.7.tgz", + "integrity": "sha512-awbAr4N7Qd/yjZAQBEEPzgcPveYG2Gi5L6gq1/Bp+3SMRjn5F68Wv1zKsntzvvoioBR6yKvhLtWqu11am1TsxA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-musl": { + "version": "4.64.7", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.64.7.tgz", + "integrity": "sha512-Ut7xQJfeLhzu2yN3rHzVvL9ccyPJvN4aCdP1V7hJ5lGxX/eCzgB9SiMk/Md3J+rWWZgvoYsDW4BUFggJr32pBA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-gnu": { + "version": "4.64.7", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.64.7.tgz", + "integrity": "sha512-trqoni/vHkuM5oo5iQhoKPh6fjjD7E80pMgCXWgGxU8vSRPUlwvG8GeYvEEcB6eJAxNa99WH9iVHPHelgtKiHA==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-musl": { + "version": "4.64.7", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.64.7.tgz", + "integrity": "sha512-gvlUy0XFIwtUWiQmhc+4GT2Knm3KosinpUVhr7CtTFA78gFDnE5NWwMPzHrJsYpKkh2LlY7yvBIboN1FAV6Xeg==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-gnu": { + "version": "4.64.7", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.64.7.tgz", + "integrity": "sha512-8yS/kSXTJ/47Z62JW+C2AJ3vd/8zZw016vFjtNpZwmZlwJumLua4s1i78dkYuSSqQ+0aIMxJcBp/4uIwp2ehjA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-musl": { + "version": "4.64.7", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.64.7.tgz", + "integrity": "sha512-mxVSKvvty0hOP1AFo/l4Kpv3i3HK0zx4rYUrirZDToYlWhS3xzmIkq3vUJ7rtrM2cPyXveDyDT6M1FfXZ9hTRA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-gnu": { + "version": "4.64.7", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.64.7.tgz", + "integrity": "sha512-lEse1zra1CagM+uHH2bl28GInDsZZ45NJzHei2OMaXQFzZWKBO1hFo07rS0xB6ayV4WU360UrSmPDSyCMpYsUQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-musl": { + "version": "4.64.7", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.64.7.tgz", + "integrity": "sha512-d/cqCoiG9WMZ5VuJZ5Qdlv9g97QyoGwnmvHccvGhKSacTy7xFrAS+jMcJSBdMNOw1oacSkl6p7K6O/DRYTKL3g==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-s390x-gnu": { + "version": "4.64.7", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.64.7.tgz", + "integrity": "sha512-kVEA//CeDOZZP1XCH2JBgqXb9+ALlwuA/4civaazMVdgzaSQC9WM38w65zG/LLk0lA7F9Od19CSBZW7J9mCbNg==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-gnu": { + "version": "4.64.7", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.64.7.tgz", + "integrity": "sha512-14oLfDsOSr0TSntT/34jRg/V8B2XW/Jomh9zX9CjIM9gwwNlI1OCymS/GVn0DV32h67eRf7U0GGem0rvfXgNwQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-musl": { + "version": "4.64.7", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.64.7.tgz", + "integrity": "sha512-dFVtPfjZqAnUPpPY4Bfg+87yo1IBW9HiY8iCFtg49Pn46MfZTebSHZh8PL6SOsgyt9LQP8Nj/sE6jm3aWpySmQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-openbsd-x64": { + "version": "4.64.7", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.64.7.tgz", + "integrity": "sha512-Dm9CZ2SM3u2NgvBj4awW/gGqkOwzH8f6MSYIJE6+bKcKLI+T0+LhpD6vtetTfrIIx+rLXDf5RJqBP6v7V5O+wg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ] + }, + "node_modules/@rollup/rollup-openharmony-arm64": { + "version": "4.64.7", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.64.7.tgz", + "integrity": "sha512-oaxsvS2mL6+78741CT2HCORBvy1USg3Wqpt5qvZwy3aMXRMl4zxyDo8maeFRWJkF3dp0Wbi71fKH5Gr9YI3vYA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ] + }, + "node_modules/@rollup/rollup-win32-arm64-msvc": { + "version": "4.64.7", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.64.7.tgz", + "integrity": "sha512-UKZz1Y4mxUqkWh60uH7B1aZn6UcAimPk4ipRktpb3wfZq7JrzZYyAXTwiafkb3T+kd5P3Sf+vzcRdsDks4WtjQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-ia32-msvc": { + "version": "4.64.7", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.64.7.tgz", + "integrity": "sha512-WWkSuC1J+mZJnsDh0mRaCAFSWfQdl6y3fDjZeWElI6zHo8CcOSG5lY3yurKJjEq+FrX0WD60sFrVVpbHqzMmrw==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-gnu": { + "version": "4.64.7", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.64.7.tgz", + "integrity": "sha512-u9bp2yXCI3/BUjUxY6uWknAY32pfvvDCPysyUTySotx0dj3ydlFHrRQYfn/b/kZgnfjyEwySMtI7Ga054uiysQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-msvc": { + "version": "4.64.7", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.64.7.tgz", + "integrity": "sha512-EhX6N3XPMEnVU5cRfNgzPOKcSucsbu3nNNWuoAaEuKIqmddBKHN5b9d4rPe65T1I+FaOT176JKiZNsUBp3rqbA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@types/babel__core": { + "version": "7.20.5", + "resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz", + "integrity": "sha512-qoQprZvz5wQFJwMDqeseRXWv3rqMvhgpbXFfVyWhbx9X47POIA6i/+dXefEmZKoAgOaTdaIgNSMqMIU61yRyzA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.20.7", + "@babel/types": "^7.20.7", + "@types/babel__generator": "*", + "@types/babel__template": "*", + "@types/babel__traverse": "*" + } + }, + "node_modules/@types/babel__generator": { + "version": "7.27.0", + "resolved": "https://registry.npmjs.org/@types/babel__generator/-/babel__generator-7.27.0.tgz", + "integrity": "sha512-ufFd2Xi92OAVPYsy+P4n7/U7e68fex0+Ee8gSG9KX7eo084CWiQ4sdxktvdl0bOPupXtVJPY19zk6EwWqUQ8lg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.0.0" + } + }, + "node_modules/@types/babel__template": { + "version": "7.4.4", + "resolved": "https://registry.npmjs.org/@types/babel__template/-/babel__template-7.4.4.tgz", + "integrity": "sha512-h/NUaSyG5EyxBIp8YRxo4RMe2/qQgvyowRwVMzhYhBCONbW8PUsg4lkFMrhgZhUe5z3L3MiLDuvyJ/CaPa2A8A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.1.0", + "@babel/types": "^7.0.0" + } + }, + "node_modules/@types/babel__traverse": { + "version": "7.28.0", + "resolved": "https://registry.npmjs.org/@types/babel__traverse/-/babel__traverse-7.28.0.tgz", + "integrity": "sha512-8PvcXf70gTDZBgt9ptxJ8elBeBjcLOAcOtoO/mPJjtji1+CdGbHgm77om1GrsPxsiE+uXIpNSK64UYaIwQXd4Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.28.2" + } + }, + "node_modules/@types/estree": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz", + "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@vitejs/plugin-react": { + "version": "4.3.4", + "resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-4.3.4.tgz", + "integrity": "sha512-SCCPBJtYLdE8PX/7ZQAs1QAZ8Jqwih+0VBLum1EGqmCCQal+MIUqLCzj3ZUy8ufbC0cAM4LRlSTm7IQJwWT4ug==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/core": "^7.26.0", + "@babel/plugin-transform-react-jsx-self": "^7.25.9", + "@babel/plugin-transform-react-jsx-source": "^7.25.9", + "@types/babel__core": "^7.20.5", + "react-refresh": "^0.14.2" + }, + "engines": { + "node": "^14.18.0 || >=16.0.0" + }, + "peerDependencies": { + "vite": "^4.2.0 || ^5.0.0 || ^6.0.0" + } + }, + "node_modules/baseline-browser-mapping": { + "version": "2.11.29", + "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.29.tgz", + "integrity": "sha512-YeesxhUmR4h5y5V8KF8iBCqJb8YFrBJ++XBTeGcWIaQOYXGN19JM0FoiOjAhwuDoln8owMgXcWBmgHtYSkky2w==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "baseline-browser-mapping": "dist/cli.cjs" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/browserslist": { + "version": "4.29.3", + "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.29.3.tgz", + "integrity": "sha512-1R4kiYKXGViqEN0CnoDrXc1StD9niAwu+j2dukWzrD4bJgsD4lDmEp0CRbc6E/vYJIfTHwPmwyaKtVSudICdPA==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "peer": true, + "dependencies": { + "baseline-browser-mapping": "^2.11.26", + "caniuse-lite": "^1.0.30001813", + "electron-to-chromium": "^1.5.439", + "node-releases": "^2.0.57", + "update-browserslist-db": "^1.3.3" + }, + "bin": { + "browserslist": "cli.js" + }, + "engines": { + "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" + } + }, + "node_modules/caniuse-lite": { + "version": "1.0.30001816", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001816.tgz", + "integrity": "sha512-+8Yx7BXCoqk6IF8yTicjfUR6D/ldJzdlsodlEOiOSPmhK844WIgk67/zIQaGAOxNkZyyvBlrRFnLvqKIoqbAFw==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/caniuse-lite" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "CC-BY-4.0" + }, + "node_modules/convert-source-map": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", + "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==", + "dev": true, + "license": "MIT" + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/electron-to-chromium": { + "version": "1.5.458", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.458.tgz", + "integrity": "sha512-/hIH2gRSmxrf4/X4Nw/t/Wc8PVS22l8/3HnWjWTWsTOM5dsnMUPZF/+u+yr3LqweNuTBJE1rq6qAQzKkZVwMfA==", + "dev": true, + "license": "ISC" + }, + "node_modules/esbuild": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.21.5.tgz", + "integrity": "sha512-mg3OPMV4hXywwpoDxu3Qda5xCKQi+vCTZq8S9J/EpkhB2HzKXq4SNFZE3+NK93JYxc8VMSep+lOUSC/RVKaBqw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=12" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.21.5", + "@esbuild/android-arm": "0.21.5", + "@esbuild/android-arm64": "0.21.5", + "@esbuild/android-x64": "0.21.5", + "@esbuild/darwin-arm64": "0.21.5", + "@esbuild/darwin-x64": "0.21.5", + "@esbuild/freebsd-arm64": "0.21.5", + "@esbuild/freebsd-x64": "0.21.5", + "@esbuild/linux-arm": "0.21.5", + "@esbuild/linux-arm64": "0.21.5", + "@esbuild/linux-ia32": "0.21.5", + "@esbuild/linux-loong64": "0.21.5", + "@esbuild/linux-mips64el": "0.21.5", + "@esbuild/linux-ppc64": "0.21.5", + "@esbuild/linux-riscv64": "0.21.5", + "@esbuild/linux-s390x": "0.21.5", + "@esbuild/linux-x64": "0.21.5", + "@esbuild/netbsd-x64": "0.21.5", + "@esbuild/openbsd-x64": "0.21.5", + "@esbuild/sunos-x64": "0.21.5", + "@esbuild/win32-arm64": "0.21.5", + "@esbuild/win32-ia32": "0.21.5", + "@esbuild/win32-x64": "0.21.5" + } + }, + "node_modules/escalade": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", + "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/gensync": { + "version": "1.0.0-beta.2", + "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz", + "integrity": "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/js-tokens": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", + "license": "MIT" + }, + "node_modules/jsesc": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.1.0.tgz", + "integrity": "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==", + "dev": true, + "license": "MIT", + "bin": { + "jsesc": "bin/jsesc" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/json5": { + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz", + "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==", + "dev": true, + "license": "MIT", + "bin": { + "json5": "lib/cli.js" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/loose-envify": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz", + "integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==", + "license": "MIT", + "dependencies": { + "js-tokens": "^3.0.0 || ^4.0.0" + }, + "bin": { + "loose-envify": "cli.js" + } + }, + "node_modules/lru-cache": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz", + "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==", + "dev": true, + "license": "ISC", + "dependencies": { + "yallist": "^3.0.2" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "dev": true, + "license": "MIT" + }, + "node_modules/nanoid": { + "version": "3.3.20", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz", + "integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/node-releases": { + "version": "2.0.59", + "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.59.tgz", + "integrity": "sha512-5qr2okC4ItAI0hG5SaV0HoYMpnM/Y6+Oqr7AmPYy/2uEoGvS+GbSKLeRxSS1uAdu59yz0ouzcuXievSgg///WA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true, + "license": "ISC" + }, + "node_modules/postcss": { + "version": "8.5.30", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.30.tgz", + "integrity": "sha512-zkd+e9S1AQHhmaBKye9zlFHWjOwVgqXl1q3ECYy8561K7qxR2cREf/STLskulBFd78k6AOFeA+ff1TtEzk9bAA==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.20", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.2" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/react": { + "version": "18.3.1", + "resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz", + "integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==", + "license": "MIT", + "peer": true, + "dependencies": { + "loose-envify": "^1.1.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/react-dom": { + "version": "18.3.1", + "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.3.1.tgz", + "integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==", + "license": "MIT", + "peer": true, + "dependencies": { + "loose-envify": "^1.1.0", + "scheduler": "^0.23.2" + }, + "peerDependencies": { + "react": "^18.3.1" + } + }, + "node_modules/react-refresh": { + "version": "0.14.2", + "resolved": "https://registry.npmjs.org/react-refresh/-/react-refresh-0.14.2.tgz", + "integrity": "sha512-jCvmsr+1IUSMUyzOkRcvnVbX3ZYC6g9TDrDbFuFmRDq7PD4yaGbLKNQL6k2jnArV8hjYxh7hVhAZB6s9HDGpZA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/react-router": { + "version": "6.28.1", + "resolved": "https://registry.npmjs.org/react-router/-/react-router-6.28.1.tgz", + "integrity": "sha512-2omQTA3rkMljmrvvo6WtewGdVh45SpL9hGiCI9uUrwGGfNFDIvGK4gYJsKlJoNVi6AQZcopSCballL+QGOm7fA==", + "license": "MIT", + "dependencies": { + "@remix-run/router": "1.21.0" + }, + "engines": { + "node": ">=14.0.0" + }, + "peerDependencies": { + "react": ">=16.8" + } + }, + "node_modules/react-router-dom": { + "version": "6.28.1", + "resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-6.28.1.tgz", + "integrity": "sha512-YraE27C/RdjcZwl5UCqF/ffXnZDxpJdk9Q6jw38SZHjXs7NNdpViq2l2c7fO7+4uWaEfcwfGCv3RSg4e1By/fQ==", + "license": "MIT", + "dependencies": { + "@remix-run/router": "1.21.0", + "react-router": "6.28.1" + }, + "engines": { + "node": ">=14.0.0" + }, + "peerDependencies": { + "react": ">=16.8", + "react-dom": ">=16.8" + } + }, + "node_modules/rollup": { + "version": "4.64.7", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.64.7.tgz", + "integrity": "sha512-aCiJONoZp0lNGJ6sYqspLkh6UXaWEey/7Ko2TZyXQ4kgzAhDUxAgbt/oulXKmD+zFHXw1k+RF6ZZWOrjp7DZnQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "1.0.9" + }, + "bin": { + "rollup": "dist/bin/rollup" + }, + "engines": { + "node": ">=18.0.0", + "npm": ">=8.0.0" + }, + "optionalDependencies": { + "@napi-rs/lzma-linux-x64-gnu": "1.5.1", + "@rollup/rollup-android-arm-eabi": "4.64.7", + "@rollup/rollup-android-arm64": "4.64.7", + "@rollup/rollup-darwin-arm64": "4.64.7", + "@rollup/rollup-darwin-x64": "4.64.7", + "@rollup/rollup-freebsd-arm64": "4.64.7", + "@rollup/rollup-freebsd-x64": "4.64.7", + "@rollup/rollup-linux-arm-gnueabihf": "4.64.7", + "@rollup/rollup-linux-arm-musleabihf": "4.64.7", + "@rollup/rollup-linux-arm64-gnu": "4.64.7", + "@rollup/rollup-linux-arm64-musl": "4.64.7", + "@rollup/rollup-linux-loong64-gnu": "4.64.7", + "@rollup/rollup-linux-loong64-musl": "4.64.7", + "@rollup/rollup-linux-ppc64-gnu": "4.64.7", + "@rollup/rollup-linux-ppc64-musl": "4.64.7", + "@rollup/rollup-linux-riscv64-gnu": "4.64.7", + "@rollup/rollup-linux-riscv64-musl": "4.64.7", + "@rollup/rollup-linux-s390x-gnu": "4.64.7", + "@rollup/rollup-linux-x64-gnu": "4.64.7", + "@rollup/rollup-linux-x64-musl": "4.64.7", + "@rollup/rollup-openbsd-x64": "4.64.7", + "@rollup/rollup-openharmony-arm64": "4.64.7", + "@rollup/rollup-win32-arm64-msvc": "4.64.7", + "@rollup/rollup-win32-ia32-msvc": "4.64.7", + "@rollup/rollup-win32-x64-gnu": "4.64.7", + "@rollup/rollup-win32-x64-msvc": "4.64.7", + "fsevents": "~2.3.2" + } + }, + "node_modules/scheduler": { + "version": "0.23.2", + "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.23.2.tgz", + "integrity": "sha512-UOShsPwz7NrMUqhR6t0hWjFduvOzbtv7toDH1/hIrfRNIDBnnBWd0CwJTGvTpngVlmwGCdP9/Zl/tVrDqcuYzQ==", + "license": "MIT", + "dependencies": { + "loose-envify": "^1.1.0" + } + }, + "node_modules/semver": { + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", + "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/source-map-js": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz", + "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/update-browserslist-db": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.3.4.tgz", + "integrity": "sha512-t8wonIOdQyOjtPd2VktlBu6QjTVTks6v8bSi7kd0r2Vll8TK1JYDZtRRdbmCHOAMphkZgrzK+L+vXK4pyZ8t4A==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "escalade": "^3.2.0", + "picocolors": "^1.1.1" + }, + "bin": { + "update-browserslist-db": "cli.js" + }, + "peerDependencies": { + "browserslist": ">= 4.21.0" + } + }, + "node_modules/vite": { + "version": "5.4.11", + "resolved": "https://registry.npmjs.org/vite/-/vite-5.4.11.tgz", + "integrity": "sha512-c7jFQRklXua0mTzneGW9QVyxFjUgwcihC4bXEtujIo2ouWCe1Ajt/amn2PCxYnhYfd5k09JX3SB7OYWFKYqj8Q==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "esbuild": "^0.21.3", + "postcss": "^8.4.43", + "rollup": "^4.20.0" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^18.0.0 || >=20.0.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^18.0.0 || >=20.0.0", + "less": "*", + "lightningcss": "^1.21.0", + "sass": "*", + "sass-embedded": "*", + "stylus": "*", + "sugarss": "*", + "terser": "^5.4.0" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "less": { + "optional": true + }, + "lightningcss": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + } + } + }, + "node_modules/yallist": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz", + "integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==", + "dev": true, + "license": "ISC" + } + } +} diff --git a/frontend/package.json b/frontend/package.json new file mode 100644 index 0000000..35a4ccb --- /dev/null +++ b/frontend/package.json @@ -0,0 +1,19 @@ +{ + "name": "tsumugu-frontend", + "private": true, + "type": "module", + "scripts": { + "dev": "vite", + "build": "vite build", + "preview": "vite preview" + }, + "dependencies": { + "react": "18.3.1", + "react-dom": "18.3.1", + "react-router-dom": "6.28.1" + }, + "devDependencies": { + "@vitejs/plugin-react": "4.3.4", + "vite": "5.4.11" + } +} diff --git a/frontend/src/App.jsx b/frontend/src/App.jsx new file mode 100644 index 0000000..120a8c4 --- /dev/null +++ b/frontend/src/App.jsx @@ -0,0 +1,85 @@ +import { useEffect, useState } from "react"; +import { Navigate, Route, Routes, useNavigate } from "react-router-dom"; +import { api, applySession, clearSession, isDirty } from "./api.js"; +import { SessionContext } from "./session.js"; +import { Login } from "./pages/Login.jsx"; +import { Shell } from "./pages/Shell.jsx"; +import { Overview } from "./pages/Overview.jsx"; +import { CaseList, CaseDetail } from "./pages/Cases.jsx"; +import { MatterList, MatterDetail } from "./pages/Matters.jsx"; +import { Rooms } from "./pages/Rooms.jsx"; +import { Search } from "./pages/Search.jsx"; + +export function App() { + const [session, setSession] = useState(undefined); + const navigate = useNavigate(); + + useEffect(() => { + let active = true; + api("/api/v1/auth/session") + .then((data) => { + if (!active) return; + applySession(data); + setSession(data); + }) + .catch(() => { + if (!active) return; + clearSession(); + setSession(null); + }); + return () => { + active = false; + }; + }, []); + + async function refresh() { + const data = await api("/api/v1/auth/session"); + applySession(data); + setSession(data); + return data; + } + + async function changeScope(next) { + if (isDirty() && !window.confirm("Ungespeicherte Eingaben verwerfen und den Datenraum wechseln?")) { + return; + } + const data = await api("/api/v1/auth/session/scope", { method: "POST", body: { kind: next.kind, id: next.id } }); + applySession(data); + setSession(data); + navigate("/"); + } + + async function logout() { + try { + await api("/api/v1/auth/logout", { method: "POST" }); + } catch { + /* Die lokale Sitzung endet auch, wenn der Server schon abgemeldet hat. */ + } + clearSession(); + setSession(null); + navigate("/login"); + } + + if (session === undefined) { + return

Tsumugu wird geladen …

; + } + + const value = { session, setSession, refresh, changeScope, logout }; + + return ( + + + : } /> + : }> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + + + + ); +} diff --git a/frontend/src/api.js b/frontend/src/api.js new file mode 100644 index 0000000..03fd3ad --- /dev/null +++ b/frontend/src/api.js @@ -0,0 +1,101 @@ +let csrf = ""; +let scope = null; +let epoch = 0; +let dirty = false; + +export function sessionState() { + return { csrf, scope, epoch }; +} + +export function applySession(data) { + csrf = data.csrf_token || ""; + scope = data.scope || null; + epoch = data.epoch || 0; + dirty = false; + return data; +} + +export function clearSession() { + csrf = ""; + scope = null; + epoch = 0; + dirty = false; +} + +export function markDirty(value) { + dirty = value; +} + +export function isDirty() { + return dirty; +} + +function scopeHeaders() { + if (!scope) return {}; + return { "X-Scope-Kind": scope.kind, "X-Scope-Id": scope.id }; +} + +export async function api(path, { method = "GET", body, form } = {}) { + const started = epoch; + const headers = { ...scopeHeaders() }; + if (csrf && method !== "GET" && method !== "HEAD") { + headers["X-CSRF-Token"] = csrf; + } + let payload; + if (form) { + payload = form; + } else if (body !== undefined) { + headers["Content-Type"] = "application/json"; + payload = JSON.stringify(body); + } + const response = await fetch(path, { method, headers, body: payload, credentials: "include" }); + if (started !== epoch) { + const error = new Error("Der Datenraum wurde gewechselt."); + error.status = 0; + throw error; + } + if (response.status === 204) return null; + const text = await response.text(); + const data = text ? JSON.parse(text) : null; + if (!response.ok) { + const error = new Error(data?.detail || "Die Anfrage ist fehlgeschlagen."); + error.status = response.status; + error.code = data?.code; + if (response.status === 401) clearSession(); + throw error; + } + return data; +} + +export async function downloadFile(elementId, context, filename) { + const params = new URLSearchParams(); + if (context?.kind && context?.id) { + params.set("context_kind", context.kind); + params.set("context_id", context.id); + } + const response = await fetch(`/api/v1/files/${elementId}/content?${params}`, { + credentials: "include", + headers: scopeHeaders(), + }); + if (!response.ok) { + throw new Error("Die Datei ist nicht verfügbar."); + } + const blob = await response.blob(); + const url = URL.createObjectURL(blob); + const link = document.createElement("a"); + link.href = url; + link.download = filename || "datei"; + document.body.appendChild(link); + link.click(); + link.remove(); + URL.revokeObjectURL(url); +} + +export function textToDocument(text) { + const blocks = text.split(/\n/).map((line) => ({ type: "paragraph", text: line })); + return { version: 1, blocks: blocks.length ? blocks : [{ type: "paragraph", text: "" }] }; +} + +export function documentToText(document) { + return (document?.blocks || []).map((block) => block.text || "").join("\n"); +} diff --git a/frontend/src/main.jsx b/frontend/src/main.jsx new file mode 100644 index 0000000..d81b9e6 --- /dev/null +++ b/frontend/src/main.jsx @@ -0,0 +1,13 @@ +import React from "react"; +import { createRoot } from "react-dom/client"; +import { BrowserRouter } from "react-router-dom"; +import { App } from "./App.jsx"; +import "./styles.css"; + +createRoot(document.getElementById("root")).render( + + + + + , +); diff --git a/frontend/src/pages/Cases.jsx b/frontend/src/pages/Cases.jsx new file mode 100644 index 0000000..8b8c7cf --- /dev/null +++ b/frontend/src/pages/Cases.jsx @@ -0,0 +1,395 @@ +import { useContext, useEffect, useState } from "react"; +import { Link, useParams } from "react-router-dom"; +import { api, markDirty, textToDocument } from "../api.js"; +import { SessionContext } from "../session.js"; +import { BindingList, Chronology, ErrorNote, ShareBox } from "./widgets.jsx"; + +export function CaseList() { + const { session } = useContext(SessionContext); + const [items, setItems] = useState([]); + const [title, setTitle] = useState(""); + const [error, setError] = useState(""); + + async function load() { + const data = await api("/api/v1/cases"); + setItems(data.items); + } + + useEffect(() => { + load().catch((err) => setError(err.message)); + }, [session.scope.id]); + + async function create(event) { + event.preventDefault(); + setError(""); + try { + await api("/api/v1/cases", { method: "POST", body: { title } }); + setTitle(""); + markDirty(false); + await load(); + } catch (err) { + setError(err.message); + } + } + + return ( +
+
+
+

Akten

+

Sichtbar ist, was du lesen darfst — auch aus anderen Datenräumen. Neue Akten entstehen in „{session.scope.name}“.

+
+
+
+ { + setTitle(event.target.value); + markDirty(true); + }} + placeholder="Neue Akte, zum Beispiel Mietstreit" + required + /> + +
+ +
    + {items.map((item) => ( +
  • + {item.title} + {item.status === "open" ? "Offen" : "Geschlossen"} +
  • + ))} +
+
+ ); +} + +export function CaseDetail() { + const { id } = useParams(); + const [record, setRecord] = useState(null); + const [events, setEvents] = useState([]); + const [error, setError] = useState(""); + const context = { kind: "case", id }; + + async function load() { + const [detail, chronology] = await Promise.all([ + api(`/api/v1/cases/${id}`), + api(`/api/v1/cases/${id}/chronology`), + ]); + setRecord(detail); + setEvents(chronology.items); + } + + useEffect(() => { + load().catch((err) => setError(err.message)); + }, [id]); + + if (error && !record) return
; + if (!record) return

Akte wird geladen …

; + + return ( +
+
+
+

{record.home_scope_name}

+

{record.title}

+

{rightsText(record.rights)} {record.status === "open" ? "Offen" : "Geschlossen"}.

+
+
+ +
+
+

Vorgänge

+
    + {record.matters.map((matter) => ( +
  • + {matter.title} +
  • + ))} +
+ {record.rights.edit ? : null} + {record.subcases?.length ? ( + <> +

Unterakten

+
    + {record.subcases.map((item) => ( +
  • {item.title}
  • + ))} +
+ + ) : null} + {record.rights.edit ? : null} +
+
+

Kapitel

+
    {record.chapters.map((chapter) =>
  • {chapter.title}
  • )}
+ {record.rights.edit ? : null} +
+
+
+

Inhalte

+ + {record.rights.edit ? : null} +
+ {record.grants || record.rights.share || record.is_owner ? ( + record.rights.share || record.is_owner ? ( + + ) : null + ) : null} +
+

Chronologie

+ +
+
+ ); +} + +function NewMatter({ caseId, onChange }) { + const [title, setTitle] = useState(""); + const [error, setError] = useState(""); + + async function submit(event) { + event.preventDefault(); + setError(""); + try { + const matter = await api("/api/v1/matters", { method: "POST", body: { title } }); + await api(`/api/v1/matters/${matter.id}/case-links`, { method: "POST", body: { case_id: caseId } }); + setTitle(""); + markDirty(false); + onChange(); + } catch (err) { + setError(err.message); + } + } + + return ( +
+

Vorgang anlegen und zuordnen

+ { setTitle(event.target.value); markDirty(true); }} placeholder="Zum Beispiel Mängelanzeige" required /> + + + + ); +} + +function NewSubcase({ parentId, onChange }) { + const [title, setTitle] = useState(""); + const [rightsMode, setRightsMode] = useState("inherit_parent"); + + async function submit(event) { + event.preventDefault(); + await api("/api/v1/cases", { method: "POST", body: { title, parent_case_id: parentId, rights_mode: rightsMode } }); + setTitle(""); + onChange(); + } + + return ( +
+

Unterakte

+ setTitle(event.target.value)} placeholder="Titel der Unterakte" required /> + + +
+ ); +} + +export function ChapterForm({ path, onChange }) { + const [title, setTitle] = useState(""); + + async function submit(event) { + event.preventDefault(); + await api(path, { method: "POST", body: { title } }); + setTitle(""); + onChange(); + } + + return ( +
+ setTitle(event.target.value)} placeholder="Kapitel" required /> + +
+ ); +} + +export function ContentForms({ context, placement, chapters, onChange }) { + return ( +
+ + + +
+ ); +} + +function chapterSelect(chapters, value, setValue) { + return ( + + ); +} + +function NoteForm({ context, placement, chapters, onChange }) { + const [title, setTitle] = useState(""); + const [text, setText] = useState(""); + const [chapterId, setChapterId] = useState(""); + const [error, setError] = useState(""); + + async function submit(event) { + event.preventDefault(); + setError(""); + try { + await api("/api/v1/notes", { + method: "POST", + body: { + title, + document: textToDocument(text), + context, + ...(placement ? { placement } : {}), + ...(chapterId ? { chapter_id: chapterId } : {}), + }, + }); + setTitle(""); + setText(""); + markDirty(false); + onChange(); + } catch (err) { + setError(err.message); + } + } + + return ( +
+

Notiz

+ { setTitle(event.target.value); markDirty(true); }} placeholder="Titel" required /> +