"""Allowlisted browser-handoff destinations. No durable secrets ever go in these URLs."""
from __future__ import annotations

ALLOWED_HANDOFF_PREFIXES: tuple[str, ...] = (
    "/billing",
    "/settings/team",
    "/settings/security",
    "/settings/profile",
    "/settings/api-keys",
    "/settings/devices",
    "/projects/",
    "/workspaces/",
)


def normalize_handoff_next(next_path: str | None) -> str:
    """Return a same-origin path under the allowlist, or raise ValueError."""
    raw = (next_path or "/billing").strip() or "/billing"
    if "://" in raw or "\\" in raw or ".." in raw:
        raise ValueError("Invalid handoff destination")
    if not raw.startswith("/"):
        raw = "/" + raw
    allowed = False
    for prefix in ALLOWED_HANDOFF_PREFIXES:
        if prefix.endswith("/"):
            if raw.startswith(prefix) or raw == prefix.rstrip("/"):
                allowed = True
                break
        elif raw == prefix or raw.startswith(prefix + "/"):
            allowed = True
            break
    if not allowed:
        raise ValueError("Handoff destination is not allowlisted")
    return raw
