#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
refactor: replace static logged-in view with dynamic landing path resolution and loading fallbacks (#7930)
brios57275fe16902
diff --git a/frontend/editor/public/locales/en-US/translation.toml b/frontend/editor/public/locales/en-US/translation.tomlindex cfc63406af..8934ec90b3 100644--- a/frontend/editor/public/locales/en-US/translation.toml+++ b/frontend/editor/public/locales/en-US/translation.toml@@ -5694,7 +5694,6 @@ unexpectedError = "Unexpected error: {{message}}"updatePassword = "Update password"useMagicLink = "Use magic link instead"username = "Username"-youAreLoggedIn = "You are logged in!"[margin]large = "Large"diff --git a/frontend/editor/src/proprietary/App.tsx b/frontend/editor/src/proprietary/App.tsxindex ca040d4bbe..78e8eb8b79 100644--- a/frontend/editor/src/proprietary/App.tsx+++ b/frontend/editor/src/proprietary/App.tsx@@ -5,14 +5,19 @@ import { AppLayout } from "@app/components/AppLayout";import { LoadingFallback } from "@app/components/shared/LoadingFallback";import { PreferencesProvider } from "@app/contexts/PreferencesContext";import { ThemeProvider } from "@app/components/shared/ThemeProvider";-import Landing from "@app/routes/Landing";-import Login from "@app/routes/Login";-import AuthCallback from "@app/routes/AuthCallback";-import InviteAccept from "@app/routes/InviteAccept";-import ShareLinkPage from "@app/routes/ShareLinkPage";-import ParticipantView from "@app/components/workflow/ParticipantView";-import Onboarding from "@app/components/onboarding/Onboarding";-import WatchedFoldersRegistration from "@app/components/watchedFolders/WatchedFoldersRegistration";++const Landing = lazy(() => import("@app/routes/Landing"));+const Login = lazy(() => import("@app/routes/Login"));+const AuthCallback = lazy(() => import("@app/routes/AuthCallback"));+const InviteAccept = lazy(() => import("@app/routes/InviteAccept"));+const ShareLinkPage = lazy(() => import("@app/routes/ShareLinkPage"));+const ParticipantView = lazy(+ () => import("@app/components/workflow/ParticipantView"),+);+const Onboarding = lazy(() => import("@app/components/onboarding/Onboarding"));+const WatchedFoldersRegistration = lazy(+ () => import("@app/components/watchedFolders/WatchedFoldersRegistration"),+);const MobileScannerPage = lazy(() => import("@app/pages/MobileScannerPage"));const MobileSignPage = lazy(() => import("@app/pages/MobileSignPage"));diff --git a/frontend/editor/src/proprietary/auth/spring/springAuthClient.ts b/frontend/editor/src/proprietary/auth/spring/springAuthClient.tsindex 6d887ce8a9..b81440e9cb 100644--- a/frontend/editor/src/proprietary/auth/spring/springAuthClient.ts+++ b/frontend/editor/src/proprietary/auth/spring/springAuthClient.ts@@ -14,6 +14,7 @@import { AxiosError, type AxiosRequestConfig } from "axios";import { getSpringAuthConfig } from "@app/auth/config";+import { JWT_STORAGE_KEY } from "@app/auth/httpClient";import { type OAuthProvider } from "@app/auth/spring/oauthTypes";import { resetOAuthState } from "@app/auth/spring/oauthStorage";import { isSafePostLoginRedirect } from "@app/services/postLoginRedirect";@@ -280,7 +281,7 @@ class SpringAuthClient {}> {try {// Get JWT from localStorage- let token = localStorage.getItem("stirling_jwt");+ let token = localStorage.getItem(JWT_STORAGE_KEY);if (!token) {// console.debug('[SpringAuth] getSession: No JWT in localStorage');@@ -292,13 +293,13 @@ class SpringAuthClient {if (tokenExpiry.expiresIn <= this.DESKTOP_SAAS_REFRESH_EARLY_SECONDS) {const refreshed = await platform().refreshPlatformSession();if (!refreshed) {- localStorage.removeItem("stirling_jwt");+ localStorage.removeItem(JWT_STORAGE_KEY);return { data: { session: null }, error: null };}- const refreshedToken = localStorage.getItem("stirling_jwt");+ const refreshedToken = localStorage.getItem(JWT_STORAGE_KEY);if (!refreshedToken) {- localStorage.removeItem("stirling_jwt");+ localStorage.removeItem(JWT_STORAGE_KEY);return { data: { session: null }, error: null };}@@ -307,7 +308,7 @@ class SpringAuthClient {}if (tokenExpiry.expiresIn <= 0) {- localStorage.removeItem("stirling_jwt");+ localStorage.removeItem(JWT_STORAGE_KEY);return { data: { session: null }, error: null };}@@ -372,7 +373,7 @@ class SpringAuthClient {if (!refreshResult.error && refreshResult.data.session) {return refreshResult;}- localStorage.removeItem("stirling_jwt");+ localStorage.removeItem(JWT_STORAGE_KEY);return { data: { session: null }, error: null };}@@ -411,7 +412,7 @@ class SpringAuthClient {const token = data.session.access_token;// Store JWT in localStorage- localStorage.setItem("stirling_jwt", token);+ localStorage.setItem(JWT_STORAGE_KEY, token);// console.log('[SpringAuth] JWT stored in localStorage');// Sync token to platform-specific storage (Tauri store for desktop)@@ -530,7 +531,7 @@ class SpringAuthClient {}// Clean up local storage- localStorage.removeItem("stirling_jwt");+ localStorage.removeItem(JWT_STORAGE_KEY);try {Object.keys(localStorage).filter((key) => key.startsWith("sb-") || key.includes("supabase"))@@ -575,7 +576,7 @@ class SpringAuthClient {} catch (error: unknown) {console.error("[SpringAuth] signOut error:", error);// Still remove token even if backend call fails- localStorage.removeItem("stirling_jwt");+ localStorage.removeItem(JWT_STORAGE_KEY);try {await platform().clearPlatformAuthAfterSignOut();} catch (cleanupError) {@@ -607,7 +608,7 @@ class SpringAuthClient {if (await platform().isDesktopSaaSAuthMode()) {const refreshed = await platform().refreshPlatformSession();if (!refreshed) {- localStorage.removeItem("stirling_jwt");+ localStorage.removeItem(JWT_STORAGE_KEY);return {data: { session: null },error: { message: "Token refresh failed - please log in again" },@@ -625,7 +626,7 @@ class SpringAuthClient {}// Calculate adaptive intervals for desktop SaaS mode- const token = localStorage.getItem("stirling_jwt");+ const token = localStorage.getItem(JWT_STORAGE_KEY);if (token) {this.calculateAdaptiveIntervals(token);}@@ -651,7 +652,7 @@ class SpringAuthClient {const token = data.session.access_token;// Update local storage with new token- localStorage.setItem("stirling_jwt", token);+ localStorage.setItem(JWT_STORAGE_KEY, token);// Sync token to platform-specific storage (Tauri store for desktop)await platform().savePlatformToken(token);@@ -673,7 +674,7 @@ class SpringAuthClient {return { data: { session }, error: null };} catch (error: unknown) {- localStorage.removeItem("stirling_jwt");+ localStorage.removeItem(JWT_STORAGE_KEY);// 401/403 means the refresh token is no longer valid - normal expired// state, not an error worth surfacing. Other statuses (network, backenddiff --git a/frontend/editor/src/proprietary/routes/Landing.tsx b/frontend/editor/src/proprietary/routes/Landing.tsxindex 8107ad26f1..04760ea058 100644--- a/frontend/editor/src/proprietary/routes/Landing.tsx+++ b/frontend/editor/src/proprietary/routes/Landing.tsx@@ -26,35 +26,14 @@ export default function Landing() {const navigate = useNavigate();const { t } = useTranslation();- const loading =- authLoading || (configLoading && !config) || backendProbe.loading;+ // The probe gates only the signed-out backend-down screen: a session means+ // /auth/me already answered.+ const loading = authLoading || (configLoading && !config);+ const probePending = backendProbe.loading;// The backend-down screen is not the app. Loading is: it resolves in a moment.useSuppressQuickNavRail(!session && backendProbe.status !== "up");- // Debug: Track Landing component lifecycle- useEffect(() => {- const mountId = Math.random().toString(36).substring(7);- console.log(- `[Landing:${mountId}] π΅ Component mounted at ${location.pathname}`,- );- console.log(`[Landing:${mountId}] Mount state:`, {- authLoading,- configLoading,- backendLoading: backendProbe.loading,- hasSession: !!session,- });- return () => {- console.log(`[Landing:${mountId}] π΄ Component unmounting`);- };- }, [- location.pathname,- authLoading,- configLoading,- backendProbe.loading,- session,- ]);-// Periodically probe while backend isn't up so the screen can auto-advance when it comes onlineuseEffect(() => {if (backendProbe.status === "up" || backendProbe.loginDisabled) {@@ -81,29 +60,8 @@ export default function Landing() {refetch,]);- useEffect(() => {- if (backendProbe.status === "up") {- void refetch();- }- }, [backendProbe.status, refetch]);-- console.log("[Landing] ββββββββββββββββββββββββββββββββββββ");- console.log("[Landing] Render state:", {- pathname: location.pathname,- loading,- authLoading,- configLoading,- backendLoading: backendProbe.loading,- hasSession: !!session,- hasConfig: !!config,- loginEnabled: config?.enableLogin === true && !backendProbe.loginDisabled,- backendStatus: backendProbe.status,- timestamp: new Date().toISOString(),- });- console.log("[Landing] ββββββββββββββββββββββββββββββββββββ");-// Show loading while checking auth and config- if (loading) {+ if (loading || (!session && probePending)) {return (<divstyle={{diff --git a/frontend/editor/src/proprietary/routes/Login.tsx b/frontend/editor/src/proprietary/routes/Login.tsxindex 3ce9d20449..4faf9aadab 100644--- a/frontend/editor/src/proprietary/routes/Login.tsx+++ b/frontend/editor/src/proprietary/routes/Login.tsx@@ -25,7 +25,7 @@ import { updateSupportedLanguages } from "@app/i18n";import SpringLoginForm from "@app/auth/ui/SpringLoginForm";import AuthDefaultCredentials from "@app/auth/ui/AuthDefaultCredentials";import { useSpringLogin } from "@app/auth/ui/useSpringLogin";-import LoggedInState from "@app/routes/login/LoggedInState";+import { LoadingFallback } from "@app/components/shared/LoadingFallback";import loginHeader from "@app/assets/brand/modern-logo/LoginLightModeHeader.svg";export default function Login() {@@ -165,7 +165,6 @@ export default function Login() {onConfigLoaded: (data) => {// If login is disabled, redirect to home (anonymous mode)if (data.enableLogin === false) {- console.debug("[Login] Login disabled, going to the editor");navigate(EDITOR_BASENAME);return;}@@ -224,11 +223,17 @@ export default function Login() {// processor. Resolved here rather than by bouncing through "/" so the app// isn't torn down and remounted on the way.let active = true;- void resolveLandingPath().then((path) => {- if (!active) return;- console.debug("[Login] Authenticated, landing on", path);- navigate(path, { replace: true });- });+ // Warm the editor chunk while /me resolves so the landing paints at once.+ void import("@app/routes/Landing").catch(() => {});+ void resolveLandingPath().then(+ (path) => {+ if (!active) return;+ navigate(path, { replace: true });+ },+ () => {+ if (active) navigate(EDITOR_BASENAME, { replace: true });+ },+ );return () => {active = false;};@@ -247,12 +252,6 @@ export default function Login() {}}, [backendProbe.loginDisabled, navigate]);- useEffect(() => {- if (backendProbe.status === "up") {- void refetch();- }- }, [backendProbe.status, refetch]);-// The email/password form is always shown when username/password auth is// allowed; SSO-only mode hides it.useEffect(() => {@@ -411,9 +410,17 @@ export default function Login() {return <Navigate to={EDITOR_BASENAME} replace />;}- // Show logged in state if authenticated- if (session && !loading) {- return <LoggedInState />;+ // The form is only for visitors known to be signed out; splash until then.+ if (loading) {+ return <LoadingFallback />;+ }++ if (session) {+ return <LoadingFallback />;+ }++ if (backendProbe.loading) {+ return <LoadingFallback />;}// If backend isn't ready yet, show a lightweight status screen instead of the formdiff --git a/frontend/editor/src/proprietary/routes/RootGate.test.tsx b/frontend/editor/src/proprietary/routes/RootGate.test.tsxindex d62414cf2a..354b149326 100644--- a/frontend/editor/src/proprietary/routes/RootGate.test.tsx+++ b/frontend/editor/src/proprietary/routes/RootGate.test.tsx@@ -71,11 +71,15 @@ const appMounted = () => screen.queryByTestId("app") !== null;describe("RootGate", () => {beforeEach(() => {h.get.mockReset();+ window.localStorage.setItem("stirling_jwt", "test-token");// The portal only exists in some builds; the decision is a no-op without it.vi.stubEnv("VITE_INCLUDE_PORTAL", "true");vi.stubEnv("VITE_LOGIN_LANDING_MODE", "dynamic");});- afterEach(() => vi.unstubAllEnvs());+ afterEach(() => {+ window.localStorage.removeItem("stirling_jwt");+ vi.unstubAllEnvs();+ });it("renders the app untouched on every path but /", async () => {backend({ portalAccess: true, loginLandingView: "processor" });@@ -113,6 +117,14 @@ describe("RootGate", () => {expect(at()).toBe("/");});+ it("leaves a visitor with no token on / without a network request", async () => {+ window.localStorage.removeItem("stirling_jwt");+ renderAt("/");+ await waitFor(() => expect(appMounted()).toBe(true));+ expect(at()).toBe("/");+ expect(h.get).not.toHaveBeenCalled();+ });+it("survives StrictMode's double-invoke", async () => {backend({ portalAccess: true, loginLandingView: "processor" });renderAt("/", true);diff --git a/frontend/editor/src/proprietary/routes/RootGate.tsx b/frontend/editor/src/proprietary/routes/RootGate.tsxindex a50c2f57b9..009a1bf852 100644--- a/frontend/editor/src/proprietary/routes/RootGate.tsx+++ b/frontend/editor/src/proprietary/routes/RootGate.tsx@@ -51,7 +51,6 @@ export function RootGate({ children }: { children: ReactNode }) {void resolveRootTarget().then((target) => {// Ignore a stale lookup cancelled by a re-run; the live one decides.if (!active) return;- console.debug("[root-gate] decision", { target });setDecision({ visit: location.key, target });});return () => {diff --git a/frontend/editor/src/proprietary/routes/login/LoggedInState.test.tsx b/frontend/editor/src/proprietary/routes/login/LoggedInState.test.tsxnew file mode 100644index 0000000000..1df43ea931--- /dev/null+++ b/frontend/editor/src/proprietary/routes/login/LoggedInState.test.tsx@@ -0,0 +1,51 @@+import { beforeEach, describe, it, expect, vi } from "vitest";+import { render, waitFor } from "@testing-library/react";+import { MemoryRouter } from "react-router-dom";+import LoggedInState from "@app/routes/login/LoggedInState";+import { resolveLandingPath } from "@app/utils/loginLanding";++vi.mock("@app/utils/loginLanding", () => ({+ resolveLandingPath: vi.fn(),+}));++const mockNavigate = vi.fn();++vi.mock("react-router-dom", async () => {+ const actual = await vi.importActual("react-router-dom");+ return {+ ...actual,+ useNavigate: () => mockNavigate,+ };+});++describe("LoggedInState", () => {+ beforeEach(() => {+ mockNavigate.mockClear();+ });++ it("navigates to the resolved landing path", async () => {+ vi.mocked(resolveLandingPath).mockResolvedValueOnce("/editor");+ render(+ <MemoryRouter>+ <LoggedInState />+ </MemoryRouter>,+ );++ await waitFor(() => {+ expect(mockNavigate).toHaveBeenCalledWith("/editor", { replace: true });+ });+ });++ it("falls back to / when landing resolution fails", async () => {+ vi.mocked(resolveLandingPath).mockRejectedValueOnce(new Error("down"));+ render(+ <MemoryRouter>+ <LoggedInState />+ </MemoryRouter>,+ );++ await waitFor(() => {+ expect(mockNavigate).toHaveBeenCalledWith("/", { replace: true });+ });+ });+});diff --git a/frontend/editor/src/proprietary/routes/login/LoggedInState.tsx b/frontend/editor/src/proprietary/routes/login/LoggedInState.tsxindex 42052d4705..4be2bb0c55 100644--- a/frontend/editor/src/proprietary/routes/login/LoggedInState.tsx+++ b/frontend/editor/src/proprietary/routes/login/LoggedInState.tsx@@ -1,77 +1,25 @@import { useEffect } from "react";import { useNavigate } from "react-router-dom";-import { useAuth } from "@app/auth/UseSession";-import { useTranslation } from "react-i18next";-import { LogoIcon } from "@app/components/shared/LogoIcon";+import { LoadingFallback } from "@app/components/shared/LoadingFallback";+import { resolveLandingPath } from "@app/utils/loginLanding";export default function LoggedInState() {const navigate = useNavigate();- const { user } = useAuth();- const { t } = useTranslation();useEffect(() => {- const timer = setTimeout(() => {- navigate("/");- }, 2000);-- return () => clearTimeout(timer);+ let active = true;+ void resolveLandingPath().then(+ (path) => {+ if (active) navigate(path, { replace: true });+ },+ () => {+ if (active) navigate("/", { replace: true });+ },+ );+ return () => {+ active = false;+ };}, [navigate]);- return (- <div- style={{- minHeight: "100vh",- display: "flex",- alignItems: "center",- justifyContent: "center",- backgroundColor: "var(--c-bg)",- padding: "16px",- }}- >- <div- style={{- maxWidth: "400px",- width: "100%",- backgroundColor: "var(--c-surface)",- borderRadius: "16px",- boxShadow: "0 10px 25px rgba(0, 0, 0, 0.1)",- padding: "32px",- }}- >- <div style={{ textAlign: "center", marginBottom: "24px" }}>- <div- style={{- marginBottom: "16px",- display: "flex",- justifyContent: "center",- }}- >- <LogoIcon- alt="Stirling PDF Logo"- style={{ width: "64px", height: "64px", objectFit: "contain" }}- />- </div>- <h1- style={{- fontSize: "24px",- fontWeight: "bold",- color: "var(--color-green-dark)",- marginBottom: "8px",- }}- >- {t("login.youAreLoggedIn")}- </h1>- <p style={{ color: "var(--c-text-subtle)", fontSize: "14px" }}>- {t("login.email")}: {user?.email}- </p>- </div>-- <div style={{ textAlign: "center", marginTop: "16px" }}>- <p style={{ color: "var(--c-text-subtle)", fontSize: "14px" }}>- Redirecting to home...- </p>- </div>- </div>- </div>- );+ return <LoadingFallback />;}diff --git a/frontend/editor/src/proprietary/utils/loginLanding.test.ts b/frontend/editor/src/proprietary/utils/loginLanding.test.tsindex 33ea7d75d1..060db74733 100644--- a/frontend/editor/src/proprietary/utils/loginLanding.test.ts+++ b/frontend/editor/src/proprietary/utils/loginLanding.test.ts@@ -30,7 +30,14 @@ describe("loginLandingMode", () => {});describe("fetchRootDestination", () => {- beforeEach(() => h.get.mockReset());+ beforeEach(() => {+ h.get.mockReset();+ window.localStorage.setItem("stirling_jwt", "test-token");+ });++ afterEach(() => {+ window.localStorage.removeItem("stirling_jwt");+ });it("sends an opted-in user to the processor", async () => {h.get.mockResolvedValueOnce(@@ -66,4 +73,21 @@ describe("fetchRootDestination", () => {h.get.mockRejectedValueOnce(httpError(401));expect(await fetchRootDestination()).toBe("signedOut");});++ it("signedOut without a request when no token is stored", async () => {+ window.localStorage.removeItem("stirling_jwt");+ expect(await fetchRootDestination()).toBe("signedOut");+ expect(h.get).not.toHaveBeenCalled();+ });++ it("still calls /me for a Supabase session with no Spring JWT", async () => {+ window.localStorage.removeItem("stirling_jwt");+ window.localStorage.setItem("sb-abcdef-auth-token", "{}");+ h.get.mockResolvedValueOnce(+ mockMe({ portalAccess: true, loginLandingView: "processor" }),+ );+ expect(await fetchRootDestination()).toBe("processor");+ expect(h.get).toHaveBeenCalledTimes(1);+ window.localStorage.removeItem("sb-abcdef-auth-token");+ });});diff --git a/frontend/editor/src/proprietary/utils/loginLanding.ts b/frontend/editor/src/proprietary/utils/loginLanding.tsindex 0ba643d700..a0ef42ba63 100644--- a/frontend/editor/src/proprietary/utils/loginLanding.ts+++ b/frontend/editor/src/proprietary/utils/loginLanding.ts@@ -1,4 +1,5 @@import apiClient from "@app/services/apiClient";+import { JWT_STORAGE_KEY } from "@app/auth/httpClient";import { EDITOR_BASENAME } from "@app/routes/editorBasename";import { PORTAL_BASENAME } from "@app/routes/portalBasename";@@ -25,6 +26,22 @@ function editorRegardless(): boolean {return loginLandingMode() !== "dynamic" || !isPortalAvailable();}+function hasAnyStoredSession(): boolean {+ try {+ if (typeof window === "undefined") return true;+ const storage = window.localStorage;+ if (storage.getItem(JWT_STORAGE_KEY)) return true;+ for (let i = 0; i < storage.length; i++) {+ const key = storage.key(i);+ if (key?.startsWith("sb-") && key.endsWith("-auth-token")) return true;+ }+ return false;+ } catch {+ // Storage blocked: fall through to the network check.+ return true;+ }+}+export async function resolveRootTarget(): Promise<string | null> {if (editorRegardless()) return EDITOR_BASENAME;const destination = await fetchRootDestination();@@ -37,6 +54,11 @@ export async function resolveLandingPath(): Promise<string> {}export async function fetchRootDestination(): Promise<RootDestination> {+ // No stored session of either flavor, so /me would only 401: self-hosted+ // keeps a Spring JWT, SaaS a Supabase sb-*-auth-token session.+ if (!hasAnyStoredSession()) {+ return "signedOut";+ }let user: MeUser | undefined;try {const me = await apiClient.get<{ user?: MeUser }>("/api/v1/auth/me", {diff --git a/frontend/editor/src/saas/routes/Login.tsx b/frontend/editor/src/saas/routes/Login.tsxindex d47e7ebce4..9b34468285 100644--- a/frontend/editor/src/saas/routes/Login.tsx+++ b/frontend/editor/src/saas/routes/Login.tsx@@ -26,6 +26,7 @@ import ErrorMessage from "@app/auth/ui/ErrorMessage";import EmailPasswordForm from "@app/routes/login/EmailPasswordForm";import OAuthButtons from "@app/routes/login/OAuthButtons";import LoggedInState from "@app/routes/login/LoggedInState";+import { LoadingFallback } from "@app/components/shared/LoadingFallback";import loginHeader from "@app/assets/brand/modern-logo/LoginLightModeHeader.svg";export default function Login() {@@ -95,6 +96,11 @@ export default function Login() {ogUrl: `${window.location.origin}${window.location.pathname}`,});+ // The form is only for visitors known to be signed out; splash until then.+ if (loading) {+ return <LoadingFallback />;+ }+// Show logged in state if authenticated (unless bouncing back to `next`)if (session && !loading) {if (nextPath) {