Yuchen Yuan Claude Opus 4.7 (1M context) commited on
Commit
b6faf15
·
1 Parent(s): 4d0158a

Multi-user: HF OAuth login + per-user plugin persistence

Browse files

What this lets users do
- Anyone can click "Sign in" in the top bar and authenticate with their
Hugging Face account (OpenID Connect via the HF OAuth flow). No
account creation, no password management on our side.
- Each signed-in user gets their own private namespace for uploaded
plugins. Other users (and other browsers from the same person)
cannot see them.
- Plugins uploaded while signed in are mirrored to a private HF
Dataset repo (qudastudio/quda-user-data) so they survive container
restarts and follow the user across devices.
- Guest (anonymous) mode is fully preserved: visitors can still drop
a .zip without signing in; those plugins continue to live in /tmp
and are per-browser, exactly as before.

Architecture

Browser ──cookie──▶ FastAPI ──HfApi──▶ HF Dataset (private)
│
└──▶ /tmp (volatile cache)

Identity = session cookie's hf_<username> (when signed in)
∥ anon UUID query param (otherwise)

Backend

- New auth_service.py: HF OAuth code exchange + signed-cookie session.
Sessions use itsdangerous.URLSafeTimedSerializer with salt
"quda-session-v1". Payload is small (sub, username, avatar, exp);
no HF access_token is persisted. 8h expiry, matching HF token
lifetime.
- New routes/auth.py: /api/auth/{login,callback,me,logout,status}.
Login mints a per-request state token, stores it in a 10-min
HttpOnly cookie, redirects to HF. Callback verifies state, swaps
code for access_token+userinfo, sets session cookie, 302s home.
- New datasets_storage.py: thin wrapper around huggingface_hub for
upload_file / delete_file / list_repo_files. push_plugin and
remove_plugin are best-effort (failures are logged, not raised),
so a dead HF Datasets backend never blocks plugin installation.
Hydration is lazy + cached for 30s per user.
- routes/plugins.py and routes/workflow.py grew an _effective_user_id
helper that ALWAYS prefers a valid session over the query-supplied
user_id. Anon callers may not pass user_id starting with "hf_" —
this prevents an unauthenticated client from squatting on a real
HF user's namespace and poisoning their plugin list on next login.
- plugin_service.install_plugin_zip now pushes to the dataset after
on-disk extraction; delete_plugin removes both. New
hydrate_from_dataset_if_needed is called at the top of every plugin
route so a logged-in user landing on a freshly-restarted Space sees
their previously-uploaded plugins after one request.
- _USER_ID_RE relaxed from {8,64} to {4,64} so short HF usernames
(e.g. hf_ab) still fit. PluginManifest.kind max_length already 31.
- main.py CORS hardened: drops literal "*" entries from
CORS_ALLOW_ORIGINS to keep allow_credentials=True safe even under
misconfiguration.

Subprocess safety preserved

- HF_TOKEN is NOT added to plugin_runner.py's _ENV_ALLOWLIST, so
plugin subprocesses still cannot read it. Confirmed by inspection.

Frontend

- New AuthButton.tsx renders either "Sign in" or an avatar dropdown.
Dropdown shows persistence status, the dataset repo name, and a
hint that pre-signin anon plugins remain under the anon UUID.
- userId.ts: getUserId() unchanged for the anon UUID; added
displayUserId() helper that surfaces hf_<username> when signed in.
- store.ts: session + authStatus state added.
- App.tsx: probes /api/auth/status on boot, fetches /api/auth/me,
re-fetches the plugin list whenever session changes, watches the
session expiry and clears local state when it fires, polls /me
every 5 min so server-side invalidation propagates. Reads
?auth_error= from the OAuth callback redirect and surfaces it as a
dismissable banner.
- api.ts: every fetch now goes through authedFetch (credentials:
"include") so the session cookie travels under the Vite dev proxy.

Infra

- README.md frontmatter adds hf_oauth: true + openid/profile scopes
+ 480-min expiration. HF auto-populates OAUTH_CLIENT_ID/SECRET +
SPACE_HOST env vars on deploy.
- Created private Dataset repo qudastudio/quda-user-data and set
HF_TOKEN + SESSION_SECRET as Space secrets via HF API.
- backend/requirements.txt: itsdangerous (cookie signing),
httpx (OAuth POST), huggingface_hub (dataset I/O).

Audited

Two parallel audits (security + UX) returned clean after a polish
round addressing: stale session detection (now we watch expires_at +
poll /me), namespace squatting (route refuses hf_ from query),
hydration spam (30s freshness cache), UploadPluginModal stale
useApp.getState() reads (now hook-subscribed), CORS wildcard guard.

Tested

Local integration suite covers: namespace isolation between Alice
and Bob (same plugin kind in both namespaces, no leak), anon
squatting defense, session precedence over query param, expired
session falls through to anon path, /me 401 + plugin list 400 on
expired cookie, logout flow.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

README.md CHANGED
@@ -7,6 +7,8 @@ sdk: docker
7
  app_port: 7860
8
  pinned: false
9
  short_description: Quantum Design Automation Studio
 
 
10
  ---
11
 
12
  # QuDA Studio
 
7
  app_port: 7860
8
  pinned: false
9
  short_description: Quantum Design Automation Studio
10
+ hf_oauth: true
11
+ hf_oauth_expiration_minutes: 480
12
  ---
13
 
14
  # QuDA Studio
backend/app/config.py CHANGED
@@ -3,6 +3,7 @@
3
  from __future__ import annotations
4
 
5
  import os
 
6
  from dataclasses import dataclass
7
  from pathlib import Path
8
 
@@ -31,11 +32,38 @@ class Settings:
31
  allow_live_ibm: bool
32
  cors_allow_origins: tuple[str, ...]
33
  log_level: str
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
 
35
  @property
36
  def has_ibm_token(self) -> bool:
37
  return bool(self.ibm_token)
38
 
 
 
 
 
 
 
 
 
39
 
40
  def _env_bool(name: str, default: bool) -> bool:
41
  raw = os.environ.get(name)
@@ -67,5 +95,22 @@ def get_settings() -> Settings:
67
  default=("http://localhost:5173", "http://127.0.0.1:5173"),
68
  ),
69
  log_level=os.environ.get("LOG_LEVEL", "INFO"),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70
  )
71
  return _settings
 
3
  from __future__ import annotations
4
 
5
  import os
6
+ import secrets
7
  from dataclasses import dataclass
8
  from pathlib import Path
9
 
 
32
  allow_live_ibm: bool
33
  cors_allow_origins: tuple[str, ...]
34
  log_level: str
35
+ # ---- OAuth (HF Sign-in) ----
36
+ # HF sets these env vars automatically when `hf_oauth: true` is in
37
+ # the Space README frontmatter. Empty when running locally outside
38
+ # an HF Space (the auth routes degrade to "feature unavailable").
39
+ oauth_client_id: str | None
40
+ oauth_client_secret: str | None
41
+ openid_provider_url: str
42
+ space_host: str | None
43
+ # Server-side secret for signing session cookies. HF Space secret,
44
+ # falls back to a per-process random in dev (sessions don't survive
45
+ # restart locally — fine).
46
+ session_secret: str
47
+ # ---- HF Datasets persistence ----
48
+ # Write-capable token for the per-user plugin dataset repo. Without
49
+ # it, OAuth still works but plugins remain volatile (live in /tmp
50
+ # only). Set as a Space secret named HF_TOKEN.
51
+ hf_token: str | None
52
+ # Owner/name of the dataset repo where user plugins are persisted.
53
+ user_data_repo: str
54
 
55
  @property
56
  def has_ibm_token(self) -> bool:
57
  return bool(self.ibm_token)
58
 
59
+ @property
60
+ def oauth_enabled(self) -> bool:
61
+ return bool(self.oauth_client_id and self.oauth_client_secret)
62
+
63
+ @property
64
+ def persistence_enabled(self) -> bool:
65
+ return bool(self.hf_token and self.user_data_repo)
66
+
67
 
68
  def _env_bool(name: str, default: bool) -> bool:
69
  raw = os.environ.get(name)
 
95
  default=("http://localhost:5173", "http://127.0.0.1:5173"),
96
  ),
97
  log_level=os.environ.get("LOG_LEVEL", "INFO"),
98
+ oauth_client_id=os.environ.get("OAUTH_CLIENT_ID") or None,
99
+ oauth_client_secret=os.environ.get("OAUTH_CLIENT_SECRET") or None,
100
+ openid_provider_url=os.environ.get(
101
+ "OPENID_PROVIDER_URL", "https://huggingface.co"
102
+ ),
103
+ space_host=os.environ.get("SPACE_HOST") or None,
104
+ # In dev we generate a fresh random secret per process so
105
+ # sessions don't survive a restart — that's fine for dev.
106
+ # In prod we expect SESSION_SECRET to be set as an HF Space
107
+ # secret so cookies survive container restarts.
108
+ session_secret=(
109
+ os.environ.get("SESSION_SECRET") or secrets.token_urlsafe(48)
110
+ ),
111
+ hf_token=os.environ.get("HF_TOKEN") or None,
112
+ user_data_repo=os.environ.get(
113
+ "USER_DATA_REPO", "qudastudio/quda-user-data"
114
+ ),
115
  )
116
  return _settings
backend/app/main.py CHANGED
@@ -19,6 +19,7 @@ from fastapi.responses import FileResponse, JSONResponse
19
  from fastapi.staticfiles import StaticFiles
20
 
21
  from app.config import FRONTEND_DIST, get_settings
 
22
  from app.routes import backends as backends_route
23
  from app.routes import circuits as circuits_route
24
  from app.routes import health as health_route
