Skip to content

armgit / kaneo

Public Imported from GitHub
0

⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.

fix(web): preserve custom OAuth logout redirects (#2103)

Tin Sever4b69fd317a30
diff --git a/apps/web/src/components/onboarding/onboarding-flow.test.tsx b/apps/web/src/components/onboarding/onboarding-flow.test.tsx
index dd1ccc7e0..735dfc35e 100644
--- a/apps/web/src/components/onboarding/onboarding-flow.test.tsx
+++ b/apps/web/src/components/onboarding/onboarding-flow.test.tsx
@@ -29,6 +29,8 @@ const m = vi.hoisted(() => ({
inviteMember: vi.fn(),
checkout: vi.fn(),
signOut: vi.fn(),
+ useSignOut: vi.fn(),
+ toastError: vi.fn(),
}));
vi.mock("@tanstack/react-router", async (importOriginal) => ({
@@ -38,6 +40,12 @@ vi.mock("@tanstack/react-router", async (importOriginal) => ({
vi.mock("@/hooks/queries/config/use-get-config", () => ({
default: () => m.config(),
}));
+vi.mock("@/hooks/mutations/use-sign-out", () => ({
+ default: (logoutUrl?: string | null) => m.useSignOut(logoutUrl),
+}));
+vi.mock("@/lib/toast", () => ({
+ toast: { error: m.toastError, success: vi.fn() },
+}));
vi.mock("@/lib/auth-client", () => ({
authClient: {
organization: { setActive: vi.fn() },
@@ -90,6 +98,7 @@ beforeEach(() => {
m.getBilling.mockResolvedValue({ billingEnabled: false });
m.inviteMember.mockResolvedValue({ id: "invite-1" });
m.signOut.mockResolvedValue({});
+ m.useSignOut.mockReturnValue({ mutateAsync: m.signOut });
});
afterEach(() => {
@@ -237,10 +246,41 @@ describe("OnboardingFlow steps", () => {
screen.getByRole("button", { name: "auth:onboarding.signOut" }),
);
+ await waitFor(() => expect(m.signOut).toHaveBeenCalledTimes(1));
+ expect(m.navigate).not.toHaveBeenCalled();
+ });
+
+ it("uses the configured provider logout without a competing sign-in navigation", async () => {
+ m.config.mockReturnValue({
+ data: { customOAuthLogoutUrl: "https://idp.example.test/end-session" },
+ isPending: false,
+ });
+ render(<OnboardingFlow />);
+ await settled();
+ fireEvent.click(
+ screen.getByRole("button", { name: "auth:onboarding.signOut" }),
+ );
+
+ await waitFor(() => expect(m.signOut).toHaveBeenCalledTimes(1));
+ expect(m.useSignOut).toHaveBeenCalledWith(
+ "https://idp.example.test/end-session",
+ );
+ expect(m.navigate).not.toHaveBeenCalled();
+ });
+
+ it("stays on onboarding and reports a failed sign-out", async () => {
+ m.signOut.mockRejectedValueOnce(new Error("Could not sign out"));
+ render(<OnboardingFlow />);
+ await settled();
+ fireEvent.click(
+ screen.getByRole("button", { name: "auth:onboarding.signOut" }),
+ );
+
await waitFor(() =>
- expect(m.navigate).toHaveBeenCalledWith({ to: "/auth/sign-in" }),
+ expect(m.toastError).toHaveBeenCalledWith("Could not sign out"),
);
- expect(m.signOut).toHaveBeenCalledTimes(1);
+ expect(m.navigate).not.toHaveBeenCalled();
+ expect(creationForm()).toBeInTheDocument();
});
});
diff --git a/apps/web/src/components/onboarding/onboarding-flow.tsx b/apps/web/src/components/onboarding/onboarding-flow.tsx
index 56c73350b..19b856ed3 100644
--- a/apps/web/src/components/onboarding/onboarding-flow.tsx
+++ b/apps/web/src/components/onboarding/onboarding-flow.tsx
@@ -10,6 +10,7 @@ import {
} from "@/constants/onboarding";
import { getBilling } from "@/fetchers/billing/get-billing";
import { useCreateCheckout } from "@/hooks/mutations/billing/use-billing-actions";
+import useSignOut from "@/hooks/mutations/use-sign-out";
import useGetConfig from "@/hooks/queries/config/use-get-config";
import useCreateWorkspace from "@/hooks/queries/workspace/use-create-workspace";
import useWorkspaceCreationAccess from "@/hooks/use-workspace-creation-access";
@@ -65,6 +66,7 @@ export function OnboardingFlow() {
const { isCreationRestricted, isDecided: isAccessDecided } =
useWorkspaceCreationAccess();
const { data: config, isPending: isConfigPending } = useGetConfig();
+ const { mutateAsync: signOut } = useSignOut(config?.customOAuthLogoutUrl);
const isDecided = isAccessDecided && !isConfigPending;
const isCloud = config?.isCloud === true;
@@ -184,9 +186,16 @@ export function OnboardingFlow() {
setOpening(true);
};
- const signOut = async () => {
- await authClient.signOut().catch(() => undefined);
- navigate({ to: "/auth/sign-in" });
+ const handleSignOut = async () => {
+ try {
+ await signOut();
+ } catch (error) {
+ toast.error(
+ error instanceof Error
+ ? error.message
+ : t("navigation:userMenu.signOutFailed"),
+ );
+ }
};
if (step === "workspace" && !isDecided) {
@@ -324,7 +333,7 @@ export function OnboardingFlow() {
description={heading.description}
email={user?.email}
opening={opening}
- onSignOut={signOut}
+ onSignOut={handleSignOut}
preview={
<WorkspacePreview
label={
diff --git a/apps/web/src/hooks/mutations/use-sign-out.test.ts b/apps/web/src/hooks/mutations/use-sign-out.test.ts
new file mode 100644
index 000000000..496a50337
--- /dev/null
+++ b/apps/web/src/hooks/mutations/use-sign-out.test.ts
@@ -0,0 +1,168 @@
+import { cleanup, renderHook } from "@testing-library/react";
+import {
+ afterEach,
+ beforeEach,
+ describe,
+ expect,
+ it,
+ vi,
+} from "vite-plus/test";
+import { handleUnauthorized } from "@/lib/http-error";
+import { signOutState } from "@/lib/sign-out-state";
+import useSignOut from "./use-sign-out";
+
+const m = vi.hoisted(() => ({
+ signOut: vi.fn(),
+ getIdToken: vi.fn(),
+ navigate: vi.fn(),
+ pause: vi.fn(),
+ resume: vi.fn(),
+ drain: vi.fn(),
+ clear: vi.fn(),
+}));
+
+vi.mock("@tanstack/react-query", () => ({
+ useMutation: ({ mutationFn }: { mutationFn: () => Promise<unknown> }) => ({
+ mutateAsync: mutationFn,
+ }),
+}));
+vi.mock("@tanstack/react-router", () => ({ useNavigate: () => m.navigate }));
+vi.mock("@/lib/auth-client", () => ({
+ authClient: {
+ useSession: () => ({ data: { user: { id: "user" } } }),
+ signOut: m.signOut,
+ },
+}));
+vi.mock("@/fetchers/oauth/get-id-token", () => ({ getIdToken: m.getIdToken }));
+vi.mock("@/lib/description-save-queue", () => ({
+ descriptionSaveQueue: { pause: m.pause, drain: m.drain, clear: m.clear },
+}));
+vi.mock("@/lib/i18n", () => ({ i18n: { t: (key: string) => key } }));
+
+const location = {
+ origin: "https://kaneo.example.test",
+ pathname: "/dashboard",
+ search: "",
+ hash: "",
+ href: "https://kaneo.example.test/dashboard",
+ replace: vi.fn(),
+};
+
+beforeEach(() => {
+ vi.resetAllMocks();
+ signOutState.isRedirecting = false;
+ location.href = "https://kaneo.example.test/dashboard";
+ vi.stubGlobal("window", { location });
+ m.pause.mockReturnValue(m.resume);
+ m.drain.mockResolvedValue(true);
+ m.getIdToken.mockResolvedValue({ idToken: "test-id-token" });
+ m.signOut.mockResolvedValue({ data: { success: true }, error: null });
+});
+
+afterEach(() => {
+ cleanup();
+ signOutState.isRedirecting = false;
+ vi.unstubAllGlobals();
+});
+
+describe("custom OAuth sign-out", () => {
+ it("protects the IdP navigation from 401s during and after local sign-out", async () => {
+ m.getIdToken.mockImplementation(async () => {
+ handleUnauthorized();
+ return { idToken: "test-id-token" };
+ });
+ m.signOut.mockImplementation(async () => {
+ expect(signOutState.isRedirecting).toBe(true);
+ expect(m.getIdToken).toHaveBeenCalledTimes(1);
+ handleUnauthorized();
+ return { data: { success: true }, error: null };
+ });
+
+ const { result } = renderHook(() =>
+ useSignOut("https://idp.example.test/logout?client_id=kaneo"),
+ );
+ await result.current.mutateAsync();
+ // Cache cleanup and session listeners can still receive 401s until unload.
+ handleUnauthorized();
+
+ const url = new URL(location.href);
+ expect(url.origin + url.pathname).toBe("https://idp.example.test/logout");
+ expect(url.searchParams.get("client_id")).toBe("kaneo");
+ expect(url.searchParams.get("id_token_hint")).toBe("test-id-token");
+ expect(url.searchParams.get("post_logout_redirect_uri")).toBe(
+ "https://kaneo.example.test/auth/sign-in",
+ );
+ expect(location.replace).not.toHaveBeenCalled();
+ expect(m.navigate).not.toHaveBeenCalled();
+ expect(m.clear).toHaveBeenCalledTimes(1);
+ expect(m.resume).toHaveBeenCalledTimes(1);
+ });
+
+ it("still logs out at the IdP when the ID token is unavailable", async () => {
+ m.getIdToken.mockRejectedValue(new Error("Token unavailable"));
+
+ const { result } = renderHook(() =>
+ useSignOut("https://idp.example.test/logout"),
+ );
+ await result.current.mutateAsync();
+
+ expect(m.signOut).toHaveBeenCalledTimes(1);
+ expect(new URL(location.href).searchParams.has("id_token_hint")).toBe(
+ false,
+ );
+ expect(signOutState.isRedirecting).toBe(true);
+ });
+
+ it.each(["response", "network"])(
+ "restores ordinary unauthorized navigation after a %s failure",
+ async (failure) => {
+ if (failure === "response") {
+ m.signOut.mockResolvedValue({ error: { message: "Sign-out failed" } });
+ } else {
+ m.signOut.mockRejectedValue(new Error("Sign-out failed"));
+ }
+
+ const { result } = renderHook(() =>
+ useSignOut("https://idp.example.test/logout"),
+ );
+ await expect(result.current.mutateAsync()).rejects.toThrow(
+ "Sign-out failed",
+ );
+
+ expect(signOutState.isRedirecting).toBe(false);
+ expect(location.href).toBe("https://kaneo.example.test/dashboard");
+ expect(m.clear).not.toHaveBeenCalled();
+ expect(m.resume).toHaveBeenCalledTimes(1);
+ handleUnauthorized();
+ expect(location.replace).toHaveBeenCalledWith(
+ "/auth/sign-in?redirect=%2Fdashboard",
+ );
+ },
+ );
+
+ it("keeps local-only sign-out and unauthorized navigation working", async () => {
+ const { result } = renderHook(() => useSignOut());
+ await result.current.mutateAsync();
+
+ expect(m.getIdToken).not.toHaveBeenCalled();
+ expect(m.navigate).toHaveBeenCalledWith({ to: "/auth/sign-in" });
+ expect(signOutState.isRedirecting).toBe(false);
+ handleUnauthorized();
+ expect(location.replace).toHaveBeenCalledTimes(1);
+ });
+
+ it("does not end the session when pending edits cannot be saved", async () => {
+ m.drain.mockResolvedValue(false);
+
+ const { result } = renderHook(() =>
+ useSignOut("https://idp.example.test/logout"),
+ );
+ await expect(result.current.mutateAsync()).rejects.toThrow(
+ "tasks:detail.editor.saveFailed",
+ );
+
+ expect(m.signOut).not.toHaveBeenCalled();
+ expect(signOutState.isRedirecting).toBe(false);
+ expect(m.resume).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/apps/web/src/hooks/mutations/use-sign-out.ts b/apps/web/src/hooks/mutations/use-sign-out.ts
index 071776637..fe5db7899 100644
--- a/apps/web/src/hooks/mutations/use-sign-out.ts
+++ b/apps/web/src/hooks/mutations/use-sign-out.ts
@@ -4,6 +4,7 @@ import { getIdToken } from "@/fetchers/oauth/get-id-token";
import { descriptionSaveQueue } from "@/lib/description-save-queue";
import { i18n } from "@/lib/i18n";
import { authClient } from "@/lib/auth-client";
+import { signOutState } from "@/lib/sign-out-state";
function useSignOut(idpLogoutUrl?: string | null) {
const navigate = useNavigate();
@@ -15,39 +16,35 @@ function useSignOut(idpLogoutUrl?: string | null) {
try {
if (!(await descriptionSaveQueue.drain(session?.user.id ?? "")))
throw new Error(i18n.t("tasks:detail.editor.saveFailed"));
- let idToken: string | null = null;
-
- if (idpLogoutUrl) {
+ const url = idpLogoutUrl ? new URL(idpLogoutUrl) : null;
+ if (url) {
+ url.searchParams.set(
+ "post_logout_redirect_uri",
+ `${window.location.origin}/auth/sign-in`,
+ );
+ signOutState.isRedirecting = true;
try {
- const data = await getIdToken();
- idToken = data.idToken;
+ const { idToken } = await getIdToken();
+ if (idToken) url.searchParams.set("id_token_hint", idToken);
} catch {
- // If we can't get the id_token, proceed without it
+ // If we can't get the id_token, proceed without it.
}
}
- const result = await authClient.signOut({
- fetchOptions: {
- onSuccess: () => {
- descriptionSaveQueue.clear();
- if (idpLogoutUrl) {
- const redirectUri = `${window.location.origin}/auth/sign-in`;
- const url = new URL(idpLogoutUrl);
- url.searchParams.set("post_logout_redirect_uri", redirectUri);
- if (idToken) {
- url.searchParams.set("id_token_hint", idToken);
- }
- window.location.href = url.toString();
- } else {
- navigate({ to: "/auth/sign-in" });
- }
- },
- },
- });
+ const result = await authClient.signOut();
if (result.error) {
throw new Error(result.error.message);
}
+ descriptionSaveQueue.clear();
+ if (url) {
+ window.location.href = url.toString();
+ } else {
+ await navigate({ to: "/auth/sign-in" });
+ }
return result.data;
+ } catch (error) {
+ signOutState.isRedirecting = false;
+ throw error;
} finally {
resume();
}
diff --git a/apps/web/src/lib/http-error.ts b/apps/web/src/lib/http-error.ts
index 2dd82005f..e496ed11f 100644
--- a/apps/web/src/lib/http-error.ts
+++ b/apps/web/src/lib/http-error.ts
@@ -1,4 +1,5 @@
import i18n from "i18next";
+import { signOutState } from "./sign-out-state";
import {
type ApiErrorDetails,
type ApiErrorIssue,
@@ -60,6 +61,7 @@ export function isUnauthorizedError(error: unknown): boolean {
// current pathname/search/hash so the sign-in page can return the user to
// where they were instead of dropping them on /dashboard.
export function handleUnauthorized(): void {
+ if (signOutState.isRedirecting) return;
const currentPath =
window.location.pathname + window.location.search + window.location.hash;
const target = currentPath
diff --git a/apps/web/src/lib/sign-out-state.ts b/apps/web/src/lib/sign-out-state.ts
new file mode 100644
index 000000000..6925bf7aa
--- /dev/null
+++ b/apps/web/src/lib/sign-out-state.ts
@@ -0,0 +1,2 @@
+// Keep late 401 responses from replacing a pending identity-provider navigation.
+export const signOutState = { isRedirecting: false };