Skip to content

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

πŸ› Stop setup from creating a second space for existing accounts (#2770)

Luke Vella178c1d001cb5
diff --git a/apps/web/src/app/[locale]/setup/page.tsx b/apps/web/src/app/[locale]/setup/page.tsx
index 6f71c89d4..de26612c5 100644
--- a/apps/web/src/app/[locale]/setup/page.tsx
+++ b/apps/web/src/app/[locale]/setup/page.tsx
@@ -4,7 +4,7 @@ import { SetupFooter } from "@/app/[locale]/setup/components/setup-footer";
import { SetupForm } from "@/app/[locale]/setup/components/setup-form";
import { ThemeSwitcher } from "@/components/theme-switcher";
import { Logo } from "@/features/branding/components/logo";
-import { getActiveSpaceForUser } from "@/features/space/data";
+import { getOwnedSpace } from "@/features/space/data";
import { requireUser } from "@/features/user/loaders";
import { Trans } from "@/i18n/client";
import { getTranslation } from "@/i18n/server";
@@ -17,7 +17,11 @@ export default async function SetupPage(props: {
const user = await requireUser();
const searchParams = await props.searchParams;
- const space = await getActiveSpaceForUser(user.id);
+ // Whether onboarding is done is "does a space exist", not "is one
+ // active": getActiveSpaceForUser hides memberships in hobby spaces the
+ // user doesn't own, so gating on it sent established accounts back here
+ // and had them create a second space.
+ const space = await getOwnedSpace(user.id);
if (user.name && user.timeZone && user.timeFormat && space) {
redirect(validateRedirectUrl(searchParams?.redirectTo) ?? "/");
diff --git a/apps/web/src/features/space/loaders.test.ts b/apps/web/src/features/space/loaders.test.ts
new file mode 100644
index 000000000..e5224b50a
--- /dev/null
+++ b/apps/web/src/features/space/loaders.test.ts
@@ -0,0 +1,139 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+vi.mock("server-only", () => ({}));
+
+const REDIRECT = "NEXT_REDIRECT";
+const NOT_FOUND = "NEXT_NOT_FOUND";
+
+const mockRedirect = vi.fn((url: string) => {
+ throw Object.assign(new Error(REDIRECT), { digest: `${REDIRECT};${url}` });
+});
+const mockNotFound = vi.fn(() => {
+ throw Object.assign(new Error(NOT_FOUND), { digest: NOT_FOUND });
+});
+
+vi.mock("next/navigation", () => ({
+ redirect: (url: string) => mockRedirect(url),
+ notFound: () => mockNotFound(),
+}));
+
+const mockGetSessionState = vi.fn();
+const mockGetActiveSpaceForUser = vi.fn();
+const mockGetOwnedSpace = vi.fn();
+
+vi.mock("@/lib/auth", () => ({
+ getSessionState: () => mockGetSessionState(),
+}));
+
+vi.mock("@/features/space/data", () => ({
+ getActiveSpaceForUser: (userId: string) => mockGetActiveSpaceForUser(userId),
+ getOwnedSpace: (userId: string) => mockGetOwnedSpace(userId),
+ getSpaceSeatCount: vi.fn(),
+ getTotalSeatsForSpace: vi.fn(),
+}));
+
+vi.mock("@/lib/pathname", () => ({
+ getPathname: () => Promise.resolve("/polls"),
+}));
+
+const completeUser = {
+ id: "user-1",
+ email: "[email protected]",
+ name: "Jessie Smith",
+ isGuest: false,
+ banned: false,
+ timeZone: "Europe/London",
+ timeFormat: "hours12",
+};
+
+const authenticatedAs = (user: Record<string, unknown>) => {
+ mockGetSessionState.mockResolvedValue({
+ status: "authenticated",
+ session: { user },
+ });
+};
+
+// getActiveSpace is React-cached, so each case needs a fresh module registry
+// or the first call's result leaks into the next test.
+const loadGate = async () => {
+ vi.resetModules();
+ const mod = await import("./loaders");
+ return mod.getActiveSpace;
+};
+
+describe("getActiveSpace", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it("returns the active space when the user has one", async () => {
+ const space = { id: "space-1", name: "Personal" };
+ authenticatedAs(completeUser);
+ mockGetActiveSpaceForUser.mockResolvedValue(space);
+
+ const gate = await loadGate();
+
+ await expect(gate()).resolves.toEqual(space);
+ expect(mockRedirect).not.toHaveBeenCalled();
+ expect(mockNotFound).not.toHaveBeenCalled();
+ });
+
+ it("redirects to /setup when the user owns no space at all", async () => {
+ authenticatedAs(completeUser);
+ mockGetActiveSpaceForUser.mockResolvedValue(null);
+ mockGetOwnedSpace.mockResolvedValue(null);
+
+ const gate = await loadGate();
+
+ await expect(gate()).rejects.toThrow(REDIRECT);
+ expect(mockRedirect).toHaveBeenCalledWith(
+ expect.stringContaining("/setup"),
+ );
+ });
+
+ // The bug: an owned-but-inaccessible space used to fall through to the
+ // /setup redirect, where onboarding created a second space.
+ it("renders not-found when the user owns a space but none is active", async () => {
+ authenticatedAs(completeUser);
+ mockGetActiveSpaceForUser.mockResolvedValue(null);
+ mockGetOwnedSpace.mockResolvedValue({ id: "space-1" });
+
+ const gate = await loadGate();
+
+ await expect(gate()).rejects.toThrow(NOT_FOUND);
+ expect(mockNotFound).toHaveBeenCalled();
+ expect(mockRedirect).not.toHaveBeenCalled();
+ });
+
+ it("redirects to /setup when profile fields are missing, before reading spaces", async () => {
+ authenticatedAs({ ...completeUser, timeFormat: undefined });
+
+ const gate = await loadGate();
+
+ await expect(gate()).rejects.toThrow(REDIRECT);
+ expect(mockRedirect).toHaveBeenCalledWith(
+ expect.stringContaining("/setup"),
+ );
+ expect(mockGetActiveSpaceForUser).not.toHaveBeenCalled();
+ });
+
+ it("redirects to /login for a guest", async () => {
+ authenticatedAs({ ...completeUser, isGuest: true });
+
+ const gate = await loadGate();
+
+ await expect(gate()).rejects.toThrow(REDIRECT);
+ expect(mockRedirect).toHaveBeenCalledWith(
+ expect.stringContaining("/login"),
+ );
+ });
+
+ it("fails the render on an unreadable session instead of redirecting", async () => {
+ mockGetSessionState.mockResolvedValue({ status: "error" });
+
+ const gate = await loadGate();
+
+ await expect(gate()).rejects.toThrow("Failed to read session");
+ expect(mockRedirect).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/web/src/features/space/loaders.ts b/apps/web/src/features/space/loaders.ts
index f1c7aabf2..53ab81092 100644
--- a/apps/web/src/features/space/loaders.ts
+++ b/apps/web/src/features/space/loaders.ts
@@ -1,10 +1,11 @@
import "server-only";
-import { redirect } from "next/navigation";
+import { notFound, redirect } from "next/navigation";
import { cache } from "react";
import {
getActiveSpaceForUser,
+ getOwnedSpace,
getSpaceSeatCount,
getTotalSeatsForSpace,
} from "@/features/space/data";
@@ -16,8 +17,8 @@ import { buildSafeRedirectUrl } from "@/lib/utils/redirect";
/**
* The active space for the signed-in user, gated for server rendering:
* redirects to /login when unauthenticated or a guest, redirects to /setup
- * when the user has no name, timezone, time format, or space, and throws
- * InvalidSessionError when banned.
+ * when the user has no name, timezone, time format, or space at all, and
+ * throws InvalidSessionError when banned.
* React cached, so every page and layout that needs the space in a request
* shares one gate and one query. Server component/page use only β€” the
* redirects make it unsuitable for route handlers and tRPC procedures.
@@ -65,6 +66,18 @@ export const getActiveSpace = cache(async () => {
const space = await getActiveSpaceForUser(user.id);
if (!space) {
+ // Only send them to onboarding when they genuinely have no space.
+ // A user can resolve to no *active* space while still owning one
+ // (their only other memberships are ineffective, or their own
+ // membership row is gone) β€” /setup would bounce them straight back,
+ // so render the not-found page instead of looping. notFound() rather
+ // than a thrown AppError: nothing adapts AppError for server
+ // components, so it would reach the error boundary as an unexpected
+ // error, showing "Something went wrong" and reporting to Sentry.
+ if (await getOwnedSpace(user.id)) {
+ notFound();
+ }
+
redirect(
buildSafeRedirectUrl({
destination: "/setup",