@@ -51,12 +52,27 @@ app = FastAPI(
51
 
52
  _settings = get_settings()
53
 
 
 
 
 
 
 
 
 
 
 
 
 
54
  app.add_middleware(
55
  CORSMiddleware,
56
- allow_origins=list(_settings.cors_allow_origins),
57
  allow_methods=["*"],
58
  allow_headers=["*"],
59
- allow_credentials=False,
 
 
 
60
  )
61
 
62
  # API routes
@@ -65,6 +81,7 @@ app.include_router(backends_route.router, prefix="/api")
65
  app.include_router(circuits_route.router, prefix="/api")
66
  app.include_router(workflow_route.router, prefix="/api")
67
  app.include_router(plugins_route.router, prefix="/api")
 
68
 
69
 
70
  # ---------- Static frontend ----------
 
19
  from fastapi.staticfiles import StaticFiles
20
 
21
  from app.config import FRONTEND_DIST, get_settings
22
+ from app.routes import auth as auth_route
23
  from app.routes import backends as backends_route
24
  from app.routes import circuits as circuits_route
25
  from app.routes import health as health_route
 
52
 
53
  _settings = get_settings()
54
 
55
+ # Safety net: with allow_credentials=True a wildcard origin would let
56
+ # any malicious page on the internet read /api/auth/me with the user's
57
+ # session cookie. CORSMiddleware itself refuses `["*"]` in that
58
+ # combination, but we also strip any literal "*" upstream so a typo in
59
+ # CORS_ALLOW_ORIGINS becomes "no cross-origin" rather than silently
60
+ # enabling it. In production the React bundle is served by the same
61
+ # FastAPI process — no cross-origin reads needed at all.
62
+ _safe_origins = [o for o in _settings.cors_allow_origins if o != "*"]
63
+ if len(_safe_origins) != len(_settings.cors_allow_origins):
64
+ logger.warning(
65
+ "CORS_ALLOW_ORIGINS contained '*'; dropped because allow_credentials=True."
66
+ )
67
  app.add_middleware(
68
  CORSMiddleware,
69
+ allow_origins=_safe_origins,
70
  allow_methods=["*"],
71
  allow_headers=["*"],
72
+ # We need cookies on cross-origin requests for the Vite dev server
73
+ # (5173) to talk to the API (7860). In production both bundles
74
+ # come from the same origin so this doesn't relax anything.
75
+ allow_credentials=True,
76
  )
77
 
78
  # API routes
 
81
  app.include_router(circuits_route.router, prefix="/api")
82
  app.include_router(workflow_route.router, prefix="/api")
83
  app.include_router(plugins_route.router, prefix="/api")
84
+ app.include_router(auth_route.router, prefix="/api")
85
 
86
 
87
  # ---------- Static frontend ----------
backend/app/routes/auth.py ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """/api/auth — HF OAuth login flow + session lookup.
2
+
3
+ Endpoints:
4
+
5
+ GET /api/auth/login — set state cookie, 302 to HF authorize URL
6
+ GET /api/auth/callback — verify state, exchange code, set session cookie, 302 to /
7
+ GET /api/auth/me — return current session (or 401 with body)
8
+ POST /api/auth/logout — clear session cookie
9
+
10
+ The frontend only ever calls /api/auth/me; the other endpoints are
11
+ hit via full-page navigation because OAuth requires a top-level redirect.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import logging
17
+
18
+ from fastapi import APIRouter, HTTPException, Request, Response
19
+ from fastapi.responses import JSONResponse, RedirectResponse
20
+
21
+ from app.config import get_settings
22
+ from app.services import auth_service
23
+
24
+ logger = logging.getLogger(__name__)
25
+ router = APIRouter(prefix="/auth")
26
+
27
+
28
+ def _request_origin(request: Request) -> str | None:
29
+ """Reconstruct the scheme://host origin from headers. With our
30
+ Dockerfile's --proxy-headers + --forwarded-allow-ips='*' the scheme
31
+ is already https in production."""
32
+ host = request.url.netloc or request.headers.get("host")
33
+ if not host:
34
+ return None
35
+ scheme = request.url.scheme or "https"
36
+ return f"{scheme}://{host}"
37
+
38
+
39
+ def _is_https(request: Request) -> bool:
40
+ return (request.url.scheme or "").lower() == "https"
41
+
42
+
43
+ @router.get("/login")
44
+ async def login(request: Request) -> Response:
45
+ """Kick off the OAuth dance. Browser is redirected to HF authorize
46
+ URL with a state we stash in a short-lived signed cookie."""
47
+ settings = get_settings()
48
+ if not settings.oauth_enabled:
49
+ # In dev (no HF env vars) we surface a clear JSON error rather
50
+ # than redirecting into a 404.
51
+ return JSONResponse(
52
+ {
53
+ "detail": (
54
+ "OAuth is not configured on this deployment. "
55
+ "Set hf_oauth: true in README and redeploy on a Space."
56
+ )
57
+ },
58
+ status_code=503,
59
+ )
60
+ state = auth_service.mint_state()
61
+ state_token = auth_service.encode_state(state)
62
+ target = auth_service.build_authorize_url(state, _request_origin(request))
63
+ resp = RedirectResponse(target, status_code=302)
64
+ resp.set_cookie(
65
+ auth_service.STATE_COOKIE,
66
+ state_token,
67
+ max_age=600,
68
+ httponly=True,
69
+ samesite="lax",
70
+ secure=_is_https(request),
71
+ path="/api/auth",
72
+ )
73
+ return resp
74
+
75
+
76
+ @router.get("/callback")
77
+ async def callback(
78
+ request: Request, code: str | None = None, state: str | None = None,
79
+ error: str | None = None, error_description: str | None = None,
80
+ ) -> Response:
81
+ """OAuth redirect target. Verify state, exchange code, set session
82
+ cookie, redirect home. Errors are surfaced as a redirect to / with
83
+ an ?auth_error= query so the frontend can show a banner."""
84
+ if error:
85
+ msg = error_description or error
86
+ return RedirectResponse(f"/?auth_error={msg}", status_code=302)
87
+ if not code or not state:
88
+ return RedirectResponse(
89
+ "/?auth_error=missing+code+or+state", status_code=302
90
+ )
91
+ expected_state = auth_service.decode_state(
92
+ request.cookies.get(auth_service.STATE_COOKIE)
93
+ )
94
+ if not expected_state or expected_state != state:
95
+ return RedirectResponse(
96
+ "/?auth_error=oauth+state+mismatch", status_code=302
97
+ )
98
+
99
+ try:
100
+ user = await auth_service.exchange_code_for_user(
101
+ code, _request_origin(request)
102
+ )
103
+ except auth_service.AuthError as exc:
104
+ return RedirectResponse(
105
+ f"/?auth_error={exc}", status_code=302
106
+ )
107
+
108
+ session_token = auth_service.encode_session(user)
109
+ resp = RedirectResponse("/?logged_in=1", status_code=302)
110
+ resp.delete_cookie(auth_service.STATE_COOKIE, path="/api/auth")
111
+ resp.set_cookie(
112
+ auth_service.SESSION_COOKIE,
113
+ session_token,
114
+ max_age=auth_service.SESSION_MAX_AGE_SECONDS,
115
+ httponly=True,
116
+ samesite="lax",
117
+ secure=_is_https(request),
118
+ path="/",
119
+ )
120
+ logger.info("Login OK for user=%s", user.username)
121
+ return resp
122
+
123
+
124
+ @router.get("/me")
125
+ async def me(request: Request) -> Response:
126
+ """Return the current logged-in user, or 401 with an empty body if
127
+ no session. The frontend polls this on boot to decide whether to
128
+ show the Login button or the avatar."""
129
+ cookie = request.cookies.get(auth_service.SESSION_COOKIE)
130
+ user = auth_service.decode_session(cookie)
131
+ if not user:
132
+ return JSONResponse({"detail": "Not logged in."}, status_code=401)
133
+ settings = get_settings()
134
+ return JSONResponse(
135
+ {
136
+ "username": user.username,
137
+ "avatar_url": user.avatar_url,
138
+ "expires_at": user.expires_at,
139
+ "persistence_enabled": settings.persistence_enabled,
140
+ "user_data_repo": (
141
+ settings.user_data_repo if settings.persistence_enabled else None
142
+ ),
143
+ }
144
+ )
145
+
146
+
147
+ @router.post("/logout")
148
+ async def logout(request: Request) -> Response:
149
+ """Clear the session cookie. Idempotent."""
150
+ resp = JSONResponse({"ok": True})
151
+ resp.delete_cookie(auth_service.SESSION_COOKIE, path="/")
152
+ return resp
153
+
154
+
155
+ @router.get("/status")
156
+ async def status() -> Response:
157
+ """Public read-only: is OAuth wired up on this deployment, and is
158
+ persistence enabled? Used by the frontend to decide whether to show
159
+ the Login button at all (e.g. hide in local dev)."""
160
+ settings = get_settings()
161
+ return JSONResponse(
162
+ {
163
+ "oauth_enabled": settings.oauth_enabled,
164
+ "persistence_enabled": settings.persistence_enabled,
165
+ "provider": settings.openid_provider_url,
166
+ }
167
+ )
backend/app/routes/plugins.py CHANGED
@@ -22,10 +22,10 @@ import re
22
  import zipfile
23
  from pathlib import Path
24
 
25
- from fastapi import APIRouter, File, HTTPException, Query, UploadFile
26
  from fastapi.responses import Response
27
 
28
- from app.services import plugin_service
29
 
30
  logger = logging.getLogger(__name__)
31
  router = APIRouter()
@@ -41,21 +41,59 @@ _EXAMPLES_DIR = Path(__file__).resolve().parents[3] / "example_plugins"
41
  _SAFE_NAME_RE = re.compile(r"^[a-z][a-z0-9_]{0,30}$")
42
 
43
 
44
- @router.get("/plugins")
45
- def list_plugins(user_id: str = Query(...)) -> list[dict]:
46
- """List all plugins this browser has uploaded. Frontend merges
47
- these into the NodeCatalog so they appear in the BlockPicker."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48
  try:
49
- plugin_service.validate_user_id(user_id)
50
  except plugin_service.PluginError as exc:
51
  raise HTTPException(status_code=400, detail=str(exc)) from None
52
- manifests = plugin_service.list_user_plugins(user_id)
 
 
 
 
 
 
 
 
 
 
53
  return [plugin_service.manifest_to_frontend(m) for m in manifests]
54
 
55
 
56
  @router.post("/plugins/upload")
57
  async def upload_plugin(
58
- user_id: str = Query(...),
 
59
  file: UploadFile = File(...),
60
  ) -> dict:
61
  """Upload a plugin .zip. Returns the validated manifest on success.
@@ -68,17 +106,19 @@ async def upload_plugin(
68
  * kind doesn't collide with built-ins or existing plugins
69
  * user is under their 5-plugin cap
70
  """
71
- try:
72
- plugin_service.validate_user_id(user_id)
73
- except plugin_service.PluginError as exc:
74
- raise HTTPException(status_code=400, detail=str(exc)) from None
 
 
75
 
76
  # Read the upload — FastAPI streams it but we want it in memory
77
  # so we can size-check before doing anything else. The size cap
78
  # in plugin_service will reject if it's >1 MB.
79
  blob = await file.read()
80
  try:
81
- manifest = plugin_service.install_plugin_zip(user_id, blob)
82
  except plugin_service.PluginError as exc:
83
  raise HTTPException(status_code=400, detail=str(exc)) from None
84
  except Exception as exc:
@@ -91,13 +131,13 @@ async def upload_plugin(
91
 
92
 
93
  @router.delete("/plugins/{kind}")
94
- def delete_plugin(kind: str, user_id: str = Query(...)) -> dict:
 
 
95
  """Remove a plugin from this user's namespace."""
96
- try:
97
- plugin_service.validate_user_id(user_id)
98
- except plugin_service.PluginError as exc:
99
- raise HTTPException(status_code=400, detail=str(exc)) from None
100
- removed = plugin_service.delete_plugin(user_id, kind)
101
  if not removed:
102
  raise HTTPException(status_code=404, detail=f"No plugin with kind={kind!r}.")
103
  return {"removed": True, "kind": kind}
 
22
  import zipfile
23
  from pathlib import Path
24
 
25
+ from fastapi import APIRouter, File, HTTPException, Query, Request, UploadFile
26
  from fastapi.responses import Response
27
 
28
+ from app.services import auth_service, plugin_service
29
 
30
  logger = logging.getLogger(__name__)
31
  router = APIRouter()
 
41
  _SAFE_NAME_RE = re.compile(r"^[a-z][a-z0-9_]{0,30}$")
42
 
43
 
44
+ def _effective_user_id(request: Request, query_user_id: str | None) -> str:
45
+ """Resolve which namespace this request operates on.
46
+
47
+ Precedence:
48
+ 1. Session-derived ``hf_<username>`` (cookie present + valid).
49
+ The server always wins — a logged-in user can't spoof someone
50
+ else's namespace by passing a different ``user_id`` query.
51
+ 2. The client-supplied anon UUID for non-logged-in browsers. We
52
+ REFUSE any query value starting with ``hf_`` because that
53
+ prefix is reserved for authenticated users; without this
54
+ check an anonymous client could squat on a real HF username's
55
+ namespace, polluting their plugin list on next login.
56
+ """
57
+ user = auth_service.decode_session(
58
+ request.cookies.get(auth_service.SESSION_COOKIE)
59
+ )
60
+ if user is not None:
61
+ return auth_service.hf_user_id(user.username)
62
+ if not query_user_id:
63
+ raise HTTPException(
64
+ status_code=400,
65
+ detail="No session cookie and no user_id query parameter.",
66
+ )
67
+ if query_user_id.startswith("hf_"):
68
+ raise HTTPException(
69
+ status_code=400,
70
+ detail=(
71
+ "The hf_ user_id prefix is reserved for authenticated "
72
+ "sessions. Sign in with Hugging Face or use a non-prefixed id."
73
+ ),
74
+ )
75
  try:
76
+ plugin_service.validate_user_id(query_user_id)
77
  except plugin_service.PluginError as exc:
78
  raise HTTPException(status_code=400, detail=str(exc)) from None
79
+ return query_user_id
80
+
81
+
82
+ @router.get("/plugins")
83
+ def list_plugins(request: Request, user_id: str | None = Query(None)) -> list[dict]:
84
+ """List all plugins this browser/account has uploaded."""
85
+ effective = _effective_user_id(request, user_id)
86
+ # For logged-in users whose /tmp was wiped by a container restart,
87
+ # hydrate from the HF Datasets backing store before listing.
88
+ plugin_service.hydrate_from_dataset_if_needed(effective)
89
+ manifests = plugin_service.list_user_plugins(effective)
90
  return [plugin_service.manifest_to_frontend(m) for m in manifests]
91
 
92
 
93
  @router.post("/plugins/upload")
94
  async def upload_plugin(
95
+ request: Request,
96
+ user_id: str | None = Query(None),
97
  file: UploadFile = File(...),
98
  ) -> dict:
99
  """Upload a plugin .zip. Returns the validated manifest on success.
 
106
  * kind doesn't collide with built-ins or existing plugins
107
  * user is under their 5-plugin cap
108
  """
109
+ effective = _effective_user_id(request, user_id)
110
+ # For logged-in users on a restarted Space, hydrate the namespace
111
+ # before the cap check so we don't let them exceed the 5-plugin cap
112
+ # by uploading a 6th while their dataset-persisted plugins are
113
+ # waiting to be pulled in.
114
+ plugin_service.hydrate_from_dataset_if_needed(effective)
115
 
116
  # Read the upload — FastAPI streams it but we want it in memory
117
  # so we can size-check before doing anything else. The size cap
118
  # in plugin_service will reject if it's >1 MB.
119
  blob = await file.read()
120
  try:
121
+ manifest = plugin_service.install_plugin_zip(effective, blob)
122
  except plugin_service.PluginError as exc:
123
  raise HTTPException(status_code=400, detail=str(exc)) from None
124
  except Exception as exc:
 
131
 
132
 
133
  @router.delete("/plugins/{kind}")
134
+ def delete_plugin(
135
+ kind: str, request: Request, user_id: str | None = Query(None)
136
+ ) -> dict:
137
  """Remove a plugin from this user's namespace."""
138
+ effective = _effective_user_id(request, user_id)
139
+ plugin_service.hydrate_from_dataset_if_needed(effective)
140
+ removed = plugin_service.delete_plugin(effective, kind)
 
 
141
  if not removed:
142
  raise HTTPException(status_code=404, detail=f"No plugin with kind={kind!r}.")
143
  return {"removed": True, "kind": kind}
backend/app/routes/workflow.py CHANGED
@@ -4,17 +4,38 @@ from __future__ import annotations
4
 
5
  import json
6
 
7
- from fastapi import APIRouter, HTTPException
8
  from fastapi.responses import StreamingResponse
9
 
10
  from app.config import get_settings
11
  from app.schemas import RunRequest, RunResponse
 
12
  from app.services.circuit_service import CircuitNotFoundError, circuit_store
13
  from app.services.plugin_service import RESERVED_KINDS as BUILTIN_KINDS
14
  from app.services.run_cache import compute_cache_key, load_cached_response
15
  from app.services.workflow_service import run_pipeline, run_pipeline_stream
16
 
17
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
  def _uses_plugins(nodes) -> bool:
19
  """True if any node has a non-built-in type (i.e. a user plugin)."""
20
  return any(n.type not in BUILTIN_KINDS for n in nodes)
@@ -23,13 +44,14 @@ router = APIRouter()
23
 
24
 
25
  @router.post("/workflow/run", response_model=RunResponse)
26
- def run_workflow(req: RunRequest) -> RunResponse:
27
  try:
28
  qc = circuit_store.get(req.circuit_id)
29
  except CircuitNotFoundError:
30
  raise HTTPException(status_code=404, detail="Unknown circuit_id") from None
31
 
32
  settings = get_settings()
 
33
 
34
  # If caller requests live IBM but the server forbids it, refuse loudly
35
  # (better UX than silently swapping in a fake backend for the whole run).
@@ -60,7 +82,7 @@ def run_workflow(req: RunRequest) -> RunResponse:
60
  nodes=req.nodes,
61
  edges=req.edges,
62
  settings=settings,
63
- user_id=req.user_id,
64
  )
65
 
66
  ok = all(s.status != "error" for s in steps)
@@ -80,7 +102,7 @@ def run_workflow(req: RunRequest) -> RunResponse:
80
 
81
 
82
  @router.post("/workflow/run-stream")
83
- def run_workflow_stream(req: RunRequest):
84
  """SSE endpoint: yields each StepResult as a Server-Sent Event as
85
  soon as it completes, instead of waiting for the whole pipeline.
86
 
@@ -95,6 +117,7 @@ def run_workflow_stream(req: RunRequest):
95
  raise HTTPException(status_code=404, detail="Unknown circuit_id") from None
96
 
97
  settings = get_settings()
 
98
 
99
  if req.use_live_ibm and not (settings.has_ibm_token and settings.allow_live_ibm):
100
  raise HTTPException(status_code=403, detail="Live IBM execution is disabled.")
@@ -114,7 +137,7 @@ def run_workflow_stream(req: RunRequest):
114
  def step_stream():
115
  for step in run_pipeline_stream(
116
  circuit=qc, nodes=req.nodes, edges=req.edges,
117
- settings=settings, user_id=req.user_id,
118
  ):
119
  yield f"data: {step.model_dump_json()}\n\n"
120
  yield "data: [DONE]\n\n"
 
4
 
5
  import json
6
 
7
+ from fastapi import APIRouter, HTTPException, Request
8
  from fastapi.responses import StreamingResponse
9
 
10
  from app.config import get_settings
11
  from app.schemas import RunRequest, RunResponse
12
+ from app.services import auth_service
13
  from app.services.circuit_service import CircuitNotFoundError, circuit_store
14
  from app.services.plugin_service import RESERVED_KINDS as BUILTIN_KINDS
15
  from app.services.run_cache import compute_cache_key, load_cached_response
16
  from app.services.workflow_service import run_pipeline, run_pipeline_stream
17
 
18
 
19
+ def _effective_user_id(request: Request, body_user_id: str | None) -> str | None:
20
+ """Same precedence as the plugin routes: session-derived hf_<username>
21
+ wins if the user is logged in; otherwise we take the body field
22
+ (the anon UUID from localStorage). Returning None is fine — the
23
+ workflow runner only consults user_id when it encounters a plugin
24
+ node, which only logged-in or anon users with uploaded plugins
25
+ would hit anyway.
26
+
27
+ Defence-in-depth: refuse body-supplied hf_* ids, matching the
28
+ plugin route's anon-squat guard."""
29
+ user = auth_service.decode_session(
30
+ request.cookies.get(auth_service.SESSION_COOKIE)
31
+ )
32
+ if user is not None:
33
+ return auth_service.hf_user_id(user.username)
34
+ if body_user_id and body_user_id.startswith("hf_"):
35
+ return None
36
+ return body_user_id
37
+
38
+
39
  def _uses_plugins(nodes) -> bool:
40
  """True if any node has a non-built-in type (i.e. a user plugin)."""
41
  return any(n.type not in BUILTIN_KINDS for n in nodes)
 
44
 
45
 
46
  @router.post("/workflow/run", response_model=RunResponse)
47
+ def run_workflow(req: RunRequest, request: Request) -> RunResponse:
48
  try:
49
  qc = circuit_store.get(req.circuit_id)
50
  except CircuitNotFoundError:
51
  raise HTTPException(status_code=404, detail="Unknown circuit_id") from None
52
 
53
  settings = get_settings()
54
+ effective_user_id = _effective_user_id(request, req.user_id)
55
 
56
  # If caller requests live IBM but the server forbids it, refuse loudly
57
  # (better UX than silently swapping in a fake backend for the whole run).
 
82
  nodes=req.nodes,
83
  edges=req.edges,
84
  settings=settings,
85
+ user_id=effective_user_id,
86
  )
