"""Cookie transport for Gradio OAuth inside storage-restricted Hub embeds.""" import hmac import os import secrets from starlette.datastructures import MutableHeaders from starlette.middleware.sessions import SessionMiddleware from starlette.requests import HTTPConnection COOKIE = "__Host-ffv-oauth" MARKER = "__Host-ffv-embed" class EmbeddedOAuth: def __init__(self, app): self.app = app secret = os.environ.get("OAUTH_CLIENT_SECRET") or secrets.token_urlsafe(48) key = hmac.digest(secret.encode(), b"FastFrames Voice embedded OAuth v1", "sha256").hex() self.embedded = SessionMiddleware(app, secret_key=key, session_cookie=COOKIE, same_site="none", https_only=True) async def __call__(self, scope, receive, send): if scope["type"] not in ("http", "websocket"): return await self.app(scope, receive, send) cookies = HTTPConnection(scope).cookies if cookies.get(MARKER) != "1" and COOKIE not in cookies: return await self.app(scope, receive, send) async def partition_cookie(message): if message["type"] == "http.response.start": headers = MutableHeaders(scope=message) values = headers.getlist("set-cookie") if any(v.startswith(COOKIE + "=") for v in values): del headers["set-cookie"] for value in values: headers.append("set-cookie", value + "; Partitioned" if value.startswith(COOKIE + "=") else value) await send(message) # Keep the embed's signed session separate from Gradio's ordinary session. # Gradio/Authlib still handle authorization, state validation and logout. await self.embedded(dict(scope), receive, partition_cookie)