A self-hostable bookmark-everything app (links, notes and images) with AI-based automatic tagging and full text search
feat(cli): add admin user deletion command (#3157)
Mohamed Bassemb6ee711bd2c7
diff --git a/apps/cli/src/commands/admin.ts b/apps/cli/src/commands/admin.tsindex 6bc07c37..81a6573d 100644--- a/apps/cli/src/commands/admin.ts+++ b/apps/cli/src/commands/admin.ts@@ -190,6 +190,48 @@ usersCmd}});+usersCmd+ .command("delete")+ .description("permanently delete a user and all of their data")+ .argument("<user>", "the id or email of the user to delete")+ .option("-y, --yes", "skip confirmation prompt")+ .action(async (idOrEmail, opts) => {+ const api = getAPIClient();++ try {+ const user = await api.admin.getUser.query(+ idOrEmail.includes("@") ? { email: idOrEmail } : { id: idOrEmail },+ );++ if (!opts.yes) {+ // Prompt on stderr to keep stdout clean for --json output.+ const rl = readline.createInterface({ input, output: process.stderr });+ const answer = (+ await rl.question(+ `This will permanently delete user "${user.name}" (${user.email}) and all of their data. Proceed? (yes/no): `,+ )+ )+ .trim()+ .toLowerCase();+ rl.close();+ if (answer !== "y" && answer !== "yes") {+ printStatusMessage(false, "Deletion aborted by user");+ return;+ }+ }++ await api.users.delete.mutate({ userId: user.id });+ if (getGlobalOptions().json) {+ printObject({ id: user.id, deleted: true });+ } else {+ printStatusMessage(true, `User ${user.email} deleted`);+ }+ } catch (error) {+ printErrorMessageWithReason("Failed to delete user", error as object);+ process.exitCode = 1;+ }+ });+adminCmd.addCommand(usersCmd);// --- Bookmarks subcommand ---diff --git a/packages/shared/types/admin.ts b/packages/shared/types/admin.tsindex 726e27b2..ce6d409c 100644--- a/packages/shared/types/admin.ts+++ b/packages/shared/types/admin.ts@@ -10,6 +10,20 @@ export const zAdminCreateUserSchema = zSignUpSchema.safeExtend(zRoleSchema.shape,);+export const zAdminUserSchema = z.object({+ id: z.string(),+ name: z.string(),+ email: z.string(),+ role: z.enum(["user", "admin"]).nullable(),+ bookmarkQuota: z.number().nullable(),+ storageQuota: z.number().nullable(),+});++export const zAdminGetUserSchema = z.union([+ z.object({ id: z.string() }),+ z.object({ email: z.string().trim().toLowerCase().email() }),+]);+export const updateUserSchema = z.object({userId: z.string(),role: z.enum(["user", "admin"]).optional(),diff --git a/packages/trpc/routers/admin.test.ts b/packages/trpc/routers/admin.test.tsindex dd786a6b..954e8a16 100644--- a/packages/trpc/routers/admin.test.ts+++ b/packages/trpc/routers/admin.test.ts@@ -467,6 +467,56 @@ describe("Admin Routes", () => {);});+ test<CustomTestContext>("getUser looks up a user by id or email", async ({+ db,+ }) => {+ const { adminApi } = await createAdmin(db);+ const target = await createTestUser(db, {+ name: "Lookup User",+ email: "[email protected]",+ password: "lookuppass123",+ });++ const byId = await adminApi.admin.getUser({ id: target.id });+ expect(byId).toEqual({+ id: target.id,+ name: "Lookup User",+ email: "[email protected]",+ role: "user",+ bookmarkQuota: null,+ storageQuota: null,+ });++ const byEmail = await adminApi.admin.getUser({+ email: " [email protected] ",+ });+ expect(byEmail.id).toBe(target.id);+ });++ test<CustomTestContext>("getUser fails for unknown users", async ({+ db,+ }) => {+ const { adminApi } = await createAdmin(db);++ await expect(() =>+ adminApi.admin.getUser({ id: "does-not-exist" }),+ ).rejects.toThrow(/User not found/);+ await expect(() =>+ adminApi.admin.getUser({ email: "[email protected]" }),+ ).rejects.toThrow(/User not found/);+ });++ test<CustomTestContext>("non-admins cannot look up users", async ({+ db,+ apiCallers,+ }) => {+ const { admin } = await createAdmin(db);++ await expect(() =>+ apiCallers[0].admin.getUser({ id: admin.id }),+ ).rejects.toThrow(/FORBIDDEN/);+ });+test<CustomTestContext>("resetPassword changes the password and signs the user out", async ({db,}) => {diff --git a/packages/trpc/routers/admin.ts b/packages/trpc/routers/admin.tsindex 3411c64a..39311494 100644--- a/packages/trpc/routers/admin.ts+++ b/packages/trpc/routers/admin.ts@@ -36,6 +36,8 @@ import {resetPasswordSchema,updateUserSchema,zAdminCreateUserSchema,+ zAdminGetUserSchema,+ zAdminUserSchema,zAdminJobModifiedWithinSecondsSchema,} from "@karakeep/shared/types/admin";import { BookmarkTypes } from "@karakeep/shared/types/bookmarks";@@ -511,6 +513,30 @@ export const adminAppRouter = router({return results;}),+ getUser: adminUsersProcedure+ .input(zAdminGetUserSchema)+ .output(zAdminUserSchema)+ .query(async ({ input, ctx }) => {+ const user = await ctx.db.query.users.findFirst({+ columns: {+ id: true,+ name: true,+ email: true,+ role: true,+ bookmarkQuota: true,+ storageQuota: true,+ },+ where:+ "id" in input ? eq(users.id, input.id) : eq(users.email, input.email),+ });+ if (!user) {+ throw new TRPCError({+ code: "NOT_FOUND",+ message: "User not found",+ });+ }+ return user;+ }),createUser: adminUsersProcedure.input(zAdminCreateUserSchema).output(diff --git a/packages/trpc/routers/users.test.ts b/packages/trpc/routers/users.test.tsindex e65fddd1..786ba54e 100644--- a/packages/trpc/routers/users.test.ts+++ b/packages/trpc/routers/users.test.ts@@ -180,6 +180,32 @@ describe("User Routes", () => {await expect(() => user2Caller.users.list()).rejects.toThrow(/FORBIDDEN/);});+ test<CustomTestContext>("admins can't delete their own account", async ({+ db,+ }) => {+ const adminUser = await createTestUser(db, {+ name: "Test User",+ email: "[email protected]",+ password: "pass1234",+ });+ assert(adminUser.role == "admin");++ const adminCaller = getApiCaller(+ db,+ adminUser.id,+ adminUser.email,+ "admin",+ );+ await expect(() =>+ adminCaller.users.delete({ userId: adminUser.id }),+ ).rejects.toThrow(/Cannot delete own account/);++ const remaining = await db.query.users.findFirst({+ where: eq(users.id, adminUser.id),+ });+ expect(remaining).toBeDefined();+ });+test<CustomTestContext>("get/update user settings", async ({ db }) => {const user = await createTestUser(db, {name: "Test User",diff --git a/packages/trpc/routers/users.ts b/packages/trpc/routers/users.tsindex fe2a9cb6..cb3798d0 100644--- a/packages/trpc/routers/users.ts+++ b/packages/trpc/routers/users.ts@@ -2,6 +2,7 @@ import { TRPCError } from "@trpc/server";import { z } from "zod";import { addLogFields } from "@karakeep/shared-server";+import { zAdminUserSchema } from "@karakeep/shared/types/admin";import {zUpdateUserSettingsSchema,zUserSettingsSchema,@@ -25,16 +26,7 @@ export const usersAppRouter = router({list: adminUsersProcedure.output(z.object({- users: z.array(- z.object({- id: z.string(),- name: z.string(),- email: z.string(),- role: z.enum(["user", "admin"]).nullable(),- bookmarkQuota: z.number().nullable(),- storageQuota: z.number().nullable(),- }),- ),+ users: z.array(zAdminUserSchema),}),).query(async ({ ctx }) => {@@ -51,6 +43,12 @@ export const usersAppRouter = router({}),).mutation(async ({ input, ctx }) => {+ if (ctx.user.id == input.userId) {+ throw new TRPCError({+ code: "BAD_REQUEST",+ message: "Cannot delete own account as an admin",+ });+ }addLogFields<"user.delete">({"user.deleted_id": input.userId,"user.deleted_by": "admin",