⚡ 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(ws): coalesce access checks and scope workspace eviction
Tinec2da509630b
diff --git a/apps/api/src/ws/index.ts b/apps/api/src/ws/index.tsindex d99649056..75a255076 100644--- a/apps/api/src/ws/index.ts+++ b/apps/api/src/ws/index.ts@@ -273,6 +273,70 @@ function currentProjectWorkspace(projectId: string) {return pending;}+const authorizationLookups = new Map<+ string,+ Promise<{ workspaceId: string | null; members: Set<string> } | null>+>();+function currentBroadcastAccess(+ projectId: string,+ recipients: Array<{ userId: string }>,+) {+ const key = JSON.stringify([+ projectId,+ [...new Set(recipients.map((conn) => conn.userId))].sort(),+ ]);+ let pending = authorizationLookups.get(key);+ if (!pending) {+ pending = (async () => {+ let workspaceId: string | null;+ try {+ workspaceId = await currentProjectWorkspace(projectId);+ } catch (error) {+ console.error("Failed to validate project broadcast access:", error);+ return null;+ }+ let members = new Set<string>();+ if (workspaceId) {+ try {+ const rows = await db+ .select({ userId: workspaceUserTable.userId })+ .from(workspaceUserTable)+ .where(+ and(+ eq(workspaceUserTable.workspaceId, workspaceId),+ inArray(workspaceUserTable.userId, [+ ...new Set(recipients.map((conn) => conn.userId)),+ ]),+ ),+ );+ members = new Set(rows.map((row) => row.userId));+ const nonmembers = [+ ...new Set(recipients.map((conn) => conn.userId)),+ ].filter((userId) => !members.has(userId));+ if (nonmembers.length > 0) {+ const admins = await db+ .select({ userId: userTable.id, role: userTable.role })+ .from(userTable)+ .where(+ and(+ inArray(userTable.id, nonmembers),+ instanceAdminRoleSql(userTable.role),+ ),+ );+ for (const admin of admins) members.add(admin.userId);+ }+ } catch (error) {+ console.error("Failed to validate broadcast membership:", error);+ return null;+ }+ }+ return { workspaceId, members };+ })().finally(() => authorizationLookups.delete(key));+ authorizationLookups.set(key, pending);+ }+ return pending;+}+async function deliverToLocalConnections(projectId: string,message: ProjectBroadcastMessage,@@ -285,48 +349,9 @@ async function deliverToLocalConnections(const connections = projectConnections.get(projectId);if (!connections) return;const recipients = [...connections];- let workspaceId: string | null;- try {- workspaceId = await currentProjectWorkspace(projectId);- } catch (error) {- console.error("Failed to validate project broadcast access:", error);- return;- }- let members = new Set<string>();- if (workspaceId) {- try {- const rows = await db- .select({ userId: workspaceUserTable.userId })- .from(workspaceUserTable)- .where(- and(- eq(workspaceUserTable.workspaceId, workspaceId),- inArray(workspaceUserTable.userId, [- ...new Set(recipients.map((conn) => conn.userId)),- ]),- ),- );- members = new Set(rows.map((row) => row.userId));- const nonmembers = [- ...new Set(recipients.map((conn) => conn.userId)),- ].filter((userId) => !members.has(userId));- if (nonmembers.length > 0) {- const admins = await db- .select({ userId: userTable.id, role: userTable.role })- .from(userTable)- .where(- and(- inArray(userTable.id, nonmembers),- instanceAdminRoleSql(userTable.role),- ),- );- for (const admin of admins) members.add(admin.userId);- }- } catch (error) {- console.error("Failed to validate broadcast membership:", error);- return;- }- }+ const access = await currentBroadcastAccess(projectId, recipients);+ if (!access) return;+ const { workspaceId, members } = access;const payload = JSON.stringify(message);for (const conn of recipients) {// A move may have closed these connections while the lookup was in flight.diff --git a/apps/web/src/hooks/use-user-websocket-lifecycle.test.tsx b/apps/web/src/hooks/use-user-websocket-lifecycle.test.tsxindex 0952f1909..c2b174e91 100644--- a/apps/web/src/hooks/use-user-websocket-lifecycle.test.tsx+++ b/apps/web/src/hooks/use-user-websocket-lifecycle.test.tsx@@ -14,11 +14,16 @@ const { client, auth, navigate } = vi.hoisted(() => ({invalidateQueries: vi.fn(),cancelQueries: vi.fn(),clear: vi.fn(),+ getQueryCache: () => ({ getAll: () => [] }),+ removeQueries: vi.fn(),},navigate: vi.fn(),- auth: { userId: "user-a" as string | null },+ auth: { userId: "user-a" as string | null, workspaceId: "workspace" },+}));+vi.mock("@tanstack/react-router", () => ({+ useNavigate: () => navigate,+ useLocation: () => `/dashboard/workspace/${auth.workspaceId}`,}));-vi.mock("@tanstack/react-router", () => ({ useNavigate: () => navigate }));vi.mock("@tanstack/react-query", () => ({ useQueryClient: () => client }));vi.mock("@/lib/auth-client", () => ({authClient: {@@ -54,6 +59,7 @@ describe("user WebSocket lifecycle", () => {vi.stubEnv("VITE_API_URL", "http://localhost:1337");TestSocket.instances = [];auth.userId = "user-a";+ auth.workspaceId = "workspace";vi.clearAllMocks();});afterEach(() => {@@ -73,7 +79,7 @@ describe("user WebSocket lifecycle", () => {}),);expect(client.cancelQueries).toHaveBeenCalledOnce();- expect(client.clear).toHaveBeenCalledOnce();+ expect(client.removeQueries).toHaveBeenCalledOnce();expect(navigate).toHaveBeenCalledWith({ to: "/dashboard" });});@@ -151,4 +157,17 @@ describe("user WebSocket lifecycle", () => {unmount();expect(vi.getTimerCount()).toBe(0);});++ it("keeps users in their current workspace when an inactive membership is revoked", () => {+ auth.workspaceId = "other-workspace";+ renderHook(() => useUserWebSocket());+ TestSocket.instances[0].onmessage?.({+ data: JSON.stringify({+ type: "WORKSPACE_ACCESS_REVOKED",+ workspaceId: "workspace",+ }),+ });+ expect(navigate).not.toHaveBeenCalled();+ expect(client.removeQueries).toHaveBeenCalledOnce();+ });});diff --git a/apps/web/src/hooks/use-user-websocket.ts b/apps/web/src/hooks/use-user-websocket.tsindex 7344a4493..5cbcb3bc1 100644--- a/apps/web/src/hooks/use-user-websocket.ts+++ b/apps/web/src/hooks/use-user-websocket.ts@@ -1,8 +1,9 @@import { windowId } from "@kaneo/libs";import { useQueryClient } from "@tanstack/react-query";-import { useNavigate } from "@tanstack/react-router";-import { useEffect } from "react";+import { useLocation, useNavigate } from "@tanstack/react-router";+import { useEffect, useRef } from "react";import { getApiUrl } from "@/fetchers/get-api-url";+import { evictWorkspaceCache } from "@/lib/evict-workspace-cache";import { authClient } from "@/lib/auth-client";export function getUserWsUrl() {@@ -23,6 +24,9 @@ const WS_PING_INTERVAL_MS = 30_000;export function useUserWebSocket() {const queryClient = useQueryClient();const navigate = useNavigate();+ const pathname = useLocation({ select: (location) => location.pathname });+ const pathnameRef = useRef(pathname);+ pathnameRef.current = pathname;const { data: session } = authClient.useSession();useEffect(() => {if (!session?.user?.id) return;@@ -64,11 +68,17 @@ export function useUserWebSocket() {try {const message = JSON.parse(event.data as string) as {type?: string;+ workspaceId?: string;};- if (message.type === "WORKSPACE_ACCESS_REVOKED") {- void queryClient.cancelQueries();- queryClient.clear();- void navigate({ to: "/dashboard" });+ if (+ message.type === "WORKSPACE_ACCESS_REVOKED" &&+ message.workspaceId+ ) {+ evictWorkspaceCache(queryClient, message.workspaceId);+ const current =+ pathnameRef.current.match(/\/workspace\/([^/]+)/)?.[1];+ if (current === message.workspaceId)+ void navigate({ to: "/dashboard" });}if (message.type === "NOTIFICATION_CREATED") {queryClient.invalidateQueries({ queryKey: ["notifications"] });diff --git a/apps/web/src/lib/evict-workspace-cache.test.ts b/apps/web/src/lib/evict-workspace-cache.test.tsnew file mode 100644index 000000000..062d3f883--- /dev/null+++ b/apps/web/src/lib/evict-workspace-cache.test.ts@@ -0,0 +1,32 @@+import { QueryClient } from "@tanstack/react-query";+import { expect, it } from "vite-plus/test";+import { evictWorkspaceCache } from "./evict-workspace-cache";++it("evicts revoked and unscoped private data while preserving another workspace's board", () => {+ const client = new QueryClient();+ client.setQueryData(["tasks", "revoked-project"], {+ id: "revoked-project",+ workspaceId: "revoked",+ columns: [+ { tasks: [{ id: "revoked-task", projectId: "revoked-project" }] },+ ],+ });+ const active = { id: "active-project", workspaceId: "active", columns: [] };+ client.setQueryData(["tasks", "active-project"], active);+ client.setQueryData(["task", "revoked-task"], {+ id: "revoked-task",+ projectId: "revoked-project",+ description: "private",+ });+ client.setQueryData(["task", "unscoped"], {+ id: "unscoped",+ projectId: "no-project-cache",+ description: "private",+ });+ evictWorkspaceCache(client, "revoked");+ expect(client.getQueryData(["tasks", "active-project"])).toEqual(active);+ expect(client.getQueryData(["tasks", "revoked-project"])).toBeUndefined();+ expect(client.getQueryData(["task", "revoked-task"])).toBeUndefined();+ expect(client.getQueryData(["task", "unscoped"])).toBeUndefined();+ client.clear();+});diff --git a/apps/web/src/lib/evict-workspace-cache.ts b/apps/web/src/lib/evict-workspace-cache.tsnew file mode 100644index 000000000..40a2c16cf--- /dev/null+++ b/apps/web/src/lib/evict-workspace-cache.ts@@ -0,0 +1,89 @@+import type { QueryClient } from "@tanstack/react-query";++export function evictWorkspaceCache(client: QueryClient, workspaceId: string) {+ const queries = client.getQueryCache().getAll();+ const ids = new Set([workspaceId]);+ const scopes = new Map<string, string>();+ const visit = (+ value: unknown,+ callback: (record: Record<string, unknown>) => void,+ ) => {+ if (!value || typeof value !== "object") return;+ if (Array.isArray(value)) {+ for (const item of value) visit(item, callback);+ return;+ }+ const record = value as Record<string, unknown>;+ callback(record);+ for (const item of Object.values(record)) visit(item, callback);+ };+ for (const query of queries)+ visit(query.state.data, (record) => {+ if (+ typeof record.workspaceId === "string" &&+ typeof record.id === "string"+ )+ scopes.set(record.id, record.workspaceId);+ if (record.workspaceId === workspaceId && typeof record.id === "string")+ ids.add(record.id);+ });+ for (const query of queries)+ visit(query.state.data, (record) => {+ if (+ typeof record.projectId === "string" &&+ typeof record.id === "string" &&+ scopes.has(record.projectId)+ )+ scopes.set(record.id, scopes.get(record.projectId)!);+ if (+ typeof record.projectId === "string" &&+ ids.has(record.projectId) &&+ typeof record.id === "string"+ )+ ids.add(record.id);+ });+ const predicate = (query: (typeof queries)[number]) => {+ if (query.queryKey[0] === "notifications") return true;+ let affected = false;+ visit([query.queryKey, query.state.data], (record) => {+ if (+ Object.values(record).some(+ (value) => typeof value === "string" && ids.has(value),+ )+ )+ affected = true;+ });+ const knownOtherWorkspace = query.queryKey.some(+ (value) =>+ typeof value === "string" &&+ scopes.has(value) &&+ scopes.get(value) !== workspaceId,+ );+ const privatePrefixes = new Set([+ "task",+ "tasks",+ "task-relations",+ "activities",+ "comments",+ "labels",+ "external-links",+ "projects",+ "project",+ "workspace",+ "workspaces",+ "members",+ "roles",+ "search",+ ]);+ return (+ (privatePrefixes.has(String(query.queryKey[0])) &&+ !knownOtherWorkspace) ||+ affected ||+ query.queryKey.some(+ (value) => typeof value === "string" && ids.has(value),+ )+ );+ };+ void client.cancelQueries({ predicate });+ client.removeQueries({ predicate });+}diff --git a/tests/api/ws/project-move.test.ts b/tests/api/ws/project-move.test.tsindex a33fa8f29..722de25ff 100644--- a/tests/api/ws/project-move.test.ts+++ b/tests/api/ws/project-move.test.ts@@ -252,3 +252,14 @@ describe("workspace membership revocation", () => {expect(ws.close).toHaveBeenCalledWith(1008, "Workspace access revoked");});});++it("coalesces authorization checks across a bulk broadcast burst", async () => {+ vi.useFakeTimers();+ await initializeWebSocketAdapter();+ const connection = connect();+ for (let index = 0; index < 50; index++)+ broadcastToProject("project", { ...update, taskId: `task-${index}` });+ await vi.advanceTimersByTimeAsync(100);+ expect(connection.send).toHaveBeenCalledTimes(50);+ expect(m.members).toHaveBeenCalledTimes(1);+});