87
 
88
  ok = all(s.status != "error" for s in steps)
 
102
 
103
 
104
  @router.post("/workflow/run-stream")
105
+ def run_workflow_stream(req: RunRequest, request: Request):
106
  """SSE endpoint: yields each StepResult as a Server-Sent Event as
107
  soon as it completes, instead of waiting for the whole pipeline.
108
 
 
117
  raise HTTPException(status_code=404, detail="Unknown circuit_id") from None
118
 
119
  settings = get_settings()
120
+ effective_user_id = _effective_user_id(request, req.user_id)
121
 
122
  if req.use_live_ibm and not (settings.has_ibm_token and settings.allow_live_ibm):
123
  raise HTTPException(status_code=403, detail="Live IBM execution is disabled.")
 
137
  def step_stream():
138
  for step in run_pipeline_stream(
139
  circuit=qc, nodes=req.nodes, edges=req.edges,
140
+ settings=settings, user_id=effective_user_id,
141
  ):
142
  yield f"data: {step.model_dump_json()}\n\n"
143
  yield "data: [DONE]\n\n"
backend/app/services/auth_service.py ADDED
@@ -0,0 +1,283 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """HF OAuth session helpers.
2
+
3
+ Why a tiny custom OAuth client instead of authlib? We need exactly three
4
+ things — build an authorize URL, exchange code for token+userinfo,
5
+ sign/verify session cookies — and authlib's session-based API drags in
6
+ Starlette session middleware that fights with our cookie strategy.
7
+ Direct httpx + itsdangerous is ~80 lines and clearer to audit.
8
+
9
+ Session storage strategy:
10
+
11
+ * Signed cookie (itsdangerous URLSafeTimedSerializer)
12
+ * Payload is small: {sub, username, avatar, exp}
13
+ * We do NOT store the HF access_token in the cookie — we don't need
14
+ it after the initial /me lookup. Less to leak.
15
+ * The session_secret comes from the SESSION_SECRET env var (HF
16
+ Space secret); fresh-random in dev.
17
+
18
+ Cookies:
19
+
20
+ * Name: ``quda_session``
21
+ * HttpOnly, SameSite=Lax, Secure-when-https
22
+ * Default max-age 8h, matching the HF token lifetime
23
+
24
+ Threats considered:
25
+
26
+ * CSRF on the OAuth callback → state cookie + signed
27
+ * Cookie tampering → itsdangerous signature
28
+ * Session fixation → state is per-login random
29
+ * XSS exfiltration → HttpOnly + we don't put anything sensitive in
30
+ the cookie payload anyway
31
+ """
32
+
33
+ from __future__ import annotations
34
+
35
+ import logging
36
+ import re
37
+ import secrets
38
+ import time
39
+ from dataclasses import dataclass
40
+ from typing import Any
41
+
42
+ import httpx
43
+ from itsdangerous import BadSignature, SignatureExpired, URLSafeTimedSerializer
44
+
45
+ from app.config import get_settings
46
+
47
+ logger = logging.getLogger(__name__)
48
+
49
+ SESSION_COOKIE = "quda_session"
50
+ STATE_COOKIE = "quda_oauth_state"
51
+
52
+ # Sessions valid for 8 hours, matching the HF token expiration we set
53
+ # in README frontmatter (hf_oauth_expiration_minutes: 480).
54
+ SESSION_MAX_AGE_SECONDS = 8 * 3600
55
+
56
+ # Authorization URL endpoint paths off the openid_provider_url.
57
+ _AUTHORIZE_PATH = "/oauth/authorize"
58
+ _TOKEN_PATH = "/oauth/token"
59
+ _USERINFO_PATH = "/oauth/userinfo"
60
+
61
+ # HF usernames are restricted server-side. We re-validate before using
62
+ # the value as a directory name / plugin namespace so a compromised
63
+ # OAuth response can't escape into "../" or weird Unicode.
64
+ _HF_USERNAME_RE = re.compile(r"^[a-zA-Z0-9][a-zA-Z0-9_-]{0,38}$")
65
+
66
+
67
+ class AuthError(Exception):
68
+ """Surfaced to the route layer as a 400/401 with a clear message."""
69
+
70
+
71
+ @dataclass(frozen=True)
72
+ class SessionUser:
73
+ sub: str # HF user opaque id (immutable across renames)
74
+ username: str # HF username, validated against _HF_USERNAME_RE
75
+ avatar_url: str | None
76
+ expires_at: int # unix seconds
77
+
78
+
79
+ # ---- Session cookie -----------------------------------------------------
80
+
81
+ def _serializer() -> URLSafeTimedSerializer:
82
+ settings = get_settings()
83
+ return URLSafeTimedSerializer(settings.session_secret, salt="quda-session-v1")
84
+
85
+
86
+ def encode_session(user: SessionUser) -> str:
87
+ """Encode a SessionUser as a signed token suitable for a cookie."""
88
+ return _serializer().dumps(
89
+ {
90
+ "sub": user.sub,
91
+ "username": user.username,
92
+ "avatar_url": user.avatar_url,
93
+ "exp": user.expires_at,
94
+ }
95
+ )
96
+
97
+
98
+ def decode_session(token: str | None) -> SessionUser | None:
99
+ """Decode a session cookie. Returns None if missing, invalid, or
100
+ expired."""
101
+ if not token:
102
+ return None
103
+ try:
104
+ payload = _serializer().loads(
105
+ token, max_age=SESSION_MAX_AGE_SECONDS
106
+ )
107
+ except SignatureExpired:
108
+ return None
109
+ except BadSignature:
110
+ return None
111
+ if not isinstance(payload, dict):
112
+ return None
113
+ exp = payload.get("exp")
114
+ if isinstance(exp, (int, float)) and exp < time.time():
115
+ return None
116
+ username = payload.get("username")
117
+ if not isinstance(username, str) or not _HF_USERNAME_RE.match(username):
118
+ return None
119
+ sub = payload.get("sub")
120
+ if not isinstance(sub, str) or not sub:
121
+ return None
122
+ avatar = payload.get("avatar_url")
123
+ if avatar is not None and not isinstance(avatar, str):
124
+ avatar = None
125
+ return SessionUser(
126
+ sub=sub,
127
+ username=username,
128
+ avatar_url=avatar,
129
+ expires_at=int(exp) if isinstance(exp, (int, float)) else int(time.time()),
130
+ )
131
+
132
+
133
+ # ---- OAuth flow --------------------------------------------------------
134
+
135
+ def _redirect_uri(request_origin: str | None) -> str:
136
+ """Compute the OAuth callback URI.
137
+
138
+ Preference order:
139
+ 1. Explicit Space host from SPACE_HOST env var (set by HF)
140
+ 2. Origin observed on the inbound request (dev / port-forward)
141
+ 3. Hardcoded fallback so the URL is at least well-formed
142
+ """
143
+ settings = get_settings()
144
+ if settings.space_host:
145
+ return f"https://{settings.space_host}/api/auth/callback"
146
+ if request_origin:
147
+ return f"{request_origin.rstrip('/')}/api/auth/callback"
148
+ return "https://qudastudio-app.hf.space/api/auth/callback"
149
+
150
+
151
+ def build_authorize_url(state: str, request_origin: str | None) -> str:
152
+ """Build the URL we redirect the browser to for HF login."""
153
+ settings = get_settings()
154
+ if not settings.oauth_enabled:
155
+ raise AuthError(
156
+ "OAuth not configured on this deployment. "
157
+ "Set hf_oauth: true in the Space README frontmatter."
158
+ )
159
+ params = httpx.QueryParams(
160
+ {
161
+ "client_id": settings.oauth_client_id,
162
+ "redirect_uri": _redirect_uri(request_origin),
163
+ "response_type": "code",
164
+ "scope": "openid profile",
165
+ "state": state,
166
+ }
167
+ )
168
+ return f"{settings.openid_provider_url}{_AUTHORIZE_PATH}?{params}"
169
+
170
+
171
+ def mint_state() -> str:
172
+ """Per-login random state, stored in a short-lived signed cookie
173
+ and verified on callback to defeat CSRF on the OAuth handshake."""
174
+ return secrets.token_urlsafe(24)
175
+
176
+
177
+ def encode_state(state: str) -> str:
178
+ return _serializer().dumps({"state": state})
179
+
180
+
181
+ def decode_state(token: str | None) -> str | None:
182
+ if not token:
183
+ return None
184
+ try:
185
+ payload = _serializer().loads(token, max_age=600) # 10 min
186
+ except (SignatureExpired, BadSignature):
187
+ return None
188
+ if isinstance(payload, dict):
189
+ st = payload.get("state")
190
+ if isinstance(st, str):
191
+ return st
192
+ return None
193
+
194
+
195
+ async def exchange_code_for_user(
196
+ code: str, request_origin: str | None
197
+ ) -> SessionUser:
198
+ """POST the code to HF /oauth/token, then GET /userinfo with the
199
+ resulting access_token. Returns a normalized SessionUser.
200
+
201
+ Raises AuthError with a user-facing string on any failure so the
202
+ route can return a 400 with the original message.
203
+ """
204
+ settings = get_settings()
205
+ if not settings.oauth_enabled:
206
+ raise AuthError("OAuth not configured.")
207
+ redirect_uri = _redirect_uri(request_origin)
208
+ async with httpx.AsyncClient(timeout=15.0) as client:
209
+ try:
210
+ token_resp = await client.post(
211
+ f"{settings.openid_provider_url}{_TOKEN_PATH}",
212
+ data={
213
+ "grant_type": "authorization_code",
214
+ "code": code,
215
+ "redirect_uri": redirect_uri,
216
+ },
217
+ auth=(settings.oauth_client_id or "", settings.oauth_client_secret or ""),
218
+ headers={"Accept": "application/json"},
219
+ )
220
+ except httpx.HTTPError as exc:
221
+ raise AuthError(f"Could not reach HF /oauth/token: {exc}") from None
222
+ if token_resp.status_code >= 400:
223
+ raise AuthError(
224
+ f"HF rejected the code: HTTP {token_resp.status_code} {token_resp.text[:200]}"
225
+ )
226
+ try:
227
+ token_data = token_resp.json()
228
+ except ValueError:
229
+ raise AuthError("HF /oauth/token returned non-JSON.") from None
230
+ access_token = token_data.get("access_token")
231
+ if not access_token or not isinstance(access_token, str):
232
+ raise AuthError("HF /oauth/token missing access_token.")
233
+
234
+ try:
235
+ user_resp = await client.get(
236
+ f"{settings.openid_provider_url}{_USERINFO_PATH}",
237
+ headers={"Authorization": f"Bearer {access_token}"},
238
+ )
239
+ except httpx.HTTPError as exc:
240
+ raise AuthError(f"Could not reach HF /oauth/userinfo: {exc}") from None
241
+ if user_resp.status_code >= 400:
242
+ raise AuthError(
243
+ f"HF /oauth/userinfo failed: HTTP {user_resp.status_code}"
244
+ )
245
+ try:
246
+ info: dict[str, Any] = user_resp.json()
247
+ except ValueError:
248
+ raise AuthError("HF /oauth/userinfo returned non-JSON.") from None
249
+
250
+ sub = info.get("sub")
251
+ username = info.get("preferred_username") or info.get("name")
252
+ avatar_url = info.get("picture")
253
+ if not isinstance(sub, str) or not sub:
254
+ raise AuthError("HF /oauth/userinfo missing sub.")
255
+ if not isinstance(username, str) or not _HF_USERNAME_RE.match(username):
256
+ raise AuthError(
257
+ "HF /oauth/userinfo returned an unexpected username format."
258
+ )
259
+ if avatar_url is not None and not isinstance(avatar_url, str):
260
+ avatar_url = None
261
+
262
+ return SessionUser(
263
+ sub=sub,
264
+ username=username,
265
+ avatar_url=avatar_url,
266
+ expires_at=int(time.time()) + SESSION_MAX_AGE_SECONDS,
267
+ )
268
+
269
+
270
+ # ---- user_id derivation -----------------------------------------------
271
+
272
+ def hf_user_id(username: str) -> str:
273
+ """Namespace key for a logged-in user. Used as a directory name in
274
+ /tmp/quda_plugins/<id>/ and the plugin path inside the HF dataset.
275
+
276
+ The hf_ prefix prevents collision with anon UUIDs (anon_*)."""
277
+ if not _HF_USERNAME_RE.match(username):
278
+ raise ValueError("Invalid HF username for hf_user_id.")
279
+ return f"hf_{username}"
280
+
281
+
282
+ def is_hf_user_id(user_id: str) -> bool:
283
+ return user_id.startswith("hf_")
backend/app/services/datasets_storage.py ADDED
@@ -0,0 +1,277 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Persist authenticated users' plugins to an HF Dataset repo.
2
+
3
+ Design summary
4
+
5
+ The HF Space's /tmp is wiped on container restart. Logged-in users
6
+ expect their uploaded plugins to outlive that — they identified
7
+ themselves via OAuth and the whole point of an account is persistence
8
+ across sessions/devices/restarts. We use a private HF Dataset repo as
9
+ the backing store:
10
+
11
+ qudastudio/quda-user-data/
12
+ users/
13
+ hf_<username>/
14
+ <kind>.zip ← the original uploaded plugin zip
15
+ ...
16
+
17
+ Only the HF Space (with HF_TOKEN as a Space secret) has write access.
18
+ Other HF users CANNOT browse this dataset because it's private. The
19
+ dataset is therefore a shared trust boundary between us (the JQub lab,
20
+ who operate the Space) and our users — same trust model as any SaaS.
21
+
22
+ Anonymous (anon_*) users do NOT sync to the dataset. Their plugins
23
+ remain volatile, which matches what they implicitly consented to by
24
+ not logging in. The mirroring functions silently no-op for anon users.
25
+
26
+ Failure model
27
+
28
+ * Sync errors are LOGGED, not RAISED. The user's plugin is already
29
+ on disk and working; whether it's been mirrored is a secondary
30
+ concern they can recover from by re-uploading after a restart.
31
+ * Hydration uses a per-process lock to avoid two concurrent requests
32
+ each downloading the same files.
33
+
34
+ Threats
35
+
36
+ * The dataset token has org-wide write scope (current limitation).
37
+ A future improvement is a fine-grained token with access only to
38
+ this one repo. Subprocess env stripping already prevents plugins
39
+ from reading HF_TOKEN.
40
+ * Filename inside the repo is `<kind>.zip` where ``kind`` matches
41
+ ``[a-z][a-z0-9_]{1,30}``, and the user_id is ``hf_<username>``
42
+ where username matches HF's own regex. No path traversal surface.
43
+ """
44
+
45
+ from __future__ import annotations
46
+
47
+ import io
48
+ import logging
49
+ import threading
50
+ import time
51
+ import zipfile
52
+ from pathlib import Path
53
+
54
+ from app.config import get_settings
55
+
56
+ logger = logging.getLogger(__name__)
57
+
58
+
59
+ # Per-process hydration lock map. Keyed on user_id; each user's
60
+ # hydration runs at most once concurrently across request handlers.
61
+ # (FastAPI within a single uvicorn worker is single-process, multi
62
+ # threaded for sync handlers and singletask for async — this lock
63
+ # serialises any of them.)
64
+ _hydration_locks: dict[str, threading.Lock] = {}
65
+ _hydration_locks_guard = threading.Lock()
66
+
67
+ # Per-user "we recently checked the dataset for this user" timestamp.
68
+ # Without it, every /api/plugins request from a logged-in user makes a
69
+ # list_repo_files round trip to HF — sub-second but completely wasted
70
+ # work after the first hit. 30 s is short enough that "I just deleted
71
+ # a plugin from another device" lands within human-noticeable time.
72
+ _HYDRATE_FRESHNESS_SECONDS = 30.0
73
+ _last_hydrate_at: dict[str, float] = {}
74
+
75
+
76
+ def _is_authenticated_user(user_id: str) -> bool:
77
+ """Anon users (anon_*) get no persistence. Logged-in users
78
+ (hf_*) get the full dataset sync."""
79
+ return user_id.startswith("hf_")
80
+
81
+
82
+ def _hf_api():
83
+ """Build an HfApi client with our write token. Returns None if
84
+ persistence is disabled (no token configured)."""
85
+ settings = get_settings()
86
+ if not settings.persistence_enabled:
87
+ return None
88
+ # Late import — huggingface_hub is a heavyweight dep; we want it
89
+ # only when actually used. (~150 ms saved at import time during
90
+ # tests that don't touch persistence.)
91
+ from huggingface_hub import HfApi
92
+
93
+ return HfApi(token=settings.hf_token)
94
+
95
+
96
+ def _repo_id() -> str:
97
+ return get_settings().user_data_repo
98
+
99
+
100
+ def _path_in_repo(user_id: str, kind: str) -> str:
101
+ """Layout: users/<user_id>/<kind>.zip"""
102
+ return f"users/{user_id}/{kind}.zip"
103
+
104
+
105
+ def _user_prefix(user_id: str) -> str:
106
+ return f"users/{user_id}/"
107
+
108
+
109
+ # ---- Public API ---------------------------------------------------------
110
+
111
+ def push_plugin(user_id: str, kind: str, zip_bytes: bytes) -> bool:
112
+ """Upload one user's plugin .zip to the dataset repo. Returns True
113
+ on success, False if persistence is off / user is anon / upload
114
+ failed. Never raises — install path stays alive even if the
115
+ backing store is down."""
116
+ if not _is_authenticated_user(user_id):
117
+ return False
118
+ api = _hf_api()
119
+ if api is None:
120
+ return False
121
+ try:
122
+ api.upload_file(
123
+ path_or_fileobj=zip_bytes,
124
+ path_in_repo=_path_in_repo(user_id, kind),
125
+ repo_id=_repo_id(),
126
+ repo_type="dataset",
127
+ commit_message=f"upload {user_id}/{kind}",
128
+ )
129
+ logger.info("Mirrored plugin %s/%s to dataset", user_id, kind)
130
+ return True
131
+ except Exception:
132
+ logger.exception(
133
+ "Failed to mirror plugin %s/%s to dataset (continuing)", user_id, kind
134
+ )
135
+ return False
136
+
137
+
138
+ def remove_plugin(user_id: str, kind: str) -> bool:
139
+ """Remove one plugin from the dataset repo. Returns True on
140
+ success, False on no-op or failure. Never raises."""
141
+ if not _is_authenticated_user(user_id):
142
+ return False
143
+ api = _hf_api()
144
+ if api is None:
145
+ return False
146
+ try:
147
+ api.delete_file(
148
+ path_in_repo=_path_in_repo(user_id, kind),
149
+ repo_id=_repo_id(),
150
+ repo_type="dataset",
151
+ commit_message=f"delete {user_id}/{kind}",
152
+ )
153
+ logger.info("Removed plugin %s/%s from dataset", user_id, kind)
154
+ return True
155
+ except Exception:
156
+ logger.exception(
157
+ "Failed to remove %s/%s from dataset (continuing)", user_id, kind
158
+ )
159
+ return False
160
+
161
+
162
+ def list_remote_kinds(user_id: str) -> list[str]:
163
+ """Return the kinds this user has plugins for in the dataset. Empty
164
+ list on any failure."""
165
+ if not _is_authenticated_user(user_id):
166
+ return []
167
+ api = _hf_api()
168
+ if api is None:
169
+ return []
170
+ try:
171
+ files = api.list_repo_files(
172
+ repo_id=_repo_id(), repo_type="dataset"
173
+ )
174
+ except Exception:
175
+ logger.exception(
176
+ "Failed to list dataset files for %s (continuing with empty list)",
177
+ user_id,
178
+ )
179
+ return []
180
+ prefix = _user_prefix(user_id)
181
+ kinds = []
182
+ for path in files:
183
+ if not path.startswith(prefix) or not path.endswith(".zip"):
184
+ continue
185
+ kind = path[len(prefix) : -len(".zip")]
186
+ # Sanity: kind matches our regex, no nested path
187
+ if "/" in kind or not kind:
188
+ continue
189
+ kinds.append(kind)
190
+ return kinds
191
+
192
+
193
+ def hydrate_into_tmp(
194
+ user_id: str, target_root: Path, install_plugin_zip_fn
195
+ ) -> int:
196
+ """Idempotent: for every plugin this user has in the dataset that
197
+ isn't already on disk under target_root, download it and re-install
198
+ via install_plugin_zip_fn (so it goes through the same validation
199
+ + extraction path as a fresh user upload).
200
+
201
+ target_root is the parent dir under which plugin_dir(user_id, kind)
202
+ sits (i.e. /tmp/quda_plugins/<user_id>/).
203
+
204
+ Returns the number of plugins newly hydrated. Anon users always
205
+ return 0.
206
+ """
207
+ if not _is_authenticated_user(user_id):
208
+ return 0
209
+ api = _hf_api()
210
+ if api is None:
211
+ return 0
212
+
213
+ # Per-user lock so concurrent /api/plugins requests don't both try
214
+ # to hydrate the same user's data.
215
+ with _hydration_locks_guard:
216
+ lock = _hydration_locks.setdefault(user_id, threading.Lock())
217
+ with lock:
218
+ # Short freshness cache so a logged-in user listing/uploading/
219
+ # deleting in quick succession doesn't hit the HF API on every
220
+ # call. The cache is per-process and short enough that
221
+ # cross-device deletes still land within ~30 s.
222
+ now = time.monotonic()
223
+ if now - _last_hydrate_at.get(user_id, 0.0) < _HYDRATE_FRESHNESS_SECONDS:
224
+ return 0
225
+ try:
226
+ remote_kinds = list_remote_kinds(user_id)
227
+ except Exception:
228
+ logger.exception("Hydration list failed for %s", user_id)
229
+ return 0
230
+ # Mark as fresh BEFORE the per-file work — if a download
231
+ # partially fails we still don't want to re-list immediately;
232
+ # the user can retry the request.
233
+ _last_hydrate_at[user_id] = now
234
+
235
+ new_count = 0
236
+ for kind in remote_kinds:
237
+ local_dir = target_root / kind
238
+ if local_dir.exists():
239
+ continue
240
+ try:
241
+ local_path = api.hf_hub_download(
242
+ repo_id=_repo_id(),
243
+ repo_type="dataset",
244
+ filename=_path_in_repo(user_id, kind),
245
+ )
246
+ except Exception:
247
+ logger.exception(
248
+ "Could not download %s/%s from dataset", user_id, kind
249
+ )
250
+ continue
251
+ try:
252
+ zip_bytes = Path(local_path).read_bytes()
253
+ except OSError:
254
+ logger.exception("Could not read downloaded %s/%s", user_id, kind)
255
+ continue
256
+ try:
257
+ install_plugin_zip_fn(user_id, zip_bytes, _skip_dataset_sync=True)
258
+ new_count += 1
259
+ except Exception:
260
+ logger.exception(
261
+ "Re-install failed for hydrated %s/%s — skipping",
262
+ user_id,
263
+ kind,
264
+ )
265
+ if new_count:
266
+ logger.info("Hydrated %d plugin(s) for %s from dataset", new_count, user_id)
267
+ return new_count
268
+
269
+
270
+ def is_zip_intact(zip_bytes: bytes) -> bool:
271
+ """Lightweight sanity for hydration — if the downloaded blob fails
272
+ to parse as a zip we skip it rather than 500."""
273
+ try:
274
+ with zipfile.ZipFile(io.BytesIO(zip_bytes)) as zf:
275
+ return zf.testzip() is None
276
+ except zipfile.BadZipFile:
277
+ return False
backend/app/services/plugin_service.py CHANGED
@@ -40,9 +40,18 @@ MAX_FILE_BYTES = 512 * 1024 # 512 KB per file inside the zip
40
  # be tiny Python modules, not data dumps.
