"""Canonical page URLs for return navigation and authentication recovery.""" import re from urllib.parse import parse_qsl, quote, unquote, urlencode, urlsplit from .dashboard_segment import parse_segment, segment_filters from .query_filter import import_filter_config LIST_PATH = "/app/forderungen/liste" DETAIL_PREFIX = "/app/forderungen/details/" DETAIL_PAGE = re.compile(r"^/app/forderungen/details/([^/]+)(?:/(?:kommentare|buchungen))?/?$") ASSIGNEE_MODAL = re.compile(r"^/app/forderungen/(liste|details)/([^/]+)/verursacher/?$") FOLLOW_UP_MODAL = re.compile(r"^/app/forderungen/liste/([^/]+)/wiedervorlage/?$") def valid_focus(value: str | None) -> bool: if not value or any(ord(c) < 32 or ord(c) == 127 or c in "/\\" for c in value): return False tenant, separator, number = value.partition("_") return bool(separator and tenant and number and len(tenant) <= 20 and len(number) <= 100) def _local_parts(value): if not isinstance(value, str) or not value.startswith("/") or value.startswith("//"): return None if any(ord(c) < 32 or ord(c) == 127 or c == "\\" for c in value): return None try: parts = urlsplit(value) except ValueError: return None decoded = unquote(parts.path) if parts.scheme or parts.netloc or decoded.startswith("//") or "\\" in decoded: return None if any(ord(c) < 32 or ord(c) == 127 for c in decoded): return None return parts def list_url(filters=None, focus: str | None = None) -> str: filters = filters or {} config = import_filter_config("forderungen") multi_fields = {f.name for f in config if f.filter_type in {"select", "text"}} params = {f.name: filters[f.name] for f in config if f.name in filters and filters[f.name] not in ("", None)} if filters.get("dashboard_segment"): try: params = {**segment_filters(parse_segment(filters["dashboard_segment"])), **params} except ValueError: pass # Untrusted return/login URLs must never carry malformed selections. if valid_focus(focus): params["focus"] = focus # Only separators remain literal; encoded commas inside values stay %252C. query = "&".join( urlencode({name: value}, safe="," if name in multi_fields else "") for name, value in params.items() ) return LIST_PATH + ("?" + query if query else "") def list_return_url(value: str | None, primary_key: str) -> str: parts = _local_parts(value) filters = dict(parse_qsl(parts.query)) if parts and parts.path == LIST_PATH else {} return list_url(filters, primary_key) def _current_parts(value): """Extract context, never a redirect origin, from the browser's current URL.""" if not value: return None try: parts = urlsplit(value) except ValueError: return None if parts.scheme and parts.scheme not in ("http", "https"): return None return _local_parts(parts.path + ("?" + parts.query if parts.query else "")) def return_url_for_request(request, primary_key: str, explicit: str | None = None) -> str: value = explicit if explicit is not None else request.query_params.get("return_to") if value is None: current = _current_parts(request.headers.get("HX-Current-URL")) match = DETAIL_PAGE.fullmatch(unquote(current.path)) if current else None if match and match[1] == primary_key: value = dict(parse_qsl(current.query)).get("return_to") return list_return_url(value, primary_key) def detail_navigation_context(request, primary_key: str, explicit: str | None = None) -> dict: return_url = return_url_for_request(request, primary_key, explicit) return { "return_url": return_url, "detail_post_url": DETAIL_PREFIX + quote(primary_key, safe="") + "?" + urlencode({"return_to": return_url}), } def normalize_page_url(value: str | None, default="/select", current_url: str | None = None) -> str: parts = _local_parts(value) if not parts: return default params = dict(parse_qsl(parts.query)) current = _current_parts(current_url) follow_up = FOLLOW_UP_MODAL.fullmatch(unquote(parts.path)) if follow_up and valid_focus(follow_up[1]): value = params.get("return_to") if value is None and current and current.path == LIST_PATH: value = current.path + ("?" + current.query if current.query else "") return list_return_url(value, follow_up[1]) modal = ASSIGNEE_MODAL.fullmatch(unquote(parts.path)) if modal and valid_focus(modal[2]): primary_key = modal[2] value = params.get("return_to") if modal[1] == "liste": if value is None and current and current.path == LIST_PATH: value = current.path + ("?" + current.query if current.query else "") return list_return_url(value, primary_key) if value is None and current: previous = DETAIL_PAGE.fullmatch(unquote(current.path)) if previous and previous[1] == primary_key: value = dict(parse_qsl(current.query)).get("return_to") return ( DETAIL_PREFIX + quote(primary_key, safe="") + "?" + urlencode({"return_to": list_return_url(value, primary_key)}) ) if parts.path == LIST_PATH: focus = params.get("focus") if not focus and current and current.path == LIST_PATH: previous = dict(parse_qsl(current.query)) if list_url(params) == list_url(previous): focus = previous.get("focus") return list_url(params, focus) match = DETAIL_PAGE.fullmatch(unquote(parts.path)) if match and valid_focus(match[1]): primary_key = match[1] value = params.get("return_to") if value is None and current: previous = DETAIL_PAGE.fullmatch(unquote(current.path)) if previous and previous[1] == primary_key: value = dict(parse_qsl(current.query)).get("return_to") detail = DETAIL_PREFIX + quote(primary_key, safe="") return detail + ("?" + urlencode({"return_to": list_return_url(value, primary_key)}) if value else "") return parts.path + ("?" + parts.query if parts.query else "") + ("#" + parts.fragment if parts.fragment else "")