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(ws): notify workspace revocations without disrupting project moves

Tind910ddb5e765
diff --git a/apps/api/src/user/controllers/delete-account-data.ts b/apps/api/src/user/controllers/delete-account-data.ts
index 4339f12a2..dca125f2e 100644
--- a/apps/api/src/user/controllers/delete-account-data.ts
+++ b/apps/api/src/user/controllers/delete-account-data.ts
@@ -110,7 +110,7 @@ export async function deleteAccountData(userId: string) {
...plan.workspaceIdsToDelete,
...plan.workspaceIdsToLeave,
]) {
- await revokeWorkspaceConnections(userId, workspaceId);
+ await revokeWorkspaceConnections(userId, workspaceId, { force: true });
}
return plan;
diff --git a/apps/api/src/ws/index.ts b/apps/api/src/ws/index.ts
index 647fc5a78..cb312f280 100644
--- a/apps/api/src/ws/index.ts
+++ b/apps/api/src/ws/index.ts
@@ -8,7 +8,10 @@ import {
workspaceUserTable,
} from "../database/schema";
import { subscribeToEvent } from "../events";
-import { instanceAdminRoleSql } from "../utils/instance-admin-role";
+import {
+ hasInstanceAdminRole,
+ instanceAdminRoleSql,
+} from "../utils/instance-admin-role";
import { isRedisConfigured } from "../redis";
import {
getRelationSourceProject,
@@ -85,7 +88,6 @@ function deliverToLocalUserConnections(
typeof message.workspaceId === "string"
) {
revokeLocalWorkspaceConnections(userId, message.workspaceId);
- return;
}
const connections = userConnections.get(userId);
if (!connections) return;
@@ -230,8 +232,19 @@ function revokeLocalWorkspaceConnections(userId: string, workspaceId: string) {
export async function revokeWorkspaceConnections(
userId: string,
workspaceId: string,
+ options: { force?: boolean } = {},
) {
- revokeLocalWorkspaceConnections(userId, workspaceId);
+ if (!options.force) {
+ const [user] = await db
+ .select({ userId: userTable.id, role: userTable.role })
+ .from(userTable)
+ .where(eq(userTable.id, userId));
+ if (hasInstanceAdminRole(user?.role)) return;
+ }
+ deliverToLocalUserConnections(userId, {
+ type: "WORKSPACE_ACCESS_REVOKED",
+ workspaceId,
+ });
try {
await adapter?.publishToUser({
userId,
diff --git a/apps/web/src/hooks/use-project-websocket-lifecycle.test.tsx b/apps/web/src/hooks/use-project-websocket-lifecycle.test.tsx
index ba9518272..396aa089a 100644
--- a/apps/web/src/hooks/use-project-websocket-lifecycle.test.tsx
+++ b/apps/web/src/hooks/use-project-websocket-lifecycle.test.tsx
@@ -34,7 +34,7 @@ class TestSocket {
static instances: TestSocket[] = [];
readyState = 0;
onopen: (() => void) | null = null;
- onclose: ((event?: { code: number }) => void) | null = null;
+ onclose: ((event?: { code: number; reason?: string }) => void) | null = null;
onmessage: ((event: { data: string }) => void) | null = null;
send = vi.fn();
// Deliberately delay close events to reproduce the project-switch race.
@@ -142,7 +142,10 @@ describe("project WebSocket lifecycle", () => {
renderHook(() => useProjectWebSocket("project-a"));
act(() => {
TestSocket.instances[0].open();
- TestSocket.instances[0].onclose?.({ code: 1008 });
+ TestSocket.instances[0].onclose?.({
+ code: 1008,
+ reason: "Workspace access revoked",
+ });
vi.advanceTimersByTime(60_000);
});
expect(client.cancelQueries).toHaveBeenCalledOnce();
@@ -152,6 +155,20 @@ describe("project WebSocket lifecycle", () => {
expect(vi.getTimerCount()).toBe(0);
});
+ it("reconnects after a project move without clearing authorized data", () => {
+ renderHook(() => useProjectWebSocket("project-a"));
+ act(() => {
+ TestSocket.instances[0].onclose?.({
+ code: 1008,
+ reason: "Project workspace changed",
+ });
+ vi.advanceTimersByTime(1000);
+ });
+ expect(client.clear).not.toHaveBeenCalled();
+ expect(navigate).not.toHaveBeenCalled();
+ expect(TestSocket.instances).toHaveLength(2);
+ });
+
it("preserves bounded exponential reconnects and active message invalidation", () => {
const { unmount } = renderHook(() => useProjectWebSocket("project-a"));
for (let retry = 0; retry < 5; retry++) {
diff --git a/apps/web/src/hooks/use-project-websocket.ts b/apps/web/src/hooks/use-project-websocket.ts
index 2f28aba01..022434f78 100644
--- a/apps/web/src/hooks/use-project-websocket.ts
+++ b/apps/web/src/hooks/use-project-websocket.ts
@@ -154,7 +154,10 @@ export function useProjectWebSocket(projectId: string) {
clearPing();
activeSocket = null;
- if (event?.code === 1008) {
+ if (
+ event?.code === 1008 &&
+ event.reason === "Workspace access revoked"
+ ) {
disposed = true;
void queryClient.cancelQueries();
queryClient.clear();
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 971f1c396..0952f1909 100644
--- a/apps/web/src/hooks/use-user-websocket-lifecycle.test.tsx
+++ b/apps/web/src/hooks/use-user-websocket-lifecycle.test.tsx
@@ -9,10 +9,16 @@ import {
} from "vite-plus/test";
import { useUserWebSocket } from "./use-user-websocket";
-const { client, auth } = vi.hoisted(() => ({
- client: { invalidateQueries: vi.fn() },
+const { client, auth, navigate } = vi.hoisted(() => ({
+ client: {
+ invalidateQueries: vi.fn(),
+ cancelQueries: vi.fn(),
+ clear: vi.fn(),
+ },
+ navigate: vi.fn(),
auth: { userId: "user-a" as string | null },
}));
+vi.mock("@tanstack/react-router", () => ({ useNavigate: () => navigate }));
vi.mock("@tanstack/react-query", () => ({ useQueryClient: () => client }));
vi.mock("@/lib/auth-client", () => ({
authClient: {
@@ -48,7 +54,7 @@ describe("user WebSocket lifecycle", () => {
vi.stubEnv("VITE_API_URL", "http://localhost:1337");
TestSocket.instances = [];
auth.userId = "user-a";
- client.invalidateQueries.mockClear();
+ vi.clearAllMocks();
});
afterEach(() => {
cleanup();
@@ -56,6 +62,21 @@ describe("user WebSocket lifecycle", () => {
vi.unstubAllGlobals();
vi.unstubAllEnvs();
});
+ it("clears revoked workspace data from the global user connection", () => {
+ renderHook(() => useUserWebSocket());
+ act(() =>
+ TestSocket.instances[0].onmessage?.({
+ data: JSON.stringify({
+ type: "WORKSPACE_ACCESS_REVOKED",
+ workspaceId: "workspace",
+ }),
+ }),
+ );
+ expect(client.cancelQueries).toHaveBeenCalledOnce();
+ expect(client.clear).toHaveBeenCalledOnce();
+ expect(navigate).toHaveBeenCalledWith({ to: "/dashboard" });
+ });
+
it("ignores events from an old account without stopping the new account's keepalive", () => {
const { rerender, unmount } = renderHook(useUserWebSocket);
const old = TestSocket.instances[0];
diff --git a/apps/web/src/hooks/use-user-websocket.ts b/apps/web/src/hooks/use-user-websocket.ts
index 1eaf91547..7344a4493 100644
--- a/apps/web/src/hooks/use-user-websocket.ts
+++ b/apps/web/src/hooks/use-user-websocket.ts
@@ -1,5 +1,6 @@
import { windowId } from "@kaneo/libs";
import { useQueryClient } from "@tanstack/react-query";
+import { useNavigate } from "@tanstack/react-router";
import { useEffect } from "react";
import { getApiUrl } from "@/fetchers/get-api-url";
import { authClient } from "@/lib/auth-client";
@@ -21,6 +22,7 @@ const WS_PING_INTERVAL_MS = 30_000;
*/
export function useUserWebSocket() {
const queryClient = useQueryClient();
+ const navigate = useNavigate();
const { data: session } = authClient.useSession();
useEffect(() => {
if (!session?.user?.id) return;
@@ -63,6 +65,11 @@ export function useUserWebSocket() {
const message = JSON.parse(event.data as string) as {
type?: string;
};
+ if (message.type === "WORKSPACE_ACCESS_REVOKED") {
+ void queryClient.cancelQueries();
+ queryClient.clear();
+ void navigate({ to: "/dashboard" });
+ }
if (message.type === "NOTIFICATION_CREATED") {
queryClient.invalidateQueries({ queryKey: ["notifications"] });
}
@@ -94,5 +101,5 @@ export function useUserWebSocket() {
}
activeSocket?.close();
};
- }, [session?.user?.id, queryClient]);
+ }, [session?.user?.id, queryClient, navigate]);
}
diff --git a/tests/api/ws/project-move.test.ts b/tests/api/ws/project-move.test.ts
index 3d4e27b18..b1209feb9 100644
--- a/tests/api/ws/project-move.test.ts
+++ b/tests/api/ws/project-move.test.ts
@@ -9,6 +9,8 @@ import {
} from "vite-plus/test";
import {
addConnection,
+ addUserConnection,
+ removeUserConnection,
broadcastToProject,
closeProjectConnections,
initializeWebSocketAdapter,
@@ -166,6 +168,32 @@ describe("project move revocation", () => {
});
describe("workspace membership revocation", () => {
+ it("preserves instance-admin access after membership removal, but forces account revocation", async () => {
+ await initializeWebSocketAdapter();
+ const ws = connect();
+ m.admins.mockResolvedValue([{ userId: "user", role: "user,admin" }]);
+ await revokeWorkspaceConnections("user", "old");
+ expect(ws.close).not.toHaveBeenCalled();
+ await revokeWorkspaceConnections("user", "old", { force: true });
+ expect(ws.close).toHaveBeenCalled();
+ });
+ it("notifies user sockets even without an open project", async () => {
+ await initializeWebSocketAdapter();
+ const ws = { send: vi.fn(), close: vi.fn() };
+ const conn = addUserConnection("user", ws as unknown as WSContext);
+ try {
+ await revokeWorkspaceConnections("user", "old");
+ expect(ws.send).toHaveBeenCalledWith(
+ JSON.stringify({
+ type: "WORKSPACE_ACCESS_REVOKED",
+ workspaceId: "old",
+ }),
+ );
+ } finally {
+ removeUserConnection("user", conn);
+ }
+ });
+
it("keeps instance admins connected without workspace membership", async () => {
vi.useFakeTimers();
await initializeWebSocketAdapter();