Skip to content

ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.

fix(auth): return to the intended page after login instead of the dashboard

Juan Denis681ac1fa6bed
diff --git a/frontend/src/App.jsx b/frontend/src/App.jsx
index af4f6469..66048e24 100644
--- a/frontend/src/App.jsx
+++ b/frontend/src/App.jsx
@@ -6,6 +6,7 @@ import { ThemeProvider } from './contexts/ThemeContext';
import { LayoutProvider } from './contexts/LayoutContext';
import { ResourceTierProvider } from './contexts/ResourceTierContext';
import { NotificationsProvider } from './contexts/NotificationsContext';
+import { rememberRedirect } from './utils/redirectAfterLogin';
import { Toaster } from './components/ui/sonner';
import ThemeSync from './components/ThemeSync';
import DashboardLayout from './layouts/DashboardLayout';
@@ -214,6 +215,7 @@ function DevOnlyRoute({ children }) {
function PrivateRoute({ children }) {
const { isAuthenticated, loading, needsSetup, needsMigration } = useAuth();
+ const location = useLocation();
if (loading) {
return <AppLoader />;
@@ -228,7 +230,14 @@ function PrivateRoute({ children }) {
return <Navigate to="/setup" />;
}
- return isAuthenticated ? children : <Navigate to="/login" />;
+ if (isAuthenticated) return children;
+
+ // Park the destination so login can return to it. Deep links into the
+ // panel (?install= from a serverkit.ai badge, a shared /servers/:id) are
+ // routinely opened without a session, and landing on the dashboard with
+ // no explanation is the worst version of that.
+ rememberRedirect(location);
+ return <Navigate to="/login" replace />;
}
function PublicRoute({ children }) {
diff --git a/frontend/src/pages/Login.jsx b/frontend/src/pages/Login.jsx
index 7d4b8034..76e81b66 100644
--- a/frontend/src/pages/Login.jsx
+++ b/frontend/src/pages/Login.jsx
@@ -5,6 +5,7 @@ import api from '../services/api';
import SSOProviderIcon from '../components/SSOProviderIcon';
import ServerKitLogo from '../components/ServerKitLogo';
import AuthLayout from './auth/AuthLayout';
+import { consumeRedirect } from '../utils/redirectAfterLogin';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
@@ -54,7 +55,7 @@ const Login = () => {
api.redeemLoginLink(token)
.then((response) => {
setUser(response.user);
- navigate('/', { replace: true });
+ navigate(consumeRedirect(), { replace: true });
})
.catch((err) => {
setError(err.message || 'Invalid or expired login link');
@@ -110,7 +111,7 @@ const Login = () => {
// No 2FA - complete login
setUser(response.user);
- navigate('/');
+ navigate(consumeRedirect());
} catch (err) {
setError(err.message || 'Failed to login');
} finally {
@@ -138,7 +139,7 @@ const Login = () => {
console.warn(response.warning);
}
- navigate('/');
+ navigate(consumeRedirect());
} catch (err) {
setError(err.message || 'Invalid verification code');
// Clear the code inputs on error
diff --git a/frontend/src/pages/SSOCallback.jsx b/frontend/src/pages/SSOCallback.jsx
index a1fd9c66..f2d6512d 100644
--- a/frontend/src/pages/SSOCallback.jsx
+++ b/frontend/src/pages/SSOCallback.jsx
@@ -2,6 +2,7 @@ import { useEffect, useState } from 'react';
import { useParams, useNavigate, useSearchParams, Link } from 'react-router-dom';
import { useAuth } from '../contexts/AuthContext';
import api from '../services/api';
+import { consumeRedirect } from '../utils/redirectAfterLogin';
import { Loader } from 'lucide-react';
import { Button } from '@/components/ui/button';
@@ -41,7 +42,9 @@ const SSOCallback = () => {
}
setUser(response.user);
- navigate('/');
+ // sessionStorage survived the round trip to the identity provider;
+ // react-router state would not have.
+ navigate(consumeRedirect());
} catch (err) {
setError(err.message || 'SSO authentication failed');
}
diff --git a/frontend/src/utils/__tests__/redirectAfterLogin.test.mjs b/frontend/src/utils/__tests__/redirectAfterLogin.test.mjs
new file mode 100644
index 00000000..8de93625
Binary files /dev/null and b/frontend/src/utils/__tests__/redirectAfterLogin.test.mjs differ
diff --git a/frontend/src/utils/redirectAfterLogin.js b/frontend/src/utils/redirectAfterLogin.js
new file mode 100644
index 00000000..c4cd7ceb
--- /dev/null
+++ b/frontend/src/utils/redirectAfterLogin.js
@@ -0,0 +1,72 @@
+// Remembers where someone was headed when auth bounced them to /login, so
+// they land there instead of on the dashboard.
+//
+// This exists because deep links into the panel are now a real entry point:
+// serverkit.ai install links (/extensions?install=<slug>,
+// /templates?install=<id>) arrive from README badges and are, by definition,
+// clicked by people who may not have an open session. Dropping the query
+// string on the way through login made every one of those links land on a
+// bare dashboard with no explanation.
+//
+// sessionStorage rather than react-router's location.state: the SSO flow
+// leaves the origin entirely for the identity provider and comes back through
+// /login/callback/<provider>, and router state cannot survive that. One
+// mechanism that covers every path beats two that each cover half.
+
+const STORAGE_KEY = 'serverkit.redirectAfterLogin';
+
+// Landing back on one of these after login is either a loop or nonsense.
+const AUTH_PATHS = ['/login', '/register', '/setup', '/migrate', '/logout'];
+
+/**
+ * Validate a stored destination before we navigate to it.
+ *
+ * Returns the path, or null when it is unusable. Same-origin is enforced by
+ * shape: a destination must be one absolute path and nothing else. `//evil.com`
+ * and `/\evil.com` are the two that matter — browsers read both as
+ * protocol-relative URLs, so either would turn login into an open redirect.
+ */
+export function sanitizeRedirect(path) {
+ if (typeof path !== 'string' || !path) return null;
+ if (path[0] !== '/') return null;
+ if (path[1] === '/' || path[1] === '\\') return null;
+ // Control characters (newline, tab, NUL) can smuggle a value past the
+ // shape checks above once something downstream re-parses it.
+ // eslint-disable-next-line no-control-regex
+ if (/[\u0000-\u001f\u007f]/.test(path)) return null;
+
+ const pathname = path.split(/[?#]/)[0];
+ if (AUTH_PATHS.includes(pathname)) return null;
+
+ return path;
+}
+
+/** Store where the visitor was going. Call this before redirecting to /login. */
+export function rememberRedirect(location) {
+ if (!location) return;
+ const path = sanitizeRedirect(
+ `${location.pathname || ''}${location.search || ''}${location.hash || ''}`,
+ );
+ if (!path || path === '/') return; // the dashboard is already the default
+ try {
+ window.sessionStorage.setItem(STORAGE_KEY, path);
+ } catch {
+ // Storage unavailable — fall back to the dashboard, as before.
+ }
+}
+
+/**
+ * Read and clear the stored destination, falling back to the dashboard.
+ * Re-validates on the way out: the value is same-origin sessionStorage, but a
+ * post-login navigation is not the place to trust that assumption.
+ */
+export function consumeRedirect() {
+ let stored = null;
+ try {
+ stored = window.sessionStorage.getItem(STORAGE_KEY);
+ window.sessionStorage.removeItem(STORAGE_KEY);
+ } catch {
+ return '/';
+ }
+ return sanitizeRedirect(stored) || '/';
+}