"""Member Dashboard — read-only usage view + API-key management. Security model: - Authentication is done by Cloudron's proxyAuth wall (SSO). Cloudron injects the authenticated user's identity via the X-Remote-User header (username). - This app holds NO privileged credentials. It calls the member portal's broker endpoints, authenticated with a shared BROKER_SECRET, and scopes every request to the logged-in member. Environment (all provided by Cloudron env vars): PORTAL_BASE — base URL of the member portal (e.g. https://portal.inference.coop) BROKER_SECRET — shared secret for the portal's broker endpoints CREDIT_PACK_URL — where the "Buy a credit pack" link sends members (defaults to the Open Collective contribute page, which is what actually credits a member). Configuration, not code, because the destination can move (a future pack page) without a deploy here. """ import os import logging from pathlib import Path import re import httpx from fastapi import FastAPI, Request, HTTPException from fastapi.responses import HTMLResponse, RedirectResponse, JSONResponse from app import oidc # The oidc module is SHARED (byte-identical copy of the canonical # ops-docs: scripts/shared/oidc_client.py — see tests/test_oidc_sync.py); # this app's identity (logger name, session cookie, session salt) is set # here. The cookie name and salt are the app's historical values, so # existing sessions survive the consolidation. oidc.configure("member-dashboard", "member_oidc_session", "member-dashboard-oidc-session") logging.basicConfig(level=logging.INFO) logger = logging.getLogger("member-dashboard") PORTAL_BASE = os.environ.get("PORTAL_BASE", "").rstrip("/") BROKER_SECRET = os.environ.get("BROKER_SECRET", "") # Where the always-visible "Buy a credit pack" link points. Configuration, not a # constant in the template: the co-op sets this per app (same convention the # portal uses) so the destination changes in one place. The Open Collective # contribution page is the default because that is what actually credits a # member today (the webhook settles contributions into credits). DEFAULT_CREDIT_PACK_URL = "https://opencollective.com/inference-cooperative/contribute" CREDIT_PACK_URL = (os.environ.get("CREDIT_PACK_URL") or "").strip() or DEFAULT_CREDIT_PACK_URL # Where a GUEST account's "Become a member" button points (the contribution # page — what actually starts a membership). Deliberately independent of # CREDIT_PACK_URL: a guest needs a membership, not a credit pack, even if the # credit-pack link is ever repointed at a pack page. BECOME_MEMBER_URL = "https://opencollective.com/inference-cooperative/contribute" app = FastAPI() # --------------------------------------------------------------------------- # Identity — Cloudron OIDC session cookie (username). proxyAuth header is the # legacy fallback during the transition. # --------------------------------------------------------------------------- def get_user_identity(request: Request) -> str: """Return the logged-in user's identity (Cloudron username). Reads the validated OIDC session cookie. No header fallback — the app no longer trusts a client-supplied identity header (that path existed only during the proxyAuth → OIDC transition and is now removed). """ if not oidc.is_oidc_configured(): return "" token = request.cookies.get(oidc.SESSION_COOKIE) if not token: return "" return oidc.read_session(token) or "" # --------------------------------------------------------------------------- # Broker calls (to the member portal) # --------------------------------------------------------------------------- def broker_headers(identity: str) -> dict: return {"X-Broker-Secret": BROKER_SECRET, "X-Member-User": identity} async def broker_get(identity: str, path: str) -> dict: async with httpx.AsyncClient(timeout=20.0) as client: r = await client.get(f"{PORTAL_BASE}{path}", headers=broker_headers(identity)) if r.status_code == 401: raise HTTPException(500, "Portal rejected broker credentials") if r.status_code == 403: raise HTTPException(403, "Not an active member") if r.status_code != 200: raise HTTPException(502, f"Portal error {r.status_code}") return r.json() async def broker_post(identity: str, path: str, payload: dict | None = None) -> dict: async with httpx.AsyncClient(timeout=20.0) as client: r = await client.post(f"{PORTAL_BASE}{path}", headers=broker_headers(identity), json=payload or {}) if r.status_code in (401, 403): raise HTTPException(r.status_code, r.text) if r.status_code not in (200, 201): raise HTTPException(502, f"Portal error {r.status_code}: {r.text}") return r.json() async def broker_delete(identity: str, path: str) -> dict: async with httpx.AsyncClient(timeout=20.0) as client: r = await client.delete(f"{PORTAL_BASE}{path}", headers=broker_headers(identity)) if r.status_code in (401, 403): raise HTTPException(r.status_code, r.text) if r.status_code not in (200, 204): raise HTTPException(502, f"Portal error {r.status_code}") return r.json() if r.content else {} async def broker_call(identity: str, method: str, path: str, payload: dict | None = None) -> tuple[int, dict]: """Portal call that returns the portal's OWN status + payload. The guest path's 429 refusals are member-facing text ("one guest per member per month") — transport-error wrapping (502) would bury them, so the guest routes surface the portal's status and detail verbatim. """ async with httpx.AsyncClient(timeout=20.0) as client: r = await client.request(method, f"{PORTAL_BASE}{path}", headers=broker_headers(identity), json=payload) try: data = r.json() except Exception: data = {"error": r.text or "portal returned no body"} if r.status_code == 401: # Broker credentials broken — an app fault, not a member condition. data = {"error": "The portal rejected this dashboard's credentials"} return r.status_code, data # --------------------------------------------------------------------------- # Routes # --------------------------------------------------------------------------- @app.get("/healthz") async def healthz(): return {"status": "ok"} @app.get("/") async def index(request: Request): identity = get_user_identity(request) if not identity: if oidc.is_oidc_configured(): return RedirectResponse("/auth/openid/login", status_code=302) return HTMLResponse( "
Please log in via the dashboard login.
", status_code=401, ) return HTMLResponse(render_page(identity)) @app.get("/api/usage") async def api_usage(request: Request): identity = get_user_identity(request) if not identity: return JSONResponse({"error": "unauthenticated"}, status_code=401) try: data = await broker_get(identity, "/broker/usage") keys = await broker_get(identity, "/broker/keys") data["keys"] = keys.get("keys", []) # Co-op-wide model popularity (aggregate, anonymized) for the leaderboard. try: board = await broker_get(identity, "/broker/model-leaderboard?days=30") data["coop_models"] = board.get("models", []) except HTTPException: data["coop_models"] = [] # best-effort; never block the main view return data except HTTPException as e: return JSONResponse({"error": e.detail}, status_code=e.status_code) @app.get("/api/metrics") async def api_metrics(request: Request): """Co-op metrics over time, for the Co-op usage view. Aggregate and non-personal (co-op size, requests served, spend), the same class as the model leaderboard. Fetched at the widest range so the metric and period toggles re-render client-side without refetching. """ identity = get_user_identity(request) if not identity: return JSONResponse({"error": "unauthenticated"}, status_code=401) try: return await broker_get(identity, "/broker/metrics?days=730") except HTTPException as e: return JSONResponse({"error": e.detail}, status_code=e.status_code) @app.post("/api/keys") async def api_create_key(request: Request): identity = get_user_identity(request) if not identity: return JSONResponse({"error": "unauthenticated"}, status_code=401) body = await request.json() name = (body.get("name") or "").strip() if not re.fullmatch(r"[A-Za-z0-9._-]{1,64}", name): return JSONResponse({"error": "Invalid key name"}, status_code=400) try: return await broker_post(identity, "/broker/keys", {"name": name}) except HTTPException as e: return JSONResponse({"error": e.detail}, status_code=e.status_code) @app.delete("/api/keys/{name}") async def api_revoke_key(name: str, request: Request): identity = get_user_identity(request) if not identity: return JSONResponse({"error": "unauthenticated"}, status_code=401) try: return await broker_delete(identity, f"/broker/keys/{name}") except HTTPException as e: return JSONResponse({"error": e.detail}, status_code=e.status_code) @app.get("/api/matrix-mxid") async def api_get_matrix_mxid(request: Request): identity = get_user_identity(request) if not identity: return JSONResponse({"error": "unauthenticated"}, status_code=401) try: return await broker_get(identity, "/broker/matrix-mxid") except HTTPException as e: return JSONResponse({"error": e.detail}, status_code=e.status_code) @app.post("/api/matrix-mxid") async def api_set_matrix_mxid(request: Request): identity = get_user_identity(request) if not identity: return JSONResponse({"error": "unauthenticated"}, status_code=401) body = await request.json() mxid = (body.get("matrix_mxid") or "").strip() try: return await broker_post(identity, "/broker/matrix-mxid", {"matrix_mxid": mxid}) except HTTPException as e: return JSONResponse({"error": e.detail}, status_code=e.status_code) @app.get("/api/guest-status") async def api_guest_status(request: Request): """What became of the caller's guest account (guest view). Loaded when the usage view refuses a GUEST (access ended): the portal answers for ended guest accounts so the dashboard can say plainly that access ended, the data is kept, and a membership is still available. Members get guest: false — the caller falls back to the usage error. """ identity = get_user_identity(request) if not identity: return JSONResponse({"error": "unauthenticated"}, status_code=401) try: return await broker_get(identity, "/broker/guest-status") except HTTPException as e: return JSONResponse({"error": e.detail}, status_code=e.status_code) @app.post("/api/cancel-guest") async def api_cancel_guest(request: Request): """End the caller's own guest account (self-service cancel, guest view). One hop to the portal broker, which holds the actual semantics: access ends immediately, unspent credit returns to the co-op, the ledger keeps the trail, and a repeat call is a no-op. Guest accounts only — the portal refuses a paying member with 403. """ identity = get_user_identity(request) if not identity: return JSONResponse({"error": "unauthenticated"}, status_code=401) try: return await broker_post(identity, "/broker/cancel-guest") except HTTPException as e: return JSONResponse({"error": e.detail}, status_code=e.status_code) @app.get("/api/guests") async def api_guests(request: Request): """The caller's guest-access view: invitation allowance + their trail. One hop to the portal broker's GET /broker/guests: whether this member can send a guest invitation now (the rolling one-per-30-days rule, counted from the guests ledger) and every invitation they have made, with its status. The portal's refusal statuses pass through as-is. """ identity = get_user_identity(request) if not identity: return JSONResponse({"error": "unauthenticated"}, status_code=401) status, data = await broker_call(identity, "GET", "/broker/guests") return JSONResponse(data, status_code=status) @app.post("/api/guests") async def api_guest_invite(request: Request): """Invite a guest, from the member dashboard (self-serve guest access). Body: {"email": "Incomplete OIDC callback.
", status_code=400) if state != expected_state: return HTMLResponse("State mismatch (possible CSRF).
", status_code=400) try: identity = await oidc.exchange_code(code, request.headers.get("host", ""), nonce) except ValueError as e: logger.warning("OIDC login failed: %s", e) return HTMLResponse("Could not complete sign-in.
", status_code=400) session = oidc.write_session(identity) resp = RedirectResponse("/", status_code=302) resp.set_cookie(oidc.SESSION_COOKIE, session, max_age=oidc.SESSION_MAX_AGE, httponly=True, samesite="lax") resp.delete_cookie("oidc_state") resp.delete_cookie("oidc_nonce") return resp @app.get("/logout") async def logout(request: Request): """Log out: clear our session, then show an explicit logged-out page. Cloudron's OIDC provider removed its RP-initiated logout endpoint (forum: "no app supports this properly"), so we cannot end the SSO session programmatically. Redirecting to / would silently re-authenticate through the still-valid SSO cookie — the "logout does nothing" bug. Instead we clear our cookies and show a page with a manual link to sign out of Cloudron SSO (my.inference.coop/logout) for a full sign-out. """ html = """Your dashboard session has been cleared.
Note: you may still be signed in to Inference Cooperative SSO (chat, portal, forum share that sign-in). To fully sign out everywhere, log out of your Cloudron account too.