Spaces:
Sleeping
Sleeping
Deploy compatible R4 managed authentication
Browse files- managed_auth.py +226 -148
managed_auth.py
CHANGED
|
@@ -4,6 +4,8 @@
|
|
| 4 |
from __future__ import annotations
|
| 5 |
|
| 6 |
import base64
|
|
|
|
|
|
|
| 7 |
import html
|
| 8 |
import io
|
| 9 |
import json
|
|
@@ -11,7 +13,6 @@ import os
|
|
| 11 |
import time
|
| 12 |
from datetime import datetime, timezone
|
| 13 |
from typing import Any, Callable
|
| 14 |
-
from urllib.parse import unquote
|
| 15 |
|
| 16 |
import qrcode
|
| 17 |
import requests
|
|
@@ -35,10 +36,15 @@ RETRY_DELAY_SECONDS = 1.0
|
|
| 35 |
SESSION_VERIFY_INTERVAL_SECONDS = 60
|
| 36 |
AUTO_LOGIN_POLL_INTERVAL_SECONDS = 2.0
|
| 37 |
TRANSIENT_HTTP_STATUS = {502, 503, 504}
|
| 38 |
-
|
|
|
|
| 39 |
ACCESS_QR_FILENAME = "SmartPaper_Access_QR.png"
|
| 40 |
-
|
| 41 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
|
| 43 |
_DIRECT_SESSION = requests.Session()
|
| 44 |
_DIRECT_SESSION.trust_env = False
|
|
@@ -64,11 +70,57 @@ def _runtime_value(name: str) -> str:
|
|
| 64 |
return str(value or "").strip()
|
| 65 |
|
| 66 |
|
| 67 |
-
def
|
| 68 |
-
value =
|
| 69 |
-
if not value:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 70 |
raise RuntimeError("SMARTPAPER_AUTH_API is not configured.")
|
| 71 |
-
return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 72 |
|
| 73 |
|
| 74 |
def _service_key() -> str:
|
|
@@ -79,8 +131,7 @@ def _service_key() -> str:
|
|
| 79 |
|
| 80 |
|
| 81 |
def _post(path: str, payload: dict[str, Any]) -> dict[str, Any]:
|
| 82 |
-
"""Call
|
| 83 |
-
url = f"{_api_base()}{path}"
|
| 84 |
headers = {
|
| 85 |
"Authorization": f"Bearer {_service_key()}",
|
| 86 |
"Content-Type": "application/json",
|
|
@@ -88,39 +139,63 @@ def _post(path: str, payload: dict[str, Any]) -> dict[str, Any]:
|
|
| 88 |
"User-Agent": "SmartPaper-HuggingFace/1.0",
|
| 89 |
"Connection": "close",
|
| 90 |
}
|
| 91 |
-
|
| 92 |
transports = (
|
| 93 |
("direct", _DIRECT_SESSION),
|
| 94 |
("environment", _ENVIRONMENT_SESSION),
|
| 95 |
)
|
| 96 |
last_error: Exception | None = None
|
| 97 |
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 107 |
|
| 108 |
if response.status_code in TRANSIENT_HTTP_STATUS:
|
| 109 |
last_error = RuntimeError(
|
| 110 |
-
|
| 111 |
f"{response.status_code} via {transport_name}."
|
| 112 |
)
|
| 113 |
-
if
|
| 114 |
time.sleep(RETRY_DELAY_SECONDS)
|
| 115 |
continue
|
|
|
|
| 116 |
|
| 117 |
try:
|
| 118 |
data = response.json()
|
| 119 |
except ValueError as exc:
|
| 120 |
-
|
| 121 |
"Authentication service returned non-JSON content "
|
| 122 |
-
f"(HTTP {response.status_code},
|
| 123 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 124 |
|
| 125 |
if response.status_code >= 400:
|
| 126 |
message = (
|
|
@@ -129,35 +204,27 @@ def _post(path: str, payload: dict[str, Any]) -> dict[str, Any]:
|
|
| 129 |
or data.get("error")
|
| 130 |
or f"HTTP {response.status_code}"
|
| 131 |
)
|
| 132 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 133 |
|
| 134 |
return data
|
| 135 |
|
| 136 |
-
except requests.exceptions.Timeout as exc:
|
| 137 |
-
last_error = exc
|
| 138 |
-
if index < len(transports) - 1:
|
| 139 |
-
time.sleep(RETRY_DELAY_SECONDS)
|
| 140 |
-
continue
|
| 141 |
-
|
| 142 |
-
except requests.exceptions.ConnectionError as exc:
|
| 143 |
-
last_error = exc
|
| 144 |
-
if index < len(transports) - 1:
|
| 145 |
-
time.sleep(RETRY_DELAY_SECONDS)
|
| 146 |
-
continue
|
| 147 |
-
|
| 148 |
if isinstance(last_error, requests.exceptions.Timeout):
|
| 149 |
raise AuthServiceTimeoutError(
|
| 150 |
"authentication_service_timeout"
|
| 151 |
) from last_error
|
| 152 |
-
|
| 153 |
if isinstance(last_error, requests.exceptions.ConnectionError):
|
| 154 |
raise AuthServiceConnectionError(
|
| 155 |
"authentication_service_connection_error"
|
| 156 |
) from last_error
|
| 157 |
-
|
| 158 |
if last_error is not None:
|
| 159 |
raise RuntimeError(str(last_error))
|
| 160 |
-
|
| 161 |
raise RuntimeError("Unknown authentication service error.")
|
| 162 |
|
| 163 |
|
|
@@ -201,97 +268,125 @@ def _clear_session(*, clear_restore: bool = False) -> None:
|
|
| 201 |
if clear_restore:
|
| 202 |
st.session_state.pop("sp_restore_token", None)
|
| 203 |
st.session_state.pop("sp_restore_expires_at", None)
|
|
|
|
|
|
|
|
|
|
| 204 |
|
| 205 |
|
| 206 |
-
def
|
| 207 |
-
"""Read the restore cookie supplied with the initial Streamlit request."""
|
| 208 |
try:
|
| 209 |
context = getattr(st, "context", None)
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 213 |
except Exception:
|
| 214 |
-
# Compatibility fallback: never interrupt the approved login page.
|
| 215 |
return ""
|
|
|
|
| 216 |
|
| 217 |
|
| 218 |
-
def
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
if
|
| 235 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 236 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 237 |
script = f"""
|
| 238 |
<script>
|
| 239 |
(() => {{
|
| 240 |
-
const
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
}}
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
.split("; ")
|
| 256 |
-
.some((entry) => entry.startsWith(`${{name}}=`));
|
| 257 |
-
cookieActionSucceeded = maxAge === 0
|
| 258 |
-
? !cookiePresent
|
| 259 |
-
: cookiePresent;
|
| 260 |
-
}} catch (error) {{
|
| 261 |
-
console.error("SmartPaper restore-cookie action failed", error);
|
| 262 |
-
}}
|
| 263 |
-
|
| 264 |
-
if (!cookieActionSucceeded) {{
|
| 265 |
-
console.error("SmartPaper restore-cookie verification failed");
|
| 266 |
-
}}
|
| 267 |
-
|
| 268 |
-
if (reloadParent && cookieActionSucceeded) {{
|
| 269 |
-
window.setTimeout(() => {{
|
| 270 |
-
try {{
|
| 271 |
-
window.parent.location.reload();
|
| 272 |
-
}} catch (error) {{
|
| 273 |
-
window.location.reload();
|
| 274 |
-
}}
|
| 275 |
-
}}, 180);
|
| 276 |
-
}}
|
| 277 |
}})();
|
| 278 |
</script>
|
| 279 |
"""
|
| 280 |
components.html(script, height=0, width=0)
|
| 281 |
|
| 282 |
|
| 283 |
-
def
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 290 |
)
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 295 |
|
| 296 |
|
| 297 |
def _verify_existing_session() -> bool:
|
|
@@ -363,10 +458,8 @@ def _create_login_request() -> dict[str, Any]:
|
|
| 363 |
def _store_authenticated_session(result: dict[str, Any]) -> None:
|
| 364 |
session_token = result.get("session_token")
|
| 365 |
user = result.get("user")
|
| 366 |
-
|
| 367 |
if not session_token or not user:
|
| 368 |
raise RuntimeError("Login succeeded but the session data is incomplete.")
|
| 369 |
-
|
| 370 |
st.session_state["sp_session_token"] = session_token
|
| 371 |
st.session_state["sp_session_expires_at"] = result.get(
|
| 372 |
"session_expires_at"
|
|
@@ -379,33 +472,21 @@ def _store_authenticated_session(result: dict[str, Any]) -> None:
|
|
| 379 |
st.session_state["sp_restore_expires_at"] = result.get(
|
| 380 |
"restore_expires_at"
|
| 381 |
)
|
| 382 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 383 |
_clear_login_request()
|
| 384 |
|
| 385 |
|
| 386 |
def _try_restore_authenticated_session() -> bool:
|
| 387 |
-
"""
|
| 388 |
-
|
| 389 |
-
st.session_state.get("sp_restore_token") or _read_restore_cookie()
|
| 390 |
-
).strip()
|
| 391 |
-
if not restore_token:
|
| 392 |
-
return False
|
| 393 |
-
try:
|
| 394 |
-
result = _post("/session/restore", {"restore_token": restore_token})
|
| 395 |
-
except (AuthServiceTimeoutError, AuthServiceConnectionError):
|
| 396 |
-
return False
|
| 397 |
-
except Exception:
|
| 398 |
-
st.session_state.pop("sp_restore_token", None)
|
| 399 |
-
st.session_state.pop("sp_restore_expires_at", None)
|
| 400 |
-
_delete_restore_cookie()
|
| 401 |
-
return False
|
| 402 |
-
if not result.get("ok") or not result.get("session_token"):
|
| 403 |
-
st.session_state.pop("sp_restore_token", None)
|
| 404 |
-
st.session_state.pop("sp_restore_expires_at", None)
|
| 405 |
-
_delete_restore_cookie()
|
| 406 |
-
return False
|
| 407 |
-
_store_authenticated_session(result)
|
| 408 |
-
return True
|
| 409 |
|
| 410 |
|
| 411 |
def _public_url() -> str:
|
|
@@ -632,11 +713,6 @@ def _poll_login_once(
|
|
| 632 |
st.stop()
|
| 633 |
|
| 634 |
if status == "authenticated":
|
| 635 |
-
# Store the authenticated Streamlit session first and rerun within the
|
| 636 |
-
# same browser session. On the authenticated rerun, the hidden cookie
|
| 637 |
-
# command is rendered without forcing another page reload, so the
|
| 638 |
-
# writing interface opens immediately and the restore token has time
|
| 639 |
-
# to persist for future manual refreshes.
|
| 640 |
_store_authenticated_session(result)
|
| 641 |
status_box.success(tr(language, "login_auto_success"))
|
| 642 |
st.rerun()
|
|
@@ -746,7 +822,11 @@ def logout_alipay_session(
|
|
| 746 |
) -> None:
|
| 747 |
session_token = str(st.session_state.get("sp_session_token") or "").strip()
|
| 748 |
restore_token = str(
|
| 749 |
-
st.session_state.get("sp_restore_token") or
|
|
|
|
|
|
|
|
|
|
|
|
|
| 750 |
).strip()
|
| 751 |
user_id = str((st.session_state.get("sp_user") or {}).get("id") or "")
|
| 752 |
task = st.session_state.get("sp_generation_task") or {}
|
|
@@ -771,18 +851,16 @@ def logout_alipay_session(
|
|
| 771 |
{
|
| 772 |
"session_token": session_token,
|
| 773 |
"restore_token": restore_token,
|
|
|
|
| 774 |
},
|
| 775 |
)
|
| 776 |
except Exception:
|
| 777 |
pass
|
| 778 |
|
| 779 |
-
# Delete the browser token first, then let browser JavaScript reload the
|
| 780 |
-
# page. This avoids interrupting the cookie deletion with st.rerun().
|
| 781 |
-
_delete_restore_cookie(reload_parent=True)
|
| 782 |
_clear_session(clear_restore=True)
|
| 783 |
_clear_login_request()
|
| 784 |
_clear_generation_session_state()
|
| 785 |
-
st.
|
| 786 |
|
| 787 |
|
| 788 |
def render_logged_in_account(
|
|
@@ -923,7 +1001,7 @@ def require_alipay_login(
|
|
| 923 |
language: str = "zh",
|
| 924 |
) -> dict[str, Any]:
|
| 925 |
"""Require Alipay authentication and return the verified user."""
|
| 926 |
-
|
| 927 |
if _verify_existing_session():
|
| 928 |
return dict(st.session_state.get("sp_user", {}))
|
| 929 |
if _try_restore_authenticated_session():
|
|
|
|
| 4 |
from __future__ import annotations
|
| 5 |
|
| 6 |
import base64
|
| 7 |
+
import hashlib
|
| 8 |
+
import hmac
|
| 9 |
import html
|
| 10 |
import io
|
| 11 |
import json
|
|
|
|
| 13 |
import time
|
| 14 |
from datetime import datetime, timezone
|
| 15 |
from typing import Any, Callable
|
|
|
|
| 16 |
|
| 17 |
import qrcode
|
| 18 |
import requests
|
|
|
|
| 36 |
SESSION_VERIFY_INTERVAL_SECONDS = 60
|
| 37 |
AUTO_LOGIN_POLL_INTERVAL_SECONDS = 2.0
|
| 38 |
TRANSIENT_HTTP_STATUS = {502, 503, 504}
|
| 39 |
+
DEFAULT_AUTH_RELAY_URL = "https://smartpaper-auth-relay-pages.pages.dev"
|
| 40 |
+
DEFAULT_PUBLIC_URL = "https://smartpaper-auth.guxiaopeng2025.workers.dev"
|
| 41 |
ACCESS_QR_FILENAME = "SmartPaper_Access_QR.png"
|
| 42 |
+
GATEWAY_HEADER_VERSION = "X-SmartPaper-Gateway-Version"
|
| 43 |
+
GATEWAY_HEADER_TIMESTAMP = "X-SmartPaper-Gateway-Timestamp"
|
| 44 |
+
GATEWAY_HEADER_BROWSER_TOKEN = "X-SmartPaper-Browser-Token"
|
| 45 |
+
GATEWAY_HEADER_SIGNATURE = "X-SmartPaper-Gateway-Signature"
|
| 46 |
+
GATEWAY_HEADER_PUBLIC_ORIGIN = "X-SmartPaper-Public-Origin"
|
| 47 |
+
GATEWAY_ASSERTION_MAX_AGE_SECONDS = 120
|
| 48 |
|
| 49 |
_DIRECT_SESSION = requests.Session()
|
| 50 |
_DIRECT_SESSION.trust_env = False
|
|
|
|
| 70 |
return str(value or "").strip()
|
| 71 |
|
| 72 |
|
| 73 |
+
def _normalize_https_origin(value: str) -> str:
|
| 74 |
+
value = str(value or "").strip().rstrip("/")
|
| 75 |
+
if not value.startswith("https://"):
|
| 76 |
+
return ""
|
| 77 |
+
return value
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def _api_bases() -> tuple[str, ...]:
|
| 81 |
+
"""Return stable authentication API candidates in failover order.
|
| 82 |
+
|
| 83 |
+
Hugging Face uses the existing Cloudflare Pages relay for server-to-server
|
| 84 |
+
calls. The public Worker URL remains the browser entry and final fallback.
|
| 85 |
+
This order also tolerates an older Space variable that still points
|
| 86 |
+
SMARTPAPER_AUTH_API at the public Worker URL.
|
| 87 |
+
"""
|
| 88 |
+
configured = _normalize_https_origin(
|
| 89 |
+
_runtime_value("SMARTPAPER_AUTH_API")
|
| 90 |
+
)
|
| 91 |
+
configured_relay = _normalize_https_origin(
|
| 92 |
+
_runtime_value("SMARTPAPER_AUTH_RELAY")
|
| 93 |
+
)
|
| 94 |
+
public_url = _normalize_https_origin(
|
| 95 |
+
_runtime_value("SMARTPAPER_PUBLIC_URL")
|
| 96 |
+
) or DEFAULT_PUBLIC_URL
|
| 97 |
+
relay_url = configured_relay or DEFAULT_AUTH_RELAY_URL
|
| 98 |
+
|
| 99 |
+
ordered: list[str] = []
|
| 100 |
+
|
| 101 |
+
def add(candidate: str) -> None:
|
| 102 |
+
normalized = _normalize_https_origin(candidate)
|
| 103 |
+
if normalized and normalized not in ordered:
|
| 104 |
+
ordered.append(normalized)
|
| 105 |
+
|
| 106 |
+
# A separately configured non-public API is authoritative. When the
|
| 107 |
+
# configured API equals the browser Worker, prefer the established Pages
|
| 108 |
+
# relay first to avoid the Hugging Face -> workers.dev timeout observed in
|
| 109 |
+
# production.
|
| 110 |
+
if configured and configured != public_url:
|
| 111 |
+
add(configured)
|
| 112 |
+
add(relay_url)
|
| 113 |
+
add(configured)
|
| 114 |
+
add(public_url)
|
| 115 |
+
|
| 116 |
+
if not ordered:
|
| 117 |
raise RuntimeError("SMARTPAPER_AUTH_API is not configured.")
|
| 118 |
+
return tuple(ordered)
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def _api_base() -> str:
|
| 122 |
+
"""Backward-compatible accessor for the primary API endpoint."""
|
| 123 |
+
return _api_bases()[0]
|
| 124 |
|
| 125 |
|
| 126 |
def _service_key() -> str:
|
|
|
|
| 131 |
|
| 132 |
|
| 133 |
def _post(path: str, payload: dict[str, Any]) -> dict[str, Any]:
|
| 134 |
+
"""Call the authentication service with bounded endpoint failover."""
|
|
|
|
| 135 |
headers = {
|
| 136 |
"Authorization": f"Bearer {_service_key()}",
|
| 137 |
"Content-Type": "application/json",
|
|
|
|
| 139 |
"User-Agent": "SmartPaper-HuggingFace/1.0",
|
| 140 |
"Connection": "close",
|
| 141 |
}
|
|
|
|
| 142 |
transports = (
|
| 143 |
("direct", _DIRECT_SESSION),
|
| 144 |
("environment", _ENVIRONMENT_SESSION),
|
| 145 |
)
|
| 146 |
last_error: Exception | None = None
|
| 147 |
|
| 148 |
+
api_bases = _api_bases()
|
| 149 |
+
for api_index, api_base in enumerate(api_bases):
|
| 150 |
+
url = f"{api_base}{path}"
|
| 151 |
+
for transport_index, (transport_name, session) in enumerate(
|
| 152 |
+
transports
|
| 153 |
+
):
|
| 154 |
+
try:
|
| 155 |
+
response = session.post(
|
| 156 |
+
url,
|
| 157 |
+
headers=headers,
|
| 158 |
+
json=payload,
|
| 159 |
+
timeout=REQUEST_TIMEOUT,
|
| 160 |
+
allow_redirects=False,
|
| 161 |
+
)
|
| 162 |
+
except requests.exceptions.Timeout as exc:
|
| 163 |
+
last_error = exc
|
| 164 |
+
if transport_index < len(transports) - 1:
|
| 165 |
+
time.sleep(RETRY_DELAY_SECONDS)
|
| 166 |
+
continue
|
| 167 |
+
break
|
| 168 |
+
except requests.exceptions.ConnectionError as exc:
|
| 169 |
+
last_error = exc
|
| 170 |
+
if transport_index < len(transports) - 1:
|
| 171 |
+
time.sleep(RETRY_DELAY_SECONDS)
|
| 172 |
+
continue
|
| 173 |
+
break
|
| 174 |
|
| 175 |
if response.status_code in TRANSIENT_HTTP_STATUS:
|
| 176 |
last_error = RuntimeError(
|
| 177 |
+
"Temporary authentication-service error: HTTP "
|
| 178 |
f"{response.status_code} via {transport_name}."
|
| 179 |
)
|
| 180 |
+
if transport_index < len(transports) - 1:
|
| 181 |
time.sleep(RETRY_DELAY_SECONDS)
|
| 182 |
continue
|
| 183 |
+
break
|
| 184 |
|
| 185 |
try:
|
| 186 |
data = response.json()
|
| 187 |
except ValueError as exc:
|
| 188 |
+
last_error = RuntimeError(
|
| 189 |
"Authentication service returned non-JSON content "
|
| 190 |
+
f"(HTTP {response.status_code}, "
|
| 191 |
+
f"transport={transport_name})."
|
| 192 |
+
)
|
| 193 |
+
if (
|
| 194 |
+
api_index < len(api_bases) - 1
|
| 195 |
+
or response.status_code in {404, 405, 502, 503, 504}
|
| 196 |
+
):
|
| 197 |
+
break
|
| 198 |
+
raise last_error from exc
|
| 199 |
|
| 200 |
if response.status_code >= 400:
|
| 201 |
message = (
|
|
|
|
| 204 |
or data.get("error")
|
| 205 |
or f"HTTP {response.status_code}"
|
| 206 |
)
|
| 207 |
+
error = RuntimeError(str(message))
|
| 208 |
+
# A relay that has not yet picked up a new route may return
|
| 209 |
+
# 404/405. Continue to the public Worker without hiding real
|
| 210 |
+
# authentication or business errors such as 400/401/403.
|
| 211 |
+
if response.status_code in {404, 405, 502, 503, 504}:
|
| 212 |
+
last_error = error
|
| 213 |
+
break
|
| 214 |
+
raise error
|
| 215 |
|
| 216 |
return data
|
| 217 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 218 |
if isinstance(last_error, requests.exceptions.Timeout):
|
| 219 |
raise AuthServiceTimeoutError(
|
| 220 |
"authentication_service_timeout"
|
| 221 |
) from last_error
|
|
|
|
| 222 |
if isinstance(last_error, requests.exceptions.ConnectionError):
|
| 223 |
raise AuthServiceConnectionError(
|
| 224 |
"authentication_service_connection_error"
|
| 225 |
) from last_error
|
|
|
|
| 226 |
if last_error is not None:
|
| 227 |
raise RuntimeError(str(last_error))
|
|
|
|
| 228 |
raise RuntimeError("Unknown authentication service error.")
|
| 229 |
|
| 230 |
|
|
|
|
| 268 |
if clear_restore:
|
| 269 |
st.session_state.pop("sp_restore_token", None)
|
| 270 |
st.session_state.pop("sp_restore_expires_at", None)
|
| 271 |
+
st.session_state.pop("sp_browser_token", None)
|
| 272 |
+
st.session_state.pop("sp_browser_grant", None)
|
| 273 |
+
st.session_state.pop("sp_browser_expires_at", None)
|
| 274 |
|
| 275 |
|
| 276 |
+
def _context_header(name: str) -> str:
|
|
|
|
| 277 |
try:
|
| 278 |
context = getattr(st, "context", None)
|
| 279 |
+
headers = getattr(context, "headers", {}) if context is not None else {}
|
| 280 |
+
direct = headers.get(name, "")
|
| 281 |
+
if direct:
|
| 282 |
+
return str(direct).strip()
|
| 283 |
+
target = name.lower()
|
| 284 |
+
for key, value in getattr(headers, "items", lambda: ())():
|
| 285 |
+
if str(key).lower() == target:
|
| 286 |
+
return str(value or "").strip()
|
| 287 |
except Exception:
|
|
|
|
| 288 |
return ""
|
| 289 |
+
return ""
|
| 290 |
|
| 291 |
|
| 292 |
+
def _verified_gateway_browser_token() -> str:
|
| 293 |
+
version = _context_header(GATEWAY_HEADER_VERSION)
|
| 294 |
+
timestamp_text = _context_header(GATEWAY_HEADER_TIMESTAMP)
|
| 295 |
+
browser_token = _context_header(GATEWAY_HEADER_BROWSER_TOKEN)
|
| 296 |
+
signature = _context_header(GATEWAY_HEADER_SIGNATURE).lower()
|
| 297 |
+
try:
|
| 298 |
+
secret = _service_key()
|
| 299 |
+
except RuntimeError:
|
| 300 |
+
return ""
|
| 301 |
+
if not all((version == "1", timestamp_text, browser_token, signature, secret)):
|
| 302 |
+
return ""
|
| 303 |
+
try:
|
| 304 |
+
timestamp_ms = int(timestamp_text)
|
| 305 |
+
except ValueError:
|
| 306 |
+
return ""
|
| 307 |
+
age_seconds = abs(time.time() - timestamp_ms / 1000.0)
|
| 308 |
+
if age_seconds > GATEWAY_ASSERTION_MAX_AGE_SECONDS:
|
| 309 |
+
return ""
|
| 310 |
+
payload = (
|
| 311 |
+
f"gateway-v1\n{timestamp_text}\n{browser_token}"
|
| 312 |
+
).encode("utf-8")
|
| 313 |
+
expected = hmac.new(
|
| 314 |
+
secret.encode("utf-8"),
|
| 315 |
+
payload,
|
| 316 |
+
hashlib.sha256,
|
| 317 |
+
).hexdigest()
|
| 318 |
+
if not hmac.compare_digest(expected, signature):
|
| 319 |
+
return ""
|
| 320 |
+
return browser_token
|
| 321 |
+
|
| 322 |
|
| 323 |
+
def _gateway_public_origin() -> str:
|
| 324 |
+
"""Return the Worker origin only for a request proxied by the gateway."""
|
| 325 |
+
return _normalize_https_origin(
|
| 326 |
+
_context_header(GATEWAY_HEADER_PUBLIC_ORIGIN)
|
| 327 |
+
)
|
| 328 |
+
|
| 329 |
+
|
| 330 |
+
def _render_browser_session_activation() -> None:
|
| 331 |
+
"""Activate the Worker HttpOnly browser session without visible UI."""
|
| 332 |
+
browser_grant = str(
|
| 333 |
+
st.session_state.get("sp_browser_grant") or ""
|
| 334 |
+
).strip()
|
| 335 |
+
public_origin = _gateway_public_origin()
|
| 336 |
+
if not browser_grant or not public_origin:
|
| 337 |
+
return
|
| 338 |
+
|
| 339 |
+
endpoint = json.dumps(
|
| 340 |
+
f"{public_origin}/_sp/browser-session/accept"
|
| 341 |
+
)
|
| 342 |
+
token = json.dumps(browser_grant)
|
| 343 |
script = f"""
|
| 344 |
<script>
|
| 345 |
(() => {{
|
| 346 |
+
const activate = async () => {{
|
| 347 |
+
try {{
|
| 348 |
+
const parentWindow = window.parent;
|
| 349 |
+
await parentWindow.fetch({endpoint}, {{
|
| 350 |
+
method: "POST",
|
| 351 |
+
credentials: "include",
|
| 352 |
+
cache: "no-store",
|
| 353 |
+
headers: {{"Content-Type": "application/json"}},
|
| 354 |
+
body: JSON.stringify({{browser_token: {token}}})
|
| 355 |
+
}});
|
| 356 |
+
}} catch (_) {{
|
| 357 |
+
// The current Streamlit session remains usable; a later rerun retries.
|
| 358 |
}}
|
| 359 |
+
}};
|
| 360 |
+
activate();
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 361 |
}})();
|
| 362 |
</script>
|
| 363 |
"""
|
| 364 |
components.html(script, height=0, width=0)
|
| 365 |
|
| 366 |
|
| 367 |
+
def _try_restore_gateway_session() -> bool:
|
| 368 |
+
browser_token = str(
|
| 369 |
+
st.session_state.get("sp_browser_token")
|
| 370 |
+
or _verified_gateway_browser_token()
|
| 371 |
+
).strip()
|
| 372 |
+
if not browser_token:
|
| 373 |
+
return False
|
| 374 |
+
try:
|
| 375 |
+
result = _post(
|
| 376 |
+
"/browser/session",
|
| 377 |
+
{"browser_token": browser_token},
|
| 378 |
)
|
| 379 |
+
except (AuthServiceTimeoutError, AuthServiceConnectionError):
|
| 380 |
+
return False
|
| 381 |
+
except Exception:
|
| 382 |
+
st.session_state.pop("sp_browser_token", None)
|
| 383 |
+
return False
|
| 384 |
+
if not result.get("ok") or not result.get("session_token"):
|
| 385 |
+
st.session_state.pop("sp_browser_token", None)
|
| 386 |
+
return False
|
| 387 |
+
result["browser_token"] = browser_token
|
| 388 |
+
_store_authenticated_session(result)
|
| 389 |
+
return True
|
| 390 |
|
| 391 |
|
| 392 |
def _verify_existing_session() -> bool:
|
|
|
|
| 458 |
def _store_authenticated_session(result: dict[str, Any]) -> None:
|
| 459 |
session_token = result.get("session_token")
|
| 460 |
user = result.get("user")
|
|
|
|
| 461 |
if not session_token or not user:
|
| 462 |
raise RuntimeError("Login succeeded but the session data is incomplete.")
|
|
|
|
| 463 |
st.session_state["sp_session_token"] = session_token
|
| 464 |
st.session_state["sp_session_expires_at"] = result.get(
|
| 465 |
"session_expires_at"
|
|
|
|
| 472 |
st.session_state["sp_restore_expires_at"] = result.get(
|
| 473 |
"restore_expires_at"
|
| 474 |
)
|
| 475 |
+
browser_token = str(result.get("browser_token") or "").strip()
|
| 476 |
+
browser_grant = str(result.get("browser_grant") or "").strip()
|
| 477 |
+
if browser_token:
|
| 478 |
+
st.session_state["sp_browser_token"] = browser_token
|
| 479 |
+
if browser_grant:
|
| 480 |
+
st.session_state["sp_browser_grant"] = browser_grant
|
| 481 |
+
st.session_state["sp_browser_expires_at"] = result.get(
|
| 482 |
+
"browser_expires_at"
|
| 483 |
+
)
|
| 484 |
_clear_login_request()
|
| 485 |
|
| 486 |
|
| 487 |
def _try_restore_authenticated_session() -> bool:
|
| 488 |
+
"""Compatibility wrapper for the server-side gateway session."""
|
| 489 |
+
return _try_restore_gateway_session()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 490 |
|
| 491 |
|
| 492 |
def _public_url() -> str:
|
|
|
|
| 713 |
st.stop()
|
| 714 |
|
| 715 |
if status == "authenticated":
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 716 |
_store_authenticated_session(result)
|
| 717 |
status_box.success(tr(language, "login_auto_success"))
|
| 718 |
st.rerun()
|
|
|
|
| 822 |
) -> None:
|
| 823 |
session_token = str(st.session_state.get("sp_session_token") or "").strip()
|
| 824 |
restore_token = str(
|
| 825 |
+
st.session_state.get("sp_restore_token") or ""
|
| 826 |
+
).strip()
|
| 827 |
+
browser_token = str(
|
| 828 |
+
st.session_state.get("sp_browser_token")
|
| 829 |
+
or _verified_gateway_browser_token()
|
| 830 |
).strip()
|
| 831 |
user_id = str((st.session_state.get("sp_user") or {}).get("id") or "")
|
| 832 |
task = st.session_state.get("sp_generation_task") or {}
|
|
|
|
| 851 |
{
|
| 852 |
"session_token": session_token,
|
| 853 |
"restore_token": restore_token,
|
| 854 |
+
"browser_token": browser_token,
|
| 855 |
},
|
| 856 |
)
|
| 857 |
except Exception:
|
| 858 |
pass
|
| 859 |
|
|
|
|
|
|
|
|
|
|
| 860 |
_clear_session(clear_restore=True)
|
| 861 |
_clear_login_request()
|
| 862 |
_clear_generation_session_state()
|
| 863 |
+
st.rerun()
|
| 864 |
|
| 865 |
|
| 866 |
def render_logged_in_account(
|
|
|
|
| 1001 |
language: str = "zh",
|
| 1002 |
) -> dict[str, Any]:
|
| 1003 |
"""Require Alipay authentication and return the verified user."""
|
| 1004 |
+
_render_browser_session_activation()
|
| 1005 |
if _verify_existing_session():
|
| 1006 |
return dict(st.session_state.get("sp_user", {}))
|
| 1007 |
if _try_restore_authenticated_session():
|