Skip to content

#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere

Remember where a visitor was heading across an auth detour (#7876)

ConnorYoh7411f3079671
diff --git a/frontend/editor/src/core/services/pendingDestination.test.ts b/frontend/editor/src/core/services/pendingDestination.test.ts
new file mode 100644
index 0000000000..f3dd77a8ad
--- /dev/null
+++ b/frontend/editor/src/core/services/pendingDestination.test.ts
@@ -0,0 +1,112 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import {
+ clearPendingDestination,
+ rememberPendingDestination,
+ resetPendingDestinationForTests,
+ takePendingDestination,
+} from "@app/services/pendingDestination";
+
+const KEY = "stirling-pending-destination";
+
+beforeEach(() => {
+ window.localStorage.clear();
+ resetPendingDestinationForTests();
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+});
+
+describe("pendingDestination", () => {
+ it("returns the remembered path", () => {
+ rememberPendingDestination("/processor/procurement");
+ expect(takePendingDestination()).toBe("/processor/procurement");
+ });
+
+ it("keeps the query string, which carries the destination's own intent", () => {
+ rememberPendingDestination("/processor/pipelines?setup=redaction");
+ expect(takePendingDestination()).toBe(
+ "/processor/pipelines?setup=redaction",
+ );
+ });
+
+ it("returns null when nothing was remembered", () => {
+ expect(takePendingDestination()).toBeNull();
+ });
+
+ it("survives a new page load", () => {
+ rememberPendingDestination("/processor/procurement");
+ resetPendingDestinationForTests();
+ expect(takePendingDestination()).toBe("/processor/procurement");
+ });
+
+ it("consumes the intent, so it redirects one sign-in only", () => {
+ rememberPendingDestination("/processor/procurement");
+ expect(takePendingDestination()).toBe("/processor/procurement");
+ resetPendingDestinationForTests();
+ expect(takePendingDestination()).toBeNull();
+ });
+
+ it("gives the same answer twice within a page load", () => {
+ rememberPendingDestination("/processor/procurement");
+ expect(takePendingDestination()).toBe("/processor/procurement");
+ expect(takePendingDestination()).toBe("/processor/procurement");
+ });
+
+ it("refuses to store an unsafe path", () => {
+ rememberPendingDestination("//evil.example.com");
+ rememberPendingDestination("https://evil.example.com");
+ rememberPendingDestination("/\\evil.example.com");
+ expect(takePendingDestination()).toBeNull();
+ });
+
+ it("refuses to return an unsafe path written directly to storage", () => {
+ window.localStorage.setItem(
+ KEY,
+ JSON.stringify({ path: "//evil.example.com", at: Date.now() }),
+ );
+ expect(takePendingDestination()).toBeNull();
+ });
+
+ it("refuses to store an auth route, which would loop", () => {
+ rememberPendingDestination("/login");
+ expect(takePendingDestination()).toBeNull();
+ resetPendingDestinationForTests();
+ rememberPendingDestination("/auth/callback");
+ expect(takePendingDestination()).toBeNull();
+ });
+
+ it("expires an intent older than the window", () => {
+ vi.useFakeTimers();
+ rememberPendingDestination("/processor/procurement");
+ vi.advanceTimersByTime(25 * 60 * 60 * 1000);
+ resetPendingDestinationForTests();
+ expect(takePendingDestination()).toBeNull();
+ });
+
+ it("keeps an intent inside the window", () => {
+ vi.useFakeTimers();
+ rememberPendingDestination("/processor/procurement");
+ vi.advanceTimersByTime(23 * 60 * 60 * 1000);
+ resetPendingDestinationForTests();
+ expect(takePendingDestination()).toBe("/processor/procurement");
+ });
+
+ it("survives a corrupt entry", () => {
+ window.localStorage.setItem(KEY, "not json");
+ expect(takePendingDestination()).toBeNull();
+ });
+
+ it("clears without reading", () => {
+ rememberPendingDestination("/processor/procurement");
+ clearPendingDestination();
+ expect(takePendingDestination()).toBeNull();
+ });
+
+ it("re-remembering replaces a taken intent in the same page load", () => {
+ rememberPendingDestination("/processor/procurement");
+ expect(takePendingDestination()).toBe("/processor/procurement");
+ rememberPendingDestination("/processor/users");
+ expect(takePendingDestination()).toBe("/processor/users");
+ });
+});
diff --git a/frontend/editor/src/core/services/pendingDestination.ts b/frontend/editor/src/core/services/pendingDestination.ts
new file mode 100644
index 0000000000..7d49f864ba
--- /dev/null
+++ b/frontend/editor/src/core/services/pendingDestination.ts
@@ -0,0 +1,71 @@
+import { isSafePostLoginRedirect } from "@app/services/postLoginRedirect";
+
+/**
+ * Remembers the in-app path a visitor was heading for, so an auth detour can return
+ * them to it. The generic form of pendingConnect, which holds one connect request id.
+ *
+ * <p>localStorage, not sessionStorage: a confirmation email opens a new tab. Paths
+ * are re-validated on read, since the guard may have tightened since the write.
+ */
+const KEY = "stirling-pending-destination";
+
+/** Long enough for a confirmation email read the next morning. */
+const TTL_MS = 24 * 60 * 60 * 1000;
+
+interface Stored {
+ path: string;
+ at: number;
+}
+
+/** StrictMode mounts an effect twice; the second read must not change the decision. */
+let taken: string | null | undefined;
+
+/** Ignores anything the guard refuses, so callers may pass a raw query param. */
+export function rememberPendingDestination(path: unknown): void {
+ if (!isSafePostLoginRedirect(path)) return;
+ try {
+ const value: Stored = { path, at: Date.now() };
+ window.localStorage.setItem(KEY, JSON.stringify(value));
+ taken = undefined;
+ } catch {
+ // Private browsing or a full quota: the visitor lands on the default.
+ }
+}
+
+export function clearPendingDestination(): void {
+ try {
+ window.localStorage.removeItem(KEY);
+ } catch {
+ // Unwritable store; nothing to remove.
+ }
+}
+
+/**
+ * The remembered path, or null when absent, expired or no longer safe. Consumes it,
+ * so an abandoned intent cannot redirect a later unrelated sign-in. Idempotent
+ * within a page load.
+ */
+export function takePendingDestination(): string | null {
+ if (taken !== undefined) return taken;
+ taken = read();
+ clearPendingDestination();
+ return taken;
+}
+
+function read(): string | null {
+ try {
+ const raw = window.localStorage.getItem(KEY);
+ if (!raw) return null;
+ const value = JSON.parse(raw) as Stored;
+ if (typeof value?.at !== "number") return null;
+ if (Date.now() - value.at > TTL_MS) return null;
+ return isSafePostLoginRedirect(value.path) ? value.path : null;
+ } catch {
+ return null;
+ }
+}
+
+/** Test seam: forget that this page load already took the intent. */
+export function resetPendingDestinationForTests(): void {
+ taken = undefined;
+}
diff --git a/frontend/editor/src/portal-saas/auth/PortalAuthBoundary.tsx b/frontend/editor/src/portal-saas/auth/PortalAuthBoundary.tsx
index 8824883baa..23af05e5b4 100644
--- a/frontend/editor/src/portal-saas/auth/PortalAuthBoundary.tsx
+++ b/frontend/editor/src/portal-saas/auth/PortalAuthBoundary.tsx
@@ -2,7 +2,8 @@ import { useEffect, type ReactNode } from "react";
import { AuthProvider } from "@app/auth";
import { useAuth } from "@app/auth/context";
import { Spinner } from "@app/ui";
-import { withBasePath } from "@app/constants/app";
+import { stripBasePath, withBasePath } from "@app/constants/app";
+import { rememberPendingDestination } from "@app/services/pendingDestination";
import { ensureSaasSupabase } from "@portal/auth/saasSupabase";
import { EDITOR_URL } from "@portal/auth/editorUrl";
@@ -50,10 +51,20 @@ function SaasPortalGate({ children }: { children: ReactNode }) {
: isAnonymous || !portalAccess
? EDITOR_URL
: null;
+ const bouncingToLogin = !settling && !session;
useEffect(() => {
- if (redirectTo) window.location.href = redirectTo;
- }, [redirectTo]);
+ if (!redirectTo) return;
+ // A full page load, so the attempted path cannot ride along in router state.
+ // Only on the sign-in bounce: an account without portal access is not one
+ // sign-in away from this page.
+ if (bouncingToLogin) {
+ rememberPendingDestination(
+ `${stripBasePath(window.location.pathname)}${window.location.search}${window.location.hash}`,
+ );
+ }
+ window.location.href = redirectTo;
+ }, [redirectTo, bouncingToLogin]);
if (settling || redirectTo) {
return (
diff --git a/frontend/editor/src/portal/ViewRouter.tsx b/frontend/editor/src/portal/ViewRouter.tsx
index 7404108d2e..00387430d2 100644
--- a/frontend/editor/src/portal/ViewRouter.tsx
+++ b/frontend/editor/src/portal/ViewRouter.tsx
@@ -1,5 +1,11 @@
-import { lazy, Suspense } from "react";
-import { Navigate, Route, Routes, useLocation } from "react-router-dom";
+import { lazy, Suspense, useEffect } from "react";
+import {
+ Navigate,
+ Route,
+ Routes,
+ useLocation,
+ useNavigate,
+} from "react-router-dom";
import { Home } from "@portal/views/Home";
import { Users } from "@portal/views/Users";
import { Documents } from "@portal/views/Documents";
@@ -12,6 +18,7 @@ import { Infrastructure } from "@portal/views/Infrastructure";
import { PortalBillingGate } from "@portal/components/billing/PortalBillingGate";
import { ConnectGuardedRoute } from "@portal/components/account-link/ConnectGuardedRoute";
import { VIEW_PATHS, toPortalPath } from "@portal/contexts/ViewContext";
+import { useUI } from "@portal/contexts/UIContext";
// Lazy so the generated docs manifest (bundled JSON) lands in its own chunk.
const DeveloperDocs = lazy(() =>
@@ -26,6 +33,21 @@ const DeveloperDocs = lazy(() =>
// so they resolve to the portal, not the editor root.
const rel = (viewPath: string) => viewPath.replace(/^\//, "");
+/**
+ * Procurement is not a surface of its own: the deal lives on Home, so this raises
+ * the trial-setup step and bounces there. Raised imperatively rather than by
+ * rendering <Navigate>, so the signal is set before the navigation, not racing it.
+ */
+function ProcurementRedirect() {
+ const { requestTrialSetup } = useUI();
+ const navigate = useNavigate();
+ useEffect(() => {
+ requestTrialSetup();
+ navigate(toPortalPath(VIEW_PATHS.home), { replace: true });
+ }, [requestTrialSetup, navigate]);
+ return null;
+}
+
/** Redirect the retired Policies path to the unified Pipelines page, carrying any query string. */
function PoliciesRedirect() {
const { search } = useLocation();
@@ -93,6 +115,8 @@ export function ViewRouter() {
</Suspense>
}
/>
+ {/* A bare path, not a VIEW_PATHS entry: nothing should list it as a view. */}
+ <Route path="procurement" element={<ProcurementRedirect />} />
{/* Account-link is now a Settings panel; redirect legacy bookmarks home. */}
<Route
path="account-link"
diff --git a/frontend/editor/src/saas/routes/AuthCallback.destination.test.tsx b/frontend/editor/src/saas/routes/AuthCallback.destination.test.tsx
new file mode 100644
index 0000000000..7dd8bfaa02
--- /dev/null
+++ b/frontend/editor/src/saas/routes/AuthCallback.destination.test.tsx
@@ -0,0 +1,112 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { render, waitFor } from "@testing-library/react";
+import AuthCallback from "@app/routes/AuthCallback";
+import { supabase } from "@app/auth/supabase";
+import {
+ rememberPendingDestination,
+ resetPendingDestinationForTests,
+} from "@app/services/pendingDestination";
+import {
+ clearPendingConnect,
+ rememberPendingConnect,
+} from "@app/routes/pendingConnect";
+
+/*
+ * Where a completed sign-in lands. An inserted branch that swallows the no-param
+ * case strands every visitor who arrived from a link and had to sign up.
+ */
+
+const mockNavigate = vi.fn();
+vi.mock("react-router-dom", async () => {
+ const actual = await vi.importActual("react-router-dom");
+ return { ...actual, useNavigate: () => mockNavigate };
+});
+
+vi.mock("@app/utils/loginLanding", () => ({
+ resolveLandingPath: vi.fn().mockResolvedValue("/processor"),
+}));
+
+async function arriveAtCallback(search = "") {
+ window.history.replaceState({}, "", `/auth/callback${search}`);
+ render(<AuthCallback />);
+ // Real timers: the redirect timeout is only scheduled once the awaited session
+ // resolves, which a fake-timer sweep races rather than observes.
+ await waitFor(() => expect(mockNavigate).toHaveBeenCalled(), {
+ timeout: 3000,
+ });
+}
+
+function landedOn() {
+ const call = mockNavigate.mock.calls.at(-1);
+ return call?.[0];
+}
+
+beforeEach(() => {
+ localStorage.clear();
+ resetPendingDestinationForTests();
+ mockNavigate.mockClear();
+ vi.mocked(supabase.auth.getSession).mockResolvedValue({
+ data: { session: { user: { id: "u1" } } },
+ error: null,
+ } as unknown as Awaited<ReturnType<typeof supabase.auth.getSession>>);
+});
+
+describe("AuthCallback destination", () => {
+ it("prefers an explicit next over anything remembered", async () => {
+ rememberPendingDestination("/processor/procurement");
+ await arriveAtCallback("?next=%2Fprocessor%2Fusers");
+ expect(landedOn()).toBe("/processor/users");
+ });
+
+ it("accepts `from`, which the shared 401 handler writes", async () => {
+ await arriveAtCallback("?from=%2Fprocessor%2Fusers");
+ expect(landedOn()).toBe("/processor/users");
+ });
+
+ it("prefers a pending connect request over a remembered destination", async () => {
+ rememberPendingConnect("req-1");
+ rememberPendingDestination("/processor/procurement");
+ await arriveAtCallback();
+ expect(landedOn()).toBe("/link?request=req-1");
+ });
+
+ it("uses a remembered destination when the URL carries nothing", async () => {
+ rememberPendingDestination("/processor/procurement");
+ await arriveAtCallback();
+ expect(landedOn()).toBe("/processor/procurement");
+ });
+
+ it("falls back to the role-based landing when nothing is remembered", async () => {
+ await arriveAtCallback();
+ expect(landedOn()).toBe("/processor");
+ });
+
+ it("refuses an off-origin next and falls back", async () => {
+ await arriveAtCallback("?next=%2F%2Fevil.example.com");
+ expect(landedOn()).toBe("/processor");
+ });
+
+ it("claims the remembered destination even when an explicit next wins", async () => {
+ rememberPendingDestination("/processor/procurement");
+ await arriveAtCallback("?next=%2Fprocessor%2Fusers");
+ expect(landedOn()).toBe("/processor/users");
+
+ resetPendingDestinationForTests();
+ mockNavigate.mockClear();
+ await arriveAtCallback();
+ expect(landedOn()).toBe("/processor");
+ });
+
+ it("claims it even when a pending connect request wins", async () => {
+ rememberPendingConnect("req-1");
+ rememberPendingDestination("/processor/procurement");
+ await arriveAtCallback();
+ expect(landedOn()).toBe("/link?request=req-1");
+
+ clearPendingConnect();
+ resetPendingDestinationForTests();
+ mockNavigate.mockClear();
+ await arriveAtCallback();
+ expect(landedOn()).toBe("/processor");
+ });
+});
diff --git a/frontend/editor/src/saas/routes/AuthCallback.tsx b/frontend/editor/src/saas/routes/AuthCallback.tsx
index 3fe081ed82..6cf197f934 100644
--- a/frontend/editor/src/saas/routes/AuthCallback.tsx
+++ b/frontend/editor/src/saas/routes/AuthCallback.tsx
@@ -6,6 +6,7 @@ import { Button } from "@app/ui/Button";
import { withBasePath } from "@app/constants/app";
import { readPendingConnect } from "@app/routes/pendingConnect";
import { isSafePostLoginRedirect } from "@app/services/postLoginRedirect";
+import { takePendingDestination } from "@app/services/pendingDestination";
import { AuthShell } from "@app/auth/ui/AuthShell";
import ErrorMessage from "@app/auth/ui/ErrorMessage";
import { Spinner } from "@app/ui/Spinner";
@@ -32,7 +33,11 @@ export default function AuthCallback() {
const code = url.searchParams.get("code");
const error = url.searchParams.get("error");
const errorDescription = url.searchParams.get("error_description");
- const next = url.searchParams.get("next") || "/";
+ // For the debug log; the redirect below reads the param itself. Left
+ // undefaulted because a default would pass the safety guard, so any branch
+ // on it in that chain matches every param-less sign-in and masks the
+ // fallbacks beneath it.
+ const next = url.searchParams.get("next");
console.log("[Auth Callback Debug] URL parameters:", {
hasCode: !!code,
@@ -130,23 +135,19 @@ export default function AuthCallback() {
}
}
- // Redirect to the intended destination. Reject protocol-relative
- // "//host" values (same guard as Login's `next`) so a crafted callback
- // URL can't bounce the user off-origin after sign-in.
- // No explicit destination: land team leads on the processor and everyone
- // else on the editor.
- // Explicit `next` first, so a sign-in started for another reason is not
- // hijacked by a remembered connect request.
+ // A deliberate `next` outranks a remembered intent so it cannot be hijacked;
+ // a remembered one is all a sign-up has, its confirmation link being unable
+ // to carry a `next`. Claimed up front because reaching here means the detour
+ // is over, so the intent is spent whichever wins.
const explicitNext =
url.searchParams.get("next") ?? url.searchParams.get("from");
const pendingConnect = readPendingConnect();
+ const remembered = takePendingDestination();
const destination = isSafePostLoginRedirect(explicitNext)
? explicitNext
: pendingConnect
? `/link?request=${encodeURIComponent(pendingConnect)}`
- : isSafePostLoginRedirect(next)
- ? next
- : await resolveLandingPath();
+ : (remembered ?? (await resolveLandingPath()));
console.log("[Auth Callback Debug] Redirecting to:", destination);
setTimeout(() => navigate(destination, { replace: true }), 1500);
diff --git a/frontend/editor/src/saas/routes/Login.tsx b/frontend/editor/src/saas/routes/Login.tsx
index ba251561fd..b77495985c 100644
--- a/frontend/editor/src/saas/routes/Login.tsx
+++ b/frontend/editor/src/saas/routes/Login.tsx
@@ -15,6 +15,10 @@ import {
withBasePath,
} from "@app/constants/app";
import { isSafePostLoginRedirect } from "@app/services/postLoginRedirect";
+import {
+ rememberPendingDestination,
+ takePendingDestination,
+} from "@app/services/pendingDestination";
import LinkRoundedIcon from "@mui/icons-material/LinkRounded";
// Import login components
@@ -68,9 +72,14 @@ export default function Login() {
}
}, [session, loading, nextPath, navigate]);
+ // Stashed as well as held in the URL: leaving to create an account loses the
+ // query string, and the confirmation link cannot carry a `next`.
+ useEffect(() => {
+ if (nextPath) rememberPendingDestination(nextPath);
+ }, [nextPath]);
+
const baseUrl = getBaseUrl();
- // Set document meta
useDocumentMeta({
title: `${t("login.title", "Sign in")} - Stirling PDF`,
description: t(
@@ -166,10 +175,15 @@ export default function Login() {
setError(error.message);
} else if (data.user) {
console.log("[Login] Email sign in successful");
- // No explicit destination: land team leads on the processor and everyone
- // else on the editor. Resolved here rather than by bouncing through "/"
- // so the app isn't torn down and remounted on the way.
- if (!nextPath) navigate(await resolveLandingPath(), { replace: true });
+ // Claimed even when `nextPath` wins: the detour is over either way.
+ const remembered = takePendingDestination();
+ // Resolved here rather than by bouncing through "/", which would tear the app
+ // down and remount it on the way.
+ if (!nextPath) {
+ navigate(remembered ?? (await resolveLandingPath()), {
+ replace: true,
+ });
+ }
}
} catch (err) {
console.error("[Login] Unexpected error]:", err);
diff --git a/frontend/editor/src/saas/routes/Signup.tsx b/frontend/editor/src/saas/routes/Signup.tsx
index 43368d9204..8af0dded30 100644
--- a/frontend/editor/src/saas/routes/Signup.tsx
+++ b/frontend/editor/src/saas/routes/Signup.tsx
@@ -5,6 +5,7 @@ import { useAuth } from "@app/auth/UseSession";
import { useTranslation } from "@app/hooks/useTranslation";
import { useDocumentMeta } from "@app/hooks/useDocumentMeta";
import { getBaseUrl, withBasePath } from "@app/constants/app";
+import { rememberPendingDestination } from "@app/services/pendingDestination";
import AuthLayout from "@app/routes/authShared/AuthLayout";
import "@app/auth/ui/auth.css";
import "@app/routes/authShared/saas-auth.css";
@@ -36,6 +37,18 @@ export default function Signup() {
const [agree, setAgree] = useState(true);
const [fieldErrors, setFieldErrors] = useState<SignupFieldErrors>({});
+ // Stashed rather than threaded onward: Supabase builds the confirmation link and
+ // it cannot carry a `next`.
+ useEffect(() => {
+ try {
+ rememberPendingDestination(
+ new URL(window.location.href).searchParams.get("next"),
+ );
+ } catch (_) {
+ // Unparseable URL; the visitor just lands on the default.
+ }
+ }, []);
+
// Check if we were redirected here with an auto-auth error
useEffect(() => {
const state = location.state as { autoAuthError?: string } | null;
@@ -95,7 +108,6 @@ export default function Signup() {
const baseUrl = getBaseUrl();
- // Set document meta
useDocumentMeta({
title: `${t("signup.title", "Create an account")} - Stirling PDF`,
description: t(