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): complete membership revocation and preserve admin access

Tin8540405c9575
diff --git a/apps/api/src/auth.ts b/apps/api/src/auth.ts
index d4b644b76..c92b74d21 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 { eq } from "drizzle-orm";
+import { and, eq } from "drizzle-orm";
import {
findBillableWorkspaces,
formatBillableWorkspacesMessage,
@@ -784,6 +784,26 @@ 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);
+ }
+ }
+
if (ctx.path.startsWith("/sign-up") || ctx.path.startsWith("/sign-in")) {
const newSession = ctx.context.newSession;
if (newSession) {
diff --git a/apps/api/src/user/controllers/delete-account-data.ts b/apps/api/src/user/controllers/delete-account-data.ts
index e0892c939..4339f12a2 100644
--- a/apps/api/src/user/controllers/delete-account-data.ts
+++ b/apps/api/src/user/controllers/delete-account-data.ts
@@ -6,6 +6,7 @@ import {
} from "../../billing/controllers/find-billable-workspaces";
import { syncWorkspaceSeats } from "../../billing/controllers/sync-seats";
import db from "../../database";
+import { revokeWorkspaceConnections } from "../../ws";
import { workspaceTable, workspaceUserTable } from "../../database/schema";
import {
formatBlockedWorkspacesMessage,
@@ -105,6 +106,13 @@ export async function deleteAccountData(userId: string) {
}
}
+ for (const workspaceId of [
+ ...plan.workspaceIdsToDelete,
+ ...plan.workspaceIdsToLeave,
+ ]) {
+ await revokeWorkspaceConnections(userId, workspaceId);
+ }
+
return plan;
}
diff --git a/apps/api/src/ws/index.ts b/apps/api/src/ws/index.ts
index 5be12770e..647fc5a78 100644
--- a/apps/api/src/ws/index.ts
+++ b/apps/api/src/ws/index.ts
@@ -2,8 +2,13 @@ import { randomUUID } from "node:crypto";
import { and, eq, inArray } from "drizzle-orm";
import type { WSContext } from "hono/ws";
import db from "../database";
-import { projectTable, workspaceUserTable } from "../database/schema";
+import {
+ projectTable,
+ userTable,
+ workspaceUserTable,
+} from "../database/schema";
import { subscribeToEvent } from "../events";
+import { instanceAdminRoleSql } from "../utils/instance-admin-role";
import { isRedisConfigured } from "../redis";
import {
getRelationSourceProject,
@@ -289,6 +294,21 @@ async function deliverToLocalConnections(
),
);
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);
}
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 ae642ab48..ba9518272 100644
--- a/apps/web/src/hooks/use-project-websocket-lifecycle.test.tsx
+++ b/apps/web/src/hooks/use-project-websocket-lifecycle.test.tsx
@@ -9,10 +9,16 @@ import {
} from "vite-plus/test";
import { useProjectWebSocket } from "./use-project-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: {
@@ -28,7 +34,7 @@ class TestSocket {
static instances: TestSocket[] = [];
readyState = 0;
onopen: (() => void) | null = null;
- onclose: (() => void) | null = null;
+ onclose: ((event?: { code: number }) => void) | null = null;
onmessage: ((event: { data: string }) => void) | null = null;
send = vi.fn();
// Deliberately delay close events to reproduce the project-switch race.
@@ -51,7 +57,7 @@ describe("project WebSocket lifecycle", () => {
vi.stubEnv("VITE_API_URL", "http://localhost:1337");
TestSocket.instances = [];
auth.userId = "user-a";
- client.invalidateQueries.mockClear();
+ vi.clearAllMocks();
});
afterEach(() => {
cleanup();
@@ -132,6 +138,20 @@ describe("project WebSocket lifecycle", () => {
}
});
+ it("clears private data and stops reconnecting after access revocation", () => {
+ renderHook(() => useProjectWebSocket("project-a"));
+ act(() => {
+ TestSocket.instances[0].open();
+ TestSocket.instances[0].onclose?.({ code: 1008 });
+ vi.advanceTimersByTime(60_000);
+ });
+ expect(client.cancelQueries).toHaveBeenCalledOnce();
+ expect(client.clear).toHaveBeenCalledOnce();
+ expect(navigate).toHaveBeenCalledWith({ to: "/dashboard" });
+ expect(TestSocket.instances).toHaveLength(1);
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
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 82033e8b9..2f28aba01 100644
--- a/apps/web/src/hooks/use-project-websocket.ts
+++ b/apps/web/src/hooks/use-project-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";
@@ -19,6 +20,7 @@ const WS_PING_INTERVAL_MS = 30_000;
export function useProjectWebSocket(projectId: string) {
const queryClient = useQueryClient();
+ const navigate = useNavigate();
const { data: session } = authClient.useSession();
useEffect(() => {
@@ -147,11 +149,19 @@ export function useProjectWebSocket(projectId: string) {
}
};
- ws.onclose = () => {
+ ws.onclose = (event) => {
if (disposed || activeSocket !== ws) return;
clearPing();
activeSocket = null;
+ if (event?.code === 1008) {
+ disposed = true;
+ void queryClient.cancelQueries();
+ queryClient.clear();
+ void navigate({ to: "/dashboard" });
+ return;
+ }
+
if (retries < MAX_RETRIES) {
const delay = BASE_DELAY * 2 ** retries; // 1s, 2s, 4s, 8s, 16s
retries += 1;
@@ -169,5 +179,5 @@ export function useProjectWebSocket(projectId: string) {
}
activeSocket?.close();
};
- }, [projectId, session?.user?.id, queryClient]);
+ }, [projectId, session?.user?.id, queryClient, navigate]);
}
diff --git a/tests/api-integration/account-deletion.test.ts b/tests/api-integration/account-deletion.test.ts
index 220046858..226984e6a 100644
--- a/tests/api-integration/account-deletion.test.ts
+++ b/tests/api-integration/account-deletion.test.ts
@@ -1,6 +1,9 @@
import { randomUUID } from "node:crypto";
import { eq } from "drizzle-orm";
-import { beforeEach, describe, expect, it } from "vite-plus/test";
+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 { createApp } from "../../apps/api/src/index";
import deleteAccountData from "../../apps/api/src/user/controllers/delete-account-data";
@@ -71,6 +74,61 @@ 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 }),
+ }),
+ );
+ expect(response.status).toBe(200);
+ expect(ws.close).toHaveBeenCalledWith(1008, "Workspace access revoked");
+ } finally {
+ removeConnection("project", conn);
+ }
+ });
+
+ it("revokes project sockets during account deletion", async () => {
+ const owner = await createWorkspaceMember({ role: "owner" });
+ const member = await addMember(owner.workspace.id, "member");
+ const ws = { send: vi.fn(), close: vi.fn() };
+ const conn = addConnection(
+ "project",
+ ws as unknown as WSContext,
+ member.id,
+ "window",
+ owner.workspace.id,
+ );
+ try {
+ await deleteAccountData(member.id);
+ expect(ws.close).toHaveBeenCalledWith(1008, "Workspace access revoked");
+ } finally {
+ removeConnection("project", conn);
+ }
+ });
+
it("leaves a shared workspace that keeps another owner", async () => {
const owner = await createWorkspaceMember({ role: "owner" });
await addMember(owner.workspace.id, "owner");
diff --git a/tests/api/ws/project-move.test.ts b/tests/api/ws/project-move.test.ts
index e833b26b2..3d4e27b18 100644
--- a/tests/api/ws/project-move.test.ts
+++ b/tests/api/ws/project-move.test.ts
@@ -20,6 +20,7 @@ import {
const m = vi.hoisted(() => ({
lookup: vi.fn(),
members: vi.fn(),
+ admins: vi.fn(),
redis: false,
publish: vi.fn(),
on: vi.fn(),
@@ -28,7 +29,12 @@ vi.mock("../../../apps/api/src/database", () => ({
default: {
select: (fields: Record<string, unknown>) => ({
from: () => ({
- where: () => (fields.userId ? m.members() : { limit: m.lookup }),
+ where: () =>
+ fields.role
+ ? m.admins()
+ : fields.userId
+ ? m.members()
+ : { limit: m.lookup },
}),
}),
},
@@ -67,6 +73,7 @@ const update = {
};
beforeEach(() => {
m.redis = false;
+ m.admins.mockResolvedValue([]);
m.members.mockResolvedValue([{ userId: "user" }]);
m.lookup.mockResolvedValue([{ workspaceId: "old" }]);
m.publish.mockResolvedValue(1);
@@ -159,6 +166,18 @@ describe("project move revocation", () => {
});
describe("workspace membership revocation", () => {
+ it("keeps instance admins connected without workspace membership", async () => {
+ vi.useFakeTimers();
+ await initializeWebSocketAdapter();
+ const ws = connect();
+ m.members.mockResolvedValue([]);
+ m.admins.mockResolvedValue([{ userId: "user", role: "admin" }]);
+ broadcastToProject("project", update);
+ await vi.advanceTimersByTimeAsync(100);
+ expect(ws.send).toHaveBeenCalledWith(JSON.stringify(update));
+ expect(ws.close).not.toHaveBeenCalled();
+ });
+
it("stops broadcasts after membership removal even when fan-out was missed", async () => {
vi.useFakeTimers();
await initializeWebSocketAdapter();