⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.
TypeScript honoissue-managementissue-trackerjira-alternativekanbanlinear-alternativemcpproject-managementreactself-hostedtypescript
fix(auth): prevent repeated 401s for pending invitations after session expiry (#1715)
sentry[bot]d4797a764f8a
diff --git a/apps/web/src/hooks/queries/invitation/use-pending-invitations.test.tsx b/apps/web/src/hooks/queries/invitation/use-pending-invitations.test.tsxnew file mode 100644index 000000000..165603e4f--- /dev/null+++ b/apps/web/src/hooks/queries/invitation/use-pending-invitations.test.tsx@@ -0,0 +1,90 @@+import { QueryClientProvider } from "@tanstack/react-query";+import { act, cleanup, renderHook } from "@testing-library/react";+import type { PropsWithChildren } from "react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { getPendingInvitations } from "@/fetchers/invitation/get-pending-invitations";+import { HttpError, handleUnauthorized } from "@/lib/http-error";+import queryClient from "@/query-client";+import { usePendingInvitations } from "./use-pending-invitations";++const auth = vi.hoisted(() => ({+ email: "[email protected]" as string | undefined,+}));++vi.mock("@/lib/auth-client", () => ({+ authClient: { useSession: () => ({ data: { user: { email: auth.email } } }) },+}));+vi.mock("@/fetchers/invitation/get-pending-invitations", () => ({+ getPendingInvitations: vi.fn(),+}));+vi.mock("@/lib/http-error", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@/lib/http-error")>()),+ // Leave the page mounted to exercise a delayed sign-in redirect.+ handleUnauthorized: vi.fn(),+}));+vi.mock("@sentry/react", () => ({ captureException: vi.fn() }));++function wrapper({ children }: PropsWithChildren) {+ return (+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>+ );+}++async function advance(ms: number) {+ await act(async () => {+ await vi.advanceTimersByTimeAsync(ms);+ });+}++beforeEach(() => {+ vi.useFakeTimers();+ vi.mocked(getPendingInvitations).mockReset();+ auth.email = "[email protected]";+});++afterEach(() => {+ cleanup();+ queryClient.clear();+ vi.useRealTimers();+});++describe("pending invitation polling", () => {+ it.each([+ ["HttpError", new HttpError(401, "Session expired")],+ ["an error with a different prototype", { name: "HttpError", status: 401 }],+ ])(+ "stops after a 401 from %s even with a stale session",+ async (_, error) => {+ vi.mocked(getPendingInvitations).mockRejectedValue(error);+ const { result, rerender } = renderHook(usePendingInvitations, {+ wrapper,+ });+ await advance(1);+ expect(handleUnauthorized).toHaveBeenCalledTimes(1);++ rerender();+ await advance(180_000);++ expect(getPendingInvitations).toHaveBeenCalledTimes(1);+ expect(result.current.error).toBe(error);+ expect(handleUnauthorized).toHaveBeenCalledTimes(1);+ },+ );++ it("continues polling every minute while signed in", async () => {+ vi.mocked(getPendingInvitations).mockResolvedValue([]);+ renderHook(usePendingInvitations, { wrapper });+ await advance(1);+ expect(getPendingInvitations).toHaveBeenCalledTimes(1);+ await advance(60_000);+ expect(getPendingInvitations).toHaveBeenCalledTimes(2);+ expect(handleUnauthorized).not.toHaveBeenCalled();+ });++ it("does not poll without a session email", async () => {+ auth.email = undefined;+ renderHook(usePendingInvitations, { wrapper });+ await advance(180_000);+ expect(getPendingInvitations).not.toHaveBeenCalled();+ });+});diff --git a/apps/web/src/lib/http-error.test.ts b/apps/web/src/lib/http-error.test.tsnew file mode 100644index 000000000..83761d42f--- /dev/null+++ b/apps/web/src/lib/http-error.test.ts@@ -0,0 +1,30 @@+import { describe, expect, it } from "vitest";+import { HttpError, isUnauthorizedError } from "./http-error";++describe("isUnauthorizedError", () => {+ it("recognizes a 401 HttpError with a different prototype", () => {+ const error = Object.assign(new Error("Session expired"), {+ name: "HttpError",+ status: 401,+ });+ expect(error).not.toBeInstanceOf(HttpError);+ expect(isUnauthorizedError(error)).toBe(true);+ expect(isUnauthorizedError(new HttpError(401, "Session expired"))).toBe(+ true,+ );+ });++ it.each([+ null,+ undefined,+ "401",+ new Error("401"),+ new HttpError(403, "Forbidden"),+ { name: "HttpError", status: "401" },+ { name: "HttpError", status: 500 },+ { name: "TypeError", status: 401 },+ { status: 401 },+ ])("rejects other errors: %j", (error) => {+ expect(isUnauthorizedError(error)).toBe(false);+ });+});diff --git a/apps/web/src/lib/http-error.ts b/apps/web/src/lib/http-error.tsindex 755deef0f..2f09fe596 100644--- a/apps/web/src/lib/http-error.ts+++ b/apps/web/src/lib/http-error.ts@@ -9,7 +9,16 @@ export class HttpError extends Error {}export function isUnauthorizedError(error: unknown): boolean {- return error instanceof HttpError && error.status === 401;+ if (error instanceof HttpError) return error.status === 401;+ // Recognize HttpError-shaped values even when their prototype differs.+ return (+ typeof error === "object" &&+ error !== null &&+ "name" in error &&+ error.name === "HttpError" &&+ "status" in error &&+ error.status === 401+ );}// Shared unauthorized redirect for both the React Query error cache and directdiff --git a/apps/web/src/query-client/index.ts b/apps/web/src/query-client/index.tsindex 387fcd979..befd3f98b 100644--- a/apps/web/src/query-client/index.ts+++ b/apps/web/src/query-client/index.ts@@ -57,6 +57,8 @@ const queryClient = new QueryClient({queryCache: new QueryCache({onError: (error) => {if (isUnauthorizedError(error)) {+ // Keep the 401 in query state so polling guards stay stopped while+ // navigation completes. Better Auth's session is a separate store.handleUnauthorized();return;}