fix(remote): keep each session cookie's domain, path and secure flag

The client set server cookies with no domain and sent all of them to every host, so a CDN refused segment requests with 400 header too large. rnet sessions now send cookies too.
This commit is contained in:
imSp4rky
2026-10-23 09:42:01 -06:00
parent af69e8aad4
commit eeaf16cd83
7 changed files with 211 additions and 27 deletions
+28 -12
View File
@@ -34,7 +34,7 @@ from unshackle.core.drm import cbcs
from unshackle.core.providers.anilist import parse_anilist_ref
from unshackle.core.proxies.resolve import initialize_proxy_providers, resolve_proxy
from unshackle.core.services import Services
from unshackle.core.session import utf8_text
from unshackle.core.session import RnetSession, utf8_text
from unshackle.core.titles import Episode, Movie, Song, Title_T
from unshackle.core.titles.music import SONG_FIELDS
from unshackle.core.tracks import Audio, Subtitle, Tracks, Video
@@ -4068,8 +4068,8 @@ async def session_titles_handler(session_id: str, request: Optional[web.Request]
)
def client_session_auth(session: Any) -> tuple[Dict[str, str], Dict[str, str]]:
"""The service session headers and cookies a remote client may receive.
def client_session_auth(session: Any) -> tuple[Dict[str, str], list[Dict[str, Any]]]:
"""The service session headers and cookies (name, value, domain, path, secure) a remote client may receive.
A client whose own login succeeded gets them back. For a server account the cookie jar
stays on the server and the server drops the auth-bearing headers, so the client cannot
@@ -4078,18 +4078,31 @@ def client_session_auth(session: Any) -> tuple[Dict[str, str], Dict[str, str]]:
"""
svc_session = session.service_instance.session
headers = dict(svc_session.headers) if hasattr(svc_session, "headers") and svc_session.headers else {}
cookies: Dict[str, str] = {}
if hasattr(svc_session, "cookies"):
for cookie in svc_session.cookies:
if hasattr(cookie, "name") and hasattr(cookie, "value"):
cookies[cookie.name] = cookie.value
cookies: list[Dict[str, Any]] = []
jar = svc_session.scoped_cookies() if isinstance(svc_session, RnetSession) else getattr(svc_session, "cookies", [])
for cookie in jar:
if hasattr(cookie, "name") and hasattr(cookie, "value"):
cookies.append(
{
"name": cookie.name,
"value": cookie.value,
"domain": getattr(cookie, "domain", None) or "",
"path": getattr(cookie, "path", None) or "/",
"secure": bool(getattr(cookie, "secure", False)),
}
)
if not client_owns_login(session):
headers = {k: v for k, v in headers.items() if not CONFIG_SECRET_KEY_RE.search(str(k))}
if not session.client_auth:
cookies = {}
cookies = []
return headers, cookies
def cookie_values(cookies: list[Dict[str, Any]]) -> Dict[str, str]:
"""The ``{name: value}`` form of :func:`client_session_auth` cookies, for clients that predate the jar."""
return {c["name"]: c["value"] for c in cookies}
def client_owns_login(session: Any) -> bool:
"""Whether the login state of ``session`` is the client's to take back.
@@ -4232,7 +4245,8 @@ async def session_tracks_handler(
"manifests": manifests,
"track_manifests": track_manifests,
"session_headers": session_headers,
"session_cookies": session_cookies,
"session_cookies": cookie_values(session_cookies),
"session_cookie_jar": session_cookies,
"server_cdm": session.server_cdm,
"server_cdm_type": server_cdm_type,
"sample_decrypt_tracks": [
@@ -4269,6 +4283,7 @@ async def session_segments_handler(
try:
result: Dict[str, Any] = {}
headers, cookies = client_session_auth(session)
for track_id in track_ids:
track = session.tracks.get(track_id)
@@ -4285,10 +4300,11 @@ async def session_segments_handler(
"descriptor": descriptor_name,
"url": str(track.url) if track.url else None,
"drm": serialize_drm(track.drm) if hasattr(track, "drm") and track.drm else None,
"headers": headers,
"cookies": cookie_values(cookies),
"cookie_jar": cookies,
}
track_info["headers"], track_info["cookies"] = client_session_auth(session)
# Include manifest-specific data for segment resolution. Round-trip through
# JSON so any non-serializable value becomes its str() (default=str).
if hasattr(track, "data") and track.data:
+22 -2
View File
@@ -426,6 +426,27 @@ def apply_service_track_data(tracks: Tracks, data: Dict[str, Any]) -> None:
track.data.update(extra)
def apply_session_cookies(session: requests.Session, result: dict) -> None:
"""Copy the server's session cookies into ``session``, each scoped to its own domain.
An older server sends only ``session_cookies`` names and values, so those cookies go to every host.
It skips malformed entries.
"""
jar = result.get("session_cookie_jar")
if not isinstance(jar, list):
old = result.get("session_cookies")
jar = [{"name": k, "value": v} for k, v in old.items()] if isinstance(old, dict) else []
for c in jar:
if isinstance(c, dict) and isinstance(c.get("name"), str) and isinstance(c.get("value"), str):
session.cookies.set(
c["name"],
c["value"],
domain=str(c.get("domain") or ""),
path=str(c.get("path") or "/"),
secure=bool(c.get("secure")),
)
def resolve_track_manifests(tracks: Tracks, track_manifests: list) -> None:
"""Fill track.data from the per-track MPD fragments the server sent.
@@ -1651,8 +1672,7 @@ class RemoteService:
for k, v in result.get("session_headers", {}).items():
if k.lower() not in ("host", "content-length", "content-type"):
self._session.headers[k] = v
for k, v in result.get("session_cookies", {}).items():
self._session.cookies.set(k, v)
apply_session_cookies(self._session, result)
resolve_track_manifests(tracks, result.get("track_manifests", []))
resolve_manifest_data(tracks, result.get("manifests", []))
+31 -5
View File
@@ -17,6 +17,7 @@ from urllib.parse import urlencode, urlparse, urlunparse
import rnet
from requests import HTTPError, Request, Response
from requests.cookies import create_cookie
from requests.structures import CaseInsensitiveDict
from unshackle.core.config import config
@@ -664,14 +665,19 @@ class RnetSession:
self._client = client
@staticmethod
def set_cookie_header(client: rnet.BlockingClient, origin: str, header: str) -> None:
"""Set every cookie in a ``name=value; ...`` header string on one origin of *client*."""
def parse_cookie_header(header: str) -> Iterator[tuple[str, str]]:
"""The ``(name, value)`` pairs of a ``name=value; ...`` header string."""
for pair in header.split(";"):
name, separator, value = pair.partition("=")
if not separator:
continue
if separator:
yield name.strip(), value.strip()
@staticmethod
def set_cookie_header(client: rnet.BlockingClient, origin: str, header: str) -> None:
"""Set every cookie in a ``name=value; ...`` header string on one origin of *client*."""
for name, value in RnetSession.parse_cookie_header(header):
try:
client.set_cookie(origin, rnet.Cookie(name.strip(), value.strip()))
client.set_cookie(origin, rnet.Cookie(name, value))
except Exception:
pass
@@ -705,6 +711,26 @@ class RnetSession:
exported[origin] = raw.decode("utf-8", errors="replace")
return exported
def scoped_cookies(self) -> CookieJar:
"""Every cookie this HTTP session sends, each scoped to its domain.
The live client's cookies of each requested origin come first, then the cookies set
through :attr:`cookies` for any other host.
"""
jar = CookieJar()
hosts: dict[str, set[str]] = {}
for origin, header in self.export_origin_cookies().items():
host = urlparse(origin).hostname or ""
for name, value in self.parse_cookie_header(header):
jar.set_cookie(create_cookie(name, value, domain=host))
hosts.setdefault(name, set()).add(host)
for domain, values in self.cookies.get_dict_by_domain().items():
bare = domain.lstrip(".")
for name, value in values.items():
if not any(h == bare or h.endswith("." + bare) for h in hosts.get(name, ())):
jar.set_cookie(create_cookie(name, value, domain=domain))
return jar
def import_origin_cookies(self, exported: dict[str, str]) -> None:
"""Load cookie headers from :meth:`export_origin_cookies` into this HTTP session's client."""
if not exported: