Skip to content

Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.

πŸ› Fix redirect loop between / and /login (RAL-1313) (#2650)

Luke Vellafd830c4a8483
diff --git a/apps/web/public/locales/en/app.json b/apps/web/public/locales/en/app.json
index 5b1d21fae..5f6332d48 100644
--- a/apps/web/public/locales/en/app.json
+++ b/apps/web/public/locales/en/app.json
@@ -41,6 +41,9 @@
"allMembers": "All",
"allParticipants": "All Participants",
"alreadyHaveAccount": "Already have an account? <a>Log in</a>",
+ "alreadyLoggedInContinue": "Continue",
+ "alreadyLoggedInDescription": "Continue to your dashboard or sign out to use a different account.",
+ "alreadyLoggedInTitle": "You're already signed in",
"alreadyMember": "This person is already a member of this space",
"annualDiscount": "Pay for {payMonths, number} months, get 12.",
"annualSavings": "Save {amount} with yearly billing",
diff --git a/apps/web/src/app/[locale]/(auth)/components/already-logged-in.tsx b/apps/web/src/app/[locale]/(auth)/components/already-logged-in.tsx
new file mode 100644
index 000000000..f3b6ad878
--- /dev/null
+++ b/apps/web/src/app/[locale]/(auth)/components/already-logged-in.tsx
@@ -0,0 +1,66 @@
+import { buttonVariants } from "@rallly/ui";
+import Link from "next/link";
+import { Trans } from "react-i18next/TransWithoutContext";
+import { getTranslation } from "@/i18n/server";
+import { validateRedirectUrl } from "@/lib/utils/redirect";
+import {
+ AuthPageContainer,
+ AuthPageContent,
+ AuthPageDescription,
+ AuthPageHeader,
+ AuthPageTitle,
+} from "./auth-page";
+import { SignOutButton } from "./sign-out-button";
+
+/**
+ * Shown on /login instead of redirecting when a session already exists.
+ * The redirect used to be automatic, which made /login one leg of the
+ * / ↔ /login redirect loop (RAL-1313) β€” a loop needs two automated legs,
+ * so the user must click to continue. The sign out button is the escape
+ * hatch when the session only looks alive (stale cookie cache).
+ *
+ * Server component: AuthPageContainer renders the async server-only Logo,
+ * so this must not be a client module.
+ */
+export async function AlreadyLoggedIn({ redirectTo }: { redirectTo?: string }) {
+ const { t } = await getTranslation();
+
+ return (
+ <AuthPageContainer>
+ <AuthPageHeader>
+ <AuthPageTitle>
+ <Trans
+ t={t}
+ ns="app"
+ i18nKey="alreadyLoggedInTitle"
+ defaults="You're already signed in"
+ />
+ </AuthPageTitle>
+ <AuthPageDescription>
+ <Trans
+ t={t}
+ ns="app"
+ i18nKey="alreadyLoggedInDescription"
+ defaults="Continue to your dashboard or sign out to use a different account."
+ />
+ </AuthPageDescription>
+ </AuthPageHeader>
+ <AuthPageContent>
+ <div className="grid gap-3">
+ <Link
+ className={buttonVariants({ variant: "primary", size: "xl" })}
+ href={validateRedirectUrl(redirectTo) ?? "/"}
+ >
+ <Trans
+ t={t}
+ ns="app"
+ i18nKey="alreadyLoggedInContinue"
+ defaults="Continue"
+ />
+ </Link>
+ <SignOutButton />
+ </div>
+ </AuthPageContent>
+ </AuthPageContainer>
+ );
+}
diff --git a/apps/web/src/app/[locale]/(auth)/components/sign-out-button.tsx b/apps/web/src/app/[locale]/(auth)/components/sign-out-button.tsx
new file mode 100644
index 000000000..65ca244b4
--- /dev/null
+++ b/apps/web/src/app/[locale]/(auth)/components/sign-out-button.tsx
@@ -0,0 +1,31 @@
+"use client";
+
+import { Button } from "@rallly/ui/button";
+import React from "react";
+import { Trans } from "@/i18n/client";
+import { signOut } from "@/lib/auth-client";
+
+export function SignOutButton() {
+ const [isSigningOut, setIsSigningOut] = React.useState(false);
+
+ return (
+ <Button
+ size="xl"
+ loading={isSigningOut}
+ onClick={() => {
+ setIsSigningOut(true);
+ signOut()
+ .catch(() => {
+ // Reload even if sign out fails: the server re-renders from
+ // the real cookie state, so the user sees this page again
+ // instead of a stuck spinner or an unhandled rejection.
+ })
+ .finally(() => {
+ window.location.reload();
+ });
+ }}
+ >
+ <Trans i18nKey="signOut" defaults="Sign Out" />
+ </Button>
+ );
+}
diff --git a/apps/web/src/app/[locale]/(auth)/login/page.tsx b/apps/web/src/app/[locale]/(auth)/login/page.tsx
index cabf0f636..fa120a4a9 100644
--- a/apps/web/src/app/[locale]/(auth)/login/page.tsx
+++ b/apps/web/src/app/[locale]/(auth)/login/page.tsx
@@ -4,8 +4,9 @@ import { OIDCAutoSignIn } from "@/app/[locale]/(auth)/login/components/oidc-auto
import { env } from "@/env";
import { getRegistrationEnabled } from "@/features/instance-settings/data";
import { getTranslation } from "@/i18n/server";
-import { authLib, redirectIfLoggedIn } from "@/lib/auth";
+import { authLib, getSessionState } from "@/lib/auth";
import { isFeatureEnabled } from "@/lib/feature-flags/server";
+import { AlreadyLoggedIn } from "../components/already-logged-in";
import {
AuthPageContainer,
AuthPageContent,
@@ -41,7 +42,17 @@ export default async function LoginPage(props: {
}) {
const searchParams = await props.searchParams;
- await redirectIfLoggedIn();
+ // No automatic redirect to / β€” an automated redirect here is one leg of
+ // the / ↔ /login redirect loop (RAL-1313). The user must click through.
+ // On "error" the session is unknown, so we fall through to the login
+ // form rather than guess.
+ const sessionState = await getSessionState();
+ if (
+ sessionState.status === "authenticated" &&
+ !sessionState.session.user.isGuest
+ ) {
+ return <AlreadyLoggedIn redirectTo={searchParams?.redirectTo} />;
+ }
const { isRegistrationEnabled, t } = await loadData();
const isEmailLoginEnabled = isFeatureEnabled("emailLogin");
diff --git a/apps/web/src/lib/auth-plugins/has-duplicate-cookie.test.ts b/apps/web/src/lib/auth-plugins/has-duplicate-cookie.test.ts
new file mode 100644
index 000000000..dfae07a06
--- /dev/null
+++ b/apps/web/src/lib/auth-plugins/has-duplicate-cookie.test.ts
@@ -0,0 +1,39 @@
+import { describe, expect, it } from "vitest";
+import { hasDuplicateCookie } from "./has-duplicate-cookie";
+
+describe("hasDuplicateCookie", () => {
+ const name = "__Secure-better-auth.session_token";
+
+ it("returns false for an empty header", () => {
+ expect(hasDuplicateCookie("", name)).toBe(false);
+ });
+
+ it("returns false when the cookie appears once", () => {
+ expect(hasDuplicateCookie(`${name}=abc.def; locale=en`, name)).toBe(false);
+ });
+
+ it("returns true when the cookie appears twice", () => {
+ expect(
+ hasDuplicateCookie(`${name}=old.sig; locale=en; ${name}=new.sig`, name),
+ ).toBe(true);
+ });
+
+ it("does not match cookies that share a prefix", () => {
+ expect(
+ hasDuplicateCookie(
+ `${name}=abc.def; ${name}.extra=zzz; better-auth.session_token=x`,
+ name,
+ ),
+ ).toBe(false);
+ });
+
+ it("matches regardless of surrounding whitespace", () => {
+ expect(hasDuplicateCookie(`${name}=a; ${name}=b`, name)).toBe(true);
+ });
+
+ it("ignores values that contain the cookie name", () => {
+ expect(hasDuplicateCookie(`other=${name}=abc; ${name}=a`, name)).toBe(
+ false,
+ );
+ });
+});
diff --git a/apps/web/src/lib/auth-plugins/has-duplicate-cookie.ts b/apps/web/src/lib/auth-plugins/has-duplicate-cookie.ts
new file mode 100644
index 000000000..c8b172012
--- /dev/null
+++ b/apps/web/src/lib/auth-plugins/has-duplicate-cookie.ts
@@ -0,0 +1,18 @@
+// Returns true when the raw Cookie header carries the same cookie name more
+// than once β€” the signature of a host-only leftover shadowing the
+// domain-scoped cookie. Must inspect the raw header: cookie parsers dedupe
+// by name, which is exactly the problem (the browser sends the older
+// host-only cookie first, so it wins every parsed read).
+export function hasDuplicateCookie(cookieHeader: string, name: string) {
+ let count = 0;
+ for (const part of cookieHeader.split(";")) {
+ const eqIndex = part.indexOf("=");
+ if (eqIndex !== -1 && part.slice(0, eqIndex).trim() === name) {
+ count++;
+ if (count > 1) {
+ return true;
+ }
+ }
+ }
+ return false;
+}
diff --git a/apps/web/src/lib/auth-plugins/host-only-cookie-cleanup.ts b/apps/web/src/lib/auth-plugins/host-only-cookie-cleanup.ts
index ee32112a6..4676a2948 100644
--- a/apps/web/src/lib/auth-plugins/host-only-cookie-cleanup.ts
+++ b/apps/web/src/lib/auth-plugins/host-only-cookie-cleanup.ts
@@ -1,10 +1,12 @@
+import { createLogger } from "@rallly/logger";
import type { BetterAuthPlugin } from "better-auth";
import { createAuthMiddleware } from "better-auth/api";
import { parseSetCookieHeader } from "better-auth/cookies";
import { env } from "@/env";
+import { hasDuplicateCookie } from "./has-duplicate-cookie";
+
+const logger = createLogger("auth");
-// Paths where better-auth either mints a new session cookie or clears the
-// existing one. The cleanup only runs on these.
// Deletes the host-only variants of better-auth's session cookies left over
// from before cross-subdomain mode was enabled. Must be registered *after*
// the anonymous plugin so its after-hook runs second β€” the anonymous plugin
@@ -18,18 +20,36 @@ export const hostOnlyCookieCleanup: BetterAuthPlugin = {
{
matcher: () => !!env.NEXT_PUBLIC_COOKIE_DOMAIN,
handler: createAuthMiddleware(async (ctx) => {
- // /sign-out always cleans up. For every other path, only clean
- // up when a real session token actually landed in the response
- // β€” covers sign-in, sign-up, OAuth callbacks, OTP verify, and
- // periodic session refresh, while skipping failed logins, OTP
- // sends, redirect-only endpoints, and plain session reads.
+ // /sign-out always cleans up. For every other path, clean up
+ // when a real session token landed in the response β€” covers
+ // sign-in, sign-up, OAuth callbacks, OTP verify, and periodic
+ // session refresh β€” or when the request itself proves a
+ // host-only leftover is shadowing the domain cookie (the same
+ // session token name appears twice in the Cookie header). The
+ // latter heals stuck users on any better-auth traffic instead
+ // of waiting for a sign-in they may never complete: a
+ // Set-Cookie carrying the domain attribute can never clear a
+ // host-only cookie, so without this the shadow wins every
+ // read until it expires.
if (ctx.path !== "/sign-out") {
const setCookie = ctx.context.responseHeaders?.get("set-cookie");
const sessionTokenName = ctx.context.authCookies.sessionToken.name;
const newToken = parseSetCookieHeader(setCookie ?? "")
.get(sessionTokenName)
?.value.split(".")[0];
- if (!newToken) return;
+ const hasShadowedSessionToken = hasDuplicateCookie(
+ ctx.headers?.get("cookie") ?? "",
+ sessionTokenName,
+ );
+ if (!newToken && !hasShadowedSessionToken) return;
+ if (!newToken) {
+ // Observability for the healing path: how often shadowed
+ // cookies are still out there. No token values logged.
+ logger.info(
+ { path: ctx.path },
+ "Clearing shadowed host-only session cookies",
+ );
+ }
}
for (const cookie of [
ctx.context.authCookies.sessionToken,
diff --git a/apps/web/src/lib/auth.ts b/apps/web/src/lib/auth.ts
index 6c7241fb6..d4ba24669 100644
--- a/apps/web/src/lib/auth.ts
+++ b/apps/web/src/lib/auth.ts
@@ -524,7 +524,25 @@ export type Auth = typeof authLib;
const parseTimeFormat = (value: unknown): TimeFormat | undefined =>
value === "hours12" || value === "hours24" ? value : undefined;
-export const getSession = cache(async () => {
+export type SessionData = {
+ user: UserDTO;
+ expires: string;
+ updatedAt: string;
+};
+
+/**
+ * "Couldn't read the session" (session store unreachable, transient
+ * failure) is not the same as "there is no session". Redirect guards must
+ * not treat an error as either logged-in or logged-out β€” reacting to an
+ * unknown state is what turns a transient failure into a redirect loop
+ * between / and /login (RAL-1313).
+ */
+export type SessionState =
+ | { status: "authenticated"; session: SessionData }
+ | { status: "unauthenticated" }
+ | { status: "error" };
+
+export const getSessionState = cache(async (): Promise<SessionState> => {
try {
const session = await authLib.api.getSession({
headers: await headers(),
@@ -546,19 +564,32 @@ export const getSession = cache(async () => {
};
return {
- user,
- expires: session.session.expiresAt.toISOString(),
- updatedAt: session.session.updatedAt.toISOString(),
+ status: "authenticated",
+ session: {
+ user,
+ expires: session.session.expiresAt.toISOString(),
+ updatedAt: session.session.updatedAt.toISOString(),
+ },
};
}
} catch (e) {
logger.error({ error: e }, "Failed to get session");
- return null;
+ return { status: "error" };
}
- return null;
+ return { status: "unauthenticated" };
});
+/**
+ * Session-or-null view for callers where an unreadable session can safely
+ * degrade to "no session" (optional personalization, public reads). Guards
+ * that redirect or gate access should use getSessionState instead.
+ */
+export const getSession = async () => {
+ const state = await getSessionState();
+ return state.status === "authenticated" ? state.session : null;
+};
+
export const signOut = async () => {
await authLib.api.signOut({
headers: await headers(),
@@ -571,8 +602,10 @@ export const getUserIdIfLoggedIn = async () => {
};
export const redirectIfLoggedIn = async () => {
- const session = await getSession();
- if (session?.user && !session.user.isGuest) {
+ const state = await getSessionState();
+ // On "error" the session is unknown β€” render the page rather than
+ // redirect, so a transient session-store failure can't feed a loop.
+ if (state.status === "authenticated" && !state.session.user.isGuest) {
redirect("/");
}
};
diff --git a/apps/web/src/trpc/server/create-ssr-helper.ts b/apps/web/src/trpc/server/create-ssr-helper.ts
index fb7fd600d..4c90416a9 100644
--- a/apps/web/src/trpc/server/create-ssr-helper.ts
+++ b/apps/web/src/trpc/server/create-ssr-helper.ts
@@ -4,7 +4,7 @@ import { cache } from "react";
import superjson from "superjson";
import { isInitialAdmin } from "@/features/setup/utils";
import { getCurrentUser } from "@/features/user/data";
-import { getSession } from "@/lib/auth";
+import { getSession, getSessionState } from "@/lib/auth";
import { InvalidSessionError } from "@/lib/errors/invalid-session-error";
import { getPathname } from "@/lib/pathname";
import { buildSafeRedirectUrl } from "@/lib/utils/redirect";
@@ -36,7 +36,18 @@ export const createPublicSSRHelper = cache(async () => {
* Redirects to /login if the user is not authenticated or is a guest.
*/
export const createPrivateSSRHelper = cache(async () => {
- const user = (await getSession())?.user;
+ const state = await getSessionState();
+
+ // An unreadable session (store unreachable, transient failure) is not
+ // "logged out". Redirecting to /login on it is one leg of the / ↔ /login
+ // redirect loop (RAL-1313) β€” fail the render instead so the user gets
+ // the error boundary's retry page.
+ if (state.status === "error") {
+ throw new Error("Failed to read session");
+ }
+
+ const user =
+ state.status === "authenticated" ? state.session.user : undefined;
if (!user || user.isGuest) {
const pathname = await getPathname();