#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere
TypeScript dockerhacktoberfestjavapdfpdf-converterpdf-editorpdf-manipulationpdf-mergerpdf-ocrpdf-toolspdf-web-appspdfmergerself-hosted
feat(security): SSO auto-login with password login enabled, bypassable via /login?all (#8486)
EthanHealy0196ee014b99a4
diff --git a/app/core/src/main/java/stirling/software/SPDF/config/CleanUrlInterceptor.java b/app/core/src/main/java/stirling/software/SPDF/config/CleanUrlInterceptor.javaindex 0f934d8034..13f30d43ad 100644--- a/app/core/src/main/java/stirling/software/SPDF/config/CleanUrlInterceptor.java+++ b/app/core/src/main/java/stirling/software/SPDF/config/CleanUrlInterceptor.java@@ -3,7 +3,7 @@ package stirling.software.SPDF.config;import java.net.URI;import java.net.URISyntaxException;import java.util.Arrays;-import java.util.HashMap;+import java.util.LinkedHashMap;import java.util.List;import java.util.Map;@@ -35,7 +35,8 @@ public class CleanUrlInterceptor implements HandlerInterceptor {"startDate","endDate","async",- "session");+ "session",+ "all");@Overridepublic boolean preHandle(@@ -50,7 +51,8 @@ public class CleanUrlInterceptor implements HandlerInterceptor {String queryString = request.getQueryString();if (queryString != null && !queryString.isEmpty()) {- Map<String, String> allowedParameters = new HashMap<>();+ // A null value is a bare flag (?all), which the frontend reads by presence.+ Map<String, String> allowedParameters = new LinkedHashMap<>();// The frontend needs state to bind the SaaS response to the initiating browser.boolean accountLinkCallback =requestURI.equals(request.getContextPath() + "/account-link/callback");@@ -58,13 +60,13 @@ public class CleanUrlInterceptor implements HandlerInterceptor {// Keep only the allowed parametersString[] queryParameters = queryString.split("&");for (String param : queryParameters) {- String[] keyValuePair = param.split("=");- if (keyValuePair.length != 2) {+ String[] keyValuePair = param.split("=", -1);+ if (keyValuePair.length > 2 || keyValuePair[0].isEmpty()) {continue;}- if (ALLOWED_PARAMS.contains(keyValuePair[0])- || (accountLinkCallback && "state".equals(keyValuePair[0]))) {- allowedParameters.put(keyValuePair[0], keyValuePair[1]);+ String key = keyValuePair[0];+ if (ALLOWED_PARAMS.contains(key) || (accountLinkCallback && "state".equals(key))) {+ allowedParameters.put(key, keyValuePair.length == 2 ? keyValuePair[1] : null);}}@@ -76,7 +78,10 @@ public class CleanUrlInterceptor implements HandlerInterceptor {if (!newQueryString.isEmpty()) {newQueryString.append("&");}- newQueryString.append(entry.getKey()).append("=").append(entry.getValue());+ newQueryString.append(entry.getKey());+ if (entry.getValue() != null) {+ newQueryString.append("=").append(entry.getValue());+ }}// Redirect to the URL with only allowed query parametersdiff --git a/app/core/src/test/java/stirling/software/SPDF/config/CleanUrlInterceptorMvcTest.java b/app/core/src/test/java/stirling/software/SPDF/config/CleanUrlInterceptorMvcTest.javaindex aa025bc7bf..a26d768bf3 100644--- a/app/core/src/test/java/stirling/software/SPDF/config/CleanUrlInterceptorMvcTest.java+++ b/app/core/src/test/java/stirling/software/SPDF/config/CleanUrlInterceptorMvcTest.java@@ -78,4 +78,25 @@ class CleanUrlInterceptorMvcTest {.andExpect(status().isFound()).andExpect(redirectedUrl(path + "?"));}++ @ParameterizedTest+ @ValueSource(strings = {"?all", "?all=", "?all=1", "?all=true", "?lang=en&all", "?all&lang=en"})+ void servesLoginShowAllWithoutRedirect(String query) throws Exception {+ for (String contextPath : new String[] {"", "/stirling", "/stirling/nested"}) {+ mvc.perform(get(contextPath + "/login" + query).contextPath(contextPath))+ .andExpect(status().isOk())+ .andExpect(header().doesNotExist("Location"))+ .andExpect(content().string(SPA_HTML));+ }+ }++ @ParameterizedTest+ @ValueSource(strings = {"", "/stirling", "/stirling/nested"})+ void loginCleaningKeepsShowAllFlagAndContextPath(String contextPath) throws Exception {+ String loginPath = contextPath + "/login";++ mvc.perform(get(loginPath + "?all&evil=x&lang=en&flag").contextPath(contextPath))+ .andExpect(status().isFound())+ .andExpect(redirectedUrl(loginPath + "?all&lang=en"));+ }}diff --git a/app/core/src/test/java/stirling/software/SPDF/config/CleanUrlInterceptorTest.java b/app/core/src/test/java/stirling/software/SPDF/config/CleanUrlInterceptorTest.javaindex 37f9b6ec75..d3181d4e77 100644--- a/app/core/src/test/java/stirling/software/SPDF/config/CleanUrlInterceptorTest.java+++ b/app/core/src/test/java/stirling/software/SPDF/config/CleanUrlInterceptorTest.java@@ -78,14 +78,40 @@ class CleanUrlInterceptorTest {}@Test- void preHandleSkipsParamsWithNoEqualsSign() throws Exception {+ void preHandleStripsDisallowedBareFlag() throws Exception {when(request.getRequestURI()).thenReturn("/page");when(request.getContextPath()).thenReturn("");when(request.getQueryString()).thenReturn("lang=en&malformed");- // "malformed" has no '=', so keyValuePair.length != 2 -> skipped- // allowedParameters has 1 entry (lang=en) but queryParameters.length is 2- // So it redirectsassertFalse(interceptor.preHandle(request, response, new Object()));+ verify(response).sendRedirect("/page?lang=en");+ }++ @ParameterizedTest+ @ValueSource(strings = {"all", "all=", "all=1", "all=true", "lang=en&all"})+ void preHandleKeepsShowAllLoginFlag(String queryString) throws Exception {+ when(request.getRequestURI()).thenReturn("/login");+ when(request.getContextPath()).thenReturn("");+ when(request.getQueryString()).thenReturn(queryString);+ assertTrue(interceptor.preHandle(request, response, new Object()));+ verify(response, never()).sendRedirect(anyString());+ }++ @Test+ void preHandleKeepsBareAllowedFlagWhenStrippingOthers() throws Exception {+ when(request.getRequestURI()).thenReturn("/login");+ when(request.getContextPath()).thenReturn("");+ when(request.getQueryString()).thenReturn("all&evil=malicious");+ assertFalse(interceptor.preHandle(request, response, new Object()));+ verify(response).sendRedirect("/login?all");+ }++ @Test+ void preHandleStripsParamWithMultipleEqualsSigns() throws Exception {+ when(request.getRequestURI()).thenReturn("/page");+ when(request.getContextPath()).thenReturn("");+ when(request.getQueryString()).thenReturn("lang=en&page=1=2");+ assertFalse(interceptor.preHandle(request, response, new Object()));+ verify(response).sendRedirect("/page?lang=en");}@ParameterizedTestdiff --git a/frontend/public/locales/en-US/translation.toml b/frontend/public/locales/en-US/translation.tomlindex 5c682482c5..bf04ce3b8e 100644--- a/frontend/public/locales/en-US/translation.toml+++ b/frontend/public/locales/en-US/translation.toml@@ -1100,7 +1100,7 @@ description = "The SAML2 registration identifier"label = "Registration ID"[admin.settings.connections.ssoAutoLogin]-description = "Automatically redirect to SSO login when authentication is required"+description = "Automatically redirect to SSO login when authentication is required and exactly one provider is configured. Open /login?all to reach the sign-in form directly."enable = "Enable SSO Auto Login"label = "SSO Auto Login"diff --git a/frontend/src/editor/proprietary/auth/ssoAutoLogin.ts b/frontend/src/editor/proprietary/auth/ssoAutoLogin.tsnew file mode 100644index 0000000000..b522040d93--- /dev/null+++ b/frontend/src/editor/proprietary/auth/ssoAutoLogin.ts@@ -0,0 +1,92 @@+/**+ * Per-tab bookkeeping that decides whether /login may send a visitor straight+ * to the single SSO provider. Lives in sessionStorage so a new tab starts over.+ *+ * Every access is guarded: a browser that blocks storage throws on the first+ * touch of `window.sessionStorage`, and a full one throws on write. State that+ * cannot be read or recorded fails towards showing the sign-in form, because+ * without the visit count nothing stops a redirect loop through a broken IdP.+ */++const ATTEMPTS_KEY = "stirling_sso_auto_login_attempts";+const ERRORS_KEY = "stirling_sso_auto_login_errors";+// Must match the key signOut() and the accountLogout extensions set.+const LOGGED_OUT_KEY = "stirling_sso_auto_login_logged_out";++// One redirect per tab: landing on /login again without having signed in means+// the IdP round trip is not working for this visitor, so they get the form.+const MAX_ATTEMPTS = 1;+const MAX_ERRORS = 1;++function readCount(storage: Storage, key: string): number {+ const value = Number(storage.getItem(key));+ return Number.isFinite(value) ? value : 0;+}++function incrementCount(key: string): boolean {+ try {+ const storage = window.sessionStorage;+ storage.setItem(key, String(readCount(storage, key) + 1));+ return true;+ } catch {+ return false;+ }+}++/** False when this tab has used its redirect, hit an SSO error, signed out, or cannot read storage. */+export function isSsoAutoLoginAllowed(): boolean {+ try {+ const storage = window.sessionStorage;+ return (+ readCount(storage, ATTEMPTS_KEY) < MAX_ATTEMPTS &&+ readCount(storage, ERRORS_KEY) < MAX_ERRORS &&+ storage.getItem(LOGGED_OUT_KEY) !== "1"+ );+ } catch {+ return false;+ }+}++/**+ * Counts this tab's redirect. False when it could not be stored, and the caller+ * must not redirect: the next view would not know this one happened.+ */+export function recordSsoAutoLoginAttempt(): boolean {+ return incrementCount(ATTEMPTS_KEY);+}++export function recordSsoAutoLoginError(): void {+ // Safe to drop on failure: storage that rejects this write rejects the+ // attempt count too, and Login does not redirect without one.+ incrementCount(ERRORS_KEY);+}++/** Restores the redirect after a completed sign-in. */+export function resetSsoAutoLoginCounts(): void {+ try {+ window.sessionStorage.removeItem(ATTEMPTS_KEY);+ window.sessionStorage.removeItem(ERRORS_KEY);+ } catch {+ // Storage blocked: there are no counts to reset.+ }+}++export function clearSignedOutFlag(): void {+ try {+ window.sessionStorage.removeItem(LOGGED_OUT_KEY);+ } catch {+ // Storage blocked: the flag was never set.+ }+}++/**+ * Whether the user signed out in this tab. False when storage is unreadable,+ * so a completed SSO round trip is never thrown away over a missing flag.+ */+export function hasSignedOutInThisTab(): boolean {+ try {+ return window.sessionStorage.getItem(LOGGED_OUT_KEY) === "1";+ } catch {+ return false;+ }+}diff --git a/frontend/src/editor/proprietary/routes/AuthCallback.test.tsx b/frontend/src/editor/proprietary/routes/AuthCallback.test.tsxindex df7d8268b2..7f4405aed5 100644--- a/frontend/src/editor/proprietary/routes/AuthCallback.test.tsx+++ b/frontend/src/editor/proprietary/routes/AuthCallback.test.tsx@@ -202,6 +202,85 @@ describe("AuthCallback", () => {expect(sessionStorage.getItem(POST_LOGIN_REDIRECT_STORAGE_KEY)).toBeNull();});+ it("should restore SSO auto-login after a completed sign-in", async () => {+ const mockToken = "oauth-jwt-token";+ window.location.hash = `#access_token=${mockToken}`;+ sessionStorage.setItem("stirling_sso_auto_login_attempts", "1");+ sessionStorage.setItem("stirling_sso_auto_login_errors", "1");++ vi.mocked(springAuth.getSession).mockResolvedValueOnce({+ data: {+ session: {+ user: {+ id: "123",+ email: "[email protected]",+ username: "oauthuser",+ role: "USER",+ },+ access_token: mockToken,+ expires_in: 3600,+ expires_at: Date.now() + 3600000,+ },+ },+ error: null,+ });++ render(+ <BrowserRouter>+ <AuthCallback />+ </BrowserRouter>,+ );++ await waitFor(() => {+ expect(mockNavigate).toHaveBeenCalled();+ });+ expect(+ sessionStorage.getItem("stirling_sso_auto_login_attempts"),+ ).toBeNull();+ expect(sessionStorage.getItem("stirling_sso_auto_login_errors")).toBeNull();+ });++ it("should complete sign-in when session storage is blocked", async () => {+ const mockToken = "oauth-jwt-token";+ window.location.hash = `#access_token=${mockToken}`;++ vi.mocked(springAuth.getSession).mockResolvedValueOnce({+ data: {+ session: {+ user: {+ id: "123",+ email: "[email protected]",+ username: "oauthuser",+ role: "USER",+ },+ access_token: mockToken,+ expires_in: 3600,+ expires_at: Date.now() + 3600000,+ },+ },+ error: null,+ });+ vi.spyOn(window, "sessionStorage", "get").mockImplementation(() => {+ throw new DOMException("blocked", "SecurityError");+ });++ try {+ render(+ <BrowserRouter>+ <AuthCallback />+ </BrowserRouter>,+ );++ await waitFor(() => {+ expect(mockNavigate).toHaveBeenCalledWith("/editor", {+ replace: true,+ });+ });+ } finally {+ vi.restoreAllMocks();+ }+ });+it("should fall back to the editor when the stored post-login path is unsafe", async () => {const mockToken = "oauth-jwt-token";const mockUser = {diff --git a/frontend/src/editor/proprietary/routes/AuthCallback.tsx b/frontend/src/editor/proprietary/routes/AuthCallback.tsxindex 0a0ecfc234..8c53c616e2 100644--- a/frontend/src/editor/proprietary/routes/AuthCallback.tsx+++ b/frontend/src/editor/proprietary/routes/AuthCallback.tsx@@ -7,6 +7,10 @@ import {springAuth,} from "@editor/auth/spring/springAuthClient";import { handleAuthCallbackSuccess } from "@editor/extensions/authCallback";+import {+ hasSignedOutInThisTab,+ resetSsoAutoLoginCounts,+} from "@editor/auth/ssoAutoLogin";import { AuthShell } from "@editor/auth/ui/AuthShell";import { Spinner } from "@editor/ui/Spinner";import { withBasePath } from "@editor/constants/app";@@ -31,11 +35,7 @@ export default function AuthCallback() {const elapsed = () => `${(performance.now() - startedAt).toFixed(0)}ms`;const handleCallback = async () => {- if (- typeof window !== "undefined" &&- window.sessionStorage.getItem("stirling_sso_auto_login_logged_out") ===- "1"- ) {+ if (hasSignedOutInThisTab()) {navigate("/login", {replace: true,state: {@@ -95,6 +95,7 @@ export default function AuthCallback() {}await handleAuthCallbackSuccess(token);+ resetSsoAutoLoginCounts();// Wait for all context providers to process jwt-available event// This prevents infinite render loop when coming from cross-domain SAML redirectdiff --git a/frontend/src/editor/proprietary/routes/Login.test.tsx b/frontend/src/editor/proprietary/routes/Login.test.tsxindex 50adac7b23..290d6310d0 100644--- a/frontend/src/editor/proprietary/routes/Login.test.tsx+++ b/frontend/src/editor/proprietary/routes/Login.test.tsx@@ -872,4 +872,187 @@ describe("Login", () => {"/share/abc123",);});++ describe("SSO auto-login", () => {+ const mockLoginConfig = (+ loginMethod: string,+ overrides: { firstTimeSetup?: boolean } = {},+ ) =>+ vi.mocked(apiClient.get).mockResolvedValue({+ data: {+ enableLogin: true,+ ssoAutoLogin: true,+ loginMethod,+ providerList: { "/oauth2/authorization/authentik": "Authentik" },+ ...overrides,+ },+ });++ const renderAt = (entry: string) =>+ render(+ <TestWrapper>+ <MemoryRouter initialEntries={[entry]}>+ <Login />+ </MemoryRouter>+ </TestWrapper>,+ );++ beforeEach(() => {+ sessionStorage.clear();+ vi.mocked(springAuth.signInWithOAuth).mockResolvedValue({ error: null });+ });++ it("redirects to the only provider even when password login is allowed", async () => {+ mockLoginConfig("all");+ renderAt("/login");++ await waitFor(() => {+ expect(springAuth.signInWithOAuth).toHaveBeenCalled();+ });+ });++ it("shows the form instead of redirecting on the second view without a sign-in", async () => {+ mockLoginConfig("all");+ const first = renderAt("/login");+ await waitFor(() => {+ expect(springAuth.signInWithOAuth).toHaveBeenCalledTimes(1);+ });+ first.unmount();++ renderAt("/login");++ await waitFor(() => {+ expect(screen.getByText(/Authentik/)).toBeInTheDocument();+ expect(document.getElementById("password")).toBeInTheDocument();+ });+ expect(springAuth.signInWithOAuth).toHaveBeenCalledTimes(1);+ });++ it("resets the visit and error counts once signed in", async () => {+ mockLoginConfig("all");+ sessionStorage.setItem("stirling_sso_auto_login_attempts", "1");+ sessionStorage.setItem("stirling_sso_auto_login_errors", "1");+ vi.mocked(useAuth).mockReturnValue({+ ...vi.mocked(useAuth)(),+ session: {+ user: {+ id: "123",+ email: "[email protected]",+ username: "testuser",+ role: "USER",+ },+ access_token: "mock-token",+ expires_in: 3600,+ },+ });++ renderAt("/login");++ await waitFor(() => {+ expect(+ sessionStorage.getItem("stirling_sso_auto_login_attempts"),+ ).toBeNull();+ expect(+ sessionStorage.getItem("stirling_sso_auto_login_errors"),+ ).toBeNull();+ });+ });++ it("shows the form instead of redirecting when session storage is blocked", async () => {+ mockLoginConfig("all");+ vi.spyOn(window, "sessionStorage", "get").mockImplementation(() => {+ throw new DOMException("blocked", "SecurityError");+ });++ try {+ renderAt("/login");++ await waitFor(() => {+ expect(screen.getByText(/Authentik/)).toBeInTheDocument();+ expect(document.getElementById("password")).toBeInTheDocument();+ });+ expect(springAuth.signInWithOAuth).not.toHaveBeenCalled();+ } finally {+ vi.restoreAllMocks();+ }+ });++ it("shows the form instead of redirecting when the visit cannot be recorded", async () => {+ mockLoginConfig("all");+ vi.spyOn(Storage.prototype, "setItem").mockImplementation(() => {+ throw new DOMException("full", "QuotaExceededError");+ });++ try {+ renderAt("/login");++ await waitFor(() => {+ expect(screen.getByText(/Authentik/)).toBeInTheDocument();+ expect(document.getElementById("password")).toBeInTheDocument();+ });+ expect(springAuth.signInWithOAuth).not.toHaveBeenCalled();+ } finally {+ vi.restoreAllMocks();+ }+ });++ it("stays on the page with the email form under ?all", async () => {+ mockLoginConfig("all");+ renderAt("/login?all");++ await waitFor(() => {+ expect(screen.getByText(/Authentik/)).toBeInTheDocument();+ expect(document.getElementById("email")).toBeInTheDocument();+ expect(document.getElementById("password")).toBeInTheDocument();+ });+ expect(springAuth.signInWithOAuth).not.toHaveBeenCalled();+ });++ it("stays on the page in SSO-only mode under ?all", async () => {+ mockLoginConfig("oauth2");+ renderAt("/login?all");++ await waitFor(() => {+ expect(screen.getByText(/Authentik/)).toBeInTheDocument();+ });+ expect(document.getElementById("email")).not.toBeInTheDocument();+ expect(springAuth.signInWithOAuth).not.toHaveBeenCalled();+ });++ it("stays on the page during first-time setup when password login is allowed", async () => {+ mockLoginConfig("all", { firstTimeSetup: true });+ renderAt("/login");++ await waitFor(() => {+ expect(screen.getByText(/Authentik/)).toBeInTheDocument();+ expect(document.getElementById("password")).toBeInTheDocument();+ });+ expect(springAuth.signInWithOAuth).not.toHaveBeenCalled();+ });++ it("still redirects during first-time setup in SSO-only mode", async () => {+ mockLoginConfig("oauth2", { firstTimeSetup: true });+ renderAt("/login");++ await waitFor(() => {+ expect(springAuth.signInWithOAuth).toHaveBeenCalled();+ });+ });++ it("stays on the page after a local account is created", async () => {+ mockLoginConfig("all");+ renderAt("/login?messageType=accountCreated");++ await waitFor(() => {+ expect(screen.getByText(/Authentik/)).toBeInTheDocument();+ expect(+ screen.getByText(+ "Account created successfully! You can now sign in.",+ ),+ ).toBeInTheDocument();+ expect(document.getElementById("password")).toBeInTheDocument();+ });+ expect(springAuth.signInWithOAuth).not.toHaveBeenCalled();+ });+ });});diff --git a/frontend/src/editor/proprietary/routes/Login.tsx b/frontend/src/editor/proprietary/routes/Login.tsxindex 28f7b40a22..f31eb7c1d1 100644--- a/frontend/src/editor/proprietary/routes/Login.tsx+++ b/frontend/src/editor/proprietary/routes/Login.tsx@@ -25,6 +25,13 @@ import { updateSupportedLanguages } from "@editor/i18n";import SpringLoginForm from "@editor/auth/ui/SpringLoginForm";import AuthDefaultCredentials from "@editor/auth/ui/AuthDefaultCredentials";import { useSpringLogin } from "@editor/auth/ui/useSpringLogin";+import {+ clearSignedOutFlag,+ isSsoAutoLoginAllowed,+ recordSsoAutoLoginAttempt,+ recordSsoAutoLoginError,+ resetSsoAutoLoginCounts,+} from "@editor/auth/ssoAutoLogin";import { LoadingFallback } from "@editor/components/shared/LoadingFallback";import loginHeader from "@editor/assets/brand/modern-logo/LoginLightModeHeader.svg";@@ -73,52 +80,6 @@ export default function Login() {const autoLoginAttempted = useRef(false);const autoLoginErrorRecorded = useRef(false);- const AUTO_LOGIN_ATTEMPTS_KEY = "stirling_sso_auto_login_attempts";- const AUTO_LOGIN_ERRORS_KEY = "stirling_sso_auto_login_errors";- const AUTO_LOGIN_LOGOUT_KEY = "stirling_sso_auto_login_logged_out";- const MAX_AUTO_LOGIN_ATTEMPTS = 2;- const MAX_AUTO_LOGIN_ERRORS = 1;-- const readSessionNumber = (key: string) => {- if (typeof window === "undefined") {- return 0;- }- const raw = window.sessionStorage.getItem(key);- const value = Number(raw);- return Number.isFinite(value) ? value : 0;- };-- const writeSessionNumber = (key: string, value: number) => {- if (typeof window === "undefined") {- return;- }- window.sessionStorage.setItem(key, String(value));- };-- const hasLogoutBlock = () => {- if (typeof window === "undefined") {- return false;- }- return window.sessionStorage.getItem(AUTO_LOGIN_LOGOUT_KEY) === "1";- };-- const clearLogoutBlock = () => {- if (typeof window === "undefined") {- return;- }- window.sessionStorage.removeItem(AUTO_LOGIN_LOGOUT_KEY);- };-- const recordAutoLoginAttempt = () => {- const attempts = readSessionNumber(AUTO_LOGIN_ATTEMPTS_KEY);- writeSessionNumber(AUTO_LOGIN_ATTEMPTS_KEY, attempts + 1);- };-- const recordAutoLoginError = () => {- const errors = readSessionNumber(AUTO_LOGIN_ERRORS_KEY);- writeSessionNumber(AUTO_LOGIN_ERRORS_KEY, errors + 1);- };-const errorFromState = (location.state as { error?: string } | null)?.error;const errorFromQuery = useMemo(() => {if (!searchParams) {@@ -148,13 +109,16 @@ export default function Login() {}, [searchParams]);const hasSsoLoginError = Boolean(errorFromState || errorFromQuery);+ // /login?all is how a local admin reaches the password form when SSO+ // auto-login would otherwise redirect straight to the provider.+ const skipSsoAutoLogin = searchParams.has("all");// Shared login state + sign-in handlers + provider fetch. Editor-specific// behaviour (auto-login, redirects, first-time setup) is layered on here.const login = useSpringLogin({ready: backendProbe.status === "up" || backendProbe.loginDisabled,redirectTo: `${BASE_PATH}/auth/callback`,- onSignInStart: clearLogoutBlock,+ onSignInStart: clearSignedOutFlag,onBeforeOAuth: () => {// Don't overwrite a path already stashed by httpErrorHandler on a 401.const returnPath = resolveReturnPath();@@ -181,6 +145,11 @@ export default function Login() {const isUserPassAllowed = login.isUserPassAllowed;const isSsoOnlyMode = !login.isUserPassAllowed;+ // Visitors who can only sign in with a password: the admin of a fresh+ // install (default credentials) and a local account just created from an+ // invite (messageType). Redirecting them to the IdP strands them there.+ const awaitsPasswordSignIn =+ isUserPassAllowed && (isFirstTimeSetup || searchParams.has("messageType"));// Periodically probe while backend isn't up so the screen can auto-advance when it comes onlineuseEffect(() => {@@ -213,6 +182,7 @@ export default function Login() {useEffect(() => {if (loading) return;if (!session) return;+ resetSsoAutoLoginCounts();const stashed = consumePostLoginRedirectPath();const returnPath = resolveReturnPath() ?? stashed;if (returnPath) {@@ -266,12 +236,6 @@ export default function Login() {return;}- const attempts = readSessionNumber(AUTO_LOGIN_ATTEMPTS_KEY);- const errors = readSessionNumber(AUTO_LOGIN_ERRORS_KEY);- const blockedByErrors = errors >= MAX_AUTO_LOGIN_ERRORS;- const blockedByAttempts = attempts >= MAX_AUTO_LOGIN_ATTEMPTS;- const blockedByLogout = hasLogoutBlock();-if (!ssoAutoLogin ||loginDisabled ||@@ -283,24 +247,22 @@ export default function Login() {}if (+ skipSsoAutoLogin ||+ awaitsPasswordSignIn ||hasSsoLoginError ||- blockedByErrors ||- blockedByAttempts ||- blockedByLogout+ !isSsoAutoLoginAllowed()) {return;}- if (login.isUserPassAllowed) {- return;- }-if (login.providers.length !== 1) {return;}autoLoginAttempted.current = true;- recordAutoLoginAttempt();+ if (!recordSsoAutoLoginAttempt()) {+ return;+ }void login.signInWithProvider(login.providers[0]);}, [ssoAutoLogin,@@ -311,8 +273,9 @@ export default function Login() {login.loginMethod,login.providers,login.signInWithProvider,- login.isUserPassAllowed,hasSsoLoginError,+ skipSsoAutoLogin,+ awaitsPasswordSignIn,]);// Handle query params (email prefill, success messages, and session expiry)@@ -371,7 +334,7 @@ export default function Login() {}if (hasSsoLoginError && !autoLoginErrorRecorded.current) {- recordAutoLoginError();+ recordSsoAutoLoginError();autoLoginErrorRecorded.current = true;}} catch (_) {