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): recheck the session instead of signing out when a socket's session ends

tiran133088467707a16
diff --git a/apps/api/src/ws/index.ts b/apps/api/src/ws/index.ts
index 7f9447bb4..5d7ec3cef 100644
--- a/apps/api/src/ws/index.ts
+++ b/apps/api/src/ws/index.ts
@@ -52,7 +52,7 @@ type UserConnection = {
sessionId: string | null;
};
-// Only sockets of an ended session get this code, so the web signs out just that browser.
+// Only sockets of an ended session get this code, so the web rechecks its cookie.
export const SESSION_ENDED_CLOSE_CODE = 4001;
/**
diff --git a/apps/web/src/hooks/use-project-websocket-access.test.tsx b/apps/web/src/hooks/use-project-websocket-access.test.tsx
index b817db69c..5c2b0d8c6 100644
--- a/apps/web/src/hooks/use-project-websocket-access.test.tsx
+++ b/apps/web/src/hooks/use-project-websocket-access.test.tsx
@@ -28,15 +28,22 @@ const { client, auth, navigate, cached, evictProjectCache } = vi.hoisted(
clear: vi.fn(),
},
navigate: vi.fn(),
- auth: { userId: "user-a" as string | null },
+ auth: {
+ userId: "user-a" as string | null,
+ sessionId: "session-a",
+ getSession: vi.fn().mockResolvedValue({ data: null }),
+ },
}),
);
vi.mock("@tanstack/react-router", () => ({ useNavigate: () => navigate }));
vi.mock("@tanstack/react-query", () => ({ useQueryClient: () => client }));
vi.mock("@/lib/auth-client", () => ({
authClient: {
+ getSession: auth.getSession,
useSession: () => ({
- data: auth.userId ? { user: { id: auth.userId } } : null,
+ data: auth.userId
+ ? { user: { id: auth.userId }, session: { id: auth.sessionId } }
+ : null,
}),
},
}));
@@ -71,6 +78,7 @@ describe("project WebSocket access", () => {
vi.stubEnv("VITE_API_URL", "http://localhost:1337");
TestSocket.instances = [];
auth.userId = "user-a";
+ auth.sessionId = "session-a";
cached.queries = [];
vi.clearAllMocks();
});
@@ -139,18 +147,88 @@ describe("project WebSocket access", () => {
expect(navigate).toHaveBeenCalledWith({ to: "/dashboard" });
});
- it("stops reconnecting after the provider ends the session", () => {
+ it.each([
+ ["no session", { data: null }],
+ ["an expired session", { data: null, error: { status: 401 } }],
+ [
+ "another account's session",
+ { data: { session: { id: "session-c" }, user: { id: "user-c" } } },
+ ],
+ ])(
+ "stops reconnecting after the provider ends the session and the cookie holds %s",
+ async (_, result) => {
+ auth.getSession.mockResolvedValueOnce(result);
+ renderHook(() => useProjectWebSocket("project-a"));
+ act(() => TestSocket.instances[0].open());
+ await act(async () =>
+ TestSocket.instances[0].onclose?.({
+ code: 4001,
+ reason: "Session ended",
+ }),
+ );
+ act(() => vi.advanceTimersByTime(60_000));
+ expect(TestSocket.instances).toHaveLength(1);
+ expect(vi.getTimerCount()).toBe(0);
+ expect(client.clear).not.toHaveBeenCalled();
+ expect(navigate).not.toHaveBeenCalled();
+ },
+ );
+
+ it.each([
+ [
+ "fails",
+ () => auth.getSession.mockRejectedValueOnce(new Error("offline")),
+ ],
+ [
+ "reports a server error",
+ () =>
+ auth.getSession.mockResolvedValueOnce({
+ data: null,
+ error: { status: 503 },
+ }),
+ ],
+ ])(
+ "keeps reconnecting after the provider ends the session when the session check %s",
+ async (_, failCheck) => {
+ failCheck();
+ renderHook(() => useProjectWebSocket("project-a"));
+ act(() => TestSocket.instances[0].open());
+ await act(async () =>
+ TestSocket.instances[0].onclose?.({
+ code: 4001,
+ reason: "Session ended",
+ }),
+ );
+ act(() => vi.advanceTimersByTime(1000));
+ expect(TestSocket.instances).toHaveLength(2);
+ expect(client.clear).not.toHaveBeenCalled();
+ expect(navigate).not.toHaveBeenCalled();
+ },
+ );
+
+ it("reconnects when the session changes but not on a plain rerender", () => {
+ const { rerender } = renderHook(() => useProjectWebSocket("project-a"));
+ rerender();
+ expect(TestSocket.instances).toHaveLength(1);
+ auth.sessionId = "session-b";
+ rerender();
+ expect(TestSocket.instances).toHaveLength(2);
+ expect(TestSocket.instances[0].close).toHaveBeenCalledOnce();
+ });
+
+ it("reconnects after the provider ends the session when another tab signed in again", async () => {
+ auth.getSession.mockResolvedValueOnce({
+ data: { session: { id: "session-b" }, user: { id: "user-a" } },
+ });
renderHook(() => useProjectWebSocket("project-a"));
- act(() => {
- TestSocket.instances[0].open();
+ act(() => TestSocket.instances[0].open());
+ await act(async () =>
TestSocket.instances[0].onclose?.({
code: 4001,
reason: "Session ended",
- });
- vi.advanceTimersByTime(60_000);
- });
- expect(TestSocket.instances).toHaveLength(1);
- expect(vi.getTimerCount()).toBe(0);
+ }),
+ );
+ expect(TestSocket.instances).toHaveLength(2);
expect(client.clear).not.toHaveBeenCalled();
expect(navigate).not.toHaveBeenCalled();
});
diff --git a/apps/web/src/hooks/use-project-websocket.ts b/apps/web/src/hooks/use-project-websocket.ts
index 705cd7df5..754dbabb9 100644
--- a/apps/web/src/hooks/use-project-websocket.ts
+++ b/apps/web/src/hooks/use-project-websocket.ts
@@ -41,6 +41,7 @@ export function useProjectWebSocket(projectId: string) {
useEffect(() => {
if (!projectId || !session?.user?.id) return;
+ const userId = session.user.id;
// Each effect owns its sockets and timers. Late events from an old project
// or session must not alter the next effect's connection or reconnect it.
@@ -529,9 +530,19 @@ export function useProjectWebSocket(projectId: string) {
}
activeSocket = null;
- // The user socket signs this tab out after the provider ended its session.
+ // The provider ended this socket's session. Reconnect if another tab signed in again.
if (event?.code === 4001) {
- disposed = true;
+ void authClient
+ .getSession()
+ .then(({ data, error }) => {
+ if (disposed) return;
+ if (error && error.status !== 401) throw error;
+ if (data?.user.id === userId) connect();
+ else disposed = true;
+ })
+ .catch(() => {
+ if (!disposed) scheduleReconnect();
+ });
return;
}
@@ -566,21 +577,24 @@ export function useProjectWebSocket(projectId: string) {
return;
}
- if (retries < MAX_RETRIES) {
- const delay = BASE_DELAY * 2 ** retries; // 1s, 2s, 4s, 8s, 16s
- retries += 1;
- retryTimeout = setTimeout(connect, delay);
- } else if (fallbackInterval === null) {
- // Refresh only when realtime delivery could not reconnect.
- fallbackInterval = setInterval(() => {
- void queryClient.invalidateQueries({
- queryKey: ["tasks", projectId],
- });
- }, 30_000);
- flushPending();
- }
+ scheduleReconnect();
};
}
+ function scheduleReconnect() {
+ if (retries < MAX_RETRIES) {
+ const delay = BASE_DELAY * 2 ** retries; // 1s, 2s, 4s, 8s, 16s
+ retries += 1;
+ retryTimeout = setTimeout(connect, delay);
+ } else if (fallbackInterval === null) {
+ // Refresh only when realtime delivery could not reconnect.
+ fallbackInterval = setInterval(() => {
+ void queryClient.invalidateQueries({
+ queryKey: ["tasks", projectId],
+ });
+ }, 30_000);
+ flushPending();
+ }
+ }
connect();
function flushPending() {
if (
@@ -646,5 +660,11 @@ export function useProjectWebSocket(projectId: string) {
}
activeSocket?.close();
};
- }, [projectId, session?.user?.id, queryClient, navigate]);
+ }, [
+ projectId,
+ session?.user?.id,
+ session?.session?.id,
+ queryClient,
+ navigate,
+ ]);
}
diff --git a/apps/web/src/hooks/use-user-websocket-lifecycle.test.tsx b/apps/web/src/hooks/use-user-websocket-lifecycle.test.tsx
index b5997d720..535485230 100644
--- a/apps/web/src/hooks/use-user-websocket-lifecycle.test.tsx
+++ b/apps/web/src/hooks/use-user-websocket-lifecycle.test.tsx
@@ -24,10 +24,12 @@ const { client, auth, navigate, evictProject } = vi.hoisted(() => ({
evictProject: vi.fn(),
auth: {
userId: "user-a" as string | null,
+ sessionId: "session-a",
workspaceId: "workspace",
pathname: "",
notify: vi.fn(),
signOut: vi.fn().mockResolvedValue(undefined),
+ getSession: vi.fn().mockResolvedValue({ data: null }),
},
}));
vi.mock("@tanstack/react-router", () => ({
@@ -40,11 +42,15 @@ vi.mock("@/lib/auth-client", () => ({
authClient: {
$store: { notify: auth.notify },
signOut: auth.signOut,
+ getSession: auth.getSession,
useSession: () => ({
data: auth.userId
? {
user: { id: auth.userId },
- session: { activeOrganizationId: auth.workspaceId },
+ session: {
+ id: auth.sessionId,
+ activeOrganizationId: auth.workspaceId,
+ },
}
: null,
}),
@@ -95,6 +101,7 @@ describe("user WebSocket lifecycle", () => {
vi.stubEnv("VITE_API_URL", "http://localhost:1337");
TestSocket.instances = [];
auth.userId = "user-a";
+ auth.sessionId = "session-a";
auth.workspaceId = "workspace";
auth.pathname = "";
vi.clearAllMocks();
@@ -224,16 +231,82 @@ describe("user WebSocket lifecycle", () => {
expect(vi.getTimerCount()).toBe(0);
});
- it("signs this browser out when the provider ends its session", async () => {
+ it.each([
+ ["no session", { data: null }],
+ ["an expired session", { data: null, error: { status: 401 } }],
+ [
+ "another account's session",
+ { data: { session: { id: "session-c" }, user: { id: "user-c" } } },
+ ],
+ ])(
+ "goes to sign-in without signing out when the provider ends its session and the cookie holds %s",
+ async (_, result) => {
+ auth.getSession.mockResolvedValueOnce(result);
+ renderHook(useUserWebSocket);
+ const socket = TestSocket.instances[0];
+ act(() => socket.open());
+ await act(async () => socket.onclose?.({ code: 4001 }));
+ act(() => vi.advanceTimersByTime(60_000));
+ expect(client.clear).toHaveBeenCalledOnce();
+ expect(auth.signOut).not.toHaveBeenCalled();
+ expect(navigate).toHaveBeenCalledWith({ to: "/auth/sign-in" });
+ expect(TestSocket.instances).toHaveLength(1);
+ },
+ );
+
+ it("reconnects when another tab already signed in again", async () => {
+ auth.getSession.mockResolvedValueOnce({
+ data: { session: { id: "session-b" }, user: { id: "user-a" } },
+ });
renderHook(useUserWebSocket);
const socket = TestSocket.instances[0];
act(() => socket.open());
await act(async () => socket.onclose?.({ code: 4001 }));
- act(() => vi.advanceTimersByTime(60_000));
- expect(client.clear).toHaveBeenCalledOnce();
- expect(auth.signOut).toHaveBeenCalledOnce();
- expect(navigate).toHaveBeenCalledWith({ to: "/auth/sign-in" });
+ expect(auth.signOut).not.toHaveBeenCalled();
+ expect(client.clear).not.toHaveBeenCalled();
+ expect(navigate).not.toHaveBeenCalled();
+ expect(TestSocket.instances).toHaveLength(2);
+ });
+
+ it.each([
+ [
+ "fails",
+ () => auth.getSession.mockRejectedValueOnce(new Error("offline")),
+ ],
+ [
+ "reports a server error",
+ () =>
+ auth.getSession.mockResolvedValueOnce({
+ data: null,
+ error: { status: 503 },
+ }),
+ ],
+ ])(
+ "checks the session again before leaving when the check %s",
+ async (_, failCheck) => {
+ failCheck();
+ renderHook(useUserWebSocket);
+ const socket = TestSocket.instances[0];
+ act(() => socket.open());
+ await act(async () => socket.onclose?.({ code: 4001 }));
+ expect(client.clear).not.toHaveBeenCalled();
+ expect(navigate).not.toHaveBeenCalled();
+ await act(() => vi.advanceTimersByTimeAsync(1000));
+ expect(auth.getSession).toHaveBeenCalledTimes(2);
+ expect(client.clear).toHaveBeenCalledOnce();
+ expect(navigate).toHaveBeenCalledWith({ to: "/auth/sign-in" });
+ expect(TestSocket.instances).toHaveLength(1);
+ },
+ );
+
+ it("reconnects when the session changes but not on a plain rerender", () => {
+ const { rerender } = renderHook(useUserWebSocket);
+ rerender();
expect(TestSocket.instances).toHaveLength(1);
+ auth.sessionId = "session-b";
+ rerender();
+ expect(TestSocket.instances).toHaveLength(2);
+ expect(TestSocket.instances[0].close).toHaveBeenCalledOnce();
});
it("keeps users in their current workspace when an inactive membership is revoked", () => {
@@ -347,7 +420,7 @@ describe("user WebSocket lifecycle", () => {
});
});
-it("clears all private caches and signs out after account-wide revocation", async () => {
+it("clears all private caches without signing out after account-wide revocation", async () => {
vi.stubGlobal("WebSocket", TestSocket);
auth.userId = "user-a";
renderHook(useUserWebSocket);
@@ -356,7 +429,7 @@ it("clears all private caches and signs out after account-wide revocation", asyn
socket.onclose?.();
await Promise.resolve();
expect(client.clear).toHaveBeenCalled();
- expect(auth.signOut).toHaveBeenCalled();
+ expect(auth.signOut).not.toHaveBeenCalled();
expect(navigate).toHaveBeenCalledWith({ to: "/auth/sign-in" });
cleanup();
vi.unstubAllGlobals();
diff --git a/apps/web/src/hooks/use-user-websocket.ts b/apps/web/src/hooks/use-user-websocket.ts
index 5edc0a46e..35820bec9 100644
--- a/apps/web/src/hooks/use-user-websocket.ts
+++ b/apps/web/src/hooks/use-user-websocket.ts
@@ -36,6 +36,7 @@ export function useUserWebSocket() {
activeWorkspaceRef.current = session?.session?.activeOrganizationId;
useEffect(() => {
if (!session?.user?.id) return;
+ const userId = session.user.id;
// A previous session's delayed socket events must not control this session.
let disposed = false;
@@ -62,16 +63,31 @@ export function useUserWebSocket() {
authClient.$store.notify(signal);
}
- function revokeUserAccess() {
+ // The cookie may hold another tab's newer session, so never sign it out.
+ function leaveSession() {
if (userRevoked) return;
userRevoked = true;
clearPing();
queryClient.clear();
refreshOrganizationState();
+ void navigate({ to: "/auth/sign-in" });
+ }
+
+ function checkEndedSession() {
void authClient
- .signOut()
- .finally(() => navigate({ to: "/auth/sign-in" }))
- .catch(() => {});
+ .getSession()
+ .then(({ data, error }) => {
+ if (disposed) return;
+ if (error && error.status !== 401) throw error;
+ if (data?.user.id === userId) connect();
+ else leaveSession();
+ })
+ .catch(() => {
+ if (disposed) return;
+ const delay = retryDelay;
+ retryDelay = Math.min(retryDelay * 2, MAX_RETRY_DELAY);
+ retryTimeout = setTimeout(checkEndedSession, delay);
+ });
}
function connect() {
@@ -101,7 +117,7 @@ export function useUserWebSocket() {
workspaceIds?: string[] | null;
};
if (message.type === "USER_ACCESS_REVOKED") {
- revokeUserAccess();
+ leaveSession();
return;
}
if (
@@ -165,7 +181,11 @@ export function useUserWebSocket() {
clearPing();
activeSocket = null;
// 4001 reaches only the sockets of a session the provider ended.
- if (event?.code === 1008 || event?.code === 4001) revokeUserAccess();
+ if (event?.code === 4001) {
+ checkEndedSession();
+ return;
+ }
+ if (event?.code === 1008) leaveSession();
if (userRevoked) return;
const delay = retryDelay;
@@ -184,5 +204,5 @@ export function useUserWebSocket() {
}
activeSocket?.close();
};
- }, [session?.user?.id, queryClient, navigate]);
+ }, [session?.user?.id, session?.session?.id, queryClient, navigate]);
}