⚡ 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(admin): reuse deletion transaction during account cleanup
Tin5f2a40d00f91
diff --git a/apps/api/src/admin/controllers/delete-user.ts b/apps/api/src/admin/controllers/delete-user.tsindex 79c35bfa4..b7646a590 100644--- a/apps/api/src/admin/controllers/delete-user.ts+++ b/apps/api/src/admin/controllers/delete-user.ts@@ -4,6 +4,7 @@ import type { ContentfulStatusCode } from "hono/utils/http-status";import db from "../../database";import { userTable } from "../../database/schema";import { ApiError } from "../../errors/api-error";+import type { DbOrTx } from "../../project-access/db-or-tx";import { deleteUserSessions } from "../../sessions/delete-user-sessions";import deleteAccountData from "../../user/controllers/delete-account-data";import { hasOtherInstanceAdmin } from "../../utils/has-other-instance-admin";@@ -15,9 +16,9 @@ import { lockAdminTargetUser } from "../users/lock-admin-target-user";import { rejectSelfAction } from "../users/reject-self-action";/** The same cleanup as self-service account deletion, with its conflicts. */-async function removeAccountData(userId: string) {+async function removeAccountData(userId: string, tx: DbOrTx) {try {- await deleteAccountData(userId);+ await deleteAccountData(userId, tx);} catch (error) {if (!isAPIError(error)) throw error;throw new ApiError(error.statusCode as ContentfulStatusCode, {@@ -49,7 +50,7 @@ async function deleteUser(message: "The instance must have at least one administrator.",});}- await removeAccountData(userId);+ await removeAccountData(userId, tx);await deleteUserSessions(tx, userId, { exceptSessionId: null });await tx.delete(userTable).where(eq(userTable.id, userId));await recordAdminAction(diff --git a/apps/api/src/billing/controllers/find-billable-workspaces.ts b/apps/api/src/billing/controllers/find-billable-workspaces.tsindex eddee1efd..c5109ca3e 100644--- a/apps/api/src/billing/controllers/find-billable-workspaces.ts+++ b/apps/api/src/billing/controllers/find-billable-workspaces.ts@@ -1,15 +1,19 @@import { eq, inArray } from "drizzle-orm";import db from "../../database";import { workspaceBillingTable, workspaceTable } from "../../database/schema";+import type { DbOrTx } from "../../project-access/db-or-tx";import { isBillingEnabled } from "../config";import { hasBillableSubscription } from "../subscription-state";-export async function findBillableWorkspaces(workspaceIds: string[]) {+export async function findBillableWorkspaces(+ workspaceIds: string[],+ database: DbOrTx = db,+) {if (!isBillingEnabled() || workspaceIds.length === 0) {return [];}- const rows = await db+ const rows = await database.select({workspaceId: workspaceBillingTable.workspaceId,name: workspaceTable.name,diff --git a/apps/api/src/billing/controllers/sync-seats.ts b/apps/api/src/billing/controllers/sync-seats.tsindex 4e114cd9c..9e228b06c 100644--- a/apps/api/src/billing/controllers/sync-seats.ts+++ b/apps/api/src/billing/controllers/sync-seats.ts@@ -4,15 +4,19 @@ import {workspaceBillingTable,workspaceUserTable,} from "../../database/schema";+import type { DbOrTx } from "../../project-access/db-or-tx";import { isBillingEnabled } from "../config";import { updateSubscriptionSeats } from "../creem-client";-export async function syncWorkspaceSeats(workspaceId: string) {+export async function syncWorkspaceSeats(+ workspaceId: string,+ database: DbOrTx = db,+) {if (!isBillingEnabled()) {return;}- const [billing] = await db+ const [billing] = await database.select().from(workspaceBillingTable).where(eq(workspaceBillingTable.workspaceId, workspaceId));@@ -26,7 +30,7 @@ export async function syncWorkspaceSeats(workspaceId: string) {return;}- const [members] = await db+ const [members] = await database.select({ value: count() }).from(workspaceUserTable).where(eq(workspaceUserTable.workspaceId, workspaceId));@@ -42,7 +46,7 @@ export async function syncWorkspaceSeats(workspaceId: string) {units: seats,});- await db+ await database.update(workspaceBillingTable).set({ seats }).where(eq(workspaceBillingTable.workspaceId, workspaceId));diff --git a/apps/api/src/user/controllers/delete-account-data.ts b/apps/api/src/user/controllers/delete-account-data.tsindex 9d1fc0684..af0a1be4e 100644--- a/apps/api/src/user/controllers/delete-account-data.ts+++ b/apps/api/src/user/controllers/delete-account-data.ts@@ -12,6 +12,7 @@ import {workspaceTable,workspaceUserTable,} from "../../database/schema";+import type { DbOrTx } from "../../project-access/db-or-tx";import { instanceAdminRoleSql } from "../../utils/instance-admin-role";import {formatBlockedWorkspacesMessage,@@ -22,8 +23,9 @@ import {async function collectMemberships(userId: string,+ database: DbOrTx,): Promise<WorkspaceMembershipSummary[]> {- const memberships = await db+ const memberships = await database.select({workspaceId: workspaceUserTable.workspaceId,role: workspaceUserTable.role,@@ -37,7 +39,7 @@ async function collectMemberships(const workspaceIds = memberships.map((membership) => membership.workspaceId);- const members = await db+ const members = await database.select({workspaceId: workspaceUserTable.workspaceId,workspaceName: workspaceTable.name,@@ -66,8 +68,8 @@ async function collectMemberships(});}-export async function deleteAccountData(userId: string) {- const plan = planAccountDeletion(await collectMemberships(userId));+export async function deleteAccountData(userId: string, database: DbOrTx = db) {+ const plan = planAccountDeletion(await collectMemberships(userId, database));if (plan.blockedWorkspaceNames.length > 0) {throw new APIError("CONFLICT", {@@ -76,7 +78,10 @@ export async function deleteAccountData(userId: string) {});}- const billable = await findBillableWorkspaces(plan.workspaceIdsToDelete);+ const billable = await findBillableWorkspaces(+ plan.workspaceIdsToDelete,+ database,+ );if (billable.length > 0) {throw new APIError("CONFLICT", {code: "WORKSPACE_HAS_ACTIVE_SUBSCRIPTION",@@ -87,7 +92,7 @@ export async function deleteAccountData(userId: string) {}if (plan.workspaceIdsToDelete.length > 0) {- const admins = await db+ const admins = await database.select({ userId: userTable.id }).from(userTable).where(instanceAdminRoleSql(userTable.role));@@ -95,7 +100,7 @@ export async function deleteAccountData(userId: string) {userId,...admins.map((admin) => admin.userId),]);- await db+ await database.delete(workspaceTable).where(inArray(workspaceTable.id, plan.workspaceIdsToDelete));for (const workspaceId of plan.workspaceIdsToDelete) {@@ -108,7 +113,7 @@ export async function deleteAccountData(userId: string) {}if (plan.workspaceIdsToLeave.length > 0) {- await db+ await database.delete(workspaceUserTable).where(and(@@ -118,7 +123,7 @@ export async function deleteAccountData(userId: string) {);for (const workspaceId of plan.workspaceIdsToLeave) {- await syncWorkspaceSeats(workspaceId).catch((error) => {+ await syncWorkspaceSeats(workspaceId, database).catch((error) => {console.error("Seat sync after account deletion failed:",workspaceId,diff --git a/tests/api-integration/admin-user-account-guards.test.ts b/tests/api-integration/admin-user-account-guards.test.tsindex df54d88d8..5ee54f62c 100644--- a/tests/api-integration/admin-user-account-guards.test.ts+++ b/tests/api-integration/admin-user-account-guards.test.ts@@ -1,7 +1,15 @@import { eq, inArray } from "drizzle-orm";-import { beforeEach, describe, expect, it } from "vite-plus/test";+import {+ afterAll,+ beforeAll,+ beforeEach,+ describe,+ expect,+ it,+ vi,+} from "vite-plus/test";import deleteUser from "../../apps/api/src/admin/controllers/delete-user";-import db, { schema } from "../../apps/api/src/database";+import db, { getDatabasePool, schema } from "../../apps/api/src/database";import { createApp } from "../../apps/api/src/index";import { signInWithRole } from "./helpers/admin/instance-roles";import { readAuditLog } from "./helpers/admin/read-audit-log";@@ -9,10 +17,17 @@ import { resetTestDatabase } from "./helpers/database";import { readErrorBody } from "./helpers/error-body";import { createWorkspaceMember } from "./helpers/fixtures";+beforeAll(() => {+ vi.stubEnv("DATABASE_POOL_MAX", "2");+});+afterAll(() => {+ vi.unstubAllEnvs();+});beforeEach(resetTestDatabase);describe("admin account guards", () => {it("keeps one administrator and their workspace during concurrent deletions", async () => {+ expect(getDatabasePool().options.max).toBe(2);const first = await createWorkspaceMember({ role: "owner" });const second = await createWorkspaceMember({ role: "owner" });const ids = [first.user.id, second.user.id];