From 29b62363c6dd63fa5db7637bae7055feefebd55d Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 4 Oct 2026 02:41:21 +0000 Subject: [PATCH 1/3] feat(setup): apps and AI assistants as an optional setup wizard step The setup wizard gets an Apps and AI step: whether apps and AI assistants (MCP clients) may sign people in with their Lens account through OAuth, how long their tokens last, and the MCP server's address to copy. Skipping it keeps OAuth on, as before. New setting tokens.oauth_enabled (on by default; Settings -> API keys). Off, discovery answers 404, apps can't register, ask or renew, 401s stop naming resource metadata and lo_ tokens don't work; grants are kept, so turning it back on restores them, and people can still revoke them. API: PUT /api/v1/setup/oauth; GET /api/v1/setup reports oauth. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01HFiySoDnqG9PX5c3WLPz5C --- CHANGELOG.md | 5 + docs/authentication.md | 3 + docs/configuration.md | 8 +- fastapi_backend/app/api/deps.py | 3 +- fastapi_backend/app/api/v1/routes/oauth.py | 33 ++++- fastapi_backend/app/api/v1/routes/setup.py | 27 +++- fastapi_backend/app/domain/oauth.py | 5 + fastapi_backend/app/domain/settings.py | 4 + fastapi_backend/app/domain/setup.py | 16 +++ fastapi_backend/app/domain/store.py | 13 +- fastapi_backend/app/schemas/setup.py | 15 ++ fastapi_backend/tests/api/test_oauth.py | 26 ++++ fastapi_backend/tests/api/test_setup.py | 11 ++ .../__tests__/setupWizard.test.tsx | 33 ++++- nextjs-frontend/app/openapi-client/index.ts | 7 + nextjs-frontend/app/openapi-client/sdk.gen.ts | 25 +++- .../app/openapi-client/types.gen.ts | 63 +++++++++ .../components/settings/bodies.tsx | 1 + nextjs-frontend/components/settings/model.ts | 7 + .../components/setup/setup-wizard.tsx | 128 +++++++++++++++++- nextjs-frontend/openapi.json | 108 ++++++++++++++- 21 files changed, 520 insertions(+), 21 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 53ff8da9b..f3106afeb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,11 @@ The backend (`fastapi_backend`) and the frontend (`nextjs-frontend`) are version ## Unreleased +- **Apps and AI assistants in the setup wizard.** A new optional step, Apps and AI, asks whether apps and AI + assistants (Claude, ChatGPT, Cursor and other MCP clients) may sign people in with their Lens account, how long + their tokens last, and shows the MCP server's address to add to an assistant. Skipping it keeps OAuth on, as + before. Admins can also turn it off in Settings → API keys (`tokens.oauth_enabled`): discovery and registration go + away and apps' tokens stop working until it is back on. API: `PUT /api/v1/setup/oauth`. - **Hardening.** Sign-in throttles count each visitor behind the web app (Docker) instead of one bucket for everyone, so one person's wrong tries can't lock others out and nobody gets unlimited tries. The web app's pages send nosniff, referrer, permissions and frame policies, and HSTS when reached through Cloudflare. The containers run with diff --git a/docs/authentication.md b/docs/authentication.md index 47c2a7d18..a9928f4ea 100644 --- a/docs/authentication.md +++ b/docs/authentication.md @@ -160,6 +160,9 @@ app ──► POST /api/v1/oauth/token grant_type=refresh_token before th what they can't see, the app can't. An admin's app has the admin's roles in every namespace but not the administration (people, settings, the audit log, everyone's keys): that stays with admins signed in or with their own API key. +* **On unless turned off**: admins switch it in Settings → API keys or the setup wizard's Apps and AI step + (`tokens.oauth_enabled`). Off, `/.well-known/…` answers 404, apps can't register, ask or renew, and their tokens + stop working; the access people gave comes back when it is turned on again. * **Lifetimes** are the admins' ([Configuration](configuration.md#api-keys)): the access token lasts `tokens.oauth_access_minutes` (60), and the app stays signed in for `tokens.oauth_refresh_days` (30) after it last renewed, at most `tokens.max_days`. diff --git a/docs/configuration.md b/docs/configuration.md index 00877b7be..6ffb6cb92 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -52,10 +52,15 @@ A fresh install (no accounts when the API first starts) walks its first admin th with a test. 4. **Storage**: where data lives (shown; set in archive.yaml and `SURREAL_URL`), the largest upload, and optionally a folder inside `sources.local_roots` to watch. +5. **Apps and AI**: whether apps and AI assistants (Claude, ChatGPT, Cursor and other MCP clients) may sign people in + with their Lens account ([OAuth](authentication.md#oauth)), on unless turned off, how long their tokens last, and + the MCP server's address to add to an assistant. +6. **Telemetry**: off unless chosen ([Telemetry](telemetry.md)). Every step can be skipped, and the whole wizard too; all of it stays in Settings. Values from the environment win and show locked. Installs that already had accounts never see the wizard. The API side is `GET /api/v1/setup`, -`POST /api/v1/setup/namespace`, `PUT /api/v1/setup/llm`, `PUT /api/v1/setup/storage` and `POST /api/v1/setup/finish` +`POST /api/v1/setup/namespace`, `PUT /api/v1/setup/llm`, `PUT /api/v1/setup/storage`, `PUT /api/v1/setup/oauth`, +`PUT /api/v1/setup/telemetry` and `POST /api/v1/setup/finish` (admins); `GET /api/v1/auth/status` says whether it is still pending (`wizard_pending`). ## Frontend environment @@ -260,6 +265,7 @@ Settings → API keys: | `tokens.default_days` | 90 | how long a new key lasts when its maker doesn't say, 1–3650 days (at most `tokens.max_days`) | | `tokens.max_days` | 365 | the longest a key may last, 1–3650 days | | `tokens.never_expire` | false | whether keys may be made that never expire | +| `tokens.oauth_enabled` | true | whether apps and AI assistants may sign people in with their Lens account ([OAuth](authentication.md#oauth)); off, discovery and registration are gone and apps' tokens stop working until it is back on, while people can still see and revoke the apps they allowed | | `tokens.oauth_access_minutes` | 60 | how long the access token of an app someone signed in to lasts ([OAuth](authentication.md#oauth)), 5–1440 minutes; the app renews it by itself | | `tokens.oauth_refresh_days` | 30 | how long such an app stays signed in after it last renewed its access, 1–3650 days (at most `tokens.max_days`) | diff --git a/fastapi_backend/app/api/deps.py b/fastapi_backend/app/api/deps.py index 7947713f9..737e59ca6 100644 --- a/fastapi_backend/app/api/deps.py +++ b/fastapi_backend/app/api/deps.py @@ -76,7 +76,8 @@ def _principal(request: Request, db: DB) -> Principal | None: u["id"], u["email"], u.get("name"), bool(u.get("admin")), "token", "write" if u.get("scope") == "write" else "read" ) elif raw.startswith("lo_"): - u = oauth.token_account(db, raw) + # with OAuth turned off, apps' tokens stop working at once (their grants stay, so turning it back on restores them) + u = oauth.token_account(db, raw) if oauth.enabled(request.app.state.settings.current()) else None if u: p = Principal(u["id"], u["email"], u.get("name"), bool(u.get("admin")), "oauth", u["scope"], resource=u.get("resource")) elif raw: diff --git a/fastapi_backend/app/api/v1/routes/oauth.py b/fastapi_backend/app/api/v1/routes/oauth.py index 6267dff36..dee2c241a 100644 --- a/fastapi_backend/app/api/v1/routes/oauth.py +++ b/fastapi_backend/app/api/v1/routes/oauth.py @@ -45,6 +45,15 @@ MCP, MCP_SCOPE = "/mcp", "read" # the MCP server (app/api/mcp.py), and the scope its tools need +OFF = "apps can't sign in to this server; an admin turns it on in Settings → API keys" + + +def _on(request: Request) -> bool: + """Whether apps and MCP clients may sign people in (tokens.oauth_enabled). Off, discovery is gone, apps can't + register, ask or renew, and their tokens don't work; people still see and revoke the apps they allowed.""" + return oauth.enabled(request.app.state.settings.current()) + + def _first(value: str | None) -> str: return (value or "").split(",")[0].strip() @@ -107,7 +116,7 @@ def _client_credentials(request: Request, client_id: str | None, client_secret: async def bearer_challenge(request: Request, exc: StarletteHTTPException) -> Response: """401s that ask for a bearer token say where to find out how to get one (RFC 9728 §5.1), as MCP clients expect.""" - if exc.status_code == 401 and (exc.headers or {}).get("WWW-Authenticate") == "Bearer": + if exc.status_code == 401 and (exc.headers or {}).get("WWW-Authenticate") == "Bearer" and _on(request): # the MCP server is a resource of its own (/mcp), so clients that check what the metadata names see their URL; # its tools only read, so that's all it asks for mcp = request.url.path == MCP @@ -121,6 +130,8 @@ async def bearer_challenge(request: Request, exc: StarletteHTTPException) -> Res @well_known.get("/.well-known/oauth-authorization-server/{rest:path}") def authorization_server(request: Request) -> JSONResponse: """Authorization server metadata (RFC 8414).""" + if not _on(request): + raise HTTPException(404, "not found") base = public_base(request) doc = { "issuer": base, @@ -143,7 +154,7 @@ def authorization_server(request: Request) -> JSONResponse: def protected_resource(request: Request, rest: str = "") -> JSONResponse: """Protected resource metadata (RFC 9728): who issues the tokens this server takes.""" base = public_base(request) - if rest and not RESOURCE.fullmatch(rest): + if not _on(request) or (rest and not RESOURCE.fullmatch(rest)): raise HTTPException(404, "not found") doc = { "resource": f"{base}/{rest}" if rest else base, @@ -159,6 +170,8 @@ def protected_resource(request: Request, rest: str = "") -> JSONResponse: def register(body: ClientRegistration, request: Request, db: Db) -> Any: """An app registers itself (RFC 7591), without signing in: it gets a `client_id`, and a `client_secret` if it asked for one. It can do nothing until someone gives it access. Audited as `oauth.client.register`.""" + if not _on(request): + return _oauth_error(oauth.OAuthError("access_denied", OFF, 403)) key = f"oauth-register|{visitor_address(request) or client_ip(request)}" if auth.throttled(key): raise HTTPException(429, "too many apps registered from this address; try again in a few minutes") @@ -185,13 +198,16 @@ def register(body: ClientRegistration, request: Request, db: Db) -> Any: ) -def _person(user: CurrentUser) -> None: +def _person(user: CurrentUser, request: Request | None = None) -> None: + if request is not None and not _on(request): + raise HTTPException(403, OFF) if user.via != "access": raise HTTPException(403, "sign in to give an app access; API tokens and apps can't") @router.get("/authorize") def consent( + request: Request, user: CurrentUser, db: Db, client_id: str = Query(), @@ -202,8 +218,9 @@ def consent( scope: str | None = Query(None), ) -> Consent: """What the consent page shows for an app's request: the app, where it takes you back to and what it asks for. - 400 when the request can't be answered (an unknown app, an address it didn't register, no PKCE challenge).""" - _person(user) + 400 when the request can't be answered (an unknown app, an address it didn't register, no PKCE challenge); 403 + when apps can't sign in to this server.""" + _person(user, request) with domain_errors(): return Consent( **oauth.authorization(db, user.id, client_id, redirect_uri, response_type, code_challenge, code_challenge_method, scope) @@ -211,11 +228,11 @@ def consent( @router.post("/authorize") -def answer(body: ConsentAnswer, user: CurrentUser, db: Db) -> ConsentResult: +def answer(body: ConsentAnswer, request: Request, user: CurrentUser, db: Db) -> ConsentResult: """Your answer to an app's request. Yes gives it a one-time code (five minutes) at its redirect address, which it swaps for tokens that act as you, with your roles; no sends it `error=access_denied`. Audited as `oauth.grant`.""" - _person(user) + _person(user, request) with domain_errors(): info = oauth.authorization( db, user.id, body.client_id, body.redirect_uri, body.response_type, body.code_challenge, body.code_challenge_method, body.scope @@ -243,6 +260,8 @@ def token( """The app swaps its code (`grant_type=authorization_code`, with `code_verifier` and the same `redirect_uri`) or its refresh token (`grant_type=refresh_token`) for an access token and a new refresh token. Form-encoded, as OAuth has it; errors are `{error, error_description}`.""" + if not _on(request): + return _oauth_error(oauth.OAuthError("access_denied", OFF, 403)) try: cid, secret = _client_credentials(request, client_id, client_secret) if grant_type == "authorization_code": diff --git a/fastapi_backend/app/api/v1/routes/setup.py b/fastapi_backend/app/api/v1/routes/setup.py index 58d8d2ffe..64009201f 100644 --- a/fastapi_backend/app/api/v1/routes/setup.py +++ b/fastapi_backend/app/api/v1/routes/setup.py @@ -1,4 +1,5 @@ -"""The first-run setup wizard (admins): the first namespace, the model provider, storage and telemetry, then finishing it. +"""The first-run setup wizard (admins): the first namespace, the model provider, storage, apps signing in (OAuth) and +telemetry, then finishing it. The first admin is created before this, with the setup code (POST /auth/setup) or from the environment. Fields the environment sets are left out of every save and reported as locked (domain/setup.py). @@ -10,7 +11,17 @@ from app.api.deps import AdminReader, AdminWriter, Db from app.domain import auth, setup -from app.schemas.setup import LocalModelServer, SetupFinish, SetupLlm, SetupNamespace, SetupSaved, SetupStorage, SetupTelemetry, SetupView +from app.schemas.setup import ( + LocalModelServer, + SetupFinish, + SetupLlm, + SetupNamespace, + SetupOAuth, + SetupSaved, + SetupStorage, + SetupTelemetry, + SetupView, +) router = APIRouter(prefix="/setup", tags=["setup"]) @@ -85,6 +96,18 @@ def save_telemetry(body: SetupTelemetry, user: AdminWriter, request: Request, db return SetupSaved(saved=saved) +@router.put("/oauth") +def save_oauth(body: SetupOAuth, user: AdminWriter, request: Request, db: Db) -> SetupSaved: + """Let apps and AI assistants (MCP clients such as Claude or Cursor) sign people in with their Lens account, or + not, and how long their tokens last (docs/authentication.md#oauth). On unless turned off.""" + try: + saved = setup.save_oauth(db, request.app.state.archive.base, body.enabled, body.access_minutes, body.refresh_days, user.email) + except ValueError as e: + raise HTTPException(400, str(e)) from None + auth.audit(db, user.as_audit(), "settings.save", "tokens", saved) + return SetupSaved(saved=saved) + + @router.post("/finish") def finish(body: SetupFinish, user: AdminWriter, db: Db) -> SetupSaved: """Finish (or skip) the wizard; the web app stops showing it. Everything stays changeable in Settings.""" diff --git a/fastapi_backend/app/domain/oauth.py b/fastapi_backend/app/domain/oauth.py index 40f76ffa6..fbdbcfe28 100644 --- a/fastapi_backend/app/domain/oauth.py +++ b/fastapi_backend/app/domain/oauth.py @@ -49,6 +49,11 @@ def _later(seconds): return (dt.datetime.now(dt.timezone.utc) + dt.timedelta(seconds=seconds)).isoformat(timespec="seconds") +def enabled(cfg): + """Whether apps and MCP clients may sign people in here (tokens.oauth_enabled; Settings → API keys, or setup).""" + return bool({**store.DEFAULTS["tokens"], **(cfg.get("tokens") or {})}["oauth_enabled"]) + + def lifetimes(cfg): """How long an app's tokens last (tokens settings): {access_minutes, refresh_days}.""" t = {**store.DEFAULTS["tokens"], **(cfg.get("tokens") or {})} diff --git a/fastapi_backend/app/domain/settings.py b/fastapi_backend/app/domain/settings.py index 754cc53bc..ea03f980c 100644 --- a/fastapi_backend/app/domain/settings.py +++ b/fastapi_backend/app/domain/settings.py @@ -392,6 +392,10 @@ def _check(section, key, value, default): if not (isinstance(value, int) and not isinstance(value, bool) and lo <= value <= hi): raise ValueError(f"tokens.oauth_access_minutes is a whole number of minutes from {lo} to {hi}") return value + if (section, key) == ("tokens", "oauth_enabled"): + if not isinstance(value, bool): + raise ValueError("tokens.oauth_enabled is true or false") + return value if section == "tokens" and key != "never_expire": lo, hi = TOKEN_DAYS if not (isinstance(value, int) and not isinstance(value, bool) and lo <= value <= hi): diff --git a/fastapi_backend/app/domain/setup.py b/fastapi_backend/app/domain/setup.py index 4ea69c400..dbdf463a1 100644 --- a/fastapi_backend/app/domain/setup.py +++ b/fastapi_backend/app/domain/setup.py @@ -123,6 +123,11 @@ def view(db, cfg): "endpoint": shown["telemetry"].get("endpoint"), "locked": [k for k in settings.locked("telemetry") if k in ("enabled", "endpoint")], }, + "oauth": { + "enabled": bool(shown["tokens"].get("oauth_enabled", True)), + "access_minutes": int(shown["tokens"]["oauth_access_minutes"]), + "refresh_days": int(shown["tokens"]["oauth_refresh_days"]), + }, } @@ -158,6 +163,17 @@ def save_telemetry(db, cfg, enabled, endpoint, user=None): return sorted(keep) +def save_oauth(db, cfg, enabled, access_minutes=None, refresh_days=None, user=None): + """Whether apps and MCP clients may sign people in through OAuth, and how long their tokens last.""" + values = {"oauth_enabled": bool(enabled)} + if access_minutes is not None: + values["oauth_access_minutes"] = access_minutes + if refresh_days is not None: + values["oauth_refresh_days"] = refresh_days + settings.save(db, cfg, "tokens", values, user) + return sorted(values) + + def save_storage(db, cfg, max_upload_mb=None, folder=None, namespace=None, user=None): """The upload limit, and optionally a folder on this machine (inside sources.local_roots) watched into a namespace. Returns the watch's id, if one was made.""" diff --git a/fastapi_backend/app/domain/store.py b/fastapi_backend/app/domain/store.py index b2ce22f62..2bff63eb2 100644 --- a/fastapi_backend/app/domain/store.py +++ b/fastapi_backend/app/domain/store.py @@ -193,9 +193,16 @@ def labels(): # without passwords; an install that already had them keeps them until an admin turns them off. "auth": {"passwords": False}, # how long API keys last (docs/configuration.md): what a new key gets, the most it may get, and whether keys may - # never expire; and how long the tokens of apps given access through OAuth last (domain/oauth.py): the access token, - # and the grant after the app last renewed it - "tokens": {"default_days": 90, "max_days": 365, "never_expire": False, "oauth_access_minutes": 60, "oauth_refresh_days": 30}, + # never expire; and whether apps and MCP clients may sign people in through OAuth (domain/oauth.py), and how long + # their tokens last: the access token, and the grant after the app last renewed it + "tokens": { + "default_days": 90, + "max_days": 365, + "never_expire": False, + "oauth_enabled": True, + "oauth_access_minutes": 60, + "oauth_refresh_days": 30, + }, # audio, video, documents and images uploaded in the web app, in pieces (docs/configuration.md); transcript files use # server.max_upload_mb "uploads": {"max_mb": 4096, "extensions": list(MEDIA_EXT + DOCUMENT_EXT + IMAGE_EXT), "chunk_mb": 8, "expire_hours": 24}, diff --git a/fastapi_backend/app/schemas/setup.py b/fastapi_backend/app/schemas/setup.py index 6204d1d1d..4f9498f74 100644 --- a/fastapi_backend/app/schemas/setup.py +++ b/fastapi_backend/app/schemas/setup.py @@ -37,6 +37,13 @@ class SetupTelemetryView(ResponseModel): locked: list[str] +class SetupOAuthView(ResponseModel): + # whether apps and MCP clients may sign people in with their Lens account (tokens.oauth_enabled) + enabled: bool + access_minutes: int + refresh_days: int + + class SetupView(ResponseModel): pending: bool admin: SetupAdmin @@ -44,6 +51,7 @@ class SetupView(ResponseModel): llm: SetupLlmView storage: SetupStorageView telemetry: SetupTelemetryView + oauth: SetupOAuthView class SetupNamespace(RequestModel): @@ -79,6 +87,13 @@ class SetupTelemetry(RequestModel): endpoint: str | None = Field(default=None, max_length=500) +class SetupOAuth(RequestModel): + enabled: bool = True + # left out: unchanged + access_minutes: int | None = None + refresh_days: int | None = None + + class SetupFinish(RequestModel): skipped: bool = False diff --git a/fastapi_backend/tests/api/test_oauth.py b/fastapi_backend/tests/api/test_oauth.py index 75e6f57be..289f9076c 100644 --- a/fastapi_backend/tests/api/test_oauth.py +++ b/fastapi_backend/tests/api/test_oauth.py @@ -426,3 +426,29 @@ def test_redirects_keep_the_apps_own_query(): assert oauth.scopes("write") == "read write" and oauth.scopes("email profile") == "read" and oauth.scopes(None) == "read" assert not oauth.redirect_ok(["https://a.example/cb"], "http://[bad") assert oauth.token_account(None, "la_not_oauth") is None and oauth.get_client(None, "nope") is None + + +def test_admins_can_turn_apps_signing_in_off(client, db): + make_user(db, "root@x.io", "root password 1", admin=True) + make_user(db, "vi@x.io", "viewer password 1", roles={"pods": "viewer"}) + hr, h = login(client, "root@x.io", "root password 1"), login(client, "vi@x.io", "viewer password 1") + app, t = _grant(client, h) + assert client.put("/api/v1/settings/tokens", headers=hr, json={"oauth_enabled": "no"}).status_code == 400 + assert client.put("/api/v1/settings/tokens", headers=hr, json={"oauth_enabled": False}).status_code == 200 + # off: no discovery, no new apps, no consent, no renewing, and the tokens apps have stop working + assert client.get("/.well-known/oauth-authorization-server").status_code == 404 + assert client.get("/.well-known/oauth-protected-resource").status_code == 404 + r = client.post(f"{O}/register", json={"client_name": "New", "redirect_uris": [BACK]}) + assert (r.status_code, r.json()["error"]) == (403, "access_denied") + _, challenge = _pkce() + assert client.get(f"{O}/authorize", headers=h, params=_ask(app, challenge)).status_code == 403 + assert client.post(f"{O}/authorize", headers=h, json={**_ask(app, challenge), "approve": True}).status_code == 403 + r = client.post(f"{O}/token", data={"grant_type": "refresh_token", "client_id": app["client_id"], "refresh_token": t["refresh_token"]}) + assert r.status_code == 403 + r = client.get("/api/v1/auth/me", headers=_bearer(t)) + assert r.status_code == 401 and r.headers["www-authenticate"] == "Bearer" # nowhere to sign in, so it names nothing + # people still see the apps they allowed and can revoke them + assert len(client.get(f"{O}/grants", headers=h).json()) == 1 + # back on, the access people gave comes back with it + assert client.put("/api/v1/settings/tokens", headers=hr, json={"oauth_enabled": True}).status_code == 200 + assert client.get("/api/v1/auth/me", headers=_bearer(t)).status_code == 200 diff --git a/fastapi_backend/tests/api/test_setup.py b/fastapi_backend/tests/api/test_setup.py index d4cdfb1d5..72b679422 100644 --- a/fastapi_backend/tests/api/test_setup.py +++ b/fastapi_backend/tests/api/test_setup.py @@ -110,6 +110,16 @@ def test_wizard_after_first_admin(fresh, folder): "watches": 1, } + # apps and MCP clients signing in (OAuth): on unless turned off, with the token lifetimes + assert client.get("/api/v1/setup", headers=h).json()["oauth"] == {"enabled": True, "access_minutes": 60, "refresh_days": 30} + assert client.put("/api/v1/setup/oauth", json={"enabled": True, "access_minutes": 2}, headers=h).status_code == 400 + r = client.put("/api/v1/setup/oauth", json={"enabled": False, "access_minutes": 30, "refresh_days": 14}, headers=h) + assert r.json()["saved"] == ["oauth_access_minutes", "oauth_enabled", "oauth_refresh_days"] + assert client.get("/api/v1/setup", headers=h).json()["oauth"] == {"enabled": False, "access_minutes": 30, "refresh_days": 14} + assert client.get("/.well-known/oauth-authorization-server").status_code == 404 + assert client.put("/api/v1/setup/oauth", json={"enabled": True}, headers=h).json()["saved"] == ["oauth_enabled"] + assert client.get("/.well-known/oauth-authorization-server").status_code == 200 + assert client.post("/api/v1/setup/finish", json={}, headers=h).status_code == 200 assert client.get("/api/v1/auth/status").json()["wizard_pending"] is False assert "setup.finish" in [e["action"] for e in client.get("/api/v1/audit", headers=h).json()] @@ -123,6 +133,7 @@ def test_only_admins_use_the_wizard(fresh): h = login(client, "ed@x.io", "editor password 1") assert client.get("/api/v1/setup", headers=h).status_code == 403 assert client.post("/api/v1/setup/finish", json={}, headers=h).status_code == 403 + assert client.put("/api/v1/setup/oauth", json={"enabled": False}, headers=h).status_code == 403 def test_existing_installs_never_see_the_wizard(app, client): diff --git a/nextjs-frontend/__tests__/setupWizard.test.tsx b/nextjs-frontend/__tests__/setupWizard.test.tsx index 07f94301b..1994a32ce 100644 --- a/nextjs-frontend/__tests__/setupWizard.test.tsx +++ b/nextjs-frontend/__tests__/setupWizard.test.tsx @@ -15,6 +15,7 @@ jest.mock("@/app/openapi-client", () => ({ detectLlm: jest.fn(), saveStorage: jest.fn(), saveTelemetry: jest.fn(), + saveOauth: jest.fn(), finish: jest.fn(), }, Admin: { testLlm: jest.fn(), testTelemetry: jest.fn() }, @@ -41,6 +42,7 @@ const VIEW = (over: Partial = {}): SetupView => ({ watches: 0, }, telemetry: { enabled: false, endpoint: null, locked: [] }, + oauth: { enabled: true, access_minutes: 60, refresh_days: 30 }, ...over, }); @@ -89,13 +91,14 @@ describe("SetupWizard", () => { ); }); - it("walks through namespace, model provider, storage and telemetry, then finishes", async () => { + it("walks through namespace, model provider, storage, apps and telemetry, then finishes", async () => { m(Setup.getSetup).mockImplementation(() => ok(VIEW())); m(Setup.saveNamespace).mockImplementation(() => ok({ ok: true })); m(Setup.saveLlm).mockImplementation(() => ok({ ok: true })); m(Admin.testLlm).mockImplementation(() => ok({ ok: true, reply: "OK", ms: 120, model: "llama3" })); m(Setup.saveStorage).mockImplementation(() => ok({ ok: true })); m(Setup.saveTelemetry).mockImplementation(() => ok({ ok: true })); + m(Setup.saveOauth).mockImplementation(() => ok({ ok: true })); m(Setup.finish).mockImplementation(() => ok({ ok: true })); wrap(); @@ -127,6 +130,12 @@ describe("SetupWizard", () => { await waitFor(() => expect(Setup.saveStorage).toHaveBeenCalled()); expect(m(Setup.saveStorage).mock.calls[0][0].body).toEqual({ max_upload_mb: 2048, folder: null, namespace: null }); + // apps signing in is optional: skipping keeps it as it is + expect(await screen.findByText("Apps and AI assistants")).toBeInTheDocument(); + expect(screen.getByLabelText("MCP server address")).toHaveValue("http://localhost/mcp"); + fireEvent.click(screen.getByRole("button", { name: "Skip this step" })); + expect(Setup.saveOauth).not.toHaveBeenCalled(); + // telemetry is off unless chosen: finishing with it off sends nothing anywhere expect(await screen.findByText(/off unless you turn it on/)).toBeInTheDocument(); expect(screen.queryByLabelText("OTLP endpoint")).not.toBeInTheDocument(); @@ -159,6 +168,28 @@ describe("SetupWizard", () => { expect(m(Setup.saveTelemetry).mock.calls[1][0].body).toEqual({ enabled: true, endpoint: "http://localhost:4318" }); }); + it("lets apps sign in for a set time, or turns it off", async () => { + m(Setup.getSetup).mockImplementation(() => ok(VIEW({ namespace: { existing: ["media"], locked: false } }))); + m(Setup.saveOauth).mockImplementation(() => ok({ ok: true })); + wrap(); + fireEvent.click(await screen.findByRole("button", { name: /Apps and AI/ })); + const minutes = await screen.findByLabelText(/Access token lasts/); + fireEvent.change(minutes, { target: { value: "2" } }); + expect(screen.getByRole("button", { name: "Save and continue" })).toBeDisabled(); + fireEvent.change(minutes, { target: { value: "30" } }); + fireEvent.change(screen.getByLabelText(/stay signed in/), { target: { value: "14" } }); + fireEvent.click(screen.getByRole("button", { name: "Save and continue" })); + await waitFor(() => expect(Setup.saveOauth).toHaveBeenCalled()); + expect(m(Setup.saveOauth).mock.calls[0][0].body).toEqual({ enabled: true, access_minutes: 30, refresh_days: 14 }); + // on to telemetry; back to apps and off: nothing else to choose + fireEvent.click(await screen.findByRole("button", { name: /Apps and AI/ })); + fireEvent.click(await screen.findByRole("radio", { name: "Off" })); + expect(screen.queryByLabelText("MCP server address")).not.toBeInTheDocument(); + fireEvent.click(screen.getByRole("button", { name: "Save and continue" })); + await waitFor(() => expect(m(Setup.saveOauth).mock.calls.length).toBe(2)); + expect(m(Setup.saveOauth).mock.calls[1][0].body).toEqual({ enabled: false }); + }); + it("shows what .env sets as locked", async () => { m(Setup.getSetup).mockImplementation(() => ok( diff --git a/nextjs-frontend/app/openapi-client/index.ts b/nextjs-frontend/app/openapi-client/index.ts index 40f561eb3..bc352ac37 100644 --- a/nextjs-frontend/app/openapi-client/index.ts +++ b/nextjs-frontend/app/openapi-client/index.ts @@ -1785,6 +1785,11 @@ export type { SaveNamespaceErrors, SaveNamespaceResponse, SaveNamespaceResponses, + SaveOauthData, + SaveOauthError, + SaveOauthErrors, + SaveOauthResponse, + SaveOauthResponses, SaveResourceFieldsData, SaveResourceFieldsError, SaveResourceFieldsErrors, @@ -1876,6 +1881,8 @@ export type { SetupLlmView, SetupNamespace, SetupNamespaceView, + SetupOAuth, + SetupOAuthView, SetupRequest, SetupResponse, SetupResponses, diff --git a/nextjs-frontend/app/openapi-client/sdk.gen.ts b/nextjs-frontend/app/openapi-client/sdk.gen.ts index bca43a7f5..42309772e 100644 --- a/nextjs-frontend/app/openapi-client/sdk.gen.ts +++ b/nextjs-frontend/app/openapi-client/sdk.gen.ts @@ -879,6 +879,9 @@ import type { SaveNamespaceData, SaveNamespaceErrors, SaveNamespaceResponses, + SaveOauthData, + SaveOauthErrors, + SaveOauthResponses, SaveResourceFieldsData, SaveResourceFieldsErrors, SaveResourceFieldsResponses, @@ -1907,7 +1910,8 @@ export class Oauth { * Consent * * What the consent page shows for an app's request: the app, where it takes you back to and what it asks for. - * 400 when the request can't be answered (an unknown app, an address it didn't register, no PKCE challenge). + * 400 when the request can't be answered (an unknown app, an address it didn't register, no PKCE challenge); 403 + * when apps can't sign in to this server. */ public static consent( options: Options, @@ -2413,6 +2417,25 @@ export class Setup { }); } + /** + * Save Oauth + * + * Let apps and AI assistants (MCP clients such as Claude or Cursor) sign people in with their Lens account, or + * not, and how long their tokens last (docs/authentication.md#oauth). On unless turned off. + */ + public static saveOauth( + options: Options, + ): RequestResult { + return (options.client ?? client).put({ + url: "/api/v1/setup/oauth", + ...options, + headers: { + "Content-Type": "application/json", + ...options.headers, + }, + }); + } + /** * Finish * diff --git a/nextjs-frontend/app/openapi-client/types.gen.ts b/nextjs-frontend/app/openapi-client/types.gen.ts index 08fa013bd..afdc96cd4 100644 --- a/nextjs-frontend/app/openapi-client/types.gen.ts +++ b/nextjs-frontend/app/openapi-client/types.gen.ts @@ -10882,6 +10882,43 @@ export type SetupNamespaceView = { [key: string]: unknown; }; +/** + * SetupOAuth + */ +export type SetupOAuth = { + /** + * Enabled + */ + enabled?: boolean; + /** + * Access Minutes + */ + access_minutes?: number | null; + /** + * Refresh Days + */ + refresh_days?: number | null; +}; + +/** + * SetupOAuthView + */ +export type SetupOAuthView = { + /** + * Enabled + */ + enabled: boolean; + /** + * Access Minutes + */ + access_minutes: number; + /** + * Refresh Days + */ + refresh_days: number; + [key: string]: unknown; +}; + /** * SetupRequest */ @@ -11018,6 +11055,7 @@ export type SetupView = { llm: SetupLlmView; storage: SetupStorageView; telemetry: SetupTelemetryView; + oauth: SetupOAuthView; [key: string]: unknown; }; @@ -15682,6 +15720,31 @@ export type SaveTelemetryResponses = { export type SaveTelemetryResponse = SaveTelemetryResponses[keyof SaveTelemetryResponses]; +export type SaveOauthData = { + body: SetupOAuth; + path?: never; + query?: never; + url: "/api/v1/setup/oauth"; +}; + +export type SaveOauthErrors = { + /** + * Validation Error + */ + 422: HttpValidationError; +}; + +export type SaveOauthError = SaveOauthErrors[keyof SaveOauthErrors]; + +export type SaveOauthResponses = { + /** + * Successful Response + */ + 200: SetupSaved; +}; + +export type SaveOauthResponse = SaveOauthResponses[keyof SaveOauthResponses]; + export type FinishData = { body: SetupFinish; path?: never; diff --git a/nextjs-frontend/components/settings/bodies.tsx b/nextjs-frontend/components/settings/bodies.tsx index 6322a5aab..930b778f3 100644 --- a/nextjs-frontend/components/settings/bodies.tsx +++ b/nextjs-frontend/components/settings/bodies.tsx @@ -315,6 +315,7 @@ export function SectionBody({ ctx }: { ctx: BodyCtx }) { +
diff --git a/nextjs-frontend/components/settings/model.ts b/nextjs-frontend/components/settings/model.ts index ec08d4435..2ba9ee001 100644 --- a/nextjs-frontend/components/settings/model.ts +++ b/nextjs-frontend/components/settings/model.ts @@ -1548,6 +1548,13 @@ export const FIELDS: FieldSpec[] = [ placeholder: "gpt-4o-mini 0.15 0.60", hint: "One model per line: its name, then the input and output price in dollars per million tokens. The AI assistant’s prices count for the configured model", }, + { + section: "tokens", + key: "oauth_enabled", + label: "Let apps and AI assistants sign in", + kind: "switch", + hint: "Claude, ChatGPT, Cursor and other apps sign in with a person’s Lens account (OAuth) and act with their roles. Off: apps need an API key, and the ones people allowed stop working until it’s back on", + }, { section: "tokens", key: "oauth_access_minutes", diff --git a/nextjs-frontend/components/setup/setup-wizard.tsx b/nextjs-frontend/components/setup/setup-wizard.tsx index e354dbb74..921fea8d0 100644 --- a/nextjs-frontend/components/setup/setup-wizard.tsx +++ b/nextjs-frontend/components/setup/setup-wizard.tsx @@ -20,6 +20,7 @@ const STEPS = [ { id: "namespace", label: "Namespace" }, { id: "llm", label: "Model provider" }, { id: "storage", label: "Storage" }, + { id: "apps", label: "Apps and AI" }, { id: "telemetry", label: "Telemetry" }, ] as const; type StepId = (typeof STEPS)[number]["id"]; @@ -39,8 +40,9 @@ function errorText(e: unknown): string { } /** - * First-run setup for a fresh install (the admin already exists): the first namespace, the model provider, storage - * and whether to send telemetry (off unless chosen), one step at a time. Each step can be skipped, and the whole wizard too; everything stays in Settings. + * First-run setup for a fresh install (the admin already exists): the first namespace, the model provider, storage, + * whether apps and AI assistants may sign people in (OAuth, on unless turned off) and whether to send telemetry (off + * unless chosen), one step at a time. Each step can be skipped, and the whole wizard too; everything stays in Settings. * Fields .env sets are shown locked, since the environment wins. */ export function SetupWizard() { @@ -118,7 +120,7 @@ export function SetupWizard() {

-
    +
      {STEPS.map((s, i) => { const on = s.id === step; const ok = done.has(s.id); @@ -174,6 +176,8 @@ export function SetupWizard() { next("llm", saved)} /> ) : step === "storage" ? ( next("storage", saved)} /> + ) : step === "apps" ? ( + next("apps", saved)} /> ) : ( next("telemetry", saved)} /> )} @@ -616,6 +620,124 @@ function StorageStep({ view, onNext }: { view: SetupView; onNext: (saved: boolea ); } +/** Apps and AI assistants (MCP clients) signing people in with their Lens account: OAuth (docs/authentication.md). */ +function AppsStep({ view, onNext }: { view: SetupView; onNext: (saved: boolean) => void }) { + const client = useApiClient(); + const o = view.oauth; + const [on, setOn] = useState(o.enabled ? "on" : "off"); + const [minutes, setMinutes] = useState(String(o.access_minutes)); + const [days, setDays] = useState(String(o.refresh_days)); + const [copied, setCopied] = useState(false); + const mcp = typeof window === "undefined" ? "/mcp" : `${window.location.origin}/mcp`; + const mins = Number(minutes); + const ds = Number(days); + const validMinutes = Number.isInteger(mins) && mins >= 5 && mins <= 1440; + const validDays = Number.isInteger(ds) && ds >= 1 && ds <= 3650; + const save = useMutation({ + mutationFn: () => + data( + Setup.saveOauth({ + client, + body: on === "on" ? { enabled: true, access_minutes: mins, refresh_days: ds } : { enabled: false }, + }), + ), + onSuccess: () => onNext(true), + }); + const copy = async () => { + try { + await navigator.clipboard.writeText(mcp); + setCopied(true); + } catch { + setCopied(false); + } + }; + + return ( + <> + + Apps and AI assistants such as Claude, ChatGPT or Cursor can sign in with someone's Lens account instead of + asking them for a key. Each person approves an app once, it sees only what they can, and they can revoke it any + time under API tokens. + + + {() => ( + + )} + + {on === "on" && ( + <> + + {({ id, describedBy }) => ( +
      + + +
      + )} +
      +
      + + {({ id, describedBy, invalid }) => ( + setMinutes(e.target.value.replace(/[^0-9]/g, ""))} + /> + )} + + + {({ id, describedBy, invalid }) => ( + setDays(e.target.value.replace(/[^0-9]/g, ""))} + /> + )} + +
      + + )} + {save.error && {errorText(save.error)}} + onNext(false)} + onSave={() => save.mutate()} + pending={save.isPending} + disabled={on === "on" && (!validMinutes || !validDays)} + /> + + ); +} + function TelemetryStep({ view, pending, diff --git a/nextjs-frontend/openapi.json b/nextjs-frontend/openapi.json index 1b5b43f9b..c8d2c1d37 100644 --- a/nextjs-frontend/openapi.json +++ b/nextjs-frontend/openapi.json @@ -1619,7 +1619,7 @@ "oauth" ], "summary": "Consent", - "description": "What the consent page shows for an app's request: the app, where it takes you back to and what it asks for.\n400 when the request can't be answered (an unknown app, an address it didn't register, no PKCE challenge).", + "description": "What the consent page shows for an app's request: the app, where it takes you back to and what it asks for.\n400 when the request can't be answered (an unknown app, an address it didn't register, no PKCE challenge); 403\nwhen apps can't sign in to this server.", "operationId": "consent", "parameters": [ { @@ -2875,6 +2875,48 @@ } } }, + "/api/v1/setup/oauth": { + "put": { + "tags": [ + "setup" + ], + "summary": "Save Oauth", + "description": "Let apps and AI assistants (MCP clients such as Claude or Cursor) sign people in with their Lens account, or\nnot, and how long their tokens last (docs/authentication.md#oauth). On unless turned off.", + "operationId": "save_oauth", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SetupOAuth" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SetupSaved" + } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, "/api/v1/setup/finish": { "post": { "tags": [ @@ -37681,6 +37723,64 @@ ], "title": "SetupNamespaceView" }, + "SetupOAuth": { + "properties": { + "enabled": { + "type": "boolean", + "title": "Enabled", + "default": true + }, + "access_minutes": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "title": "Access Minutes" + }, + "refresh_days": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "title": "Refresh Days" + } + }, + "additionalProperties": false, + "type": "object", + "title": "SetupOAuth" + }, + "SetupOAuthView": { + "properties": { + "enabled": { + "type": "boolean", + "title": "Enabled" + }, + "access_minutes": { + "type": "integer", + "title": "Access Minutes" + }, + "refresh_days": { + "type": "integer", + "title": "Refresh Days" + } + }, + "additionalProperties": true, + "type": "object", + "required": [ + "enabled", + "access_minutes", + "refresh_days" + ], + "title": "SetupOAuthView" + }, "SetupRequest": { "properties": { "code": { @@ -37907,6 +38007,9 @@ }, "telemetry": { "$ref": "#/components/schemas/SetupTelemetryView" + }, + "oauth": { + "$ref": "#/components/schemas/SetupOAuthView" } }, "additionalProperties": true, @@ -37917,7 +38020,8 @@ "namespace", "llm", "storage", - "telemetry" + "telemetry", + "oauth" ], "title": "SetupView" }, From e9293694edf53eaae0e68f2fe5b380e6a78de558 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 4 Oct 2026 06:10:49 +0000 Subject: [PATCH 2/3] test(setup): give the apps step test room on a busy runner Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01HFiySoDnqG9PX5c3WLPz5C --- nextjs-frontend/__tests__/setupWizard.test.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nextjs-frontend/__tests__/setupWizard.test.tsx b/nextjs-frontend/__tests__/setupWizard.test.tsx index 1994a32ce..d9a943043 100644 --- a/nextjs-frontend/__tests__/setupWizard.test.tsx +++ b/nextjs-frontend/__tests__/setupWizard.test.tsx @@ -188,7 +188,7 @@ describe("SetupWizard", () => { fireEvent.click(screen.getByRole("button", { name: "Save and continue" })); await waitFor(() => expect(m(Setup.saveOauth).mock.calls.length).toBe(2)); expect(m(Setup.saveOauth).mock.calls[1][0].body).toEqual({ enabled: false }); - }); + }, 20_000); // two saves and two visits to the step: slow on a busy CI runner it("shows what .env sets as locked", async () => { m(Setup.getSetup).mockImplementation(() => From 9452d89eaebf17b759b352d604ce84ef5737d296 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 4 Oct 2026 06:12:32 +0000 Subject: [PATCH 3/3] fix(types): addresses from getaddrinfo are strings for mypy Main's mypy run fails on deps._proxy_hosts (getaddrinfo's address tuple may hold an int); this makes CI pass here. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01HFiySoDnqG9PX5c3WLPz5C --- fastapi_backend/app/api/deps.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fastapi_backend/app/api/deps.py b/fastapi_backend/app/api/deps.py index 737e59ca6..70186c863 100644 --- a/fastapi_backend/app/api/deps.py +++ b/fastapi_backend/app/api/deps.py @@ -316,7 +316,7 @@ def _proxy_hosts() -> tuple[str, ...]: hit = _PROXY_HOSTS.get(name) if not hit or time.monotonic() - hit[0] > 30: try: - found = tuple(sorted({i[4][0] for i in socket.getaddrinfo(name, None)})) + found = tuple(sorted({str(i[4][0]) for i in socket.getaddrinfo(name, None)})) except OSError: found = () hit = _PROXY_HOSTS[name] = (time.monotonic(), found)