41
  ALLOWED_ZIP_EXTENSIONS = {".py", ".json", ".txt", ".md"}
42
 
43
- # user_id must look like a UUID-ish token; constrains the directory
44
- # structure we'll create on disk.
45
- _USER_ID_RE = re.compile(r"^[a-zA-Z0-9_-]{8,64}$")
 
 
 
 
 
 
 
 
 
46
  _KIND_RE = re.compile(r"^[a-z][a-z0-9_]{1,30}$")
47
 
48
  # Reserved kinds collide with built-in NodeType — refuse to let a
@@ -210,20 +219,39 @@ def find_plugin(user_id: str, kind: str) -> tuple[PluginManifest, Path] | None:
210
 
211
  def delete_plugin(user_id: str, kind: str) -> bool:
212
  """Remove the given plugin from this user's namespace. Returns
213
- True if something was removed, False if it didn't exist."""
 
 
 
214
  d = plugin_dir(user_id, kind)
215
- if not d.exists():
216
- return False
217
- shutil.rmtree(d, ignore_errors=True)
218
- return True
 
 
 
 
 
 
 
219
 
220
 
221
  # ---- Upload + validation -----------------------------------------------
222
 
223
- def install_plugin_zip(user_id: str, zip_bytes: bytes) -> PluginManifest:
 
 
 
 
 
