⚡ 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: recover missed project access revocations
Andrej6918ae81766a
diff --git a/apps/api/src/ws/index.ts b/apps/api/src/ws/index.tsindex 081587d8e..a60616661 100644--- a/apps/api/src/ws/index.ts+++ b/apps/api/src/ws/index.ts@@ -215,11 +215,12 @@ export async function initializeWebSocketAdapter() {deliverToLocalUserConnections(msg.userId, msg.message);},async () => {- await Promise.all(- [...userConnections].flatMap(([userId, connections]) =>+ await Promise.all([+ ...[...userConnections].flatMap(([userId, connections]) =>[...connections].map(({ ws }) => syncWorkspaceAccess(userId, ws)),),- );+ recheckLocalProjectAccess(),+ ]);},);} catch (err) {@@ -313,16 +314,19 @@ function revokeLocalWorkspaceConnections(userId: string, workspaceId: string) {async function revokeLocalProjectConnections(userId: string,- workspaceId: string,+ workspaceId?: string,) {+ const revokedWorkspaceIds = new Set<string>();const owned = [...projectConnections].flatMap(([projectId, connections]) =>[...connections].filter(- (conn) => conn.userId === userId && conn.workspaceId === workspaceId,+ (conn) =>+ conn.userId === userId &&+ (workspaceId === undefined || conn.workspaceId === workspaceId),).map((conn) => ({ projectId, conn })),);- if (owned.length === 0) return;+ if (owned.length === 0) return revokedWorkspaceIds;let denied: Set<string>;try {denied = new Set(@@ -333,16 +337,41 @@ async function revokeLocalProjectConnections();} catch (error) {console.error("Failed to verify project access:", error);- return;+ return revokedWorkspaceIds;}for (const { projectId, conn } of owned) {if (!denied.has(projectId)) continue;if (!projectConnections.get(projectId)?.has(conn)) continue;removeConnection(projectId, conn);+ revokedWorkspaceIds.add(conn.workspaceId);try {conn.ws.close(1008, "Project access revoked");} catch {}}+ return revokedWorkspaceIds;+}++async function recheckLocalProjectAccess() {+ const userIds = new Set(+ [...projectConnections.values()].flatMap((connections) =>+ [...connections].map((conn) => conn.userId),+ ),+ );+ await Promise.all(+ [...userIds].map(async (userId) => {+ for (const workspaceId of await revokeLocalProjectConnections(userId)) {+ const payload = JSON.stringify({+ type: "PROJECT_ACCESS_CHANGED",+ workspaceId,+ });+ for (const { ws } of userConnections.get(userId) ?? []) {+ try {+ ws.send(payload);+ } catch {}+ }+ }+ }),+ );}export async function revokeUserConnections(userId: string) {diff --git a/apps/web/src/hooks/use-user-websocket-lifecycle.test.tsx b/apps/web/src/hooks/use-user-websocket-lifecycle.test.tsxindex f124251ad..ff3d781e8 100644--- a/apps/web/src/hooks/use-user-websocket-lifecycle.test.tsx+++ b/apps/web/src/hooks/use-user-websocket-lifecycle.test.tsx@@ -9,16 +9,19 @@ import {} from "vite-plus/test";import { useUserWebSocket } from "./use-user-websocket";-const { client, auth, navigate } = vi.hoisted(() => ({+const { client, auth, navigate, evictProject } = vi.hoisted(() => ({client: {invalidateQueries: vi.fn(),cancelQueries: vi.fn(),clear: vi.fn(),getQueryCache: () => ({ getAll: () => [] }),+ getQueryData: vi.fn(),+ fetchQuery: vi.fn(),removeQueries: vi.fn(),resetQueries: vi.fn(),},navigate: vi.fn(),+ evictProject: vi.fn(),auth: {userId: "user-a" as string | null,workspaceId: "workspace",@@ -48,6 +51,17 @@ vi.mock("@/lib/auth-client", () => ({},}));vi.mock("@kaneo/libs", () => ({ windowId: "local-test" }));+vi.mock("@/lib/evict-project-cache", () => ({+ evictProjectCache: evictProject,+}));+function projectAccessChanged(socket: TestSocket) {+ socket.onmessage?.({+ data: JSON.stringify({+ type: "PROJECT_ACCESS_CHANGED",+ workspaceId: "workspace",+ }),+ });+}class TestSocket {static OPEN = 1;static instances: TestSocket[] = [];@@ -222,25 +236,65 @@ describe("user WebSocket lifecycle", () => {it("refreshes project lists in every tab after a project access change", () => {renderHook(useUserWebSocket);- act(() =>- TestSocket.instances[0].onmessage?.({- data: JSON.stringify({- type: "PROJECT_ACCESS_CHANGED",- workspaceId: "workspace",- }),- }),- );+ act(() => projectAccessChanged(TestSocket.instances[0]));for (const queryKey of [["projects", "workspace"],["assigned-tasks", "workspace"],["search", { workspaceId: "workspace" }],["workspace-activity", "workspace"],+ ["notifications"],])expect(client.invalidateQueries).toHaveBeenCalledWith({ queryKey });+ expect(client.fetchQuery).not.toHaveBeenCalled();+ expect(evictProject).not.toHaveBeenCalled();expect(client.removeQueries).not.toHaveBeenCalled();expect(navigate).not.toHaveBeenCalled();});+ it("evicts cached data for projects that left the refreshed list", async () => {+ client.getQueryData.mockReturnValueOnce([+ { id: "kept" },+ { id: "removed" },+ ]);+ client.fetchQuery.mockResolvedValueOnce([{ id: "kept" }, { id: "added" }]);+ renderHook(useUserWebSocket);+ await act(async () => projectAccessChanged(TestSocket.instances[0]));+ expect(client.getQueryData).toHaveBeenCalledWith(["projects", "workspace"]);+ expect(client.fetchQuery).toHaveBeenCalledWith(+ expect.objectContaining({ queryKey: ["projects", "workspace"] }),+ );+ expect(evictProject).toHaveBeenCalledOnce();+ expect(evictProject).toHaveBeenCalledWith(client, "removed");+ expect(client.invalidateQueries).toHaveBeenCalledWith({+ queryKey: ["notifications"],+ });+ expect(navigate).not.toHaveBeenCalled();+ });++ it("keeps project caches when the project list refresh fails", async () => {+ client.getQueryData.mockReturnValueOnce([{ id: "project" }]);+ client.fetchQuery.mockRejectedValueOnce(new Error("Network unavailable"));+ renderHook(useUserWebSocket);+ await act(async () => projectAccessChanged(TestSocket.instances[0]));+ expect(client.fetchQuery).toHaveBeenCalledOnce();+ expect(evictProject).not.toHaveBeenCalled();+ });++ it("ignores a project list refresh that finishes after the session ends", async () => {+ let finish!: (projects: { id: string }[]) => void;+ client.getQueryData.mockReturnValueOnce([{ id: "project" }]);+ client.fetchQuery.mockReturnValueOnce(+ new Promise((resolve) => {+ finish = resolve;+ }),+ );+ const { unmount } = renderHook(useUserWebSocket);+ act(() => projectAccessChanged(TestSocket.instances[0]));+ unmount();+ await act(async () => finish([]));+ expect(evictProject).not.toHaveBeenCalled();+ });+it("redirects after a reconnect snapshot reveals a missed workspace revocation", () => {renderHook(useUserWebSocket);act(() =>diff --git a/apps/web/src/hooks/use-user-websocket.ts b/apps/web/src/hooks/use-user-websocket.tsindex f23344f4a..437f19962 100644--- a/apps/web/src/hooks/use-user-websocket.ts+++ b/apps/web/src/hooks/use-user-websocket.ts@@ -3,11 +3,14 @@ import { useQueryClient } from "@tanstack/react-query";import { useLocation, useNavigate } from "@tanstack/react-router";import { useEffect, useRef } from "react";import { getApiUrl } from "@/fetchers/get-api-url";+import getProjects from "@/fetchers/project/get-projects";+import { evictProjectCache } from "@/lib/evict-project-cache";import {evictInaccessibleWorkspaceCache,evictWorkspaceCache,} from "@/lib/evict-workspace-cache";import { authClient } from "@/lib/auth-client";+import { findRemovedProjectIds } from "@/lib/find-removed-project-ids";export function getUserWsUrl() {const base = getApiUrl("ws");@@ -137,13 +140,31 @@ export function useUserWebSocket() {message.workspaceId) {const { workspaceId } = message;+ const projectsKey = ["projects", workspaceId];+ const before =+ queryClient.getQueryData<+ NonNullable<Awaited<ReturnType<typeof getProjects>>>+ >(projectsKey);for (const queryKey of [- ["projects", workspaceId],+ projectsKey,["assigned-tasks", workspaceId],["search", { workspaceId }],["workspace-activity", workspaceId],+ ["notifications"],])void queryClient.invalidateQueries({ queryKey });+ if (before)+ void queryClient+ .fetchQuery({+ queryKey: projectsKey,+ queryFn: () => getProjects({ workspaceId }),+ })+ .then((after) => {+ if (disposed) return;+ for (const projectId of findRemovedProjectIds(before, after))+ evictProjectCache(queryClient, projectId);+ })+ .catch(() => {});}if (message.type === "NOTIFICATION_CREATED") {queryClient.invalidateQueries({ queryKey: ["notifications"] });diff --git a/apps/web/src/lib/find-removed-project-ids.test.ts b/apps/web/src/lib/find-removed-project-ids.test.tsnew file mode 100644index 000000000..d10f079fb--- /dev/null+++ b/apps/web/src/lib/find-removed-project-ids.test.ts@@ -0,0 +1,22 @@+import { expect, it } from "vite-plus/test";+import { findRemovedProjectIds } from "./find-removed-project-ids";++it("returns projects missing from the refreshed list", () => {+ expect(+ findRemovedProjectIds(+ [{ id: "kept" }, { id: "removed" }, { id: "also-removed" }],+ [{ id: "kept" }, { id: "added" }],+ ),+ ).toEqual(["removed", "also-removed"]);+});++it("reports each removed project once", () => {+ expect(+ findRemovedProjectIds([{ id: "removed" }, { id: "removed" }], []),+ ).toEqual(["removed"]);+});++it("removes nothing when either list is unknown", () => {+ expect(findRemovedProjectIds(undefined, [{ id: "kept" }])).toEqual([]);+ expect(findRemovedProjectIds([{ id: "kept" }], undefined)).toEqual([]);+});diff --git a/apps/web/src/lib/find-removed-project-ids.ts b/apps/web/src/lib/find-removed-project-ids.tsnew file mode 100644index 000000000..5eee0a7a2--- /dev/null+++ b/apps/web/src/lib/find-removed-project-ids.ts@@ -0,0 +1,10 @@+export function findRemovedProjectIds(+ before: readonly { id: string }[] | undefined,+ after: readonly { id: string }[] | undefined,+) {+ if (!before || !after) return [];+ const remaining = new Set(after.map((project) => project.id));+ return [...new Set(before.map((project) => project.id))].filter(+ (id) => !remaining.has(id),+ );+}diff --git a/tests/api/ws/project-move.test.ts b/tests/api/ws/project-move.test.tsindex 25e177ef6..8ab2752e3 100644--- a/tests/api/ws/project-move.test.ts+++ b/tests/api/ws/project-move.test.ts@@ -27,10 +27,20 @@ const m = vi.hoisted(() => ({admins: vi.fn(),projectAccess: vi.fn(),inaccessible: vi.fn(),+ sync: vi.fn(),redis: false,publish: vi.fn(),on: vi.fn(),}));+vi.mock(+ "../../../apps/api/src/ws/workspace-access",+ async (importOriginal) => ({+ ...(await importOriginal<+ typeof import("../../../apps/api/src/ws/workspace-access")+ >()),+ syncWorkspaceAccess: m.sync,+ }),+);vi.mock("../../../apps/api/src/database", () => ({default: {select: (fields: Record<string, unknown>) => ({@@ -72,20 +82,20 @@ vi.mock("../../../apps/api/src/redis", () => ({getRedisSub: () => ({on: m.on,off: vi.fn(),- psubscribe: vi.fn(),+ psubscribe: vi.fn(async () => {}),punsubscribe: vi.fn(),}),closeRedis: vi.fn(),}));const tracked: Array<[string, ReturnType<typeof addConnection>]> = [];-function connect(projectId = "project", workspaceId = "old") {+function connect(projectId = "project", workspaceId = "old", userId = "user") {const ws = { send: vi.fn(), close: vi.fn() };tracked.push([projectId,addConnection(projectId,ws as unknown as WSContext,- "user",+ userId,"window",workspaceId,),@@ -387,6 +397,81 @@ describe("project access revocation", () => {types.filter((type) => type === "PROJECT_ACCESS_CHANGED"),).toHaveLength(2);});++ it("rechecks local project sockets once per user after Redis reconnects", async () => {+ m.redis = true;+ await initializeWebSocketAdapter();+ const revoked = connect();+ const kept = connect("kept-project");+ const elsewhere = connect("other-project", "other-workspace");+ const colleague = connect("project", "old", "colleague");+ const tab = { send: vi.fn(), close: vi.fn() };+ const colleagueTab = { send: vi.fn(), close: vi.fn() };+ const conn = addUserConnection("user", tab as unknown as WSContext);+ const colleagueConn = addUserConnection(+ "colleague",+ colleagueTab as unknown as WSContext,+ );+ m.inaccessible.mockImplementation(async (userId: string) =>+ userId === "user" ? ["project"] : [],+ );+ try {+ const ready = m.on.mock.calls.find(([event]) => event === "ready")![1];+ ready();+ await vi.waitFor(() =>+ expect(revoked.close).toHaveBeenCalledWith(+ 1008,+ "Project access revoked",+ ),+ );+ expect(m.inaccessible).toHaveBeenCalledTimes(2);+ expect(m.inaccessible).toHaveBeenCalledWith("user", [+ "project",+ "kept-project",+ "other-project",+ ]);+ expect(m.inaccessible).toHaveBeenCalledWith("colleague", ["project"]);+ expect(kept.close).not.toHaveBeenCalled();+ expect(elsewhere.close).not.toHaveBeenCalled();+ expect(colleague.close).not.toHaveBeenCalled();+ await vi.waitFor(() =>+ expect(tab.send).toHaveBeenCalledWith(+ JSON.stringify({+ type: "PROJECT_ACCESS_CHANGED",+ workspaceId: "old",+ }),+ ),+ );+ expect(tab.send).toHaveBeenCalledOnce();+ expect(tab.close).not.toHaveBeenCalled();+ expect(colleagueTab.send).not.toHaveBeenCalled();+ expect(m.sync).toHaveBeenCalledWith("user", tab);+ expect(m.sync).toHaveBeenCalledWith("colleague", colleagueTab);+ } finally {+ removeUserConnection("user", conn);+ removeUserConnection("colleague", colleagueConn);+ }+ });++ it("keeps project sockets open when the reconnect recheck fails", async () => {+ m.redis = true;+ await initializeWebSocketAdapter();+ const ws = connect();+ const tab = { send: vi.fn(), close: vi.fn() };+ const conn = addUserConnection("user", tab as unknown as WSContext);+ m.inaccessible.mockRejectedValueOnce(new Error("database unavailable"));+ try {+ const ready = m.on.mock.calls.find(([event]) => event === "ready")![1];+ ready();+ await vi.waitFor(() => expect(m.inaccessible).toHaveBeenCalledOnce());+ await vi.waitFor(() => expect(m.sync).toHaveBeenCalled());+ await Promise.resolve();+ expect(ws.close).not.toHaveBeenCalled();+ expect(tab.send).not.toHaveBeenCalled();+ } finally {+ removeUserConnection("user", conn);+ }+ });});it("coalesces authorization checks across a bulk broadcast burst", async () => {