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): reconcile access on reconnect and committed leave

Tin900291969d35
diff --git a/apps/api/src/auth.ts b/apps/api/src/auth.ts
index bf6a0ea9a..275ab187f 100644
--- a/apps/api/src/auth.ts
+++ b/apps/api/src/auth.ts
@@ -36,7 +36,7 @@ import {
import type { AccessControl } from "better-auth/plugins/access";
import type { UserWithAnonymous } from "better-auth/plugins/anonymous";
import { config } from "dotenv-mono";
-import { and, eq } from "drizzle-orm";
+import { eq } from "drizzle-orm";
import {
findBillableWorkspaces,
formatBillableWorkspacesMessage,
@@ -815,22 +815,23 @@ export const auth = betterAuth({
}),
after: createAuthMiddleware(async (ctx) => {
if (ctx.path === "/organization/leave") {
- const session = await getSessionFromCtx(ctx, { disableRefresh: true });
- const userId = session?.user.id;
- const workspaceId = ctx.body?.organizationId;
- if (userId && typeof workspaceId === "string") {
- const [membership] = await db
- .select({ id: schema.workspaceUserTable.id })
- .from(schema.workspaceUserTable)
- .where(
- and(
- eq(schema.workspaceUserTable.userId, userId),
- eq(schema.workspaceUserTable.workspaceId, workspaceId),
- ),
- )
- .limit(1);
- if (!membership)
- await revokeWorkspaceConnections(userId, workspaceId);
+ // The successful endpoint returns the removed member. No post-delete
+ // query may prevent revocation after membership has already committed.
+ const removed = ctx.context.returned as
+ | { userId?: string; organizationId?: string }
+ | undefined;
+ if (
+ typeof removed?.userId === "string" &&
+ typeof removed.organizationId === "string" &&
+ removed.organizationId === ctx.body?.organizationId
+ ) {
+ await revokeWorkspaceConnections(
+ removed.userId,
+ removed.organizationId,
+ {
+ role: ctx.context.session?.user.role ?? null,
+ },
+ );
}
}
diff --git a/apps/api/src/index.ts b/apps/api/src/index.ts
index 8c0eaa963..21e5c1f4a 100644
--- a/apps/api/src/index.ts
+++ b/apps/api/src/index.ts
@@ -1,3 +1,4 @@
+import { syncWorkspaceAccess } from "./ws/workspace-access";
import { drainPasswordResetDeliveries } from "./utils/password-reset-delivery";
import "./instrument";
@@ -811,6 +812,7 @@ export function createApp() {
onOpen(_evt, ws) {
if (userId) {
conn = addUserConnection(userId, ws);
+ void syncWorkspaceAccess(userId, ws);
}
},
onMessage: handleWebSocketMessage,
diff --git a/apps/api/src/ws/workspace-access.ts b/apps/api/src/ws/workspace-access.ts
new file mode 100644
index 000000000..4fa0ec535
--- /dev/null
+++ b/apps/api/src/ws/workspace-access.ts
@@ -0,0 +1,35 @@
+import { eq } from "drizzle-orm";
+import type { WSContext } from "hono/ws";
+import db from "../database";
+import { userTable, workspaceUserTable } from "../database/schema";
+import { hasInstanceAdminRole } from "../utils/instance-admin-role";
+
+export async function syncWorkspaceAccess(userId: string, ws: WSContext) {
+ try {
+ const [[user], memberships] = await Promise.all([
+ db
+ .select({ role: userTable.role })
+ .from(userTable)
+ .where(eq(userTable.id, userId)),
+ db
+ .select({ workspaceId: workspaceUserTable.workspaceId })
+ .from(workspaceUserTable)
+ .where(eq(workspaceUserTable.userId, userId)),
+ ]);
+ if (!user) {
+ ws.close(1008, "User access revoked");
+ return;
+ }
+ ws.send(
+ JSON.stringify({
+ type: "WORKSPACE_ACCESS_SYNC",
+ workspaceIds: hasInstanceAdminRole(user.role)
+ ? null
+ : memberships.map((member) => member.workspaceId),
+ }),
+ );
+ } catch (error) {
+ console.error("Failed to synchronize workspace access:", error);
+ ws.close(1011, "Workspace access synchronization failed");
+ }
+}
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 a9e064446..8cb6bd00b 100644
--- a/apps/web/src/hooks/use-user-websocket-lifecycle.test.tsx
+++ b/apps/web/src/hooks/use-user-websocket-lifecycle.test.tsx
@@ -200,4 +200,18 @@ describe("user WebSocket lifecycle", () => {
expect(navigate).not.toHaveBeenCalled();
expect(client.removeQueries).toHaveBeenCalledOnce();
});
+
+ it("redirects after a reconnect snapshot reveals a missed workspace revocation", () => {
+ renderHook(useUserWebSocket);
+ act(() =>
+ TestSocket.instances[0].onmessage?.({
+ data: JSON.stringify({
+ type: "WORKSPACE_ACCESS_SYNC",
+ workspaceIds: ["other"],
+ }),
+ }),
+ );
+ expect(navigate).toHaveBeenCalledWith({ to: "/dashboard" });
+ expect(client.removeQueries).toHaveBeenCalledOnce();
+ });
});
diff --git a/apps/web/src/hooks/use-user-websocket.ts b/apps/web/src/hooks/use-user-websocket.ts
index bf1e33310..a8047ba82 100644
--- a/apps/web/src/hooks/use-user-websocket.ts
+++ b/apps/web/src/hooks/use-user-websocket.ts
@@ -3,7 +3,10 @@ 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 { evictWorkspaceCache } from "@/lib/evict-workspace-cache";
+import {
+ evictInaccessibleWorkspaceCache,
+ evictWorkspaceCache,
+} from "@/lib/evict-workspace-cache";
import { authClient } from "@/lib/auth-client";
export function getUserWsUrl() {
@@ -71,7 +74,22 @@ export function useUserWebSocket() {
const message = JSON.parse(event.data as string) as {
type?: string;
workspaceId?: string;
+ workspaceIds?: string[] | null;
};
+ if (
+ message.type === "WORKSPACE_ACCESS_SYNC" &&
+ Array.isArray(message.workspaceIds) &&
+ message.workspaceIds.every((id) => typeof id === "string")
+ ) {
+ evictInaccessibleWorkspaceCache(queryClient, message.workspaceIds);
+ const path = pathnameRef.current;
+ const current =
+ /^\/dashboard\/settings\/(workspace|projects)(\/|$)/.test(path)
+ ? activeWorkspaceRef.current
+ : path.match(/^\/dashboard\/workspace\/([^/]+)/)?.[1];
+ if (current && !message.workspaceIds.includes(current))
+ void navigate({ to: "/dashboard" });
+ }
if (
message.type === "WORKSPACE_ACCESS_REVOKED" &&
message.workspaceId
diff --git a/apps/web/src/lib/evict-workspace-cache.test.ts b/apps/web/src/lib/evict-workspace-cache.test.ts
index 2cbdf83e3..bbc3f573a 100644
--- a/apps/web/src/lib/evict-workspace-cache.test.ts
+++ b/apps/web/src/lib/evict-workspace-cache.test.ts
@@ -1,6 +1,9 @@
import { QueryClient } from "@tanstack/react-query";
import { expect, it } from "vite-plus/test";
-import { evictWorkspaceCache } from "./evict-workspace-cache";
+import {
+ evictInaccessibleWorkspaceCache,
+ evictWorkspaceCache,
+} from "./evict-workspace-cache";
it("evicts revoked and unscoped private data while preserving another workspace's board", () => {
const client = new QueryClient();
@@ -64,3 +67,24 @@ it("cancels unknown project settings reads when membership is revoked", async ()
}
client.clear();
});
+
+it("reconciles missed revocations against a reconnect access snapshot", () => {
+ const client = new QueryClient();
+ const active = { id: "active-project", workspaceId: "active", columns: [] };
+ client.setQueryData(["tasks", "active-project"], active);
+ client.setQueryData(["tasks", "old-project"], {
+ id: "old-project",
+ workspaceId: "revoked",
+ columns: [],
+ });
+ client.setQueryData(["github-integration", "unknown-project"], {
+ repository: "private",
+ });
+ evictInaccessibleWorkspaceCache(client, ["active"]);
+ expect(client.getQueryData(["tasks", "active-project"])).toEqual(active);
+ expect(client.getQueryData(["tasks", "old-project"])).toBeUndefined();
+ expect(
+ client.getQueryData(["github-integration", "unknown-project"]),
+ ).toBeUndefined();
+ client.clear();
+});
diff --git a/apps/web/src/lib/evict-workspace-cache.ts b/apps/web/src/lib/evict-workspace-cache.ts
index 5a74938cf..0b3d209e7 100644
--- a/apps/web/src/lib/evict-workspace-cache.ts
+++ b/apps/web/src/lib/evict-workspace-cache.ts
@@ -1,8 +1,23 @@
import type { QueryClient } from "@tanstack/react-query";
export function evictWorkspaceCache(client: QueryClient, workspaceId: string) {
+ evictPrivateQueries(client, workspaceId);
+}
+
+export function evictInaccessibleWorkspaceCache(
+ client: QueryClient,
+ workspaceIds: string[],
+) {
+ evictPrivateQueries(client, undefined, new Set(workspaceIds));
+}
+
+function evictPrivateQueries(
+ client: QueryClient,
+ workspaceId?: string,
+ allowed?: Set<string>,
+) {
const queries = client.getQueryCache().getAll();
- const ids = new Set([workspaceId]);
+ const ids = new Set<string>(workspaceId ? [workspaceId] : []);
const scopes = new Map<string, string>();
const visit = (
value: unknown,
@@ -26,7 +41,13 @@ export function evictWorkspaceCache(client: QueryClient, workspaceId: string) {
typeof record.id === "string"
)
scopes.set(record.id, record.workspaceId);
- if (record.workspaceId === workspaceId && typeof record.id === "string")
+ if (
+ typeof record.workspaceId === "string" &&
+ (allowed
+ ? !allowed.has(record.workspaceId)
+ : record.workspaceId === workspaceId) &&
+ typeof record.id === "string"
+ )
ids.add(record.id);
});
for (const query of queries)
@@ -49,6 +70,9 @@ export function evictWorkspaceCache(client: QueryClient, workspaceId: string) {
let affected = false;
visit([query.queryKey, query.state.data], (record) => {
if (
+ (allowed &&
+ typeof record.workspaceId === "string" &&
+ !allowed.has(record.workspaceId)) ||
Object.values(record).some(
(value) => typeof value === "string" && ids.has(value),
)
@@ -59,7 +83,9 @@ export function evictWorkspaceCache(client: QueryClient, workspaceId: string) {
(value) =>
typeof value === "string" &&
scopes.has(value) &&
- scopes.get(value) !== workspaceId,
+ (allowed
+ ? allowed.has(scopes.get(value)!)
+ : scopes.get(value) !== workspaceId),
);
const privatePrefixes = new Set([
"github-repositories",
diff --git a/tests/api-integration/account-deletion.test.ts b/tests/api-integration/account-deletion.test.ts
index a2696d486..30a290a42 100644
--- a/tests/api-integration/account-deletion.test.ts
+++ b/tests/api-integration/account-deletion.test.ts
@@ -4,7 +4,7 @@ import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
import type { WSContext } from "hono/ws";
import { auth } from "../../apps/api/src/auth";
import { addConnection, removeConnection } from "../../apps/api/src/ws";
-import db, { schema } from "../../apps/api/src/database";
+import db, { getDatabase, schema } from "../../apps/api/src/database";
import { createApp } from "../../apps/api/src/index";
import deleteAccountData from "../../apps/api/src/user/controllers/delete-account-data";
import { mockAuthenticatedSession } from "./helpers/auth";
@@ -74,41 +74,57 @@ describe("API integration: account deletion", () => {
expect(workspaces).toHaveLength(1);
});
- it("revokes project sockets when a member leaves through Better Auth", async () => {
- const owner = await createWorkspaceMember({ role: "owner" });
- const member = await addMember(owner.workspace.id, "member");
- const token = `leave-${randomUUID()}`;
- await db.insert(schema.sessionTable).values({
- id: randomUUID(),
- userId: member.id,
- token,
- expiresAt: new Date(Date.now() + 60_000),
- });
- const ws = { send: vi.fn(), close: vi.fn() };
- const conn = addConnection(
- "project",
- ws as unknown as WSContext,
- member.id,
- "window",
- owner.workspace.id,
- );
- try {
- const response = await auth.handler(
- new Request("http://localhost:1337/api/auth/organization/leave", {
- method: "POST",
- headers: {
- "content-type": "application/json",
- authorization: `Bearer ${token}`,
- },
- body: JSON.stringify({ organizationId: owner.workspace.id }),
- }),
+ it.each([false, true])(
+ "revokes project sockets after leaving even if the old post-delete lookup fails (%s)",
+ async (failLookup) => {
+ const owner = await createWorkspaceMember({ role: "owner" });
+ const member = await addMember(owner.workspace.id, "member");
+ const token = `leave-${randomUUID()}`;
+ await db.insert(schema.sessionTable).values({
+ id: randomUUID(),
+ userId: member.id,
+ token,
+ expiresAt: new Date(Date.now() + 60_000),
+ });
+ const ws = { send: vi.fn(), close: vi.fn() };
+ const conn = addConnection(
+ "project",
+ ws as unknown as WSContext,
+ member.id,
+ "window",
+ owner.workspace.id,
);
- expect(response.status).toBe(200);
- expect(ws.close).toHaveBeenCalledWith(1008, "Workspace access revoked");
- } finally {
- removeConnection("project", conn);
- }
- });
+ const select = getDatabase().select.bind(getDatabase());
+ const injected = failLookup
+ ? vi.spyOn(getDatabase(), "select").mockImplementation((fields) => {
+ if (
+ fields &&
+ Object.keys(fields).length === 1 &&
+ fields.id === schema.workspaceUserTable.id
+ )
+ throw new Error("Post-delete membership lookup unavailable");
+ return select(fields);
+ })
+ : undefined;
+ try {
+ const response = await auth.handler(
+ new Request("http://localhost:1337/api/auth/organization/leave", {
+ method: "POST",
+ headers: {
+ "content-type": "application/json",
+ authorization: `Bearer ${token}`,
+ },
+ body: JSON.stringify({ organizationId: owner.workspace.id }),
+ }),
+ );
+ expect(response.status).toBe(200);
+ expect(ws.close).toHaveBeenCalledWith(1008, "Workspace access revoked");
+ } finally {
+ injected?.mockRestore();
+ removeConnection("project", conn);
+ }
+ },
+ );
it("revokes other members after deleting a workspace through Better Auth", async () => {
const owner = await createWorkspaceMember({ role: "owner" });
diff --git a/tests/api/ws/workspace-access.test.ts b/tests/api/ws/workspace-access.test.ts
new file mode 100644
index 000000000..63e725f6b
--- /dev/null
+++ b/tests/api/ws/workspace-access.test.ts
@@ -0,0 +1,42 @@
+import { beforeEach, expect, it, vi } from "vite-plus/test";
+import type { WSContext } from "hono/ws";
+import { syncWorkspaceAccess } from "../../../apps/api/src/ws/workspace-access";
+const m = vi.hoisted(() => ({ user: vi.fn(), memberships: vi.fn() }));
+vi.mock("../../../apps/api/src/database", () => ({
+ default: {
+ select: (fields: Record<string, unknown>) => ({
+ from: () => ({ where: () => (fields.role ? m.user() : m.memberships()) }),
+ }),
+ },
+}));
+beforeEach(() => {
+ m.user.mockResolvedValue([{ role: "user" }]);
+ m.memberships.mockResolvedValue([{ workspaceId: "still-authorized" }]);
+});
+it("sends current workspace access when reconnecting after an offline removal", async () => {
+ const ws = { send: vi.fn(), close: vi.fn() };
+ await syncWorkspaceAccess("user", ws as unknown as WSContext);
+ expect(JSON.parse(ws.send.mock.calls[0][0])).toEqual({
+ type: "WORKSPACE_ACCESS_SYNC",
+ workspaceIds: ["still-authorized"],
+ });
+});
+it("preserves instance-admin access independently of memberships", async () => {
+ m.user.mockResolvedValue([{ role: "user,admin" }]);
+ const ws = { send: vi.fn(), close: vi.fn() };
+ await syncWorkspaceAccess("user", ws as unknown as WSContext);
+ expect(JSON.parse(ws.send.mock.calls[0][0])).toEqual({
+ type: "WORKSPACE_ACCESS_SYNC",
+ workspaceIds: null,
+ });
+});
+it("requires a reconnect if access synchronization fails", async () => {
+ m.memberships.mockRejectedValueOnce(new Error("database unavailable"));
+ const ws = { send: vi.fn(), close: vi.fn() };
+ await syncWorkspaceAccess("user", ws as unknown as WSContext);
+ expect(ws.send).not.toHaveBeenCalled();
+ expect(ws.close).toHaveBeenCalledWith(
+ 1011,
+ "Workspace access synchronization failed",
+ );
+});