224
  """Validate and install a plugin .zip for the given user. Raises
225
  :class:`PluginError` with a human-readable message if anything
226
- goes wrong; the caller maps to HTTP 400."""
 
 
 
 
227
  validate_user_id(user_id)
228
 
229
  # Hard size cap up front.
@@ -361,9 +389,33 @@ def install_plugin_zip(user_id: str, zip_bytes: bytes) -> PluginManifest:
361
  raise
362
 
363
  logger.info("Installed plugin %s/%s", user_id, manifest.kind)
 
 
 
 
 
 
 
 
364
  return manifest
365
 
366
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
367
  def get_plugin_handler_path(user_id: str, kind: str) -> Path | None:
368
  """Resolve to the handler.py for a (user, kind) plugin, or None."""
369
  d = plugin_dir(user_id, kind)
 
40
  # be tiny Python modules, not data dumps.
41
  ALLOWED_ZIP_EXTENSIONS = {".py", ".json", ".txt", ".md"}
42
 
43
+ # user_id must look like an identifier-ish token; constrains the
44
+ # directory structure we'll create on disk. Two flavours allowed:
45
+ #
46
+ # * ``hf_<username>`` — server-derived from an authenticated session.
47
+ # HF usernames are 1–39 chars matching [a-zA-Z0-9][a-zA-Z0-9_-]*,
48
+ # so the prefixed form can be as short as 4 chars (hf_a).
49
+ # * any other token of 8+ chars — the anon browser UUID generated by
50
+ # frontend/src/lib/userId.ts.
51
+ #
52
+ # The hf_ prefix is reserved for server-derived ids and the route layer
53
+ # refuses to accept it on the query-parameter path (anon squat defense).
54
+ _USER_ID_RE = re.compile(r"^[a-zA-Z0-9_-]{4,64}$")
55
  _KIND_RE = re.compile(r"^[a-z][a-z0-9_]{1,30}$")
56
 
57
  # Reserved kinds collide with built-in NodeType — refuse to let a
 
219
 
220
  def delete_plugin(user_id: str, kind: str) -> bool:
