Spaces:
Paused
Paused
reportflow-mcp bot commited on
Commit ·
04eeb91
1
Parent(s): f333282
Sync Space from reportflow-mcp@8fb72d6
Browse files- app.py +76 -29
- oauth.py +89 -13
- workspace.py +78 -19
app.py
CHANGED
|
@@ -28,6 +28,7 @@ from oauth import (
|
|
| 28 |
OAuthError,
|
| 29 |
access_token_for,
|
| 30 |
finish_authorization,
|
|
|
|
| 31 |
session_status,
|
| 32 |
sign_out,
|
| 33 |
start_authorization,
|
|
@@ -38,6 +39,8 @@ from workspace import (
|
|
| 38 |
design_choices,
|
| 39 |
design_parameters,
|
| 40 |
empty_params_template,
|
|
|
|
|
|
|
| 41 |
list_designs,
|
| 42 |
parse_design_choice,
|
| 43 |
render_document,
|
|
@@ -209,19 +212,24 @@ def _session_id(request: gr.Request) -> str:
|
|
| 209 |
return sid
|
| 210 |
|
| 211 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 212 |
def _empty_workspace(
|
| 213 |
status: str,
|
| 214 |
-
) -> tuple[str, dict, str, str, str]:
|
| 215 |
return (
|
| 216 |
status,
|
| 217 |
gr.update(choices=[], value=None),
|
| 218 |
"Sign in, then pick one of your designs. The fields below become the form.",
|
| 219 |
"{}",
|
|
|
|
| 220 |
"",
|
| 221 |
)
|
| 222 |
|
| 223 |
|
| 224 |
-
def consume_oauth_redirect(request: gr.Request):
|
| 225 |
"""Complete PKCE if the App was opened with ?code=&state=."""
|
| 226 |
params = getattr(request, "query_params", None) or {}
|
| 227 |
code = params.get("code") if hasattr(params, "get") else None
|
|
@@ -229,15 +237,24 @@ def consume_oauth_redirect(request: gr.Request):
|
|
| 229 |
try:
|
| 230 |
sid = _session_id(request)
|
| 231 |
except OAuthError:
|
| 232 |
-
return
|
| 233 |
-
|
|
|
|
|
|
|
|
|
|
| 234 |
)
|
| 235 |
if code and state:
|
| 236 |
try:
|
| 237 |
-
finish_authorization(
|
|
|
|
|
|
|
| 238 |
except OAuthError as err:
|
| 239 |
-
|
| 240 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 241 |
|
| 242 |
|
| 243 |
def _status_markdown(session_id: str) -> str:
|
|
@@ -267,15 +284,25 @@ def _workspace_form(session_id: str, prefer: str | None = None):
|
|
| 267 |
gr.update(choices=[], value=None),
|
| 268 |
"This workspace has no designs yet. Copy a public slug from the gallery above (once).",
|
| 269 |
"{}",
|
|
|
|
| 270 |
"",
|
| 271 |
)
|
| 272 |
-
selected =
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 273 |
guide, template = _schema_for_choice(session_id, selected)
|
| 274 |
return (
|
| 275 |
status,
|
| 276 |
gr.update(choices=choices, value=selected),
|
| 277 |
guide,
|
| 278 |
template,
|
|
|
|
| 279 |
"",
|
| 280 |
)
|
| 281 |
|
|
@@ -306,31 +333,38 @@ def start_sign_in() -> str:
|
|
| 306 |
)
|
| 307 |
|
| 308 |
|
| 309 |
-
def do_sign_out(request: gr.Request):
|
| 310 |
try:
|
| 311 |
-
sign_out(_session_id(request))
|
| 312 |
except OAuthError:
|
| 313 |
pass
|
| 314 |
-
return _empty_workspace("Signed out.")
|
| 315 |
|
| 316 |
|
| 317 |
-
def reload_my_designs(request: gr.Request):
|
| 318 |
try:
|
| 319 |
-
return _workspace_form(
|
| 320 |
except OAuthError as err:
|
| 321 |
return _empty_workspace(str(err))
|
| 322 |
|
| 323 |
|
| 324 |
-
def load_selected_design(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 325 |
try:
|
| 326 |
-
|
| 327 |
except OAuthError as err:
|
| 328 |
-
return str(err), "{}"
|
|
|
|
| 329 |
|
| 330 |
|
| 331 |
-
def copy_slug_into_workspace(
|
|
|
|
|
|
|
| 332 |
try:
|
| 333 |
-
sid =
|
| 334 |
payload = copy_public_template(
|
| 335 |
access_token_for(sid), workspace_id_for(sid), slug
|
| 336 |
)
|
|
@@ -345,6 +379,7 @@ def render_my_document(
|
|
| 345 |
choice: str,
|
| 346 |
params_json: str,
|
| 347 |
file_name: str,
|
|
|
|
| 348 |
request: gr.Request,
|
| 349 |
) -> str:
|
| 350 |
try:
|
|
@@ -353,11 +388,11 @@ def render_my_document(
|
|
| 353 |
raise OAuthError("params must be a JSON object of values you supplied.")
|
| 354 |
design_id, version = parse_design_choice(choice)
|
| 355 |
result = render_document(
|
| 356 |
-
access_token_for(
|
| 357 |
design_id,
|
| 358 |
version,
|
| 359 |
params,
|
| 360 |
-
file_name
|
| 361 |
)
|
| 362 |
except (OAuthError, ValueError, json.JSONDecodeError) as err:
|
| 363 |
return str(err)
|
|
@@ -427,6 +462,11 @@ workspace, sign in below. The Hub MCP tools on this Space stay read-only.
|
|
| 427 |
gr.api(get_gallery_template, api_name="get_gallery_template")
|
| 428 |
gr.api(get_register_url, api_name="get_register_url")
|
| 429 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 430 |
with gr.Accordion("Sign in to your workspace", open=True):
|
| 431 |
auth_status = gr.Markdown()
|
| 432 |
sign_in_md = gr.Markdown()
|
|
@@ -449,7 +489,7 @@ workspace, sign in below. The Hub MCP tools on this Space stay read-only.
|
|
| 449 |
value="{}",
|
| 450 |
interactive=True,
|
| 451 |
)
|
| 452 |
-
file_name = gr.Textbox(label="file name", value="document.pdf")
|
| 453 |
render_btn = gr.Button("Render from this workspace", variant="primary")
|
| 454 |
render_out = gr.Markdown()
|
| 455 |
workspace_outputs = [
|
|
@@ -457,36 +497,43 @@ workspace, sign in below. The Hub MCP tools on this Space stay read-only.
|
|
| 457 |
design_pick,
|
| 458 |
schema_md,
|
| 459 |
params_box,
|
|
|
|
| 460 |
render_out,
|
| 461 |
]
|
| 462 |
demo.load(
|
| 463 |
fn=consume_oauth_redirect,
|
| 464 |
-
inputs=
|
| 465 |
-
outputs=workspace_outputs,
|
| 466 |
show_api=False,
|
| 467 |
)
|
| 468 |
sign_in_btn.click(fn=start_sign_in, outputs=[sign_in_md], show_api=False)
|
| 469 |
sign_out_btn.click(
|
| 470 |
-
fn=do_sign_out,
|
|
|
|
|
|
|
|
|
|
| 471 |
)
|
| 472 |
reload_btn.click(
|
| 473 |
-
fn=reload_my_designs,
|
|
|
|
|
|
|
|
|
|
| 474 |
)
|
| 475 |
copy_btn.click(
|
| 476 |
fn=copy_slug_into_workspace,
|
| 477 |
-
inputs=[slug],
|
| 478 |
outputs=workspace_outputs,
|
| 479 |
show_api=False,
|
| 480 |
)
|
| 481 |
design_pick.change(
|
| 482 |
fn=load_selected_design,
|
| 483 |
-
inputs=[design_pick],
|
| 484 |
-
outputs=[schema_md, params_box],
|
| 485 |
show_api=False,
|
| 486 |
)
|
| 487 |
render_btn.click(
|
| 488 |
fn=render_my_document,
|
| 489 |
-
inputs=[design_pick, params_box, file_name],
|
| 490 |
outputs=[render_out],
|
| 491 |
show_api=False,
|
| 492 |
)
|
|
|
|
| 28 |
OAuthError,
|
| 29 |
access_token_for,
|
| 30 |
finish_authorization,
|
| 31 |
+
resolve_session,
|
| 32 |
session_status,
|
| 33 |
sign_out,
|
| 34 |
start_authorization,
|
|
|
|
| 39 |
design_choices,
|
| 40 |
design_parameters,
|
| 41 |
empty_params_template,
|
| 42 |
+
ensure_pdf_filename,
|
| 43 |
+
filename_from_choice_label,
|
| 44 |
list_designs,
|
| 45 |
parse_design_choice,
|
| 46 |
render_document,
|
|
|
|
| 212 |
return sid
|
| 213 |
|
| 214 |
|
| 215 |
+
def _bound(request: gr.Request, visitor_key: str | None = None) -> str:
|
| 216 |
+
return resolve_session(_session_id(request), visitor_key or None)
|
| 217 |
+
|
| 218 |
+
|
| 219 |
def _empty_workspace(
|
| 220 |
status: str,
|
| 221 |
+
) -> tuple[str, dict, str, str, str, str]:
|
| 222 |
return (
|
| 223 |
status,
|
| 224 |
gr.update(choices=[], value=None),
|
| 225 |
"Sign in, then pick one of your designs. The fields below become the form.",
|
| 226 |
"{}",
|
| 227 |
+
"document.pdf",
|
| 228 |
"",
|
| 229 |
)
|
| 230 |
|
| 231 |
|
| 232 |
+
def consume_oauth_redirect(visitor_key: str | None, request: gr.Request):
|
| 233 |
"""Complete PKCE if the App was opened with ?code=&state=."""
|
| 234 |
params = getattr(request, "query_params", None) or {}
|
| 235 |
code = params.get("code") if hasattr(params, "get") else None
|
|
|
|
| 237 |
try:
|
| 238 |
sid = _session_id(request)
|
| 239 |
except OAuthError:
|
| 240 |
+
return (
|
| 241 |
+
*_empty_workspace(
|
| 242 |
+
"Not signed in. Public gallery above does not need an account."
|
| 243 |
+
),
|
| 244 |
+
visitor_key or "",
|
| 245 |
)
|
| 246 |
if code and state:
|
| 247 |
try:
|
| 248 |
+
finish_authorization(
|
| 249 |
+
sid, str(code), str(state), visitor_id=visitor_key or None
|
| 250 |
+
)
|
| 251 |
except OAuthError as err:
|
| 252 |
+
bound = resolve_session(sid, visitor_key or None)
|
| 253 |
+
if session_status(bound).get("signedIn"):
|
| 254 |
+
return (*_workspace_form(bound), bound)
|
| 255 |
+
return (*_empty_workspace(str(err)), visitor_key or "")
|
| 256 |
+
bound = resolve_session(sid, visitor_key or None)
|
| 257 |
+
return (*_workspace_form(bound), bound)
|
| 258 |
|
| 259 |
|
| 260 |
def _status_markdown(session_id: str) -> str:
|
|
|
|
| 284 |
gr.update(choices=[], value=None),
|
| 285 |
"This workspace has no designs yet. Copy a public slug from the gallery above (once).",
|
| 286 |
"{}",
|
| 287 |
+
"document.pdf",
|
| 288 |
"",
|
| 289 |
)
|
| 290 |
+
selected = choices[0][1]
|
| 291 |
+
if prefer:
|
| 292 |
+
for _label, value in choices:
|
| 293 |
+
if value == prefer or value.startswith(f"{prefer}::"):
|
| 294 |
+
selected = value
|
| 295 |
+
break
|
| 296 |
+
selected_label = next(
|
| 297 |
+
(label for label, value in choices if value == selected), "document"
|
| 298 |
+
)
|
| 299 |
guide, template = _schema_for_choice(session_id, selected)
|
| 300 |
return (
|
| 301 |
status,
|
| 302 |
gr.update(choices=choices, value=selected),
|
| 303 |
guide,
|
| 304 |
template,
|
| 305 |
+
filename_from_choice_label(selected_label),
|
| 306 |
"",
|
| 307 |
)
|
| 308 |
|
|
|
|
| 333 |
)
|
| 334 |
|
| 335 |
|
| 336 |
+
def do_sign_out(visitor_key: str | None, request: gr.Request):
|
| 337 |
try:
|
| 338 |
+
sign_out(_session_id(request), visitor_key or None)
|
| 339 |
except OAuthError:
|
| 340 |
pass
|
| 341 |
+
return (*_empty_workspace("Signed out."), "")
|
| 342 |
|
| 343 |
|
| 344 |
+
def reload_my_designs(visitor_key: str | None, request: gr.Request):
|
| 345 |
try:
|
| 346 |
+
return _workspace_form(_bound(request, visitor_key))
|
| 347 |
except OAuthError as err:
|
| 348 |
return _empty_workspace(str(err))
|
| 349 |
|
| 350 |
|
| 351 |
+
def load_selected_design(
|
| 352 |
+
choice: str, visitor_key: str | None, request: gr.Request
|
| 353 |
+
) -> tuple[str, str, str]:
|
| 354 |
+
_, _, label = (choice or "").partition("::")
|
| 355 |
+
suggested = filename_from_choice_label(label) if label else "document.pdf"
|
| 356 |
try:
|
| 357 |
+
guide, template = _schema_for_choice(_bound(request, visitor_key), choice)
|
| 358 |
except OAuthError as err:
|
| 359 |
+
return str(err), "{}", suggested
|
| 360 |
+
return guide, template, suggested
|
| 361 |
|
| 362 |
|
| 363 |
+
def copy_slug_into_workspace(
|
| 364 |
+
slug: str, visitor_key: str | None, request: gr.Request
|
| 365 |
+
):
|
| 366 |
try:
|
| 367 |
+
sid = _bound(request, visitor_key)
|
| 368 |
payload = copy_public_template(
|
| 369 |
access_token_for(sid), workspace_id_for(sid), slug
|
| 370 |
)
|
|
|
|
| 379 |
choice: str,
|
| 380 |
params_json: str,
|
| 381 |
file_name: str,
|
| 382 |
+
visitor_key: str | None,
|
| 383 |
request: gr.Request,
|
| 384 |
) -> str:
|
| 385 |
try:
|
|
|
|
| 388 |
raise OAuthError("params must be a JSON object of values you supplied.")
|
| 389 |
design_id, version = parse_design_choice(choice)
|
| 390 |
result = render_document(
|
| 391 |
+
access_token_for(_bound(request, visitor_key)),
|
| 392 |
design_id,
|
| 393 |
version,
|
| 394 |
params,
|
| 395 |
+
ensure_pdf_filename(file_name),
|
| 396 |
)
|
| 397 |
except (OAuthError, ValueError, json.JSONDecodeError) as err:
|
| 398 |
return str(err)
|
|
|
|
| 462 |
gr.api(get_gallery_template, api_name="get_gallery_template")
|
| 463 |
gr.api(get_register_url, api_name="get_register_url")
|
| 464 |
|
| 465 |
+
try:
|
| 466 |
+
visitor_key = gr.BrowserState("", storage_key="reportflow-readme-visitor")
|
| 467 |
+
except TypeError:
|
| 468 |
+
visitor_key = gr.State("")
|
| 469 |
+
|
| 470 |
with gr.Accordion("Sign in to your workspace", open=True):
|
| 471 |
auth_status = gr.Markdown()
|
| 472 |
sign_in_md = gr.Markdown()
|
|
|
|
| 489 |
value="{}",
|
| 490 |
interactive=True,
|
| 491 |
)
|
| 492 |
+
file_name = gr.Textbox(label="file name (.pdf is added if missing)", value="document.pdf")
|
| 493 |
render_btn = gr.Button("Render from this workspace", variant="primary")
|
| 494 |
render_out = gr.Markdown()
|
| 495 |
workspace_outputs = [
|
|
|
|
| 497 |
design_pick,
|
| 498 |
schema_md,
|
| 499 |
params_box,
|
| 500 |
+
file_name,
|
| 501 |
render_out,
|
| 502 |
]
|
| 503 |
demo.load(
|
| 504 |
fn=consume_oauth_redirect,
|
| 505 |
+
inputs=[visitor_key],
|
| 506 |
+
outputs=[*workspace_outputs, visitor_key],
|
| 507 |
show_api=False,
|
| 508 |
)
|
| 509 |
sign_in_btn.click(fn=start_sign_in, outputs=[sign_in_md], show_api=False)
|
| 510 |
sign_out_btn.click(
|
| 511 |
+
fn=do_sign_out,
|
| 512 |
+
inputs=[visitor_key],
|
| 513 |
+
outputs=[*workspace_outputs, visitor_key],
|
| 514 |
+
show_api=False,
|
| 515 |
)
|
| 516 |
reload_btn.click(
|
| 517 |
+
fn=reload_my_designs,
|
| 518 |
+
inputs=[visitor_key],
|
| 519 |
+
outputs=workspace_outputs,
|
| 520 |
+
show_api=False,
|
| 521 |
)
|
| 522 |
copy_btn.click(
|
| 523 |
fn=copy_slug_into_workspace,
|
| 524 |
+
inputs=[slug, visitor_key],
|
| 525 |
outputs=workspace_outputs,
|
| 526 |
show_api=False,
|
| 527 |
)
|
| 528 |
design_pick.change(
|
| 529 |
fn=load_selected_design,
|
| 530 |
+
inputs=[design_pick, visitor_key],
|
| 531 |
+
outputs=[schema_md, params_box, file_name],
|
| 532 |
show_api=False,
|
| 533 |
)
|
| 534 |
render_btn.click(
|
| 535 |
fn=render_my_document,
|
| 536 |
+
inputs=[design_pick, params_box, file_name, visitor_key],
|
| 537 |
outputs=[render_out],
|
| 538 |
show_api=False,
|
| 539 |
)
|
oauth.py
CHANGED
|
@@ -52,6 +52,7 @@ class PendingAuth:
|
|
| 52 |
|
| 53 |
_pending: dict[str, PendingAuth] = {}
|
| 54 |
_sessions: dict[str, TokenSet] = {}
|
|
|
|
| 55 |
_client_id: str | None = None
|
| 56 |
|
| 57 |
|
|
@@ -65,7 +66,7 @@ def pkce_pair() -> tuple[str, str]:
|
|
| 65 |
return verifier, challenge
|
| 66 |
|
| 67 |
|
| 68 |
-
def
|
| 69 |
parts = access_token.split(".")
|
| 70 |
if len(parts) < 2:
|
| 71 |
return None
|
|
@@ -74,10 +75,40 @@ def decode_workspace_id(access_token: str) -> str | None:
|
|
| 74 |
payload = json.loads(base64.urlsafe_b64decode(parts[1] + pad))
|
| 75 |
except (ValueError, json.JSONDecodeError):
|
| 76 |
return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 77 |
ws = payload.get("workspace_id")
|
| 78 |
return ws if isinstance(ws, str) and ws else None
|
| 79 |
|
| 80 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 81 |
def redirect_uri() -> str:
|
| 82 |
host = (os.environ.get("SPACE_HOST") or "").strip()
|
| 83 |
if host:
|
|
@@ -145,11 +176,10 @@ def _store_tokens(session_id: str, payload: dict[str, Any]) -> TokenSet:
|
|
| 145 |
raise OAuthError("Token response had no access_token.")
|
| 146 |
refresh = payload.get("refresh_token")
|
| 147 |
expires_in = payload.get("expires_in")
|
| 148 |
-
ttl = float(expires_in) if isinstance(expires_in, (int, float)) else 3600.0
|
| 149 |
stored = TokenSet(
|
| 150 |
access_token=access,
|
| 151 |
refresh_token=refresh if isinstance(refresh, str) else None,
|
| 152 |
-
expires_at=
|
| 153 |
workspace_id=decode_workspace_id(access),
|
| 154 |
)
|
| 155 |
_sessions[session_id] = stored
|
|
@@ -161,6 +191,7 @@ def finish_authorization(
|
|
| 161 |
code: str,
|
| 162 |
state: str,
|
| 163 |
client: httpx.Client | None = None,
|
|
|
|
| 164 |
) -> TokenSet:
|
| 165 |
if not session_id:
|
| 166 |
raise OAuthError("No Gradio session — cannot attach tokens to a visitor.")
|
|
@@ -191,11 +222,15 @@ def finish_authorization(
|
|
| 191 |
http.close()
|
| 192 |
if not isinstance(payload, dict):
|
| 193 |
raise OAuthError("Token response was not JSON.")
|
| 194 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 195 |
|
| 196 |
|
| 197 |
-
def session_status(session_id: str) -> dict[str, Any]:
|
| 198 |
-
token = _sessions.get(session_id)
|
| 199 |
if token is None:
|
| 200 |
return {"signedIn": False}
|
| 201 |
return {
|
|
@@ -205,24 +240,64 @@ def session_status(session_id: str) -> dict[str, Any]:
|
|
| 205 |
}
|
| 206 |
|
| 207 |
|
| 208 |
-
def
|
| 209 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 210 |
if token is None:
|
| 211 |
raise OAuthError("Sign in with Re:port Flow first.")
|
| 212 |
if time.time() >= token.expires_at:
|
| 213 |
-
|
| 214 |
return token.access_token
|
| 215 |
|
| 216 |
|
| 217 |
-
def workspace_id_for(session_id: str) -> str:
|
| 218 |
-
token = _sessions.get(session_id)
|
| 219 |
if token is None or not token.workspace_id:
|
| 220 |
raise OAuthError("Sign in and pick a workspace on the consent screen.")
|
| 221 |
return token.workspace_id
|
| 222 |
|
| 223 |
|
| 224 |
-
def sign_out(session_id: str) -> None:
|
| 225 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 226 |
|
| 227 |
|
| 228 |
def reset_client_cache() -> None:
|
|
@@ -230,3 +305,4 @@ def reset_client_cache() -> None:
|
|
| 230 |
_client_id = None
|
| 231 |
_pending.clear()
|
| 232 |
_sessions.clear()
|
|
|
|
|
|
| 52 |
|
| 53 |
_pending: dict[str, PendingAuth] = {}
|
| 54 |
_sessions: dict[str, TokenSet] = {}
|
| 55 |
+
_aliases: dict[str, str] = {}
|
| 56 |
_client_id: str | None = None
|
| 57 |
|
| 58 |
|
|
|
|
| 66 |
return verifier, challenge
|
| 67 |
|
| 68 |
|
| 69 |
+
def _jwt_payload(access_token: str) -> dict[str, Any] | None:
|
| 70 |
parts = access_token.split(".")
|
| 71 |
if len(parts) < 2:
|
| 72 |
return None
|
|
|
|
| 75 |
payload = json.loads(base64.urlsafe_b64decode(parts[1] + pad))
|
| 76 |
except (ValueError, json.JSONDecodeError):
|
| 77 |
return None
|
| 78 |
+
return payload if isinstance(payload, dict) else None
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def decode_workspace_id(access_token: str) -> str | None:
|
| 82 |
+
payload = _jwt_payload(access_token)
|
| 83 |
+
if not payload:
|
| 84 |
+
return None
|
| 85 |
ws = payload.get("workspace_id")
|
| 86 |
return ws if isinstance(ws, str) and ws else None
|
| 87 |
|
| 88 |
|
| 89 |
+
def _token_expires_at(access_token: str, expires_in: Any) -> float:
|
| 90 |
+
payload = _jwt_payload(access_token)
|
| 91 |
+
exp = payload.get("exp") if payload else None
|
| 92 |
+
if isinstance(exp, (int, float)):
|
| 93 |
+
return max(float(exp) - 60.0, time.time() + 30.0)
|
| 94 |
+
ttl = float(expires_in) if isinstance(expires_in, (int, float)) else 3600.0
|
| 95 |
+
return time.time() + max(ttl - 60.0, 30.0)
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def resolve_session(session_id: str, visitor_id: str | None = None) -> str:
|
| 99 |
+
"""Prefer the browser-stored visitor id so a new Gradio hash still finds tokens."""
|
| 100 |
+
if visitor_id and visitor_id in _sessions:
|
| 101 |
+
if session_id:
|
| 102 |
+
_aliases[session_id] = visitor_id
|
| 103 |
+
return visitor_id
|
| 104 |
+
if session_id in _sessions:
|
| 105 |
+
return session_id
|
| 106 |
+
alias = _aliases.get(session_id)
|
| 107 |
+
if alias and alias in _sessions:
|
| 108 |
+
return alias
|
| 109 |
+
return visitor_id or session_id
|
| 110 |
+
|
| 111 |
+
|
| 112 |
def redirect_uri() -> str:
|
| 113 |
host = (os.environ.get("SPACE_HOST") or "").strip()
|
| 114 |
if host:
|
|
|
|
| 176 |
raise OAuthError("Token response had no access_token.")
|
| 177 |
refresh = payload.get("refresh_token")
|
| 178 |
expires_in = payload.get("expires_in")
|
|
|
|
| 179 |
stored = TokenSet(
|
| 180 |
access_token=access,
|
| 181 |
refresh_token=refresh if isinstance(refresh, str) else None,
|
| 182 |
+
expires_at=_token_expires_at(access, expires_in),
|
| 183 |
workspace_id=decode_workspace_id(access),
|
| 184 |
)
|
| 185 |
_sessions[session_id] = stored
|
|
|
|
| 191 |
code: str,
|
| 192 |
state: str,
|
| 193 |
client: httpx.Client | None = None,
|
| 194 |
+
visitor_id: str | None = None,
|
| 195 |
) -> TokenSet:
|
| 196 |
if not session_id:
|
| 197 |
raise OAuthError("No Gradio session — cannot attach tokens to a visitor.")
|
|
|
|
| 222 |
http.close()
|
| 223 |
if not isinstance(payload, dict):
|
| 224 |
raise OAuthError("Token response was not JSON.")
|
| 225 |
+
vid = visitor_id.strip() if isinstance(visitor_id, str) and visitor_id.strip() else secrets.token_urlsafe(24)
|
| 226 |
+
stored = _store_tokens(vid, payload)
|
| 227 |
+
if session_id:
|
| 228 |
+
_aliases[session_id] = vid
|
| 229 |
+
return stored
|
| 230 |
|
| 231 |
|
| 232 |
+
def session_status(session_id: str, visitor_id: str | None = None) -> dict[str, Any]:
|
| 233 |
+
token = _sessions.get(resolve_session(session_id, visitor_id))
|
| 234 |
if token is None:
|
| 235 |
return {"signedIn": False}
|
| 236 |
return {
|
|
|
|
| 240 |
}
|
| 241 |
|
| 242 |
|
| 243 |
+
def _refresh(key: str, token: TokenSet, client: httpx.Client | None = None) -> TokenSet:
|
| 244 |
+
if not token.refresh_token:
|
| 245 |
+
_sessions.pop(key, None)
|
| 246 |
+
raise OAuthError("Session expired. Sign in again.")
|
| 247 |
+
own = client is None
|
| 248 |
+
http = client or httpx.Client(timeout=15.0)
|
| 249 |
+
try:
|
| 250 |
+
response = http.post(
|
| 251 |
+
f"{MCP_AS}/token",
|
| 252 |
+
data={
|
| 253 |
+
"grant_type": "refresh_token",
|
| 254 |
+
"refresh_token": token.refresh_token,
|
| 255 |
+
"client_id": register_public_client(http),
|
| 256 |
+
"resource": MCP_RESOURCE,
|
| 257 |
+
},
|
| 258 |
+
headers={"Accept": "application/json"},
|
| 259 |
+
)
|
| 260 |
+
response.raise_for_status()
|
| 261 |
+
payload = response.json()
|
| 262 |
+
except httpx.HTTPError as err:
|
| 263 |
+
raise OAuthError("Session expired. Sign in again.") from err
|
| 264 |
+
finally:
|
| 265 |
+
if own:
|
| 266 |
+
http.close()
|
| 267 |
+
if not isinstance(payload, dict):
|
| 268 |
+
raise OAuthError("Session expired. Sign in again.")
|
| 269 |
+
if not payload.get("refresh_token"):
|
| 270 |
+
payload = {**payload, "refresh_token": token.refresh_token}
|
| 271 |
+
return _store_tokens(key, payload)
|
| 272 |
+
|
| 273 |
+
|
| 274 |
+
def access_token_for(
|
| 275 |
+
session_id: str,
|
| 276 |
+
visitor_id: str | None = None,
|
| 277 |
+
client: httpx.Client | None = None,
|
| 278 |
+
) -> str:
|
| 279 |
+
key = resolve_session(session_id, visitor_id)
|
| 280 |
+
token = _sessions.get(key)
|
| 281 |
if token is None:
|
| 282 |
raise OAuthError("Sign in with Re:port Flow first.")
|
| 283 |
if time.time() >= token.expires_at:
|
| 284 |
+
token = _refresh(key, token, client=client)
|
| 285 |
return token.access_token
|
| 286 |
|
| 287 |
|
| 288 |
+
def workspace_id_for(session_id: str, visitor_id: str | None = None) -> str:
|
| 289 |
+
token = _sessions.get(resolve_session(session_id, visitor_id))
|
| 290 |
if token is None or not token.workspace_id:
|
| 291 |
raise OAuthError("Sign in and pick a workspace on the consent screen.")
|
| 292 |
return token.workspace_id
|
| 293 |
|
| 294 |
|
| 295 |
+
def sign_out(session_id: str, visitor_id: str | None = None) -> None:
|
| 296 |
+
keys = {session_id, visitor_id, _aliases.get(session_id)}
|
| 297 |
+
for key in keys:
|
| 298 |
+
if key:
|
| 299 |
+
_sessions.pop(key, None)
|
| 300 |
+
_aliases.pop(session_id, None)
|
| 301 |
|
| 302 |
|
| 303 |
def reset_client_cache() -> None:
|
|
|
|
| 305 |
_client_id = None
|
| 306 |
_pending.clear()
|
| 307 |
_sessions.clear()
|
| 308 |
+
_aliases.clear()
|
workspace.py
CHANGED
|
@@ -7,6 +7,7 @@ returned in these payloads.
|
|
| 7 |
from __future__ import annotations
|
| 8 |
|
| 9 |
import json
|
|
|
|
| 10 |
from typing import Any
|
| 11 |
from urllib.parse import unquote
|
| 12 |
|
|
@@ -139,14 +140,19 @@ def render_document(
|
|
| 139 |
json={
|
| 140 |
"designId": design_id.strip(),
|
| 141 |
"version": version,
|
| 142 |
-
"content": {
|
|
|
|
|
|
|
|
|
|
| 143 |
},
|
| 144 |
)
|
| 145 |
response.raise_for_status()
|
| 146 |
except httpx.HTTPStatusError as err:
|
| 147 |
if err.response.status_code in (401, 403):
|
| 148 |
raise OAuthError("Render was denied for this workspace.") from err
|
| 149 |
-
raise OAuthError(
|
|
|
|
|
|
|
| 150 |
except httpx.HTTPError as err:
|
| 151 |
raise OAuthError("Could not render the document.") from err
|
| 152 |
finally:
|
|
@@ -180,11 +186,12 @@ def normalize_parameter_schema(payload: Any) -> list[dict[str, Any]]:
|
|
| 180 |
|
| 181 |
|
| 182 |
def parse_design_choice(choice: str) -> tuple[str, int]:
|
| 183 |
-
"""Parse a dropdown value `designId@version`."""
|
| 184 |
raw = (choice or "").strip()
|
| 185 |
-
|
|
|
|
| 186 |
raise OAuthError("Pick a design from the list.")
|
| 187 |
-
design_id, sep, version =
|
| 188 |
if not sep or not design_id or not version.isdigit():
|
| 189 |
raise OAuthError("Pick a design from the list.")
|
| 190 |
return design_id, int(version)
|
|
@@ -205,10 +212,67 @@ def design_choices(payload: dict[str, Any]) -> list[tuple[str, str]]:
|
|
| 205 |
if not isinstance(version, int) or version < 1:
|
| 206 |
continue
|
| 207 |
label = item.get("label") if isinstance(item.get("label"), str) else design_id
|
| 208 |
-
choices.append(
|
|
|
|
|
|
|
| 209 |
return choices
|
| 210 |
|
| 211 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 212 |
def schema_guide(schema: list[dict[str, Any]]) -> str:
|
| 213 |
if not schema:
|
| 214 |
return "This design published no parameters. You can render with `{}`."
|
|
@@ -241,19 +305,14 @@ def _describe_spec(spec: dict[str, Any]) -> str:
|
|
| 241 |
|
| 242 |
|
| 243 |
def empty_params_template(schema: list[dict[str, Any]]) -> dict[str, Any]:
|
| 244 |
-
"""
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
if typ == "boolean":
|
| 253 |
-
return None
|
| 254 |
-
if typ in ("array", "collection"):
|
| 255 |
-
return []
|
| 256 |
-
return ""
|
| 257 |
|
| 258 |
|
| 259 |
def safe_https_url(url: str | None) -> str | None:
|
|
|
|
| 7 |
from __future__ import annotations
|
| 8 |
|
| 9 |
import json
|
| 10 |
+
import re
|
| 11 |
from typing import Any
|
| 12 |
from urllib.parse import unquote
|
| 13 |
|
|
|
|
| 140 |
json={
|
| 141 |
"designId": design_id.strip(),
|
| 142 |
"version": version,
|
| 143 |
+
"content": {
|
| 144 |
+
"fileName": ensure_pdf_filename(file_name),
|
| 145 |
+
"params": sanitize_params_for_render(params),
|
| 146 |
+
},
|
| 147 |
},
|
| 148 |
)
|
| 149 |
response.raise_for_status()
|
| 150 |
except httpx.HTTPStatusError as err:
|
| 151 |
if err.response.status_code in (401, 403):
|
| 152 |
raise OAuthError("Render was denied for this workspace.") from err
|
| 153 |
+
raise OAuthError(
|
| 154 |
+
f"Render failed: {_response_message(err.response)}"
|
| 155 |
+
) from err
|
| 156 |
except httpx.HTTPError as err:
|
| 157 |
raise OAuthError("Could not render the document.") from err
|
| 158 |
finally:
|
|
|
|
| 186 |
|
| 187 |
|
| 188 |
def parse_design_choice(choice: str) -> tuple[str, int]:
|
| 189 |
+
"""Parse a dropdown value `designId@version` or `designId@version::label`."""
|
| 190 |
raw = (choice or "").strip()
|
| 191 |
+
main, _, _label = raw.partition("::")
|
| 192 |
+
if not main or "/" in main or ".." in main:
|
| 193 |
raise OAuthError("Pick a design from the list.")
|
| 194 |
+
design_id, sep, version = main.partition("@")
|
| 195 |
if not sep or not design_id or not version.isdigit():
|
| 196 |
raise OAuthError("Pick a design from the list.")
|
| 197 |
return design_id, int(version)
|
|
|
|
| 212 |
if not isinstance(version, int) or version < 1:
|
| 213 |
continue
|
| 214 |
label = item.get("label") if isinstance(item.get("label"), str) else design_id
|
| 215 |
+
choices.append(
|
| 216 |
+
(f"{label} (v{version})", f"{design_id}@{version}::{label}")
|
| 217 |
+
)
|
| 218 |
return choices
|
| 219 |
|
| 220 |
|
| 221 |
+
_VERSION_SUFFIX = re.compile(r"\s+\(v\d+\)\s*$")
|
| 222 |
+
_UNSAFE_FILENAME = re.compile(r'[/\\:*?"<>|\x00-\x1f]+')
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
def filename_from_choice_label(label: str) -> str:
|
| 226 |
+
return ensure_pdf_filename(_VERSION_SUFFIX.sub("", label or "").strip())
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
def ensure_pdf_filename(name: str, fallback: str = "document") -> str:
|
| 230 |
+
base = _UNSAFE_FILENAME.sub("", (name or "").strip()) or fallback
|
| 231 |
+
if base.lower().endswith(".pdf"):
|
| 232 |
+
base = base[:-4].rstrip()
|
| 233 |
+
base = base or fallback
|
| 234 |
+
return f"{base}.pdf"
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
def sanitize_params_for_render(params: dict[str, Any]) -> dict[str, Any]:
|
| 238 |
+
"""Drop null/empty values. content-service 400s on null or '' for numbers."""
|
| 239 |
+
cleaned: dict[str, Any] = {}
|
| 240 |
+
for key, value in params.items():
|
| 241 |
+
if value is None or value == "":
|
| 242 |
+
continue
|
| 243 |
+
if isinstance(value, dict):
|
| 244 |
+
nested = sanitize_params_for_render(value)
|
| 245 |
+
if nested:
|
| 246 |
+
cleaned[key] = nested
|
| 247 |
+
continue
|
| 248 |
+
if isinstance(value, list):
|
| 249 |
+
rows = [
|
| 250 |
+
sanitize_params_for_render(row)
|
| 251 |
+
for row in value
|
| 252 |
+
if isinstance(row, dict)
|
| 253 |
+
]
|
| 254 |
+
rows = [row for row in rows if row]
|
| 255 |
+
if rows:
|
| 256 |
+
cleaned[key] = rows
|
| 257 |
+
continue
|
| 258 |
+
cleaned[key] = value
|
| 259 |
+
return cleaned
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
def _response_message(response: httpx.Response) -> str:
|
| 263 |
+
try:
|
| 264 |
+
body = response.json()
|
| 265 |
+
except (json.JSONDecodeError, ValueError):
|
| 266 |
+
return f"HTTP {response.status_code}"
|
| 267 |
+
if isinstance(body, dict):
|
| 268 |
+
message = body.get("message") or body.get("error")
|
| 269 |
+
if isinstance(message, list):
|
| 270 |
+
message = "; ".join(str(part) for part in message)
|
| 271 |
+
if isinstance(message, str) and message:
|
| 272 |
+
return message[:500]
|
| 273 |
+
return f"HTTP {response.status_code}"
|
| 274 |
+
|
| 275 |
+
|
| 276 |
def schema_guide(schema: list[dict[str, Any]]) -> str:
|
| 277 |
if not schema:
|
| 278 |
return "This design published no parameters. You can render with `{}`."
|
|
|
|
| 305 |
|
| 306 |
|
| 307 |
def empty_params_template(schema: list[dict[str, Any]]) -> dict[str, Any]:
|
| 308 |
+
"""Text/date keys only, empty. Omit number/boolean/array — those 400 if null."""
|
| 309 |
+
template: dict[str, Any] = {}
|
| 310 |
+
for spec in schema:
|
| 311 |
+
typ = spec.get("type")
|
| 312 |
+
if typ in ("number", "boolean", "array", "collection"):
|
| 313 |
+
continue
|
| 314 |
+
template[spec["name"]] = ""
|
| 315 |
+
return template
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 316 |
|
| 317 |
|
| 318 |
def safe_https_url(url: str | None) -> str | None:
|