Open-source personal finance manager. Self-hosted, privacy-first.
Add OIDC-only local auth toggle (#434)
Romulo Gattoa43cc6417fa3
diff --git a/.env.example b/.env.exampleindex 96f805bd..02954f52 100644--- a/.env.example+++ b/.env.example@@ -31,6 +31,9 @@ ENABLE_BANKING_APP_ID=# OIDC_SCOPES=openid email profile# OIDC_AUTO_REGISTER=true# OIDC_REQUIRE_VERIFIED_EMAIL=true+# Optional: require OIDC-only login; requires OIDC_ENABLED, OIDC_CLIENT_ID, and OIDC_DISCOVERY_URL+# Disables local login, registration, password reset/change, and new passkey ceremonies+# LOCAL_AUTH_ENABLED=false# Link an OIDC login to an existing Securo account with the same email:# disabled (default) never links, verified_email links only when the provider# sends email_verified=true, email links on a matching email alone.diff --git a/README.md b/README.mdindex 917d8759..7f63f0fb 100644--- a/README.md+++ b/README.md@@ -116,6 +116,12 @@ OIDC_CLIENT_SECRET=your-client-secretOIDC_REDIRECT_URI=https://your-securo-host/api/auth/oidc/callback```+To require SSO-only access after OIDC is configured, set `LOCAL_AUTH_ENABLED=false`. Securo will start in this mode only when `OIDC_ENABLED=true`, `OIDC_CLIENT_ID`, and `OIDC_DISCOVERY_URL` are all configured; otherwise startup fails with a validation error instead of leaving the instance with no usable login method. The login page shows an explicit configuration error if the server reports that neither local auth nor OIDC is available. If only the optional OIDC-config request fails, the client keeps local controls available with a warning; the backend remains authoritative and still rejects them in OIDC-only mode.++With local auth disabled, Securo rejects password and passkey login, public registration, first-admin password setup, admin or workspace-invite creation of password-backed users, forgot/reset-password requests, password updates, new passkey registration or verification, and new TOTP setup or enablement. Local credential controls are hidden from login, account, setup, registration, and admin user-management screens. Existing users, password hashes, active sessions, passkeys, and TOTP configuration are not deleted; existing passkeys and TOTP can still be removed as cleanup paths. OIDC user provisioning and existing-account linking remain controlled separately by `OIDC_AUTO_REGISTER` and `OIDC_EXISTING_USER_LINK_MODE`.++On a fresh OIDC-only instance, the first account must be provisioned through OIDC. Keep `OIDC_AUTO_REGISTER=true`, enable `OIDC_SYNC_ROLES=true`, and include one of the values from `OIDC_ADMIN_ROLES` in that identity's configured roles claim so the first login becomes a Securo administrator. Do not disable OIDC auto-registration before at least one matching account exists.+New OIDC users are auto-provisioned by default (`OIDC_AUTO_REGISTER=true`) using verified email addresses. Set `OIDC_AUTO_REGISTER=false` to allow only existing Securo users whose email matches the provider claim.### Linking existing accountsdiff --git a/backend/.env.example b/backend/.env.exampleindex e5e24a43..cf7b0897 100644--- a/backend/.env.example+++ b/backend/.env.example@@ -21,6 +21,8 @@ OIDC_REDIRECT_URI=OIDC_SCOPES=openid email profileOIDC_AUTO_REGISTER=trueOIDC_REQUIRE_VERIFIED_EMAIL=true+# Set to false only with OIDC_ENABLED=true, OIDC_CLIENT_ID, and OIDC_DISCOVERY_URL configured+LOCAL_AUTH_ENABLED=trueOIDC_SYNC_ROLES=falseOIDC_ROLES_CLAIM=groupsOIDC_ADMIN_ROLES=diff --git a/backend/app/api/admin.py b/backend/app/api/admin.pyindex 0fa4e87b..09f076f3 100644--- a/backend/app/api/admin.py+++ b/backend/app/api/admin.py@@ -5,6 +5,7 @@ from fastapi import APIRouter, Depends, HTTPException, Query, Request, statusfrom sqlalchemy.ext.asyncio import AsyncSessionfrom app.core.auth import UserManager, current_active_user, current_superuser, get_user_manager+from app.core.auth_policy import require_local_auth_enabledfrom app.core.database import get_async_sessionfrom app.models.user import Userfrom app.schemas.admin import (@@ -45,7 +46,12 @@ async def list_users()[email protected]("/users", response_model=AdminUserRead, status_code=status.HTTP_201_CREATED)+ "/users",+ response_model=AdminUserRead,+ status_code=status.HTTP_201_CREATED,+ dependencies=[Depends(require_local_auth_enabled)],+)async def create_user(data: AdminUserCreate,session: AsyncSession = Depends(get_async_session),@@ -78,6 +84,8 @@ async def update_user(session: AsyncSession = Depends(get_async_session),current_user: User = Depends(current_superuser),):+ if data.password is not None:+ require_local_auth_enabled()try:user = await admin_service.update_user(session, user_id, data, current_user.id)except ValueError as e:diff --git a/backend/app/api/custom_auth.py b/backend/app/api/custom_auth.pyindex ee414fa3..5194f02a 100644--- a/backend/app/api/custom_auth.py+++ b/backend/app/api/custom_auth.py@@ -7,6 +7,7 @@ from sqlalchemy import func, selectfrom sqlalchemy.ext.asyncio import AsyncSessionfrom app.core.auth import get_jwt_strategy, get_user_manager+from app.core.auth_policy import require_local_auth_enabledfrom app.core.database import get_async_sessionfrom app.core.redis import get_redisfrom app.models.passkey import UserPasskey@@ -16,7 +17,7 @@ router = APIRouter()TEMP_TOKEN_TTL = 300 # 5 minutes[email protected]("/login")[email protected]("/login", dependencies=[Depends(require_local_auth_enabled)])async def login(credentials: OAuth2PasswordRequestForm = Depends(),user_manager=Depends(get_user_manager),diff --git a/backend/app/api/oidc_auth.py b/backend/app/api/oidc_auth.pyindex 0f1dae5a..326f67c1 100644--- a/backend/app/api/oidc_auth.py+++ b/backend/app/api/oidc_auth.py@@ -34,6 +34,7 @@ OIDC_STATE_TTL = 600class OIDCConfigResponse(BaseModel):enabled: boolprovider_name: str = "OIDC"+ local_auth_enabled: bool = Trueasync def _discover() -> dict[str, Any]:@@ -57,8 +58,9 @@ def _redirect_uri() -> str:async def oidc_config():settings = get_settings()return OIDCConfigResponse(- enabled=bool(settings.oidc_enabled and settings.oidc_client_id and settings.oidc_discovery_url),+ enabled=settings.oidc_login_available,provider_name=settings.oidc_provider_name or "OIDC",+ local_auth_enabled=settings.local_auth_enabled,)diff --git a/backend/app/api/passkeys.py b/backend/app/api/passkeys.pyindex fd0f124a..d23e32c9 100644--- a/backend/app/api/passkeys.py+++ b/backend/app/api/passkeys.py@@ -26,6 +26,7 @@ from webauthn.helpers.structs import ()from app.core.auth import current_active_user, get_jwt_strategy+from app.core.auth_policy import require_local_auth_enabledfrom app.core.config import get_settingsfrom app.core.database import get_async_sessionfrom app.core.rate_limit import login_rate_limit@@ -199,7 +200,11 @@ async def list_passkeys(return result.scalars().all()[email protected]("/passkeys/register/options", response_model=PasskeyOptionsResponse)+ "/passkeys/register/options",+ response_model=PasskeyOptionsResponse,+ dependencies=[Depends(require_local_auth_enabled)],+)async def passkey_registration_options(request: Request,body: PasskeyRegisterOptionsRequest,@@ -241,7 +246,11 @@ async def passkey_registration_options(return PasskeyOptionsResponse(challenge_id=challenge_id, options=_options_dict(options))[email protected]("/passkeys/register/verify", response_model=PasskeyRead)+ "/passkeys/register/verify",+ response_model=PasskeyRead,+ dependencies=[Depends(require_local_auth_enabled)],+)async def verify_passkey_registration(body: PasskeyRegisterVerifyRequest,user: User = Depends(current_active_user),@@ -304,7 +313,7 @@ async def delete_passkey(@router.post("/passkeys/authenticate/options",response_model=PasskeyOptionsResponse,- dependencies=[Depends(login_rate_limit)],+ dependencies=[Depends(require_local_auth_enabled), Depends(login_rate_limit)],)async def passkey_authentication_options(request: Request,@@ -354,7 +363,10 @@ async def passkey_authentication_options(return PasskeyOptionsResponse(challenge_id=challenge_id, options=_options_dict(options))[email protected]("/passkeys/authenticate/verify", dependencies=[Depends(login_rate_limit)])+ "/passkeys/authenticate/verify",+ dependencies=[Depends(require_local_auth_enabled), Depends(login_rate_limit)],+)async def verify_passkey_authentication(body: PasskeyAuthenticateVerifyRequest,session: AsyncSession = Depends(get_async_session),@@ -389,7 +401,11 @@ async def verify_passkey_authentication(return {"access_token": token, "token_type": "bearer"}[email protected]("/passkeys/2fa/options", response_model=PasskeyOptionsResponse, dependencies=[Depends(login_rate_limit)])+ "/passkeys/2fa/options",+ response_model=PasskeyOptionsResponse,+ dependencies=[Depends(require_local_auth_enabled), Depends(login_rate_limit)],+)async def passkey_second_factor_options(request: Request,body: PasskeySecondFactorOptionsRequest,@@ -424,7 +440,10 @@ async def passkey_second_factor_options(return PasskeyOptionsResponse(challenge_id=challenge_id, options=_options_dict(options))[email protected]("/passkeys/2fa/verify", dependencies=[Depends(login_rate_limit)])+ "/passkeys/2fa/verify",+ dependencies=[Depends(require_local_auth_enabled), Depends(login_rate_limit)],+)async def verify_passkey_second_factor(body: PasskeySecondFactorVerifyRequest,session: AsyncSession = Depends(get_async_session),diff --git a/backend/app/api/setup.py b/backend/app/api/setup.pyindex e5660ba8..0c350a74 100644--- a/backend/app/api/setup.py+++ b/backend/app/api/setup.py@@ -6,6 +6,7 @@ from sqlalchemy import select, func, update as sql_updatefrom sqlalchemy.ext.asyncio import AsyncSessionfrom app.core.auth import get_jwt_strategy, get_user_manager, UserManager+from app.core.auth_policy import require_local_auth_enabledfrom app.core.database import get_async_sessionfrom app.models.account import Accountfrom app.models.user import User@@ -32,7 +33,7 @@ async def get_setup_status(session: AsyncSession = Depends(get_async_session)):return SetupStatus(has_users=count > 0)[email protected]("/create-admin")[email protected]("/create-admin", dependencies=[Depends(require_local_auth_enabled)])async def create_admin(body: CreateAdminRequest,session: AsyncSession = Depends(get_async_session),diff --git a/backend/app/api/two_factor.py b/backend/app/api/two_factor.pyindex d7e0d685..641373c9 100644--- a/backend/app/api/two_factor.py+++ b/backend/app/api/two_factor.py@@ -7,6 +7,7 @@ from sqlalchemy import selectfrom sqlalchemy.ext.asyncio import AsyncSessionfrom app.core.auth import current_active_user, get_jwt_strategy+from app.core.auth_policy import require_local_auth_enabledfrom app.core.database import get_async_sessionfrom app.core.rate_limit import login_rate_limitfrom app.core.redis import get_redis@@ -39,7 +40,11 @@ def _parse_temp_token_payload(raw: str | bytes) -> dict[str, object] | None:return payload[email protected]("/2fa/setup", response_model=TwoFactorSetupResponse)+ "/2fa/setup",+ response_model=TwoFactorSetupResponse,+ dependencies=[Depends(require_local_auth_enabled)],+)async def setup_2fa(user: User = Depends(current_active_user),session: AsyncSession = Depends(get_async_session),@@ -55,7 +60,7 @@ async def setup_2fa(return TwoFactorSetupResponse(secret=secret, otpauth_uri=otpauth_uri)[email protected]("/2fa/enable")[email protected]("/2fa/enable", dependencies=[Depends(require_local_auth_enabled)])async def enable_2fa(body: TwoFactorEnableRequest,user: User = Depends(current_active_user),diff --git a/backend/app/api/workspaces.py b/backend/app/api/workspaces.pyindex 947ee6c2..ed9f1f50 100644--- a/backend/app/api/workspaces.py+++ b/backend/app/api/workspaces.py@@ -13,6 +13,7 @@ from sqlalchemy import selectfrom sqlalchemy.ext.asyncio import AsyncSessionfrom app.core.auth import current_active_user, get_user_manager, UserManager+from app.core.auth_policy import local_auth_enabled, require_local_auth_enabledfrom app.core.database import get_async_sessionfrom app.core.workspace_context import WorkspaceContext, current_workspacefrom app.models.user import User@@ -206,8 +207,21 @@ async def invite_member(target = existing.scalar_one_or_none()if target is None:- # Brand-new user — only allowed if a password was provided.- if not body.password:+ # Brand-new user — creating the account here mints a local password,+ # so it is only allowed while local credentials are accepted.+ if body.password:+ require_local_auth_enabled()+ elif not local_auth_enabled():+ # There is no password to ask for in OIDC-only mode, so point at+ # what actually unblocks the invite.+ raise HTTPException(+ status_code=400,+ detail=(+ "User not found. They must sign in through the identity "+ "provider once before they can be added."+ ),+ )+ else:raise HTTPException(status_code=400,detail="User not found. Provide a password to create them.",diff --git a/backend/app/core/auth.py b/backend/app/core/auth.pyindex 3bd3397f..e7730606 100644--- a/backend/app/core/auth.py+++ b/backend/app/core/auth.py@@ -3,7 +3,7 @@ from decimal import Decimalfrom typing import Optionalfrom fastapi import Depends, Request-from fastapi_users import BaseUserManager, FastAPIUsers, UUIDIDMixin+from fastapi_users import BaseUserManager, FastAPIUsers, UUIDIDMixin, schemasfrom fastapi_users.authentication import (AuthenticationBackend,BearerTransport,@@ -12,6 +12,7 @@ from fastapi_users.authentication import (from fastapi_users.db import SQLAlchemyUserDatabasefrom sqlalchemy.ext.asyncio import AsyncSession+from app.core.auth_policy import require_local_auth_enabledfrom app.core.config import get_settingsfrom app.core.database import get_async_sessionfrom app.models.user import User@@ -28,6 +29,17 @@ class UserManager(UUIDIDMixin, BaseUserManager[User, uuid.UUID]):reset_password_token_secret = settings.secret_keyverification_token_secret = settings.secret_key+ async def update(+ self,+ user_update: schemas.BaseUserUpdate,+ user: User,+ safe: bool = False,+ request: Request | None = None,+ ) -> User:+ if user_update.password is not None:+ require_local_auth_enabled()+ return await super().update(user_update, user, safe=safe, request=request)+async def on_after_register(self, user: User, request: Optional[Request] = None):print(f"User {user.id} has registered.")# If request is None, this was called programmatically (e.g., from setup endpoint)diff --git a/backend/app/core/auth_policy.py b/backend/app/core/auth_policy.pynew file mode 100644index 00000000..dcfa7a62--- /dev/null+++ b/backend/app/core/auth_policy.py@@ -0,0 +1,17 @@+from fastapi import HTTPException, status++from app.core.config import get_settings+++def local_auth_enabled() -> bool:+ """True when the deployment still accepts local credentials."""+ return get_settings().local_auth_enabled+++def require_local_auth_enabled() -> None:+ """Reject local credential operations when OIDC-only mode is active."""+ if not local_auth_enabled():+ raise HTTPException(+ status_code=status.HTTP_403_FORBIDDEN,+ detail="LOCAL_AUTH_DISABLED",+ )diff --git a/backend/app/core/config.py b/backend/app/core/config.pyindex f2b9932f..d1868726 100644--- a/backend/app/core/config.py+++ b/backend/app/core/config.py@@ -2,7 +2,7 @@ from functools import lru_cachefrom os import getenvfrom pathlib import Path-from pydantic import SecretStr+from pydantic import SecretStr, model_validatorfrom pydantic_settings import BaseSettings, SettingsConfigDict# Use the same environment variable that systemd uses: https://systemd.io/CREDENTIALS/@@ -22,6 +22,7 @@ class Settings(BaseSettings):# Authsecret_key: SecretStr = SecretStr("change-me-in-production")+ local_auth_enabled: bool = Truealgorithm: str = "HS256"access_token_expire_minutes: int = 60 * 24 # 24 hours@@ -120,6 +121,26 @@ class Settings(BaseSettings):# external dependency on the Brazilian government endpoint).tesouro_direto_enabled: bool = True+ @property+ def oidc_login_available(self) -> bool:+ return bool(self.oidc_enabled and self.oidc_client_id and self.oidc_discovery_url)++ @model_validator(mode="after")+ def validate_auth_settings(self) -> "Settings":+ if not self.local_auth_enabled and not self.oidc_login_available:+ missing = []+ if not self.oidc_enabled:+ missing.append("OIDC_ENABLED=true")+ if not self.oidc_client_id:+ missing.append("OIDC_CLIENT_ID")+ if not self.oidc_discovery_url:+ missing.append("OIDC_DISCOVERY_URL")+ raise ValueError(+ "LOCAL_AUTH_ENABLED=false requires a complete OIDC configuration; "+ f"missing: {', '.join(missing)}"+ )+ return self+# The CWD-relative ".env" is kept for backward compatibility; the anchored# backend/.env guarantees the API and the Celery worker/beat resolve the# same file no matter which working directory each service is launcheddiff --git a/backend/app/main.py b/backend/app/main.pyindex 983fce1b..a859acf6 100644--- a/backend/app/main.py+++ b/backend/app/main.py@@ -41,6 +41,7 @@ from app.api.user_lookup import router as user_lookup_routerfrom app.api.workspaces import router as workspaces_routerfrom app.api.admin import router as admin_router, check_registration_enabledfrom app.core.auth import fastapi_users+from app.core.auth_policy import require_local_auth_enabledfrom app.core.config import get_settingsfrom app.core.rate_limit import login_rate_limit, register_rate_limit, password_reset_rate_limitfrom app.core.redis import close_redis@@ -136,13 +137,17 @@ app.include_router(fastapi_users.get_register_router(UserRead, UserCreate),prefix="/api/auth",tags=["auth"],- dependencies=[Depends(check_registration_enabled), Depends(register_rate_limit)],+ dependencies=[+ Depends(require_local_auth_enabled),+ Depends(check_registration_enabled),+ Depends(register_rate_limit),+ ],)app.include_router(fastapi_users.get_reset_password_router(),prefix="/api/auth",tags=["auth"],- dependencies=[Depends(password_reset_rate_limit)],+ dependencies=[Depends(require_local_auth_enabled), Depends(password_reset_rate_limit)],)# user_lookup must precede the fastapi-users router below so the# `/api/users/lookup` path isn't captured by the catch-all `/{id}`diff --git a/backend/tests/conftest.py b/backend/tests/conftest.pyindex 335c1f29..77f64a9b 100644--- a/backend/tests/conftest.py+++ b/backend/tests/conftest.py@@ -149,6 +149,27 @@ async def client() -> AsyncGenerator[AsyncClient, None]:yield ac+def oidc_only_settings():+ """Enable a complete OIDC-only policy and restore only changed keys."""+ from app.core.config import get_settings++ settings = get_settings()+ previous = {+ "oidc_enabled": settings.oidc_enabled,+ "oidc_discovery_url": settings.oidc_discovery_url,+ "oidc_client_id": settings.oidc_client_id,+ "local_auth_enabled": settings.local_auth_enabled,+ }+ settings.oidc_enabled = True+ settings.oidc_discovery_url = "https://id.example.com/.well-known/openid-configuration"+ settings.oidc_client_id = "securo"+ settings.local_auth_enabled = False+ yield settings+ for key, value in previous.items():+ setattr(settings, key, value)++@pytest_asyncio.fixtureasync def test_user(session: AsyncSession, clean_db) -> User:"""Create a test user with an auto-created Personal workspace.diff --git a/backend/tests/test_admin_api.py b/backend/tests/test_admin_api.pyindex 2778861e..43db893c 100644--- a/backend/tests/test_admin_api.py+++ b/backend/tests/test_admin_api.py@@ -7,6 +7,7 @@ from sqlalchemy.ext.asyncio import AsyncSessionfrom app.models.app_settings import AppSettingfrom app.models.user import User+from app.core.auth import get_jwt_strategypytestmark = pytest.mark.asyncio@@ -50,6 +51,47 @@ class TestAdminUserCRUD:assert data["is_active"] is Trueassert data["is_superuser"] is False+ async def test_create_user_forbidden_when_local_auth_disabled(+ self,+ client: AsyncClient,+ test_superuser: User,+ oidc_only_settings,+ ):+ token = await get_jwt_strategy().write_token(test_superuser)+ response = await client.post(+ "/api/admin/users",+ json={"email": "[email protected]", "password": "password123"},+ headers={"Authorization": f"Bearer {token}"},+ )++ assert response.status_code == 403+ assert response.json()["detail"] == "LOCAL_AUTH_DISABLED"++ async def test_admin_password_update_forbidden_but_profile_update_allowed(+ self,+ client: AsyncClient,+ test_superuser: User,+ oidc_only_settings,+ ):+ headers = {+ "Authorization": f"Bearer {await get_jwt_strategy().write_token(test_superuser)}"+ }+ password_response = await client.patch(+ f"/api/admin/users/{test_superuser.id}",+ json={"password": "newpassword456"},+ headers=headers,+ )+ profile_response = await client.patch(+ f"/api/admin/users/{test_superuser.id}",+ json={"preferences": {"language": "de"}},+ headers=headers,+ )++ assert password_response.status_code == 403+ assert password_response.json()["detail"] == "LOCAL_AUTH_DISABLED"+ assert profile_response.status_code == 200+ assert profile_response.json()["preferences"]["language"] == "de"+async def test_create_user_seeds_defaults(self, client: AsyncClient, admin_auth_headers: dict, test_superuser: User):diff --git a/backend/tests/test_auth_api.py b/backend/tests/test_auth_api.pyindex 7cba25d7..6d2e4b27 100644--- a/backend/tests/test_auth_api.py+++ b/backend/tests/test_auth_api.py@@ -1,6 +1,8 @@import pytestfrom httpx import AsyncClient+from app.core.auth import get_jwt_strategy+@pytest.mark.asyncioasync def test_register(client: AsyncClient, clean_db):@@ -60,3 +62,81 @@ async def test_get_me(client: AsyncClient, auth_headers):async def test_get_me_unauthenticated(client: AsyncClient, clean_db):response = await client.get("/api/users/me")assert response.status_code == 401+++async def test_login_forbidden_when_local_auth_disabled(client: AsyncClient, test_user, oidc_only_settings):+ response = await client.post(+ "/api/auth/login",+ data={"username": "[email protected]", "password": "testpass123"},+ headers={"Content-Type": "application/x-www-form-urlencoded"},+ )++ assert response.status_code == 403+ assert response.json()["detail"] == "LOCAL_AUTH_DISABLED"+++async def test_register_forbidden_when_local_auth_disabled(client: AsyncClient, clean_db, oidc_only_settings):+ response = await client.post(+ "/api/auth/register",+ json={"email": "[email protected]", "password": "newpass123"},+ )++ assert response.status_code == 403+ assert response.json()["detail"] == "LOCAL_AUTH_DISABLED"+++ ("path", "payload"),+ [+ ("/api/auth/forgot-password", {"email": "[email protected]"}),+ ("/api/auth/reset-password", {"token": "invalid", "password": "newpass123"}),+ ],+)+async def test_password_reset_forbidden_when_local_auth_disabled(+ client: AsyncClient,+ clean_db,+ oidc_only_settings,+ path: str,+ payload: dict[str, str],+):+ response = await client.post(path, json=payload)++ assert response.status_code == 403+ assert response.json()["detail"] == "LOCAL_AUTH_DISABLED"+++async def test_self_password_update_forbidden_when_local_auth_disabled(+ client: AsyncClient,+ test_user,+ oidc_only_settings,+):+ token = await get_jwt_strategy().write_token(test_user)+ response = await client.patch(+ "/api/users/me",+ json={"password": "replacement123"},+ headers={"Authorization": f"Bearer {token}"},+ )++ assert response.status_code == 403+ assert response.json()["detail"] == "LOCAL_AUTH_DISABLED"+++async def test_profile_update_allowed_when_local_auth_disabled(+ client: AsyncClient,+ test_user,+ oidc_only_settings,+):+ token = await get_jwt_strategy().write_token(test_user)+ response = await client.patch(+ "/api/users/me",+ json={"preferences": {"language": "en"}},+ headers={"Authorization": f"Bearer {token}"},+ )++ assert response.status_code == 200+ assert response.json()["preferences"]["language"] == "en"diff --git a/backend/tests/test_config.py b/backend/tests/test_config.pyindex 13b306ba..3f635987 100644--- a/backend/tests/test_config.py+++ b/backend/tests/test_config.py@@ -1,5 +1,5 @@from pathlib import Path-from pydantic import SecretStr+from pydantic import SecretStr, ValidationErrorimport pytestfrom app.core.config import Settings@@ -110,3 +110,53 @@ def test_multiple_secrets_dirs_merge(tmp_path: Path):value = value.get_secret_value()assert value == expectedValue+++def test_local_auth_enabled_defaults_true(secrets: Path):+ settings = Settings(_secrets_dir=str(secrets))++ assert settings.local_auth_enabled is True+++def test_local_auth_can_be_disabled_when_oidc_is_enabled(secrets: Path):+ settings = Settings(+ oidc_enabled=True,+ oidc_client_id="securo",+ oidc_discovery_url="https://id.example.com/.well-known/openid-configuration",+ local_auth_enabled=False,+ _secrets_dir=str(secrets),+ )++ assert settings.local_auth_enabled is False+++def test_local_auth_disabled_requires_oidc(secrets: Path):+ with pytest.raises(ValidationError, match="LOCAL_AUTH_ENABLED=false requires a complete OIDC configuration"):+ Settings(local_auth_enabled=False, _secrets_dir=str(secrets))+++ ("missing_field", "oidc_client_id", "oidc_discovery_url"),+ [+ (+ "OIDC_CLIENT_ID",+ "",+ "https://id.example.com/.well-known/openid-configuration",+ ),+ ("OIDC_DISCOVERY_URL", "securo", ""),+ ],+)+def test_local_auth_disabled_requires_complete_oidc_configuration(+ secrets: Path,+ missing_field: str,+ oidc_client_id: str,+ oidc_discovery_url: str,+):+ with pytest.raises(ValidationError, match=missing_field):+ Settings(+ oidc_enabled=True,+ oidc_client_id=oidc_client_id,+ oidc_discovery_url=oidc_discovery_url,+ local_auth_enabled=False,+ _secrets_dir=str(secrets),+ )diff --git a/backend/tests/test_oidc_auth.py b/backend/tests/test_oidc_auth.pyindex 1f001ecd..a4f11543 100644--- a/backend/tests/test_oidc_auth.py+++ b/backend/tests/test_oidc_auth.py@@ -116,7 +116,22 @@ async def test_decode_id_token_accepts_google_style_at_hash(monkeypatch, oidc_seasync def test_oidc_config_disabled_by_default(client: AsyncClient, clean_db):response = await client.get("/api/auth/oidc/config")assert response.status_code == 200- assert response.json()["enabled"] is False+ data = response.json()+ assert data["enabled"] is False+ assert data["local_auth_enabled"] is True+++async def test_oidc_config_exposes_local_auth_disabled(client: AsyncClient, clean_db, oidc_settings):+ oidc_settings.local_auth_enabled = False++ response = await client.get("/api/auth/oidc/config")++ assert response.status_code == 200+ data = response.json()+ assert data["enabled"] is True+ assert data["provider_name"] == "Pocket ID"+ assert data["local_auth_enabled"] is False@pytest.mark.asynciodiff --git a/backend/tests/test_passkeys.py b/backend/tests/test_passkeys.pyindex 3b81169e..b6cd2b6b 100644--- a/backend/tests/test_passkeys.py+++ b/backend/tests/test_passkeys.py@@ -615,6 +615,85 @@ async def test_register_verify_deletes_challenge_after_failure(assert _passkey_redis_store.store == {}+async def test_passkey_registration_forbidden_when_local_auth_disabled(+ client: AsyncClient,+ auth_headers: dict,+ oidc_only_settings,+):+ options_response = await client.post(+ "/api/auth/passkeys/register/options",+ json={"name": "Key"},+ headers=auth_headers,+ )+ assert options_response.status_code == 403+ assert options_response.json()["detail"] == "LOCAL_AUTH_DISABLED"++ verify_response = await client.post(+ "/api/auth/passkeys/register/verify",+ json={"challenge_id": "missing", "name": "Key", "credential": {}},+ headers=auth_headers,+ )+ assert verify_response.status_code == 403+ assert verify_response.json()["detail"] == "LOCAL_AUTH_DISABLED"+++async def test_delete_passkey_allowed_when_local_auth_disabled(+ client: AsyncClient,+ auth_headers: dict,+ session: AsyncSession,+ test_user,+ oidc_only_settings,+):+ passkey = UserPasskey(+ user_id=test_user.id,+ credential_id="cleanup-credential",+ public_key="cleanup-public-key",+ sign_count=0,+ name="Cleanup key",+ )+ session.add(passkey)+ await session.commit()+ await session.refresh(passkey)++ response = await client.delete(f"/api/auth/passkeys/{passkey.id}", headers=auth_headers)++ assert response.status_code == 204+ result = await session.execute(select(UserPasskey).where(UserPasskey.id == passkey.id))+ assert result.scalar_one_or_none() is None+++async def test_passkey_login_forbidden_when_local_auth_disabled(client: AsyncClient, oidc_only_settings):+ options_response = await client.post(+ "/api/auth/passkeys/authenticate/options",+ json={"email": "[email protected]"},+ )+ assert options_response.status_code == 403+ assert options_response.json()["detail"] == "LOCAL_AUTH_DISABLED"++ verify_response = await client.post(+ "/api/auth/passkeys/authenticate/verify",+ json={"challenge_id": "missing", "credential": {}},+ )+ assert verify_response.status_code == 403+ assert verify_response.json()["detail"] == "LOCAL_AUTH_DISABLED"+++async def test_passkey_second_factor_forbidden_when_local_auth_disabled(client: AsyncClient, oidc_only_settings):+ options_response = await client.post(+ "/api/auth/passkeys/2fa/options",+ json={"temp_token": "missing"},+ )+ assert options_response.status_code == 403+ assert options_response.json()["detail"] == "LOCAL_AUTH_DISABLED"++ verify_response = await client.post(+ "/api/auth/passkeys/2fa/verify",+ json={"temp_token": "missing", "challenge_id": "missing", "credential": {}},+ )+ assert verify_response.status_code == 403+ assert verify_response.json()["detail"] == "LOCAL_AUTH_DISABLED"++# --- Relying-party resolution -------------------------------------------------# The RP ID must match the domain the browser is on, or the browser refuses the# credential with a SecurityError. See issues #403 and #410.diff --git a/backend/tests/test_setup_api.py b/backend/tests/test_setup_api.pyindex ce0a5b92..a9879460 100644--- a/backend/tests/test_setup_api.py+++ b/backend/tests/test_setup_api.py@@ -41,6 +41,23 @@ async def test_create_admin_success(client: AsyncClient, clean_db):assert data["token_type"] == "bearer"+async def test_create_admin_forbidden_when_local_auth_disabled(+ client: AsyncClient,+ clean_db,+ oidc_only_settings,+):+ response = await client.post(+ "/api/setup/create-admin",+ json={"email": "[email protected]", "password": "StrongPass123!"},+ )++ assert response.status_code == 403+ assert response.json()["detail"] == "LOCAL_AUTH_DISABLED"+ status_response = await client.get("/api/setup/status")+ assert status_response.json()["has_users"] is False++@pytest.mark.asyncioasync def test_create_admin_already_exists(client: AsyncClient, test_user):"""Create admin fails when users already exist."""diff --git a/backend/tests/test_two_factor.py b/backend/tests/test_two_factor.pyindex 0dad6918..b9e9df9b 100644--- a/backend/tests/test_two_factor.py+++ b/backend/tests/test_two_factor.py@@ -6,6 +6,7 @@ import pytestfrom httpx import AsyncClientfrom app.api.two_factor import _verify_totp+from app.core.auth import get_jwt_strategydef _make_redis_mock_with_store():@@ -58,6 +59,47 @@ async def test_setup_2fa(client: AsyncClient, auth_headers: dict):assert "otpauth://totp/" in data["otpauth_uri"][email protected]("path", ["/api/auth/2fa/setup", "/api/auth/2fa/enable"])+async def test_totp_enrollment_forbidden_when_local_auth_disabled(+ client: AsyncClient,+ test_user,+ oidc_only_settings,+ path: str,+):+ token = await get_jwt_strategy().write_token(test_user)+ response = await client.post(+ path,+ json={"code": "123456"} if path.endswith("/enable") else None,+ headers={"Authorization": f"Bearer {token}"},+ )++ assert response.status_code == 403+ assert response.json()["detail"] == "LOCAL_AUTH_DISABLED"+++async def test_disable_2fa_allowed_for_cleanup_when_local_auth_disabled(+ client: AsyncClient,+ test_user,+ session,+ oidc_only_settings,+):+ secret = pyotp.random_base32()+ test_user.totp_secret = secret+ test_user.is_2fa_enabled = True+ session.add(test_user)+ await session.commit()++ token = await get_jwt_strategy().write_token(test_user)+ response = await client.post(+ "/api/auth/2fa/disable",+ json={"password": "testpass123", "code": pyotp.TOTP(secret).now()},+ headers={"Authorization": f"Bearer {token}"},+ )++ assert response.status_code == 200+ assert response.json()["detail"] == "2FA disabled"++async def test_enable_2fa(client: AsyncClient, auth_headers: dict, test_user):# First setupsetup_resp = await client.post("/api/auth/2fa/setup", headers=auth_headers)diff --git a/backend/tests/test_workspaces_api_coverage.py b/backend/tests/test_workspaces_api_coverage.pyindex f1a0136b..4cbcabf2 100644--- a/backend/tests/test_workspaces_api_coverage.py+++ b/backend/tests/test_workspaces_api_coverage.py@@ -8,6 +8,8 @@ import uuidimport pytestfrom httpx import AsyncClient+from app.core.auth import get_jwt_strategy+# ---------------------------------------------------------------------------# list / create / current@@ -140,6 +142,44 @@ async def test_invite_new_user_member(client: AsyncClient, auth_headers, test_woassert body["role"] == "editor"+async def test_invite_cannot_create_password_user_when_local_auth_disabled(+ client: AsyncClient,+ test_user,+ test_workspace,+ oidc_only_settings,+):+ token = await get_jwt_strategy().write_token(test_user)+ resp = await client.post(+ f"/api/workspaces/{test_workspace.id}/members",+ headers={"Authorization": f"Bearer {token}"},+ json={"email": "[email protected]", "role": "editor", "password": "supersecret123"},+ )++ assert resp.status_code == 403+ assert resp.json()["detail"] == "LOCAL_AUTH_DISABLED"+++async def test_invite_unknown_user_without_password_points_at_oidc_when_local_auth_disabled(+ client: AsyncClient,+ test_user,+ test_workspace,+ oidc_only_settings,+):+ token = await get_jwt_strategy().write_token(test_user)+ resp = await client.post(+ f"/api/workspaces/{test_workspace.id}/members",+ headers={"Authorization": f"Bearer {token}"},+ json={"email": "[email protected]", "role": "editor"},+ )++ assert resp.status_code == 400+ # Asking for a password would be dead-end advice in OIDC-only mode.+ assert "password" not in resp.json()["detail"].lower()+ assert "identity provider" in resp.json()["detail"]++@pytest.mark.asyncioasync def test_invite_unknown_user_without_password_400(client: AsyncClient, auth_headers, test_workspace):resp = await client.post(diff --git a/charts/securo/values.yaml b/charts/securo/values.yamlindex 2a43f209..1e9fb292 100644--- a/charts/securo/values.yaml+++ b/charts/securo/values.yaml@@ -43,6 +43,8 @@ secret:# Non-sensitive configurationconfig:debug: "false"+ # Set false only when oidc.enabled, oidc.clientId, and oidc.discoveryUrl are configured.+ localAuthEnabled: "true"# Leave empty to auto-compute from global.domain (e.g. http://securo.local/oauth/callback)pluggyOauthRedirectUri: ""enableBankingApiUrl: "https://api.enablebanking.com"diff --git a/docker-compose.prod.yml b/docker-compose.prod.ymlindex 96ad9c71..9617e37b 100644--- a/docker-compose.prod.yml+++ b/docker-compose.prod.yml@@ -35,6 +35,7 @@ x-backend-env: &backend-envOIDC_ROLES_CLAIM: ${OIDC_ROLES_CLAIM:-groups}OIDC_ADMIN_ROLES: ${OIDC_ADMIN_ROLES:-}OIDC_WORKSPACE_ROLE_MAP: ${OIDC_WORKSPACE_ROLE_MAP:-}+ LOCAL_AUTH_ENABLED: ${LOCAL_AUTH_ENABLED:-true}OPENEXCHANGERATES_APP_ID: ${OPENEXCHANGERATES_APP_ID:-}FX_SYNC_MODE: ${FX_SYNC_MODE:-on_demand}TESOURO_DIRETO_ENABLED: ${TESOURO_DIRETO_ENABLED:-true}diff --git a/docker-compose.yml b/docker-compose.ymlindex dc438cd4..91e37417 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -38,6 +38,7 @@ x-backend-env: &backend-envOIDC_ROLES_CLAIM: ${OIDC_ROLES_CLAIM:-groups}OIDC_ADMIN_ROLES: ${OIDC_ADMIN_ROLES:-}OIDC_WORKSPACE_ROLE_MAP: ${OIDC_WORKSPACE_ROLE_MAP:-}+ LOCAL_AUTH_ENABLED: ${LOCAL_AUTH_ENABLED:-true}REDIS_URL: redis://redis:6379/0OPENEXCHANGERATES_APP_ID: ${OPENEXCHANGERATES_APP_ID:-}FX_SYNC_MODE: ${FX_SYNC_MODE:-on_demand}diff --git a/frontend/src/components/app-layout.tsx b/frontend/src/components/app-layout.tsxindex 6f16dc09..c5cd7f5a 100644--- a/frontend/src/components/app-layout.tsx+++ b/frontend/src/components/app-layout.tsx@@ -60,6 +60,7 @@ import { GlobalChatPanel } from '@/components/global-chat-panel'import { useFeatureFlags } from '@/hooks/use-feature-flags'import { Bot, Search, Sparkles } from 'lucide-react'import { setThemeBasedOnSystem } from '@/lib/theme-utils'+import { useLocalAuthEnabled } from '@/hooks/use-local-auth'import { formatCurrency } from '@/lib/format'/** Placeholder rows shown while the workspace's module list is in flight. */@@ -116,6 +117,7 @@ export function AppLayout() {// read-only session only exposes the reading ones; then this becomes// `agentsEnabled` again.const chatAvailable = agentsEnabled && canWrite+ const localAuthEnabled = useLocalAuthEnabled()// ⌘J / Ctrl+J toggles the global slide-over chat from anywhere.// Distinct from ⌘K (command palette) so users can have both open.@@ -259,6 +261,7 @@ export function AppLayout() {onChangePassword={() => setChangePasswordOpen(true)}onTwoFactor={() => setTwoFactorOpen(true)}onPasskeys={() => setPasskeysOpen(true)}+ localAuthEnabled={localAuthEnabled}agentsEnabled={agentsEnabled}onBackup={() => setBackupOpen(true)}dark@@ -493,6 +496,7 @@ export function AppLayout() {onChangePassword={() => setChangePasswordOpen(true)}onTwoFactor={() => setTwoFactorOpen(true)}onPasskeys={() => setPasskeysOpen(true)}+ localAuthEnabled={localAuthEnabled}onBackup={() => setBackupOpen(true)}onUpdateAvailable={() => setUpdateDialogOpen(true)}agentsEnabled={agentsEnabled}@@ -524,19 +528,23 @@ export function AppLayout() {</div>{showTour && <OnboardingTour onComplete={handleTourComplete} />}- <ChangePasswordDialog- open={changePasswordOpen}- onClose={() => setChangePasswordOpen(false)}- />+ {localAuthEnabled && (+ <>+ <ChangePasswordDialog+ open={changePasswordOpen}+ onClose={() => setChangePasswordOpen(false)}+ />+ <TwoFactorSetup+ open={twoFactorOpen}+ onClose={() => setTwoFactorOpen(false)}+ />+ <PasskeyManagementDialog+ open={passkeysOpen}+ onClose={() => setPasskeysOpen(false)}+ />+ </>+ )}<BackupDialog open={backupOpen} onClose={() => setBackupOpen(false)} />- <TwoFactorSetup- open={twoFactorOpen}- onClose={() => setTwoFactorOpen(false)}- />- <PasskeyManagementDialog- open={passkeysOpen}- onClose={() => setPasskeysOpen(false)}- /><CommandPalette open={paletteOpen} onOpenChange={setPaletteOpen} />{/* Slide-over global chat — opened from the sidebar pill or via⌘J. The previous floating bottom-right button was removed@@ -556,6 +564,7 @@ function UserMenu({onChangePassword,onTwoFactor,onPasskeys,+ localAuthEnabled,onBackup,dark,isAdmin,@@ -566,6 +575,7 @@ function UserMenu({onChangePassword: () => voidonTwoFactor: () => voidonPasskeys: () => void+ localAuthEnabled: booleanonBackup: () => voiddark?: booleanisAdmin?: boolean@@ -604,27 +614,31 @@ function UserMenu({<DropdownMenuSeparator /></>)}- <DropdownMenuItem- onClick={onChangePassword}- className="flex items-center gap-2"- >- <KeyRound size={14} />- {t('auth.changePassword')}- </DropdownMenuItem>- <DropdownMenuItem- onClick={onTwoFactor}- className="flex items-center gap-2"- >- <ShieldCheck size={14} />- {t('auth.twoFactorTitle')}- </DropdownMenuItem>- <DropdownMenuItem- onClick={onPasskeys}- className="flex items-center gap-2"- >- <Fingerprint size={14} />- {t('auth.passkeysTitle')}- </DropdownMenuItem>+ {localAuthEnabled && (+ <>+ <DropdownMenuItem+ onClick={onChangePassword}+ className="flex items-center gap-2"+ >+ <KeyRound size={14} />+ {t('auth.changePassword')}+ </DropdownMenuItem>+ <DropdownMenuItem+ onClick={onTwoFactor}+ className="flex items-center gap-2"+ >+ <ShieldCheck size={14} />+ {t('auth.twoFactorTitle')}+ </DropdownMenuItem>+ <DropdownMenuItem+ onClick={onPasskeys}+ className="flex items-center gap-2"+ >+ <Fingerprint size={14} />+ {t('auth.passkeysTitle')}+ </DropdownMenuItem>+ </>+ )}<DropdownMenuItemonClick={onBackup}className="flex items-center gap-2"diff --git a/frontend/src/components/workspace-switcher.tsx b/frontend/src/components/workspace-switcher.tsxindex 4405a0e9..9187e555 100644--- a/frontend/src/components/workspace-switcher.tsx+++ b/frontend/src/components/workspace-switcher.tsx@@ -83,6 +83,8 @@ interface AccountMenuProps {onUpdateAvailable: () => void/** True when the AGENTS_ENABLED env flag is on. */agentsEnabled: boolean+ /** True when local password/passkey auth is enabled. */+ localAuthEnabled: boolean}/**@@ -101,6 +103,7 @@ export function WorkspaceSwitcher({onBackup,onUpdateAvailable,agentsEnabled,+ localAuthEnabled,}: AccountMenuProps) {const { t, i18n } = useTranslation()const navigate = useNavigate()@@ -230,27 +233,31 @@ export function WorkspaceSwitcher({)}{/* Account actions */}- <DropdownMenuItem- onClick={onChangePassword}- className="flex items-center gap-2"- >- <KeyRound size={14} />- {t('auth.changePassword')}- </DropdownMenuItem>- <DropdownMenuItem- onClick={onTwoFactor}- className="flex items-center gap-2"- >- <ShieldCheck size={14} />- {t('auth.twoFactorTitle')}- </DropdownMenuItem>- <DropdownMenuItem- onClick={onPasskeys}- className="flex items-center gap-2"- >- <Fingerprint size={14} />- {t('auth.passkeysTitle')}- </DropdownMenuItem>+ {localAuthEnabled && (+ <>+ <DropdownMenuItem+ onClick={onChangePassword}+ className="flex items-center gap-2"+ >+ <KeyRound size={14} />+ {t('auth.changePassword')}+ </DropdownMenuItem>+ <DropdownMenuItem+ onClick={onTwoFactor}+ className="flex items-center gap-2"+ >+ <ShieldCheck size={14} />+ {t('auth.twoFactorTitle')}+ </DropdownMenuItem>+ <DropdownMenuItem+ onClick={onPasskeys}+ className="flex items-center gap-2"+ >+ <Fingerprint size={14} />+ {t('auth.passkeysTitle')}+ </DropdownMenuItem>+ </>+ )}<DropdownMenuItemonClick={onBackup}className="flex items-center gap-2"diff --git a/frontend/src/hooks/use-local-auth.ts b/frontend/src/hooks/use-local-auth.tsnew file mode 100644index 00000000..63733c1c--- /dev/null+++ b/frontend/src/hooks/use-local-auth.ts@@ -0,0 +1,25 @@+import { useQuery } from '@tanstack/react-query'+import { auth as authApi } from '@/lib/api'+import { resolveLocalAuthEnabled } from '@/lib/auth-config-utils'++/**+ * Whether the screens that expose local credential controls (change password,+ * 2FA, passkeys, password-backed invites) should render them.+ *+ * `retry` and `networkMode` are pinned here on purpose. With the defaults a+ * failing request does not settle on `isError`: the retry can be parked, so the+ * query sits in `pending` and the controls stay hidden for as long as that+ * lasts. Failing once and settling immediately is what makes the fallback in+ * `resolveLocalAuthEnabled` actually reachable. The backend stays authoritative+ * either way and still rejects local auth in OIDC-only mode.+ */+export function useLocalAuthEnabled(): boolean {+ const { data, isError } = useQuery({+ queryKey: ['auth', 'oidc-config'],+ queryFn: authApi.oidcConfig,+ staleTime: 60_000,+ retry: false,+ networkMode: 'always',+ })+ return resolveLocalAuthEnabled(data, isError)+}diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 931cb754..fc64deb0 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -262,8 +262,11 @@ export const auth = {})return data},- oidcConfig: async (): Promise<{ enabled: boolean; provider_name: string }> => {- const { data } = await api.get('/auth/oidc/config')+ oidcConfig: async (): Promise<{ enabled: boolean; provider_name: string; local_auth_enabled: boolean }> => {+ // The login card blocks on this call while it decides which sign-in+ // methods to offer, so a hung request must fail fast and let the caller+ // fall back instead of leaving the page stuck on its loading state.+ const { data } = await api.get('/auth/oidc/config', { timeout: 5000 })return data},}diff --git a/frontend/src/lib/auth-config-utils.test.ts b/frontend/src/lib/auth-config-utils.test.tsnew file mode 100644index 00000000..364fbdc2--- /dev/null+++ b/frontend/src/lib/auth-config-utils.test.ts@@ -0,0 +1,22 @@+import { describe, expect, it } from 'vitest'++import { resolveLocalAuthEnabled } from './auth-config-utils'++describe('resolveLocalAuthEnabled', () => {+ it('hides local controls while configuration is pending', () => {+ expect(resolveLocalAuthEnabled(null, false)).toBe(false)+ })++ it('uses a successfully loaded server policy', () => {+ expect(resolveLocalAuthEnabled({ local_auth_enabled: false }, false)).toBe(false)+ expect(resolveLocalAuthEnabled({ local_auth_enabled: true }, false)).toBe(true)+ })++ it('falls back to local controls when the config request fails', () => {+ expect(resolveLocalAuthEnabled(null, true)).toBe(true)+ })++ it('never lets an error override a loaded OIDC-only policy', () => {+ expect(resolveLocalAuthEnabled({ local_auth_enabled: false }, true)).toBe(false)+ })+})diff --git a/frontend/src/lib/auth-config-utils.ts b/frontend/src/lib/auth-config-utils.tsnew file mode 100644index 00000000..8196399b--- /dev/null+++ b/frontend/src/lib/auth-config-utils.ts@@ -0,0 +1,15 @@+export type LocalAuthConfig = {+ local_auth_enabled: boolean+}++/**+ * Hide local credential controls while configuration is unresolved, but+ * preserve access when the optional OIDC-config request itself fails. The+ * backend remains authoritative and rejects local auth in OIDC-only mode.+ */+export function resolveLocalAuthEnabled(+ config: LocalAuthConfig | null | undefined,+ configFailed: boolean,+): boolean {+ return config?.local_auth_enabled ?? configFailed+}diff --git a/frontend/src/locales/de.json b/frontend/src/locales/de.jsonindex 03f7e025..287a866c 100644--- a/frontend/src/locales/de.json+++ b/frontend/src/locales/de.json@@ -17,6 +17,7 @@"addMember": "Mitglied hinzufügen","addMemberTitle": "Mitglied hinzufügen","addMemberDescription": "Lade einen bestehenden Benutzer per E-Mail ein oder erstelle ein neues Konto durch Angabe eines Passworts.",+ "addMemberDescriptionExistingOnly": "Lade eine vorhandene Person per E-Mail ein.","role": "Rolle","roleOwner": "Besitzer","roleEditor": "Editor",@@ -167,6 +168,8 @@"loginDescription": "Melde dich an, um auf dein Konto zuzugreifen","invalidCredentials": "Ungültige E-Mail-Adresse oder Passwort","serverError": "Verbindung zum Server fehlgeschlagen. Überprüfe deine Verbindung oder ob das Backend läuft und versuche es erneut.",+ "authConfigUnavailable": "Die Authentifizierungsoptionen konnten nicht geladen werden. Die lokale Anmeldung bleibt verfügbar; der Server erzwingt die konfigurierte Richtlinie.",+ "noAuthMethodConfigured": "Es ist keine Authentifizierungsmethode konfiguriert. Wende dich an den Administrator und prüfe die OIDC-Einstellungen.","noAccount": "Noch kein Konto?","hasAccount": "Bereits ein Konto?","changePassword": "Passwort ändern",diff --git a/frontend/src/locales/en.json b/frontend/src/locales/en.jsonindex f6cf83bc..0d9c698e 100644--- a/frontend/src/locales/en.json+++ b/frontend/src/locales/en.json@@ -17,6 +17,7 @@"addMember": "Add member","addMemberTitle": "Add member","addMemberDescription": "Invite an existing user by email, or create a new account by providing a password.",+ "addMemberDescriptionExistingOnly": "Invite an existing user by email.","role": "Role","roleOwner": "Owner","roleEditor": "Editor",@@ -167,6 +168,8 @@"loginDescription": "Sign in to access your account","invalidCredentials": "Invalid email or password","serverError": "Couldn't connect to the server. Check your connection or that the backend is running, then try again.",+ "authConfigUnavailable": "Authentication options could not be loaded. Local login remains available; the server will enforce its configured policy.",+ "noAuthMethodConfigured": "No authentication method is configured. Contact the administrator and check the OIDC settings.","noAccount": "Don't have an account?","hasAccount": "Already have an account?","changePassword": "Change password",diff --git a/frontend/src/locales/es.json b/frontend/src/locales/es.jsonindex 0e0a78e9..e34f7f9c 100644--- a/frontend/src/locales/es.json+++ b/frontend/src/locales/es.json@@ -17,6 +17,7 @@"addMember": "Añadir miembro","addMemberTitle": "Añadir miembro","addMemberDescription": "Invita a un usuario existente por correo, o crea una cuenta nueva proporcionando una contraseña.",+ "addMemberDescriptionExistingOnly": "Invita por correo a un usuario existente.","role": "Rol","roleOwner": "Propietario","roleEditor": "Editor",@@ -167,6 +168,8 @@"loginDescription": "Inicia sesión para acceder a tu cuenta","invalidCredentials": "Correo o contraseña inválidos","serverError": "No se pudo conectar con el servidor. Comprueba tu conexión o que el backend esté en ejecución e inténtalo de nuevo.",+ "authConfigUnavailable": "No se pudieron cargar las opciones de autenticación. El inicio de sesión local sigue disponible; el servidor aplicará la política configurada.",+ "noAuthMethodConfigured": "No hay ningún método de autenticación configurado. Contacta con el administrador y revisa la configuración de OIDC.","noAccount": "¿No tienes una cuenta?","hasAccount": "¿Ya tienes una cuenta?","changePassword": "Cambiar contraseña",diff --git a/frontend/src/locales/fr.json b/frontend/src/locales/fr.jsonindex be9f8b0d..349a66c7 100644--- a/frontend/src/locales/fr.json+++ b/frontend/src/locales/fr.json@@ -17,6 +17,7 @@"addMember": "Ajouter un membre","addMemberTitle": "Ajouter un membre","addMemberDescription": "Invitez un utilisateur existant par e-mail, ou créez un nouveau compte en fournissant un mot de passe.",+ "addMemberDescriptionExistingOnly": "Invitez un utilisateur existant par e-mail.","role": "Rôle","roleOwner": "Propriétaire","roleEditor": "Éditeur",@@ -167,6 +168,8 @@"loginDescription": "Connectez-vous pour accéder à votre compte","invalidCredentials": "E-mail ou mot de passe invalide","serverError": "Impossible de se connecter au serveur. Vérifiez votre connexion ou que le backend est en cours d'exécution, puis réessayez.",+ "authConfigUnavailable": "Les options d’authentification n’ont pas pu être chargées. La connexion locale reste disponible ; le serveur appliquera la politique configurée.",+ "noAuthMethodConfigured": "Aucune méthode d’authentification n’est configurée. Contactez l’administrateur et vérifiez les paramètres OIDC.","noAccount": "Vous n'avez pas de compte ?","hasAccount": "Vous avez déjà un compte ?","changePassword": "Changer le mot de passe",diff --git a/frontend/src/locales/it.json b/frontend/src/locales/it.jsonindex ca2ffc7d..130cf029 100644--- a/frontend/src/locales/it.json+++ b/frontend/src/locales/it.json@@ -17,6 +17,7 @@"addMember": "Aggiungi membro","addMemberTitle": "Aggiungi membro","addMemberDescription": "Invita un utente esistente tramite email, oppure crea un nuovo account fornendo una password.",+ "addMemberDescriptionExistingOnly": "Invita un utente esistente tramite e-mail.","role": "Ruolo","roleOwner": "Proprietario","roleEditor": "Editore",@@ -167,6 +168,8 @@"loginDescription": "Accedi per usare il tuo account","invalidCredentials": "Email o password non validi","serverError": "Impossibile connettersi al server. Controlla la connessione o che il backend sia in esecuzione e riprova.",+ "authConfigUnavailable": "Impossibile caricare le opzioni di autenticazione. L’accesso locale resta disponibile; il server applicherà la configurazione prevista.",+ "noAuthMethodConfigured": "Non è configurato alcun metodo di autenticazione. Contatta l’amministratore e verifica le impostazioni OIDC.","noAccount": "Non hai un account?","hasAccount": "Hai già un account?","changePassword": "Cambia password",diff --git a/frontend/src/locales/pl.json b/frontend/src/locales/pl.jsonindex b27ce366..d3217edf 100644--- a/frontend/src/locales/pl.json+++ b/frontend/src/locales/pl.json@@ -17,6 +17,7 @@"addMember": "Dodaj członka","addMemberTitle": "Dodaj członka","addMemberDescription": "Zaproś istniejącego użytkownika przez e-mail albo utwórz nowe konto, podając hasło.",+ "addMemberDescriptionExistingOnly": "Zaproś istniejącego użytkownika przez e-mail.","role": "Rola","roleOwner": "Właściciel","roleEditor": "Edytor",@@ -167,6 +168,8 @@"loginDescription": "Zaloguj się, aby uzyskać dostęp do konta","invalidCredentials": "Nieprawidłowy e-mail lub hasło","serverError": "Nie można połączyć się z serwerem. Sprawdź połączenie lub czy backend działa, a następnie spróbuj ponownie.",+ "authConfigUnavailable": "Nie udało się wczytać opcji uwierzytelniania. Logowanie lokalne pozostaje dostępne; serwer zastosuje skonfigurowane zasady.",+ "noAuthMethodConfigured": "Nie skonfigurowano żadnej metody uwierzytelniania. Skontaktuj się z administratorem i sprawdź ustawienia OIDC.","noAccount": "Nie masz konta?","hasAccount": "Masz już konto?","changePassword": "Zmień hasło",diff --git a/frontend/src/locales/pt-BR.json b/frontend/src/locales/pt-BR.jsonindex 187645be..5564ca1a 100644--- a/frontend/src/locales/pt-BR.json+++ b/frontend/src/locales/pt-BR.json@@ -17,6 +17,7 @@"addMember": "Adicionar membro","addMemberTitle": "Adicionar membro","addMemberDescription": "Convide um usuário existente por email, ou crie uma nova conta fornecendo uma senha.",+ "addMemberDescriptionExistingOnly": "Convide um usuário existente pelo e-mail.","role": "Papel","roleOwner": "Dono","roleEditor": "Editor",@@ -167,6 +168,8 @@"loginDescription": "Entre para acessar sua conta","invalidCredentials": "E-mail ou senha incorretos","serverError": "Não foi possível conectar ao servidor. Verifique sua conexão ou se o backend está em execução e tente novamente.",+ "authConfigUnavailable": "Não foi possível carregar as opções de autenticação. O login local continua disponível; o servidor aplicará a política configurada.",+ "noAuthMethodConfigured": "Nenhum método de autenticação está configurado. Entre em contato com o administrador e verifique as configurações do OIDC.","noAccount": "Não tem uma conta?","hasAccount": "Já tem uma conta?","changePassword": "Alterar senha",diff --git a/frontend/src/locales/pt-PT.json b/frontend/src/locales/pt-PT.jsonindex 72a64526..3ec00066 100644--- a/frontend/src/locales/pt-PT.json+++ b/frontend/src/locales/pt-PT.json@@ -17,6 +17,7 @@"addMember": "Adicionar membro","addMemberTitle": "Adicionar membro","addMemberDescription": "Convida um utilizador existente através do e-mail ou cria uma nova conta ao definir uma palavra-passe.",+ "addMemberDescriptionExistingOnly": "Convide um utilizador existente pelo e-mail.","role": "Função","roleOwner": "Proprietário","roleEditor": "Editor",@@ -167,6 +168,8 @@"loginDescription": "Inicia sessão para aceder à tua conta","invalidCredentials": "E-mail ou palavra-passe incorretos","serverError": "Não foi possível ligar ao servidor. Verifica a tua ligação ou confirma que o backend está em execução e tenta novamente.",+ "authConfigUnavailable": "Não foi possível carregar as opções de autenticação. O início de sessão local continua disponível; o servidor aplicará a política configurada.",+ "noAuthMethodConfigured": "Não está configurado nenhum método de autenticação. Contacta o administrador e verifica as definições de OIDC.","noAccount": "Ainda não tens conta?","hasAccount": "Já tens conta?","changePassword": "Alterar palavra-passe",diff --git a/frontend/src/locales/ru.json b/frontend/src/locales/ru.jsonindex e0758faa..5c3bb8a9 100644--- a/frontend/src/locales/ru.json+++ b/frontend/src/locales/ru.json@@ -17,6 +17,7 @@"addMember": "Добавить участника","addMemberTitle": "Добавить участника","addMemberDescription": "Пригласите существующего пользователя по email или создайте новую учётную запись, указав пароль.",+ "addMemberDescriptionExistingOnly": "Пригласите существующего пользователя по электронной почте.","role": "Роль","roleOwner": "Владелец","roleEditor": "Редактор",@@ -167,6 +168,8 @@"loginDescription": "Войдите, чтобы получить доступ к аккаунту","invalidCredentials": "Неверный email или пароль","serverError": "Не удалось подключиться к серверу. Проверьте соединение или работу бэкенда, затем повторите попытку.",+ "authConfigUnavailable": "Не удалось загрузить параметры аутентификации. Локальный вход остаётся доступным; сервер применит настроенную политику.",+ "noAuthMethodConfigured": "Не настроен ни один способ аутентификации. Обратитесь к администратору и проверьте настройки OIDC.","noAccount": "Нет аккаунта?","hasAccount": "Уже есть аккаунт?","changePassword": "Изменить пароль",diff --git a/frontend/src/locales/uk.json b/frontend/src/locales/uk.jsonindex 4c4722a7..d3936d76 100644--- a/frontend/src/locales/uk.json+++ b/frontend/src/locales/uk.json@@ -17,6 +17,7 @@"addMember": "Додати учасника","addMemberTitle": "Додати учасника","addMemberDescription": "Запросіть наявного користувача за email або створіть новий обліковий запис, вказавши пароль.",+ "addMemberDescriptionExistingOnly": "Запросіть наявного користувача за електронною поштою.","role": "Роль","roleOwner": "Власник","roleEditor": "Редактор",@@ -167,6 +168,8 @@"loginDescription": "Увійдіть, щоб отримати доступ до акаунта","invalidCredentials": "Невірний email або пароль","serverError": "Не вдалося підключитися до сервера. Перевірте з'єднання або роботу бекенду, потім повторіть спробу.",+ "authConfigUnavailable": "Не вдалося завантажити параметри автентифікації. Локальний вхід залишається доступним; сервер застосує налаштовану політику.",+ "noAuthMethodConfigured": "Не налаштовано жодного способу автентифікації. Зверніться до адміністратора та перевірте налаштування OIDC.","noAccount": "Немає акаунта?","hasAccount": "Уже є акаунт?","changePassword": "Змінити пароль",diff --git a/frontend/src/pages/admin/settings.tsx b/frontend/src/pages/admin/settings.tsxindex 3bf9187a..e8ae5a9c 100644--- a/frontend/src/pages/admin/settings.tsx+++ b/frontend/src/pages/admin/settings.tsx@@ -30,6 +30,7 @@ import {} from '@/components/ui/select'import { PageHeader } from '@/components/page-header'import { setThemeBasedOnSystem } from '@/lib/theme-utils'+import { useLocalAuthEnabled } from '@/hooks/use-local-auth'import { Search, Plus, Trash2, Shield, ShieldOff, UserCog, Users, Scale, Tag, Palette, Save, Hash, CalendarDays } from 'lucide-react'import type { AdminUser } from '@/types'@@ -65,6 +66,7 @@ export default function AdminSettingsPage() {queryKey: ['admin', 'users', search],queryFn: () => adminApi.listUsers({ search: search || undefined }),})+ const localAuthEnabled = useLocalAuthEnabled()const createMutation = useMutation({mutationFn: (data: { email: string; password: string; is_superuser: boolean; preferences: Record<string, unknown> }) =>@@ -282,10 +284,12 @@ export default function AdminSettingsPage() {section={t('nav.groupAdmin')}title={t('admin.settings.title')}action={- <Button onClick={() => { resetCreateForm(); setCreateOpen(true) }}>- <Plus size={16} className="mr-1.5" />- {t('admin.users.add')}- </Button>+ localAuthEnabled ? (+ <Button onClick={() => { resetCreateForm(); setCreateOpen(true) }}>+ <Plus size={16} className="mr-1.5" />+ {t('admin.users.add')}+ </Button>+ ) : undefined}/>@@ -741,7 +745,7 @@ export default function AdminSettingsPage() {<Label className="text-[13px]">{t('admin.users.email')}</Label><Input type="email" value={editEmail} onChange={(e) => setEditEmail(e.target.value)} required autoComplete="off" className="h-10 rounded-lg" /></div>- {showPasswordField ? (+ {localAuthEnabled && (showPasswordField ? (<div className="space-y-1.5"><Label className="text-[13px]">{t('admin.users.resetPassword')}</Label><Input@@ -765,7 +769,7 @@ export default function AdminSettingsPage() {>{t('admin.users.resetPassword')}</Button>- )}+ ))}<div className="flex items-center gap-2"><buttondiff --git a/frontend/src/pages/login.tsx b/frontend/src/pages/login.tsxindex 05c36d09..f01ddd6a 100644--- a/frontend/src/pages/login.tsx+++ b/frontend/src/pages/login.tsx@@ -10,6 +10,7 @@ import { Card, CardContent, CardFooter } from '@/components/ui/card'import { ShellLogo } from '@/components/shell-logo'import type { AxiosError } from 'axios'import { isServerUnreachable } from '@/lib/auth-errors'+import { resolveLocalAuthEnabled } from '@/lib/auth-config-utils'import { useTheme } from 'next-themes'import { setThemeBasedOnSystem } from '@/lib/theme-utils'import { isPasskeySupported, passkeyFailure, startPasskeyAuthentication } from '@/lib/webauthn'@@ -26,6 +27,12 @@ const PASSKEY_LOGIN_FAILURE_KEYS: Record<PasskeyFailure, string> = {unknown: 'auth.passkeyLoginError',}+type OIDCConfig = {+ enabled: boolean+ provider_name: string+ local_auth_enabled: boolean+}+export default function LoginPage() {const { t } = useTranslation()const { login, verify2fa, loginWithToken, token } = useAuth()@@ -38,7 +45,8 @@ export default function LoginPage() {const [isPasskeyLoading, setIsPasskeyLoading] = useState(false)const [passkeySupported, setPasskeySupported] = useState(false)const [registrationEnabled, setRegistrationEnabled] = useState(true)- const [oidcConfig, setOidcConfig] = useState<{ enabled: boolean; provider_name: string }>({ enabled: false, provider_name: 'OIDC' })+ const [oidcConfig, setOidcConfig] = useState<OIDCConfig | null>(null)+ const [oidcConfigFailed, setOidcConfigFailed] = useState(false)// 2FA stateconst [requires2fa, setRequires2fa] = useState(false)@@ -53,20 +61,39 @@ export default function LoginPage() {navigate('/', { replace: true })return}- setup.status().then(({ has_users }) => {- if (!has_users) {- navigate('/setup', { replace: true })- }- }).catch(() => {})adminApi.registrationStatus().then(({ enabled }) => {setRegistrationEnabled(enabled)}).catch(() => {})- authApi.oidcConfig().then(setOidcConfig).catch(() => {})+ authApi.oidcConfig()+ .then((config) => {+ setOidcConfig(config)+ setOidcConfigFailed(false)+ })+ .catch(() => setOidcConfigFailed(true))adminApi.defaultColors().then(({ light, dark }) => {setThemeBasedOnSystem(light, dark, resolvedTheme)}).catch(() => {})}, [navigate, token, resolvedTheme])+ useEffect(() => {+ if (token || (oidcConfig === null && !oidcConfigFailed)) return++ let active = true+ setup.status().then(({ has_users }) => {+ if (+ active &&+ !has_users &&+ resolveLocalAuthEnabled(oidcConfig, oidcConfigFailed)+ ) {+ navigate('/setup', { replace: true })+ }+ }).catch(() => {})++ return () => {+ active = false+ }+ }, [navigate, oidcConfig, oidcConfigFailed, token])+const handleSubmit = async (e: React.FormEvent) => {e.preventDefault()setError('')@@ -181,6 +208,13 @@ export default function LoginPage() {}}+ const localAuthEnabled = resolveLocalAuthEnabled(oidcConfig, oidcConfigFailed)+ const oidcEnabled = oidcConfig?.enabled === true+ const authConfigLoading = oidcConfig === null && !oidcConfigFailed+ const noAuthMethodConfigured = oidcConfig !== null && !localAuthEnabled && !oidcEnabled+ const showPasskeyLogin = localAuthEnabled && passkeySupported+ const showAuthDivider = localAuthEnabled && (showPasskeyLogin || oidcEnabled)+if (requires2fa) {return (<div className="flex flex-col items-center justify-center min-h-screen bg-background px-4">@@ -291,70 +325,100 @@ export default function LoginPage() {<h1 className="text-xl font-semibold tracking-tight">{t('auth.login')}</h1><p className="text-sm text-muted-foreground mt-1">{t('auth.loginDescription')}</p></div>- <CardContent className="space-y-4 px-8 pt-4">- {error && (- <div className="p-3 text-sm text-destructive bg-destructive/10 rounded-lg">- {error}+ {authConfigLoading && (+ <CardContent className="px-8 py-6 text-center text-sm text-muted-foreground" role="status">+ {t('common.loading')}+ </CardContent>+ )}+ {oidcConfigFailed && (+ <CardContent className="px-8 py-4">+ <div role="alert" className="p-3 text-sm text-muted-foreground bg-muted rounded-lg">+ {t('auth.authConfigUnavailable')}</div>- )}- <div className="space-y-1.5">- <Label htmlFor="email" className="text-sm">{t('auth.email')}</Label>- <Input- id="email"- type="email"- value={email}- onChange={(e) => setEmail(e.target.value)}- placeholder="[email protected]"- required- />- </div>- <div className="space-y-1.5">- <Label htmlFor="password" className="text-sm">{t('auth.password')}</Label>- <Input- id="password"- type="password"- value={password}- onChange={(e) => setPassword(e.target.value)}- required- />- </div>- </CardContent>- <CardFooter className="flex flex-col gap-4 px-8 pb-8 pt-2">- <Button type="submit" className="w-full" disabled={isLoading || isPasskeyLoading}>- {isLoading ? t('common.loading') : t('auth.login')}- </Button>- {(passkeySupported || oidcConfig.enabled) && (- <div className="flex items-center gap-3 w-full">- <div className="h-px flex-1 bg-border" />- <span className="text-xs text-muted-foreground">{t('auth.or')}</span>- <div className="h-px flex-1 bg-border" />+ </CardContent>+ )}+ {noAuthMethodConfigured && (+ <CardContent className="px-8 py-4">+ <div role="alert" className="p-3 text-sm text-destructive bg-destructive/10 rounded-lg">+ {t('auth.noAuthMethodConfigured')}</div>- )}- {passkeySupported && (- <Button- type="button"- variant="outline"- className="w-full"- onClick={handlePasskeyLogin}- disabled={isLoading || isPasskeyLoading}- >- {isPasskeyLoading ? t('common.loading') : t('auth.loginWithPasskey')}- </Button>- )}- {oidcConfig.enabled && (- <Button type="button" variant="outline" className="w-full" onClick={handleOIDCLogin}>- {t('auth.loginWithProvider', { provider: oidcConfig.provider_name })}- </Button>- )}- {registrationEnabled && (- <p className="text-sm text-muted-foreground">- {t('auth.noAccount')}{' '}- <Link to="/register" className="text-primary font-medium hover:underline">- {t('auth.register')}- </Link>- </p>- )}- </CardFooter>+ </CardContent>+ )}+ {localAuthEnabled && (+ <CardContent className="space-y-4 px-8 pt-4">+ {error && (+ <div className="p-3 text-sm text-destructive bg-destructive/10 rounded-lg">+ {error}+ </div>+ )}+ <div className="space-y-1.5">+ <Label htmlFor="email" className="text-sm">{t('auth.email')}</Label>+ <Input+ id="email"+ type="email"+ value={email}+ onChange={(e) => setEmail(e.target.value)}+ placeholder="[email protected]"+ required+ />+ </div>+ <div className="space-y-1.5">+ <Label htmlFor="password" className="text-sm">{t('auth.password')}</Label>+ <Input+ id="password"+ type="password"+ value={password}+ onChange={(e) => setPassword(e.target.value)}+ required+ />+ </div>+ </CardContent>+ )}+ {!authConfigLoading && !noAuthMethodConfigured && (+ <CardFooter className={`flex flex-col gap-4 px-8 pb-8 ${localAuthEnabled ? 'pt-2' : 'pt-6'}`}>+ {localAuthEnabled && (+ <Button type="submit" className="w-full" disabled={isLoading || isPasskeyLoading}>+ {isLoading ? t('common.loading') : t('auth.login')}+ </Button>+ )}+ {showAuthDivider && (+ <div className="flex items-center gap-3 w-full">+ <div className="h-px flex-1 bg-border" />+ <span className="text-xs text-muted-foreground">{t('auth.or')}</span>+ <div className="h-px flex-1 bg-border" />+ </div>+ )}+ {showPasskeyLogin && (+ <Button+ type="button"+ variant="outline"+ className="w-full"+ onClick={handlePasskeyLogin}+ disabled={isLoading || isPasskeyLoading}+ >+ {isPasskeyLoading ? t('common.loading') : t('auth.loginWithPasskey')}+ </Button>+ )}+ {oidcEnabled && (+ <Button+ type="button"+ variant={localAuthEnabled ? 'outline' : 'default'}+ className="w-full"+ onClick={handleOIDCLogin}+ >+ {t('auth.loginWithProvider', { provider: oidcConfig?.provider_name ?? 'OIDC' })}+ </Button>+ )}+ {localAuthEnabled && registrationEnabled && (+ <p className="text-sm text-muted-foreground">+ {t('auth.noAccount')}{' '}+ <Link to="/register" className="text-primary font-medium hover:underline">+ {t('auth.register')}+ </Link>+ </p>+ )}+ </CardFooter>+ )}</form></Card></div>diff --git a/frontend/src/pages/register.tsx b/frontend/src/pages/register.tsxindex ca71962e..ad1d9982 100644--- a/frontend/src/pages/register.tsx+++ b/frontend/src/pages/register.tsx@@ -3,7 +3,7 @@ import { Link, useNavigate } from 'react-router-dom'import { useTranslation } from 'react-i18next'import { useTheme } from 'next-themes'import { useAuth } from '@/contexts/auth-context'-import { admin as adminApi } from '@/lib/api'+import { admin as adminApi, auth as authApi } from '@/lib/api'import { resolveSupportedLang } from '@/lib/i18n'import { Button } from '@/components/ui/button'import { Input } from '@/components/ui/input'@@ -26,14 +26,29 @@ export default function RegisterPage() {const [currency, setCurrency] = useState('USD')const [error, setError] = useState('')const [isLoading, setIsLoading] = useState(false)+ const [checking, setChecking] = useState(true)useEffect(() => {- adminApi.registrationStatus().then(({ enabled }) => {- if (!enabled) navigate('/login', { replace: true })- }).catch(() => {})- adminApi.defaultColors().then(({ light, dark }) => {+ let active = true+ Promise.all([+ adminApi.registrationStatus(),+ authApi.oidcConfig().catch(() => null),+ ]).then(([registration, authConfig]) => {+ if (!active) return+ if (!registration.enabled || authConfig?.local_auth_enabled === false) {+ navigate('/login', { replace: true })+ return+ }+ setChecking(false)+ }).catch(() => {+ if (active) setChecking(false)+ })+ adminApi.defaultColors().then(({ light, dark }) => {setThemeBasedOnSystem(light, dark, resolvedTheme)}).catch(() => {})+ return () => {+ active = false+ }}, [navigate, resolvedTheme])const handleSubmit = async (e: React.FormEvent) => {@@ -72,6 +87,14 @@ export default function RegisterPage() {}}+ if (checking) {+ return (+ <div className="flex items-center justify-center min-h-screen">+ <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary" />+ </div>+ )+ }+return (<div className="flex flex-col items-center justify-center min-h-screen bg-background px-4"><Card className="w-full max-w-[400px] shadow-sm">diff --git a/frontend/src/pages/setup.tsx b/frontend/src/pages/setup.tsxindex 6ee2b63a..2277a150 100644--- a/frontend/src/pages/setup.tsx+++ b/frontend/src/pages/setup.tsx@@ -2,7 +2,7 @@ import { useState, useEffect } from 'react'import { useNavigate } from 'react-router-dom'import { useTranslation } from 'react-i18next'import { useTheme } from 'next-themes'-import { setup } from '@/lib/api'+import { setup, auth as authApi } from '@/lib/api'import { resolveSupportedLang, SUPPORTED_LANGS } from '@/lib/i18n'import { useAuth } from '@/contexts/auth-context'import { Button } from '@/components/ui/button'@@ -42,8 +42,11 @@ export default function SetupPage() {navigate('/', { replace: true })return}- setup.status().then(({ has_users }) => {- if (has_users) {+ Promise.all([+ setup.status(),+ authApi.oidcConfig().catch(() => null),+ ]).then(([{ has_users }, authConfig]) => {+ if (has_users || authConfig?.local_auth_enabled === false) {navigate('/login', { replace: true })} else {setChecking(false)diff --git a/frontend/src/pages/workspace-settings.tsx b/frontend/src/pages/workspace-settings.tsxindex b0a84a80..48a6adab 100644--- a/frontend/src/pages/workspace-settings.tsx+++ b/frontend/src/pages/workspace-settings.tsx@@ -7,6 +7,7 @@ import { toast } from 'sonner'import { auth as authApi, currencies as currenciesApi, fiscal as fiscalApi, workspaces as workspacesApi } from '@/lib/api'import { useAuth } from '@/contexts/auth-context'import { useWorkspace } from '@/contexts/workspace-context'+import { useLocalAuthEnabled } from '@/hooks/use-local-auth'import { Button } from '@/components/ui/button'import { Input } from '@/components/ui/input'import { Label } from '@/components/ui/label'@@ -125,6 +126,8 @@ export default function WorkspaceSettingsPage() {staleTime: Infinity,})+ const localAuthEnabled = useLocalAuthEnabled()+// The server lists codes; the user reads names. Sorted by the name actually// shown, in the reader's own collation.const sortedJurisdictions = useMemo(@@ -201,7 +204,7 @@ export default function WorkspaceSettingsPage() {return workspacesApi.invite(current.id, {email: inviteEmail.trim(),role: inviteRole,- password: invitePassword || undefined,+ password: localAuthEnabled ? (invitePassword || undefined) : undefined,})},onSuccess: () => {@@ -610,7 +613,13 @@ export default function WorkspaceSettingsPage() {<DialogContent><DialogHeader><DialogTitle>{t('workspace.addMemberTitle')}</DialogTitle>- <DialogDescription>{t('workspace.addMemberDescription')}</DialogDescription>+ <DialogDescription>+ {t(+ localAuthEnabled+ ? 'workspace.addMemberDescription'+ : 'workspace.addMemberDescriptionExistingOnly',+ )}+ </DialogDescription></DialogHeader><div className="space-y-4 py-1"><div className="space-y-1.5">@@ -644,22 +653,24 @@ export default function WorkspaceSettingsPage() {))}</select></div>- <div className="space-y-1.5">- <Label htmlFor="invite-password" className="text-[13px]">- {t('workspace.passwordForNewUsers')}- </Label>- <Input- id="invite-password"- type="password"- value={invitePassword}- onChange={(e) => setInvitePassword(e.target.value)}- className="h-10 rounded-lg"- placeholder=""- />- <p className="text-[11px] text-muted-foreground leading-relaxed">- {t('workspace.passwordHint')}- </p>- </div>+ {localAuthEnabled && (+ <div className="space-y-1.5">+ <Label htmlFor="invite-password" className="text-[13px]">+ {t('workspace.passwordForNewUsers')}+ </Label>+ <Input+ id="invite-password"+ type="password"+ value={invitePassword}+ onChange={(e) => setInvitePassword(e.target.value)}+ className="h-10 rounded-lg"+ placeholder=""+ />+ <p className="text-[11px] text-muted-foreground leading-relaxed">+ {t('workspace.passwordHint')}+ </p>+ </div>+ )}</div><DialogFooter><Button