221
  """Remove the given plugin from this user's namespace. Returns
222
+ True if something was removed, False if it didn't exist.
223
+
224
+ For authenticated users (hf_*), also removes the plugin from the
225
+ HF Datasets backing store so it doesn't get re-hydrated next time."""
226
  d = plugin_dir(user_id, kind)
227
+ existed_locally = d.exists()
228
+ if existed_locally:
229
+ shutil.rmtree(d, ignore_errors=True)
230
+ # Mirror the removal to the dataset (no-op for anon users / off
231
+ # deployments). Even if the local dir didn't exist, attempt the
232
+ # remote delete in case the previous restart wiped /tmp without
233
+ # giving the user a chance to re-list.
234
+ from app.services import datasets_storage
235
+
236
+ datasets_storage.remove_plugin(user_id, kind)
237
+ return existed_locally
238
 
239
 
240
  # ---- Upload + validation -----------------------------------------------
241
 
242
+ def install_plugin_zip(
243
+ user_id: str,
244
+ zip_bytes: bytes,
245
+ *,
246
+ _skip_dataset_sync: bool = False,
247
+ ) -> PluginManifest:
248
  """Validate and install a plugin .zip for the given user. Raises
249
  :class:`PluginError` with a human-readable message if anything
250
+ goes wrong; the caller maps to HTTP 400.
251
+
252
+ ``_skip_dataset_sync`` is an internal flag used by hydration to
253
+ avoid re-uploading a plugin we just downloaded from the dataset.
254
+ Always omit it from external callers."""
255
  validate_user_id(user_id)
256
 
257
  # Hard size cap up front.
 
389
  raise
390
 
391
  logger.info("Installed plugin %s/%s", user_id, manifest.kind)
392
+
393
+ # Mirror to the HF Datasets backing store so authenticated users'
394
+ # plugins survive container restarts. No-op for anon users.
395
+ if not _skip_dataset_sync:
396
+ from app.services import datasets_storage
397
+
398
+ datasets_storage.push_plugin(user_id, manifest.kind, zip_bytes)
399
+
400
  return manifest
401
 
402
 
403
+ def hydrate_from_dataset_if_needed(user_id: str) -> int:
404
+ """For authenticated users on a freshly-restarted Space, pull any
405
+ plugins from the HF Datasets backing store that aren't yet on
406
+ /tmp. Idempotent + cheap when there's nothing to hydrate.
407
+
408
+ Anon users always no-op (no persistent backing store)."""
409
+ from app.services import datasets_storage
410
+
411
+ if not user_id.startswith("hf_"):
412
+ return 0
413
+ user_dir = user_plugin_dir(user_id)
414
+ return datasets_storage.hydrate_into_tmp(
415
+ user_id, user_dir, install_plugin_zip
416
+ )
417
+
418
+
419
  def get_plugin_handler_path(user_id: str, kind: str) -> Path | None:
420
  """Resolve to the handler.py for a (user, kind) plugin, or None."""
421
  d = plugin_dir(user_id, kind)
backend/requirements.txt CHANGED
@@ -8,6 +8,15 @@ fastapi==0.115.6
8
  uvicorn[standard]==0.32.1
9
  pydantic==2.9.2
10
  python-multipart==0.0.12
 
 
 
 
 
 
 
 
 
11
 
12
  # Qiskit stack (Jovin's working combo for Qiskit 2.3)
13
  qiskit==2.3.0
 
8
  uvicorn[standard]==0.32.1
9
  pydantic==2.9.2
10
  python-multipart==0.0.12
11
+ # OAuth + session: itsdangerous signs the session cookie, httpx is used
12
+ # to POST to HF's OAuth /token endpoint. (FastAPI already pulls httpx
13
+ # transitively for TestClient, but pinning it here makes the runtime
14
+ # dependency explicit.)
15
+ itsdangerous==2.2.0
16
+ httpx==0.27.2
17
+ # HF Datasets sync — used to persist authenticated users' plugins to
18
+ # a private dataset repo so they survive container restarts.
19
+ huggingface_hub==0.27.1
20
 
21
  # Qiskit stack (Jovin's working combo for Qiskit 2.3)
22
  qiskit==2.3.0
frontend/src/App.tsx CHANGED
@@ -198,6 +198,9 @@ export default function App() {
198
  }, [isDesktop, leftCollapsed, rightCollapsed, leftW, rightW]);
199
 
200
  const setPlugins = useApp((s) => s.setPlugins);
 
 
 
201
  useEffect(() => {
202
  api
203
  .health()
@@ -206,9 +209,20 @@ export default function App() {
206
  setReady(true);
207
  })
208
  .catch(() => setReady(true));
209
- // Fetch this browser's plugin manifests (anonymous user_id stored
210
- // in localStorage). Silent on failure — the user just won't see
211
- // their previously-uploaded plugins until they re-upload.
 
 
 
 
 
 
 
 
 
 
 
212
  const refreshPlugins = () => {
213
  api
214
  .listPlugins(getUserId())
@@ -227,7 +241,78 @@ export default function App() {
227
  };
228
  window.addEventListener("storage", onStorage);
229
  return () => window.removeEventListener("storage", onStorage);
230
- }, [setHealth, setPlugins]);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
231
 
232
  const leftWidth = leftCollapsed ? COLLAPSED_W : leftW;
233
  const rightWidth = rightCollapsed ? COLLAPSED_W : rightW;
@@ -240,6 +325,22 @@ export default function App() {
240
  onOpenLeftDrawer={() => setLeftDrawerOpen(true)}
241
  onOpenRightDrawer={() => setRightDrawerOpen(true)}
242
  />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
243
  {isDesktop ? (
244
  /* ===================== Desktop ===================== */
245
  <div className="flex-1 flex min-h-0">
 
198
  }, [isDesktop, leftCollapsed, rightCollapsed, leftW, rightW]);
199
 
200
  const setPlugins = useApp((s) => s.setPlugins);
201
+ const setSession = useApp((s) => s.setSession);
202
+ const setAuthStatus = useApp((s) => s.setAuthStatus);
203
+ const session = useApp((s) => s.session);
204
  useEffect(() => {
205
  api
206
  .health()
 
209
  setReady(true);
210
  })
211
  .catch(() => setReady(true));
212
+ // Capability probe — does this deployment have OAuth wired up?
213
+ api
214
+ .authStatus()
215
+ .then(setAuthStatus)
216
+ .catch(() => setAuthStatus(null));
217
+ // Current session (may be null when no cookie present).
218
+ api
219
+ .authMe()
220
+ .then(setSession)
221
+ .catch(() => setSession(null));
222
+
223
+ // Fetch the current namespace's plugin manifests. We re-run this
224
+ // whenever the session changes (login → reloads plugins under the
225
+ // hf_<username> namespace; logout → reloads under the anon UUID).
226
  const refreshPlugins = () => {
227
  api
228
  .listPlugins(getUserId())
 
241
  };
242
  window.addEventListener("storage", onStorage);
243
  return () => window.removeEventListener("storage", onStorage);
244
+ }, [setHealth, setPlugins, setSession, setAuthStatus]);
245
+
246
+ // Whenever the session changes (post-login redirect or post-logout)
247
+ // refetch the plugin list — the namespace just changed under us.
248
+ useEffect(() => {
249
+ api
250
+ .listPlugins(getUserId())
251
+ .then(setPlugins)
252
+ .catch(() => {
253
+ /* ignore */
254
+ });
255
+ }, [session?.username, setPlugins]);
256
+
257
+ // Session-expiry detection. Without this the avatar dropdown would
258
+ // claim "signed in" while the server has long since started serving
259
+ // the anon namespace. We arm a timer for the cookie's expires_at and
260
+ // clear the local session state when it fires. We also probe /me
261
+ // every 5 minutes so a server-side invalidation propagates fast.
262
+ useEffect(() => {
263
+ if (!session) return;
264
+ const msUntil = session.expires_at * 1000 - Date.now();
265
+ if (msUntil <= 0) {
266
+ setSession(null);
267
+ return;
268
+ }
269
+ const expiryTimer = window.setTimeout(() => {
270
+ setSession(null);
271
+ }, msUntil);
272
+ const probeTimer = window.setInterval(() => {
273
+ api
274
+ .authMe()
275
+ .then((u) => {
276
+ if (!u) setSession(null);
277
+ })
278
+ .catch(() => {
279
+ /* network blip — leave the session alone */
280
+ });
281
+ }, 5 * 60 * 1000);
282
+ return () => {
283
+ window.clearTimeout(expiryTimer);
284
+ window.clearInterval(probeTimer);
285
+ };
286
+ }, [session?.expires_at, setSession, session]);
287
+
288
+ // Surface an auth error if the OAuth callback redirected with
289
+ // ?auth_error=... — strip it from the URL afterwards so a reload
290
+ // doesn't re-trigger the alert.
291
+ const [authErr, setAuthErr] = useState<string | null>(null);
292
+ useEffect(() => {
293
+ if (typeof window === "undefined") return;
294
+ const params = new URLSearchParams(window.location.search);
295
+ const err = params.get("auth_error");
296
+ if (err) {
297
+ setAuthErr(err);
298
+ params.delete("auth_error");
299
+ params.delete("logged_in");
300
+ const newQs = params.toString();
301
+ window.history.replaceState(
302
+ {},
303
+ "",
304
+ window.location.pathname + (newQs ? "?" + newQs : ""),
305
+ );
306
+ } else if (params.has("logged_in")) {
307
+ params.delete("logged_in");
308
+ const newQs = params.toString();
309
+ window.history.replaceState(
310
+ {},
311
+ "",
312
+ window.location.pathname + (newQs ? "?" + newQs : ""),
313
+ );
314
+ }
315
+ }, []);
316
 
317
  const leftWidth = leftCollapsed ? COLLAPSED_W : leftW;
318
  const rightWidth = rightCollapsed ? COLLAPSED_W : rightW;
 
325
  onOpenLeftDrawer={() => setLeftDrawerOpen(true)}
326
  onOpenRightDrawer={() => setRightDrawerOpen(true)}
327
  />
