Spaces:
Running on Zero
Running on Zero
File size: 1,842 Bytes
236388e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | """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)
|