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): revoke deleted users without waiting for Redis

Tin4f6ac312d5ff
diff --git a/apps/api/src/auth.ts b/apps/api/src/auth.ts
index 275ab187f..30672271b 100644
--- a/apps/api/src/auth.ts
+++ b/apps/api/src/auth.ts
@@ -1,4 +1,4 @@
-import { revokeWorkspaceConnections } from "./ws";
+import { revokeUserConnections, revokeWorkspaceConnections } from "./ws";
import { apiKey } from "@better-auth/api-key";
import {
isSmtpConfigured,
@@ -638,6 +638,19 @@ export const auth = betterAuth({
},
databaseHooks: {
user: {
+ delete: {
+ after: async (user, ctx) => {
+ // Anonymous linking deletes the old identity after issuing a new
+ // session. The replacement account must retain its authentication.
+ if (
+ (user as Partial<UserWithAnonymous>).isAnonymous &&
+ ctx?.context.newSession &&
+ ctx.context.newSession.user.id !== user.id
+ )
+ return;
+ await revokeUserConnections(user.id);
+ },
+ },
update: {
before: async (user, ctx) => {
if (
diff --git a/apps/api/src/ws/index.ts b/apps/api/src/ws/index.ts
index b59105c8e..e7babcd5a 100644
--- a/apps/api/src/ws/index.ts
+++ b/apps/api/src/ws/index.ts
@@ -91,6 +91,19 @@ function deliverToLocalUserConnections(
) {
revokeLocalWorkspaceConnections(userId, message.workspaceId);
}
+ const allAccessRevoked = message.type === "USER_ACCESS_REVOKED";
+ if (allAccessRevoked) {
+ for (const [projectId, connections] of projectConnections)
+ for (const conn of [...connections]) {
+ if (conn.userId !== userId) continue;
+ removeConnection(projectId, conn);
+ try {
+ conn.ws.close(1008, "User access revoked");
+ } catch {
+ /* Already closed. */
+ }
+ }
+ }
const connections = userConnections.get(userId);
if (!connections) return;
@@ -101,6 +114,14 @@ function deliverToLocalUserConnections(
} catch {
connections.delete(conn);
}
+ if (allAccessRevoked) {
+ connections.delete(conn);
+ try {
+ conn.ws.close(1008, "User access revoked");
+ } catch {
+ /* Already closed. */
+ }
+ }
}
if (connections.size === 0) {
userConnections.delete(userId);
@@ -235,6 +256,12 @@ function revokeLocalWorkspaceConnections(userId: string, workspaceId: string) {
}
}
+export async function revokeUserConnections(userId: string) {
+ const message = { type: "USER_ACCESS_REVOKED" };
+ deliverToLocalUserConnections(userId, message);
+ await revocationDelivery?.send({ userId, message, origin: INSTANCE_ID });
+}
+
export async function revokeWorkspaceConnections(
userId: string,
workspaceId: string,
diff --git a/apps/api/src/ws/revocation-delivery.ts b/apps/api/src/ws/revocation-delivery.ts
index cbd260022..a604bd183 100644
--- a/apps/api/src/ws/revocation-delivery.ts
+++ b/apps/api/src/ws/revocation-delivery.ts
@@ -4,6 +4,7 @@ export function createRevocationDelivery(adapter: BroadcastAdapter) {
type Pending = {
message: UserBroadcast;
shouldRetry?: () => Promise<boolean>;
+ inFlight?: boolean;
};
const pending = new Map<string, Pending>();
let timer: ReturnType<typeof setTimeout> | undefined;
@@ -11,6 +12,8 @@ export function createRevocationDelivery(adapter: BroadcastAdapter) {
let delay = 1_000;
const attempt = async (key: string, entry: Pending, retry = false) => {
+ if (entry.inFlight) return;
+ entry.inFlight = true;
try {
if (!retry || !entry.shouldRetry || (await entry.shouldRetry())) {
if (stopped || pending.get(key) !== entry) return;
@@ -19,6 +22,8 @@ export function createRevocationDelivery(adapter: BroadcastAdapter) {
if (pending.get(key) === entry) pending.delete(key);
} catch {
// Membership is already removed. Keep the signal until Redis recovers.
+ } finally {
+ entry.inFlight = false;
}
};
const schedule = () => {
@@ -39,7 +44,9 @@ export function createRevocationDelivery(adapter: BroadcastAdapter) {
const key = JSON.stringify([message.userId, message.message.workspaceId]);
const entry = { message, shouldRetry };
pending.set(key, entry);
- await attempt(key, entry);
+ // Redis can queue PUBLISH through a long outage. Local revocation has
+ // already happened; the committed request must not await recovery.
+ void attempt(key, entry).then(schedule);
schedule();
},
stop() {
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 ca3065078..d6e8f3e55 100644
--- a/apps/web/src/hooks/use-user-websocket-lifecycle.test.tsx
+++ b/apps/web/src/hooks/use-user-websocket-lifecycle.test.tsx
@@ -24,6 +24,7 @@ const { client, auth, navigate } = vi.hoisted(() => ({
workspaceId: "workspace",
pathname: "",
notify: vi.fn(),
+ signOut: vi.fn().mockResolvedValue(undefined),
},
}));
vi.mock("@tanstack/react-router", () => ({
@@ -35,6 +36,7 @@ vi.mock("@tanstack/react-query", () => ({ useQueryClient: () => client }));
vi.mock("@/lib/auth-client", () => ({
authClient: {
$store: { notify: auth.notify },
+ signOut: auth.signOut,
useSession: () => ({
data: auth.userId
? {
@@ -234,3 +236,18 @@ describe("user WebSocket lifecycle", () => {
expect(auth.notify).toHaveBeenCalledWith("$activeOrgSignal");
});
});
+
+it("clears all private caches and signs out after account-wide revocation", async () => {
+ vi.stubGlobal("WebSocket", TestSocket);
+ auth.userId = "user-a";
+ renderHook(useUserWebSocket);
+ const socket = TestSocket.instances.at(-1)!;
+ socket.onmessage?.({ data: JSON.stringify({ type: "USER_ACCESS_REVOKED" }) });
+ socket.onclose?.();
+ await Promise.resolve();
+ expect(client.clear).toHaveBeenCalled();
+ expect(auth.signOut).toHaveBeenCalled();
+ expect(navigate).toHaveBeenCalledWith({ to: "/auth/sign-in" });
+ cleanup();
+ vi.unstubAllGlobals();
+});
diff --git a/apps/web/src/hooks/use-user-websocket.ts b/apps/web/src/hooks/use-user-websocket.ts
index f96817a84..da4d0ad32 100644
--- a/apps/web/src/hooks/use-user-websocket.ts
+++ b/apps/web/src/hooks/use-user-websocket.ts
@@ -38,6 +38,7 @@ export function useUserWebSocket() {
// A previous session's delayed socket events must not control this session.
let disposed = false;
+ let userRevoked = false;
let activeSocket: WebSocket | null = null;
let retryDelay = BASE_DELAY;
let retryTimeout: ReturnType<typeof setTimeout> | null = null;
@@ -60,6 +61,18 @@ export function useUserWebSocket() {
authClient.$store.notify(signal);
}
+ function revokeUserAccess() {
+ if (userRevoked) return;
+ userRevoked = true;
+ clearPing();
+ queryClient.clear();
+ refreshOrganizationState();
+ void authClient
+ .signOut()
+ .finally(() => navigate({ to: "/auth/sign-in" }))
+ .catch(() => {});
+ }
+
function connect() {
if (disposed) return;
retryTimeout = null;
@@ -86,6 +99,10 @@ export function useUserWebSocket() {
workspaceId?: string;
workspaceIds?: string[] | null;
};
+ if (message.type === "USER_ACCESS_REVOKED") {
+ revokeUserAccess();
+ return;
+ }
if (
message.type === "WORKSPACE_ACCESS_SYNC" &&
Array.isArray(message.workspaceIds) &&
@@ -123,10 +140,12 @@ export function useUserWebSocket() {
}
};
- ws.onclose = () => {
+ ws.onclose = (event) => {
if (disposed || activeSocket !== ws) return;
clearPing();
activeSocket = null;
+ if (event?.code === 1008) revokeUserAccess();
+ if (userRevoked) return;
const delay = retryDelay;
retryDelay = Math.min(retryDelay * 2, MAX_RETRY_DELAY);
diff --git a/tests/api-integration/account-deletion.test.ts b/tests/api-integration/account-deletion.test.ts
index 30a290a42..6dc85cb19 100644
--- a/tests/api-integration/account-deletion.test.ts
+++ b/tests/api-integration/account-deletion.test.ts
@@ -3,7 +3,12 @@ import { eq } from "drizzle-orm";
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 {
+ addConnection,
+ addUserConnection,
+ removeUserConnection,
+ removeConnection,
+} from "../../apps/api/src/ws";
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";
@@ -433,3 +438,61 @@ describe("API integration: avatar routes", () => {
expect(response.status).toBe(401);
});
});
+
+it("revokes an administrator's implicit workspace and user sockets after account deletion commits", async () => {
+ const { workspace } = await createWorkspaceMember();
+ const { project } = await createProjectFixture({ workspaceId: workspace.id });
+ const [admin] = await db
+ .insert(schema.userTable)
+ .values({
+ id: randomUUID(),
+ email: `${randomUUID()}@example.com`,
+ name: "Admin",
+ role: "admin",
+ emailVerified: true,
+ })
+ .returning();
+ const token = randomUUID();
+ await db.insert(schema.sessionTable).values({
+ id: randomUUID(),
+ userId: admin.id,
+ token,
+ expiresAt: new Date(Date.now() + 60_000),
+ });
+ const projectWs = { send: vi.fn(), close: vi.fn() };
+ const userWs = { send: vi.fn(), close: vi.fn() };
+ const conn = addConnection(
+ project.id,
+ projectWs as unknown as WSContext,
+ admin.id,
+ "window",
+ workspace.id,
+ );
+ const userConn = addUserConnection(admin.id, userWs as unknown as WSContext);
+ try {
+ const response = await auth.handler(
+ new Request("http://localhost:1337/api/auth/delete-user", {
+ method: "POST",
+ headers: {
+ "content-type": "application/json",
+ authorization: `Bearer ${token}`,
+ },
+ body: "{}",
+ }),
+ );
+ expect(response.status).toBe(200);
+ expect(
+ await db.query.userTable.findFirst({
+ where: eq(schema.userTable.id, admin.id),
+ }),
+ ).toBeUndefined();
+ expect(projectWs.close).toHaveBeenCalledWith(1008, "User access revoked");
+ expect(userWs.send).toHaveBeenCalledWith(
+ JSON.stringify({ type: "USER_ACCESS_REVOKED" }),
+ );
+ expect(userWs.close).toHaveBeenCalledWith(1008, "User access revoked");
+ } finally {
+ removeConnection(project.id, conn);
+ removeUserConnection(admin.id, userConn);
+ }
+});
diff --git a/tests/api/ws/project-move.test.ts b/tests/api/ws/project-move.test.ts
index 17abdee90..1c55286d2 100644
--- a/tests/api/ws/project-move.test.ts
+++ b/tests/api/ws/project-move.test.ts
@@ -16,6 +16,7 @@ import {
initializeWebSocketAdapter,
removeConnection,
revokeWorkspaceConnections,
+ revokeUserConnections,
shutdownWebSocketAdapter,
} from "../../../apps/api/src/ws";
@@ -352,3 +353,48 @@ it("retries a membership revocation while access remains absent", async () => {
await vi.advanceTimersByTimeAsync(1_000);
expect(m.publish).toHaveBeenCalledTimes(2);
});
+
+it("returns after local revocation while Redis PUBLISH remains queued", async () => {
+ vi.useFakeTimers();
+ m.redis = true;
+ await initializeWebSocketAdapter();
+ const ws = connect();
+ let finish!: (value: number) => void;
+ m.publish.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ finish = resolve;
+ }),
+ );
+ await expect(
+ revokeWorkspaceConnections("user", "old", { force: true }),
+ ).resolves.toBeUndefined();
+ expect(ws.close).toHaveBeenCalled();
+ await vi.advanceTimersByTimeAsync(60_000);
+ expect(m.publish).toHaveBeenCalledTimes(1);
+ finish(1);
+ await vi.advanceTimersByTimeAsync(60_000);
+ expect(m.publish).toHaveBeenCalledTimes(1);
+});
+it("revokes every project subscription for a deleted user regardless of membership", async () => {
+ const first = connect();
+ const second = connect("other", "implicit-admin-workspace");
+ await revokeUserConnections("user");
+ expect(first.close).toHaveBeenCalledWith(1008, "User access revoked");
+ expect(second.close).toHaveBeenCalledWith(1008, "User access revoked");
+});
+it("revokes all remote subscriptions on a deleted-user Redis message", async () => {
+ m.redis = true;
+ await initializeWebSocketAdapter();
+ const ws = connect("other", "implicit-admin-workspace");
+ const handler = m.on.mock.calls[1][1];
+ handler(
+ "kaneo:ws-user:*:broadcast",
+ "kaneo:ws-user:user:broadcast",
+ JSON.stringify({
+ userId: "user",
+ message: { type: "USER_ACCESS_REVOKED" },
+ }),
+ );
+ expect(ws.close).toHaveBeenCalledWith(1008, "User access revoked");
+});