328
+ {authErr && (
329
+ <div
330
+ role="alert"
331
+ className="px-4 py-2 text-xs text-warn bg-warn/10 border-b border-warn/30 flex items-center justify-between"
332
+ >
333
+ <span>Sign-in didn't complete: {authErr}</span>
334
+ <button
335
+ type="button"
336
+ onClick={() => setAuthErr(null)}
337
+ className="text-warn hover:text-ink px-2"
338
+ aria-label="Dismiss"
339
+ >
340
+ ×
341
+ </button>
342
+ </div>
343
+ )}
344
  {isDesktop ? (
345
  /* ===================== Desktop ===================== */
346
  <div className="flex-1 flex min-h-0">
frontend/src/components/AuthButton.tsx ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useEffect, useRef, useState } from "react";
2
+ import { Cloud, LogIn, LogOut, User } from "lucide-react";
3
+ import { api } from "../lib/api";
4
+ import { useApp } from "../lib/store";
5
+ import { bumpPluginsRev } from "../lib/userId";
6
+
7
+ /**
8
+ * Compact user-state control in the TopBar:
9
+ * * Not logged in → "Sign in" button that kicks off the OAuth dance
10
+ * (full-page navigation, since OAuth needs a top-level redirect).
11
+ * * Logged in → avatar / name pill that toggles a dropdown with
12
+ * a logout button and a persistence-status hint.
13
+ *
14
+ * Hidden entirely when the server reports oauth_enabled=false (local
15
+ * dev without HF metadata).
16
+ */
17
+ export function AuthButton({ mobile = false }: { mobile?: boolean } = {}) {
18
+ const session = useApp((s) => s.session);
19
+ const authStatus = useApp((s) => s.authStatus);
20
+ const setSession = useApp((s) => s.setSession);
21
+ const setPlugins = useApp((s) => s.setPlugins);
22
+ const [menuOpen, setMenuOpen] = useState(false);
23
+ const wrapRef = useRef<HTMLDivElement | null>(null);
24
+
25
+ // Click-outside closes the dropdown.
26
+ useEffect(() => {
27
+ if (!menuOpen) return;
28
+ const onClick = (e: MouseEvent) => {
29
+ if (
30
+ wrapRef.current &&
31
+ !wrapRef.current.contains(e.target as Node)
32
+ ) {
33
+ setMenuOpen(false);
34
+ }
35
+ };
36
+ document.addEventListener("mousedown", onClick);
37
+ return () => document.removeEventListener("mousedown", onClick);
38
+ }, [menuOpen]);
39
+
40
+ // Don't render anything if this deployment can't do OAuth at all
41
+ // (e.g. local dev without README hf_oauth metadata).
42
+ if (!authStatus?.oauth_enabled) return null;
43
+
44
+ if (!session) {
45
+ return (
46
+ <a
47
+ href={api.authLoginUrl()}
48
+ className="btn-ghost"
49
+ title="Sign in with your Hugging Face account to keep plugins across devices and restarts"
50
+ aria-label="Sign in with Hugging Face"
51
+ >
52
+ <LogIn className="w-3.5 h-3.5" />
53
+ <span className="hidden sm:inline">Sign in</span>
54
+ </a>
55
+ );
56
+ }
57
+
58
+ const handleLogout = async () => {
59
+ try {
60
+ await api.authLogout();
61
+ } catch {
62
+ /* network errors are fine — we still clear local state */
63
+ }
64
+ setSession(null);
65
+ setPlugins([]); // Visible plugins were tied to the session; clear.
66
+ setMenuOpen(false);
67
+ bumpPluginsRev();
68
+ };
69
+
70
+ return (
71
+ <div className="relative" ref={wrapRef}>
72
+ <button
73
+ type="button"
74
+ onClick={() => setMenuOpen((v) => !v)}
75
+ className="flex items-center gap-1.5 px-2 py-1 rounded-md border border-edge bg-surface/60 text-mute hover:text-ink hover:border-accent/40 text-xs"
76
+ aria-haspopup="menu"
77
+ aria-expanded={menuOpen}
78
+ title={`Signed in as ${session.username}`}
79
+ >
80
+ {session.avatar_url ? (
81
+ <img
82
+ src={session.avatar_url}
83
+ alt=""
84
+ className="w-5 h-5 rounded-full bg-surface object-cover"
85
+ aria-hidden
86
+ />
87
+ ) : (
88
+ <User className="w-3.5 h-3.5" aria-hidden />
89
+ )}
90
+ {!mobile && (
91
+ <span className="text-ink font-medium max-w-[10ch] truncate">
92
+ {session.username}
93
+ </span>
94
+ )}
95
+ </button>
96
+ {menuOpen && (
97
+ <div
98
+ role="menu"
99
+ className="absolute right-0 mt-1 w-64 panel-alt shadow-lg z-50 text-xs"
100
+ >
101
+ <div className="px-3 py-2 border-b border-edge">
102
+ <div className="text-mute text-[10px] uppercase tracking-wider">
103
+ Signed in as
104
+ </div>
105
+ <div className="text-ink font-medium truncate">
106
+ {session.username}
107
+ </div>
108
+ </div>
109
+ <div className="px-3 py-2 border-b border-edge text-mute leading-relaxed space-y-2">
110
+ <div>
111
+ {session.persistence_enabled ? (
112
+ <>
113
+ <Cloud className="w-3 h-3 inline-block mr-1 -mt-0.5 text-accent2" />
114
+ Plugins you upload are saved to your private HF Datasets
115
+ repo (<span className="font-mono">{session.user_data_repo}</span>),
116
+ so they survive container restarts.
117
+ </>
118
+ ) : (
119
+ <span className="text-warn/80">
120
+ Persistence is not configured on this deployment, so
121
+ your plugins will still vanish on container restart.
122
+ </span>
123
+ )}
124
+ </div>
125
+ <div className="text-[10px] text-mute/70 leading-snug">
126
+ If you uploaded plugins before signing in, they're still
127
+ under your anonymous browser id — sign out to access them.
128
+ </div>
129
+ </div>
130
+ <button
131
+ type="button"
132
+ onClick={handleLogout}
133
+ className="w-full text-left px-3 py-2 hover:bg-surface text-ink flex items-center gap-2"
134
+ role="menuitem"
135
+ >
136
+ <LogOut className="w-3.5 h-3.5" aria-hidden />
137
+ Sign out
138
+ </button>
139
+ </div>
140
+ )}
141
+ </div>
142
+ );
143
+ }
frontend/src/components/TopBar.tsx CHANGED
@@ -12,6 +12,7 @@ import { PapersPopover } from "./PapersPopover";
12
  import { DevelopersPopover } from "./DevelopersPopover";
13
  import { SupportPopover } from "./SupportPopover";
14
  import { TipIcon } from "./TipIcon";
 
15
 
16
  /**
17
  * Top application bar.
@@ -166,6 +167,7 @@ export function TopBar({
166
  aria-hidden="true"
167
  />
168
  <SupportPopover />
 
169
  {mobile && onOpenRightDrawer && (
170
  <button
171
  type="button"
 
12
  import { DevelopersPopover } from "./DevelopersPopover";
13
  import { SupportPopover } from "./SupportPopover";
14
  import { TipIcon } from "./TipIcon";
15
+ import { AuthButton } from "./AuthButton";
16
 
17
  /**
18
  * Top application bar.
 
167
  aria-hidden="true"
168
  />
169
  <SupportPopover />
170
+ <AuthButton mobile={mobile} />
171
  {mobile && onOpenRightDrawer && (
172
  <button
173
  type="button"
frontend/src/components/UploadPluginModal.tsx CHANGED
@@ -49,6 +49,8 @@ export function UploadPluginModal({
49
  }) {
50
  const setPlugins = useApp((s) => s.setPlugins);
51
  const installedPlugins = useApp((s) => s.plugins);
 
 
52
  const [busy, setBusy] = useState(false);
53
  const [error, setError] = useState<string | null>(null);
54
  const [success, setSuccess] = useState<string | null>(null);
@@ -173,7 +175,9 @@ export function UploadPluginModal({
173
  setInstallingExample(ex.name);
174
  setBusy(true);
175
  try {
176
- const res = await fetch(api.exampleZipUrl(ex.name));
 
 
177
  if (!res.ok) {
178
  throw new Error(`Could not fetch example: HTTP ${res.status}`);
179
  }
@@ -367,8 +371,24 @@ export function UploadPluginModal({
367
  Upload your own block
368
  </div>
369
  <div className="text-[11px] text-mute">
370
- Add a custom source/algorithm/metric/sink to your catalog. Only
371
- you see it.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
372
  </div>
373
  </div>
374
  <button
 
49
  }) {
50
  const setPlugins = useApp((s) => s.setPlugins);
51
  const installedPlugins = useApp((s) => s.plugins);
52
+ const session = useApp((s) => s.session);
53
+ const authStatus = useApp((s) => s.authStatus);
54
  const [busy, setBusy] = useState(false);
55
  const [error, setError] = useState<string | null>(null);
56
  const [success, setSuccess] = useState<string | null>(null);
 
175
  setInstallingExample(ex.name);
176
  setBusy(true);
177
  try {
178
+ const res = await fetch(api.exampleZipUrl(ex.name), {
179
+ credentials: "include",
180
+ });
181
  if (!res.ok) {
182
  throw new Error(`Could not fetch example: HTTP ${res.status}`);
183
  }
 
371
  Upload your own block
372
  </div>
373
  <div className="text-[11px] text-mute">
374
+ {session?.persistence_enabled ? (
375
+ <>
376
+ Add a custom source/algorithm/metric/sink to{" "}
377
+ <span className="text-ink">your account</span>. Persisted
378
+ to your private HF Datasets repo — survives restarts and
379
+ follows you across devices.
380
+ </>
381
+ ) : (
382
+ <>
383
+ Add a custom source/algorithm/metric/sink to your
384
+ catalog. Only you see it.{" "}
385
+ {authStatus?.oauth_enabled && (
386
+ <span className="text-mute/80">
387
+ Sign in to keep plugins across restarts.
388
+ </span>
389
+ )}
390
+ </>
391
+ )}
392
  </div>
393
  </div>
394
  <button
frontend/src/lib/api.ts CHANGED
@@ -98,6 +98,24 @@ export interface RunRequest {
98
  user_id?: string;
99
  }
100
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
101
  /** Plugin manifest returned by the server. Mirrors PluginManifest in
102
  * backend/app/services/plugin_service.py + a `is_plugin: true` flag
103
  * the frontend uses to tell user-uploaded blocks apart from
@@ -134,43 +152,79 @@ async function json<T>(res: Response): Promise<T> {
134
  return res.json();
135
  }
136
 
 
 
 
 
 
 
 
 
137
  export const api = {
138
- health: () => fetch(`${BASE}/health`).then((r) => json<HealthResponse>(r)),
139
 
140
- backends: () => fetch(`${BASE}/backends`).then((r) => json<BackendInfo[]>(r)),
141
 
142
- listSamples: () => fetch(`${BASE}/circuits/samples`).then((r) => json<SampleCircuit[]>(r)),
 
143
 
144
  loadSample: (key: string) =>
145
- fetch(`${BASE}/circuits/samples/${encodeURIComponent(key)}`, { method: "POST" }).then(
146
- (r) => json<CircuitInfo>(r),
147
- ),
148
 
149
  upload: (file: File) => {
150
  const fd = new FormData();
151
  fd.append("file", file);
152
- return fetch(`${BASE}/circuits/upload`, { method: "POST", body: fd }).then(
153
  (r) => json<CircuitInfo>(r),
154
  );
155
  },
156
 
157
  getCircuit: (circuit_id: string) =>
158
- fetch(`${BASE}/circuits/${encodeURIComponent(circuit_id)}`).then(
159
  (r) => json<CircuitInfo>(r),
160
  ),
161
 
162
  run: (body: RunRequest) =>
163
- fetch(`${BASE}/workflow/run`, {
164
  method: "POST",
165
  headers: { "Content-Type": "application/json" },
166
  body: JSON.stringify(body),
167
  }).then((r) => json<RunResponse>(r)),
168
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
169
  // ---- plugin endpoints ----
170
 
171
- /** List the plugin manifests this browser has uploaded. */
 
 
 
172
  listPlugins: (userId: string) =>
173
- fetch(`${BASE}/plugins?user_id=${encodeURIComponent(userId)}`)
174
  .then((r) => json<PluginManifest[]>(r)),
175
 
176
  /** Upload a plugin .zip. Resolves to the parsed manifest on success;
@@ -178,7 +232,7 @@ export const api = {
178
  uploadPlugin: async (userId: string, file: File): Promise<PluginManifest> => {
179
  const fd = new FormData();
180
  fd.append("file", file);
181
- const res = await fetch(
182
  `${BASE}/plugins/upload?user_id=${encodeURIComponent(userId)}`,
183
  { method: "POST", body: fd },
184
  );
@@ -195,9 +249,9 @@ export const api = {
195
  return res.json();
196
  },
197
 
198
- /** Remove a plugin from this browser's namespace. */
199
  deletePlugin: (userId: string, kind: string) =>
200
- fetch(
201
  `${BASE}/plugins/${encodeURIComponent(kind)}?user_id=${encodeURIComponent(userId)}`,
202
  { method: "DELETE" },
203
  ).then((r) => json<{ removed: boolean; kind: string }>(r)),
@@ -206,7 +260,7 @@ export const api = {
206
  * the upload flow. The server reads each manifest.json inside the
207
  * zip and returns its label / family / tagline. */
208
  listExamplePlugins: () =>
209
- fetch(`${BASE}/plugins/examples`).then(
210
  (r) =>
211
  json<
212
  Array<{
@@ -238,7 +292,7 @@ export const api = {
238
  onError: (err: Error) => void,
239
  ) => {
240
  try {
241
- const res = await fetch(`${BASE}/workflow/run-stream`, {
242
  method: "POST",
243
  headers: { "Content-Type": "application/json" },
244
  body: JSON.stringify(body),
 
98
  user_id?: string;
99
  }
100
 
101
+ /** /api/auth/status — public capability probe. The frontend uses
102
+ * this to decide whether to render the Login button at all (e.g.
103
+ * hide it in local dev where OAuth isn't wired up). */
104
+ export interface AuthStatus {
105
+ oauth_enabled: boolean;
106
+ persistence_enabled: boolean;
107
+ provider: string;
108
+ }
109
+
110
+ /** /api/auth/me payload (when logged in). */
111
+ export interface SessionUser {
112
+ username: string;
113
+ avatar_url: string | null;
114
+ expires_at: number;
115
+ persistence_enabled: boolean;
116
+ user_data_repo: string | null;
117
+ }
118
+
119
  /** Plugin manifest returned by the server. Mirrors PluginManifest in
120
  * backend/app/services/plugin_service.py + a `is_plugin: true` flag
121
  * the frontend uses to tell user-uploaded blocks apart from
 
152
  return res.json();
153
  }
154
 
155
+ /** Shorthand for fetch with credentials always included so the session
156
+ * cookie travels on the dev Vite proxy (5173 → 7860 is technically
157
+ * cross-origin even with proxy_pass). In prod same-origin this flag
158
+ * is a no-op. */
159
+ function authedFetch(input: RequestInfo, init: RequestInit = {}): Promise<Response> {
160
+ return fetch(input, { credentials: "include", ...init });
161
+ }
162
+
163
  export const api = {
164
+ health: () => authedFetch(`${BASE}/health`).then((r) => json<HealthResponse>(r)),
165
 
166
+ backends: () => authedFetch(`${BASE}/backends`).then((r) => json<BackendInfo[]>(r)),
167
 
168
+ listSamples: () =>
169
+ authedFetch(`${BASE}/circuits/samples`).then((r) => json<SampleCircuit[]>(r)),
170
 
171
  loadSample: (key: string) =>
172
+ authedFetch(`${BASE}/circuits/samples/${encodeURIComponent(key)}`, {
173
+ method: "POST",
174
+ }).then((r) => json<CircuitInfo>(r)),
175
 
176
  upload: (file: File) => {
177
  const fd = new FormData();
178
  fd.append("file", file);
179
+ return authedFetch(`${BASE}/circuits/upload`, { method: "POST", body: fd }).then(
180
  (r) => json<CircuitInfo>(r),
181
  );
182
  },
183
 
184
  getCircuit: (circuit_id: string) =>
185
+ authedFetch(`${BASE}/circuits/${encodeURIComponent(circuit_id)}`).then(
186
  (r) => json<CircuitInfo>(r),
187
  ),
188
 
189
  run: (body: RunRequest) =>
190
+ authedFetch(`${BASE}/workflow/run`, {
191
  method: "POST",
192
  headers: { "Content-Type": "application/json" },
193
  body: JSON.stringify(body),
194
  }).then((r) => json<RunResponse>(r)),
195
 
196
+ // ---- auth ----
197
+
198
+ /** Public capability probe: is OAuth wired up on this deployment? */
199
+ authStatus: () =>
200
+ authedFetch(`${BASE}/auth/status`).then((r) => json<AuthStatus>(r)),
201
+
202
+ /** Current session or null if not logged in. */
203
+ authMe: async (): Promise<SessionUser | null> => {
204
+ const r = await authedFetch(`${BASE}/auth/me`);
205
+ if (r.status === 401) return null;
206
+ if (!r.ok) throw new Error(`HTTP ${r.status}`);
207
+ return r.json();
208
+ },
209
+
210
+ /** URL the browser should navigate to (full page navigation, NOT
211
+ * fetch) to start the OAuth dance. */
212
+ authLoginUrl: () => `${BASE}/auth/login`,
213
+
214
+ /** Clear the session cookie. */
215
+ authLogout: () =>
216
+ authedFetch(`${BASE}/auth/logout`, { method: "POST" }).then(
217
+ (r) => json<{ ok: boolean }>(r),
218
+ ),
219
+
220
  // ---- plugin endpoints ----
221
 
222
+ /** List the plugin manifests this browser/account has uploaded.
223
+ * The server prefers the session cookie's hf_<username> over the
224
+ * query-string user_id; we still send the anon UUID for the case
225
+ * where there's no session. */
226
  listPlugins: (userId: string) =>
227
+ authedFetch(`${BASE}/plugins?user_id=${encodeURIComponent(userId)}`)
228
  .then((r) => json<PluginManifest[]>(r)),
229
 
230
  /** Upload a plugin .zip. Resolves to the parsed manifest on success;
 
232
  uploadPlugin: async (userId: string, file: File): Promise<PluginManifest> => {
233
  const fd = new FormData();
234
  fd.append("file", file);
235
+ const res = await authedFetch(
236
  `${BASE}/plugins/upload?user_id=${encodeURIComponent(userId)}`,
237
  { method: "POST", body: fd },
238
  );
 
249
  return res.json();
250
  },
251
 
252
+ /** Remove a plugin from this browser/account's namespace. */
253
  deletePlugin: (userId: string, kind: string) =>
254
+ authedFetch(
255
  `${BASE}/plugins/${encodeURIComponent(kind)}?user_id=${encodeURIComponent(userId)}`,
256
  { method: "DELETE" },
257
  ).then((r) => json<{ removed: boolean; kind: string }>(r)),
 
260
  * the upload flow. The server reads each manifest.json inside the
261
  * zip and returns its label / family / tagline. */
262
  listExamplePlugins: () =>
263
+ authedFetch(`${BASE}/plugins/examples`).then(
264
  (r) =>
265
  json<
266
  Array<{
 
292
  onError: (err: Error) => void,
293
  ) => {
294
  try {
295
+ const res = await authedFetch(`${BASE}/workflow/run-stream`, {
296
  method: "POST",
297
  headers: { "Content-Type": "application/json" },
298
  body: JSON.stringify(body),
frontend/src/lib/store.ts CHANGED
@@ -3,10 +3,12 @@
3
 
4
  import { create } from "zustand";
5
  import type {
 
6
  CircuitInfo,
7
  HealthResponse,
8
  PluginManifest,
9
  RunResponse,
 
10
  } from "./api";
11
  import type { NodeKind } from "./nodeCatalog";
12
 
@@ -88,6 +90,23 @@ interface AppState {
88
  * built-in blocks. */
89
  plugins: PluginManifest[];
90
  setPlugins: (p: PluginManifest[]) => void;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91
  }
92
 
93
  export const useApp = create<AppState>((set) => ({
@@ -122,4 +141,8 @@ export const useApp = create<AppState>((set) => ({
122
  set((s) => ({ hintExpandLeftPane: s.hintExpandLeftPane + 1 })),
123
  plugins: [],
124
  setPlugins: (p) => set({ plugins: p }),
 
 
 
 
125
  }));
 
3
 
4
  import { create } from "zustand";
5
  import type {
6
+ AuthStatus,
7
  CircuitInfo,
8
  HealthResponse,
9
  PluginManifest,
10
  RunResponse,
11
+ SessionUser,
12
  } from "./api";
13
  import type { NodeKind } from "./nodeCatalog";
14
 
 
90
  * built-in blocks. */
91
  plugins: PluginManifest[];
92
  setPlugins: (p: PluginManifest[]) => void;
93
+
94
+ /**
95
+ * OAuth + persistence capability of this deployment. Probed once at
96
+ * boot via /api/auth/status. When `oauth_enabled` is false (e.g.
97
+ * local dev without HF_OAUTH metadata), the TopBar hides the Login
98
+ * button entirely.
99
+ */
100
+ authStatus: AuthStatus | null;
101
+ setAuthStatus: (s: AuthStatus | null) => void;
102
+
103
+ /**
104
+ * The current signed-in HF user, or null when running as guest.
105
+ * Drives the avatar/dropdown in TopBar and propagates to userId.ts
106
+ * so plugin requests use the hf_<username> namespace.
107
+ */
108
+ session: SessionUser | null;
109
+ setSession: (u: SessionUser | null) => void;
110
  }
111
 
112
  export const useApp = create<AppState>((set) => ({
 
141
  set((s) => ({ hintExpandLeftPane: s.hintExpandLeftPane + 1 })),
142
  plugins: [],
143
  setPlugins: (p) => set({ plugins: p }),
144
+ authStatus: null,
145
+ setAuthStatus: (s) => set({ authStatus: s }),
146
+ session: null,
147
+ setSession: (u) => set({ session: u }),
148
  }));
frontend/src/lib/userId.ts CHANGED
@@ -1,10 +1,28 @@
1
- // Anonymous browser-scoped identifier. Used as a namespace key for
2
- // per-user plugin storage on the server. Generated on first visit
3
- // and persisted in localStorage; not tied to any actual user account.
 
 
 
 
 
 
 
 
 
 
 
 
4
 
5
  const LS_KEY = "quda.userId";
6
 
7
- /** Read the current user id, or mint one on first visit. */
 
 
 
 
 
 
8
  export function getUserId(): string {
9
  try {
10
  const existing = localStorage.getItem(LS_KEY);
@@ -23,6 +41,16 @@ export function getUserId(): string {
23
  return fresh;
24
  }
25
 
 
 
 
 
 
 
 
 
 
 
26
  /** Bump a localStorage counter so other tabs' `storage` listeners fire.
27
  * Plugin lists themselves live in Zustand (in-memory per tab); this
28
  * counter is the only thing that crosses the localStorage boundary
 
1
+ // Browser/account identifier used as the user_id query parameter on
2
+ // plugin API calls. Two flavours:
3
+ //
4
+ // * For a guest (no HF session): a per-browser anonymous UUID
5
+ // persisted in localStorage. Plugins stored under this id live in
6
+ // /tmp on the Space (volatile, per-browser).
7
+ // * For a signed-in HF user: never read by getUserId() directly —
8
+ // the server overrides the query value with the session-derived
9
+ // hf_<username> whenever it sees a session cookie. We still send
10
+ // the anon UUID as a fallback so the route works without cookies.
11
+ //
12
+ // In other words: the frontend always sends the anon UUID. The server
13
+ // decides which namespace to operate on (session > query).
14
+
15
+ import { useApp } from "./store";
16
 
17
  const LS_KEY = "quda.userId";
18
 
19
+ /** Read the current anonymous user id, or mint one on first visit.
20
+ *
21
+ * Even when the user is signed in, we still surface the anon id —
22
+ * the server treats it as the fallback namespace for unauthenticated
23
+ * routes. The actual logged-in namespace is server-derived, not
24
+ * client-controlled (anti-spoofing).
25
+ */
26
  export function getUserId(): string {
27
  try {
28
  const existing = localStorage.getItem(LS_KEY);
 
41
  return fresh;
42
  }
43
 
44
+ /** Convenience: the namespace label the server is currently treating
45
+ * the caller as. Returns "hf_<username>" when signed in, the anon
46
+ * UUID otherwise. Used only for display (e.g. tooltips); the actual
47
+ * authoritative resolution happens on the server. */
48
+ export function displayUserId(): string {
49
+ const session = useApp.getState().session;
50
+ if (session?.username) return `hf_${session.username}`;
51
+ return getUserId();
52
+ }
53
+
54
  /** Bump a localStorage counter so other tabs' `storage` listeners fire.
55
  * Plugin lists themselves live in Zustand (in-memory per tab); this
56
  * counter is the only thing that crosses the localStorage boundary