A self-hostable bookmark-everything app (links, notes and images) with AI-based automatic tagging and full text search
fix: reject user deletion with active subscription
Mohamed Bassem635f8469e109
diff --git a/apps/web/components/settings/DeleteAccount.tsx b/apps/web/components/settings/DeleteAccount.tsxindex bbe61ca3..cf2ad60a 100644--- a/apps/web/components/settings/DeleteAccount.tsx+++ b/apps/web/components/settings/DeleteAccount.tsx@@ -4,6 +4,7 @@ import { useState } from "react";import { useRouter } from "next/navigation";import { ActionButton } from "@/components/ui/action-button";import ActionConfirmingDialog from "@/components/ui/action-confirming-dialog";+import { Alert, AlertDescription } from "@/components/ui/alert";import {Form,FormControl,@@ -38,6 +39,7 @@ export function DeleteAccount() {const router = useRouter();const [showPassword, setShowPassword] = useState(false);const [isDialogOpen, setIsDialogOpen] = useState(false);+ const [serverError, setServerError] = useState<string | null>(null);const { data: user } = useWhoAmI();const isLocalUser = user?.localUser ?? false;@@ -52,6 +54,7 @@ export function DeleteAccount() {const deleteAccountMutation = useDeleteAccount({onSuccess: () => {+ setServerError(null);toast({description: "Your account has been successfully deleted.",});@@ -61,23 +64,40 @@ export function DeleteAccount() {},onError: (error) => {if (error.data?.code === "UNAUTHORIZED") {- toast({- description: "Invalid password. Please try again.",- variant: "destructive",- });- } else {- toast({- description: "Failed to delete account. Please try again.",- variant: "destructive",+ form.setError("password", {+ type: "server",+ message: "Invalid password. Please try again.",});+ setServerError(null);+ return;+ }++ if (error.data?.code === "BAD_REQUEST") {+ setServerError(error.message);+ return;}++ toast({+ description: "Failed to delete account. Please try again.",+ variant: "destructive",+ });},});const onSubmit = (values: z.infer<typeof deleteAccountSchema>) => {+ setServerError(null);+ form.clearErrors();deleteAccountMutation.mutate({ password: values.password });};+ const handleDialogOpenChange = (open: boolean) => {+ setIsDialogOpen(open);+ if (!open) {+ setServerError(null);+ form.clearErrors();+ }+ };+return (<SettingsSection title="Danger Zone" variant="danger"><div className="space-y-2">@@ -90,7 +110,7 @@ export function DeleteAccount() {<ActionConfirmingDialogopen={isDialogOpen}- setOpen={setIsDialogOpen}+ setOpen={handleDialogOpenChange}title="Delete Account"description={<div className="space-y-4">@@ -106,6 +126,12 @@ export function DeleteAccount() {</p></div></div>+ {serverError && (+ <Alert variant="destructive">+ <AlertTriangle className="h-4 w-4" />+ <AlertDescription>{serverError}</AlertDescription>+ </Alert>+ )}<Form {...form}><formdiff --git a/packages/shared-server/src/eventLogTypes.ts b/packages/shared-server/src/eventLogTypes.tsindex c3700073..5424261b 100644--- a/packages/shared-server/src/eventLogTypes.ts+++ b/packages/shared-server/src/eventLogTypes.ts@@ -151,12 +151,14 @@ type EventLogInternal =| { ["event.name"]: "subscription.portal_opened" }| {["event.name"]: "subscription.synced";- "subscription.tier": string;+ "stripe.customer_id"?: string;+ "subscription.tier"?: string;"subscription.status"?: string;"subscription.prev_tier"?: string;"subscription.prev_status"?: string;+ "subscription.sync_skipped_reason"?: "unknown_customer";"subscription.cancel_at_period_end"?: boolean;- "subscription.transition":+ "subscription.transition"?:| "upgrade"| "downgrade"| "renewed"@@ -167,6 +169,7 @@ type EventLogInternal =| {["event.name"]: "subscription.webhook_received";"stripe.event_type": string;+ "stripe.customer_id"?: string;};interface CommonEventLogFields {diff --git a/packages/trpc/models/users.ts b/packages/trpc/models/users.tsindex e91c2ef9..a5d8327d 100644--- a/packages/trpc/models/users.ts+++ b/packages/trpc/models/users.ts@@ -14,6 +14,7 @@ import {bookmarkTags,highlights,passwordResetTokens,+ subscriptions,tagsOnBookmarks,users,verificationTokens,@@ -369,7 +370,32 @@ export class User {.where(eq(passwordResetTokens.token, input.token));}+ private static async assertNoActiveStripeSubscriptionForUser(+ db: Context["db"],+ userId: string,+ ) {+ const subscription = await db.query.subscriptions.findFirst({+ where: eq(subscriptions.userId, userId),+ columns: {+ status: true,+ },+ });++ if (+ subscription?.status === "active" ||+ subscription?.status === "trialing"+ ) {+ throw new TRPCError({+ code: "BAD_REQUEST",+ message:+ "Can't delete user while subscription is active. Please cancel your subscription first and try again.",+ });+ }+ }+private static async deleteInternal(db: Context["db"], userId: string) {+ await User.assertNoActiveStripeSubscriptionForUser(db, userId);+const res = await db.delete(users).where(eq(users.id, userId));if (res.changes === 0) {diff --git a/packages/trpc/routers/subscriptions.test.ts b/packages/trpc/routers/subscriptions.test.tsindex 33815cb5..22b8488c 100644--- a/packages/trpc/routers/subscriptions.test.ts+++ b/packages/trpc/routers/subscriptions.test.ts@@ -28,6 +28,7 @@ const mockStripeInstance = vi.hoisted(() => ({subscriptions: {update: vi.fn(),list: vi.fn(),+ cancel: vi.fn(),},webhooks: {constructEvent: vi.fn(),@@ -695,6 +696,29 @@ describe("Subscription Routes", () => {expect(subscription?.endDate).toBeNull();});+ test<CustomTestContext>("acknowledges webhook for unknown Stripe customer", async ({+ unauthedAPICaller,+ }) => {+ const mockEvent = {+ type: "payment_intent.succeeded",+ data: {+ object: {+ customer: "cus_deleted_user",+ },+ },+ };++ mockWebhooksConstructEvent.mockReturnValue(mockEvent);++ const result = await unauthedAPICaller.subscriptions.handleWebhook({+ body: "webhook-body",+ signature: "webhook-signature",+ });++ expect(result).toEqual({ received: true });+ expect(mockSubscriptionsList).not.toHaveBeenCalled();+ });+test<CustomTestContext>("handles unknown webhook event type", async ({unauthedAPICaller,}) => {diff --git a/packages/trpc/routers/subscriptions.ts b/packages/trpc/routers/subscriptions.tsindex 81b2622a..4d77f823 100644--- a/packages/trpc/routers/subscriptions.ts+++ b/packages/trpc/routers/subscriptions.ts@@ -95,6 +95,10 @@ function computeSubscriptionTransition(async function syncStripeDataToDatabase(customerId: string, db: Context["db"]) {return withEventLog("subscription.synced", async () => {+ addLogFields<"subscription.synced">({+ "stripe.customer_id": customerId,+ });+if (!stripe) {throw new Error("Stripe is not configured");}@@ -108,13 +112,13 @@ async function syncStripeDataToDatabase(customerId: string, db: Context["db"]) {existingSubscription?.cancelAtPeriodEnd ?? false;if (!existingSubscription) {- console.error(- `ERROR: No subscription found for customer with this ID ${customerId}`,+ console.warn(+ `Ignoring Stripe webhook for unknown customer ID ${customerId}`,);- throw new TRPCError({- code: "INTERNAL_SERVER_ERROR",- message: "No subscription found for customer with this ID",+ addLogFields<"subscription.synced">({+ "subscription.sync_skipped_reason": "unknown_customer",});+ return;}addLogFields<"subscription.synced">({@@ -264,6 +268,10 @@ async function processEvent(event: Stripe.Event, db: Context["db"]) {);}+ addLogFields<"subscription.webhook_received">({+ "stripe.customer_id": customerId,+ });+return await syncStripeDataToDatabase(customerId, db);}diff --git a/packages/trpc/routers/users.test.ts b/packages/trpc/routers/users.test.tsindex 2aa82f83..168d200c 100644--- a/packages/trpc/routers/users.test.ts+++ b/packages/trpc/routers/users.test.ts@@ -6,6 +6,7 @@ import {AssetTypes,bookmarks,passwordResetTokens,+ subscriptions,users,} from "@karakeep/db/schema";import { BookmarkTypes } from "@karakeep/shared/types/bookmarks";@@ -928,6 +929,41 @@ describe("User Routes", () => {expect(deletedUser).toHaveLength(0);});+ test<CustomTestContext>("deleteAccount refuses active Stripe subscription", async ({+ db,+ unauthedAPICaller,+ }) => {+ const user = await unauthedAPICaller.users.create({+ name: "Test User",+ email: "[email protected]",+ password: "pass1234",+ confirmPassword: "pass1234",+ });+ const caller = getApiCaller(db, user.id, user.email, user.role || "user");++ await db.insert(subscriptions).values({+ userId: user.id,+ stripeCustomerId: "cus_123",+ stripeSubscriptionId: "sub_123",+ status: "active",+ tier: "paid",+ });++ await expect(() =>+ caller.users.deleteAccount({+ password: "pass1234",+ }),+ ).rejects.toThrow(+ /Can't delete user while subscription is active. Please cancel your subscription first and try again./,+ );++ const deletedUser = await db+ .select()+ .from(users)+ .where(eq(users.id, user.id));+ expect(deletedUser).toHaveLength(1);+ });+test<CustomTestContext>("deleteAccount - wrong password", async ({db,unauthedAPICaller,