Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.
TypeScript i18nextnext-authnextjspostgresqlprismareact-emailt3-stacktailwindcsstrpcturborepotypescriptzod
✨ Account deletion: consequences, subscription cancel, soft delete with recovery window (#2699)
Luke Vella3b1f3ea8fdd6
diff --git a/apps/web/public/locales/en/app.json b/apps/web/public/locales/en/app.jsonindex 74b8fcb6d..431f74a2e 100644--- a/apps/web/public/locales/en/app.json+++ b/apps/web/public/locales/en/app.json@@ -7,6 +7,7 @@"acceptInviteTitle": "{inviterName} invited you to join {spaceName}","accessDenied": "Access Denied","account": "Account",+ "accountDeletionCancelled": "Your account is no longer scheduled for deletion","accountMenu": "Account menu","accountNotLinkedDescription": "A user with this email already exists. Please log in using the original method.","actionErrorForbidden": "You are not allowed to perform this action",@@ -101,6 +102,7 @@"calendarSelectionSetError": "Failed to set calendar selection","calendarSelectionSetSuccess": "Calendar selection set successfully","cancel": "Cancel",+ "cancelAccountDeletion": "Cancel deletion","canceled": "Canceled","canceledEventsEmptyStateDescription": "Canceled events will show up here.","canceledEventsEmptyStateTitle": "No Canceled Events",@@ -176,7 +178,7 @@"customBrandingPromptDescription": "Get professional scheduling polls with your own logo and colors.","customBrandingPromptTitle": "Custom Branding","dangerZone": "Danger Zone",- "dangerZoneAccount": "Delete your account permanently. This action cannot be undone.",+ "dangerZoneAccountDeletion": "Delete your account and all data associated with it","dateAndTime": "Date & Time","dateAndTimeDescription": "Change your preferred date and time settings","dates": "Dates",@@ -188,9 +190,13 @@"defaultCalendarSetSuccess": "Default calendar set successfully","delete": "Delete","deleteAccount": "Delete Account",- "deleteAccountDialogDescription": "Are you sure you want to delete your account?",+ "deleteAccountActivePolls": "{count, plural, one {# active poll} other {# active polls}}",+ "deleteAccountDataWarning": "All data associated with your account, including your polls, events, votes, and comments, will be permanently deleted.",+ "deleteAccountDialogScheduleDescription": "Your account will be scheduled for deletion.","deleteAccountDialogTitle": "Delete Account",- "deleteAccountInstruction": "Please confirm your email address to delete your account",+ "deleteAccountRecoveryWindow": "You can cancel the deletion within {count, plural, one {# day} other {# days}}. After that, your account and data will be permanently deleted.",+ "deleteAccountSubscriptionNotice": "Your Pro subscription will not renew and will end with your current billing period. If you cancel the deletion, your subscription will continue as normal.",+ "deleteAccountUpcomingEvents": "{count, plural, one {# upcoming event} other {# upcoming events}}","deleteDate": "Delete date","deletedSpaceSuccess": "Space has been permanently deleted","deleteEventTypeDescription": "<b>{name}</b> will be hidden from creation pickers. This cannot be undone.",@@ -246,7 +252,6 @@"emailChangeVerifyDescription": "Enter the 6 digit verification code we sent to {email}.","emailChangeVerifyError": "Verification failed. Please try again.","emailDoesNotMatch": "The email address does not match.",- "emailMismatch": "Email does not match the account email","emailPlaceholder": "[email protected]","enabled": "Enabled","endOfList": "You've reached the end of the list",@@ -466,10 +471,10 @@"optionalLabel": "(Optional)","optionCount": "{count, plural, one {# option} other {# options}}","or": "Or",- "organizedBy": "Organized by {name}","organizationName": "Organization Name","organizationNamePlaceholder": "e.g. Acme Corp","organizationNameRequired": "Organization name is required",+ "organizedBy": "Organized by {name}","outlook": "Outlook","owner": "Owner","ownerPermissionsRequired": "Only space owners can access billing settings.",@@ -498,6 +503,7 @@"pastEventsEmptyStateDescription": "Past events will show up here.","pastEventsEmptyStateTitle": "No Past Events","pending": "Pending",+ "pendingDeletionNotice": "Your account and data will be permanently deleted on {deletionDate}.","pendingInvites": "Pending Invites","pendingInvitesDescription": "Invite other users to share your space.","pendingInvitesUpgradeDescription": "Upgrade to Pro to invite members to your space.",@@ -628,7 +634,6 @@"setupAccountDescription": "Tell us a bit about yourself.","setupAccountTitle": "Set Up Your Account","setupFooterLoggedInAs": "Logged in as <email>{email}</email>",- "setupFooterSignOut": "Sign out?","setupPasswordAlertDesc": "Set up a password to make logging in faster and more convenient.","setupPasswordAlertTitle": "Login quicker with a password","setupPasswordButton": "Set up password",diff --git a/apps/web/src/app/[locale]/(space)/settings/profile/actions.ts b/apps/web/src/app/[locale]/(space)/settings/profile/actions.tsnew file mode 100644index 000000000..eeb4f6e9c--- /dev/null+++ b/apps/web/src/app/[locale]/(space)/settings/profile/actions.ts@@ -0,0 +1,87 @@+"use server";+import { subject } from "@casl/ability";+import { sendAccountDeletionScheduledEmail } from "@rallly/emails/templates/account-deletion-scheduled";+import { after } from "next/server";+import { getInstanceBranding } from "@/emails/branding";+import {+ resumeUserSubscriptionRenewals,+ stopUserSubscriptionRenewals,+} from "@/features/billing/mutations";+import {+ cancelAccountDeletion,+ scheduleAccountDeletion,+} from "@/features/user/account-deletion/mutations";+import { getScheduledDeletionDate } from "@/features/user/account-deletion/utils";+import { getLocale } from "@/i18n/server/get-locale";+import { formatDateTime } from "@/lib/datetime/format";+import { AppError } from "@/lib/errors/app-error";+import { track } from "@/lib/posthog";+import {+ authActionClient,+ createRateLimitMiddleware,+} from "@/lib/safe-action/server";++// Renewals are stopped (cancel_at_period_end) rather than the subscription+// cancelled, so nothing here is irreversible: no charge can land during the+// recovery window, the user keeps the Pro time they paid for, and cancelling+// the deletion restores the subscription. deletedAt is written first; if the+// Stripe call fails, it is rolled back so the two never drift apart. The+// reaper hard-cancels at the end of the window.+export const scheduleAccountDeletionAction = authActionClient+ .metadata({ actionName: "schedule_account_deletion" })+ // Each call hits Stripe and sends an email — keep the ceiling low.+ .use(createRateLimitMiddleware(3, "1 h"))+ .action(async ({ ctx }) => {+ if (ctx.ability.cannot("delete", subject("User", ctx.user))) {+ throw new AppError({+ code: "FORBIDDEN",+ message: "You are not authorized to delete this account",+ });+ }++ const deletedAt = await scheduleAccountDeletion({ userId: ctx.user.id });++ let stoppedRenewals: number;+ try {+ stoppedRenewals = await stopUserSubscriptionRenewals({+ userId: ctx.user.id,+ });+ } catch (error) {+ await cancelAccountDeletion({ userId: ctx.user.id });+ throw error;+ }++ track(ctx.user, {+ event: "account_deletion_schedule",+ properties: {+ hadActiveSubscription: stoppedRenewals > 0,+ },+ });++ const locale = ctx.user.locale ?? (await getLocale());+ const branding = await getInstanceBranding();+ const deletionDate = formatDateTime(getScheduledDeletionDate(deletedAt), {+ preset: "dateLong",+ locale,+ timeZone: ctx.user.timeZone,+ });++ after(() =>+ sendAccountDeletionScheduledEmail({+ to: ctx.user.email,+ locale,+ branding,+ props: { deletionDate },+ }),+ );+ });++export const cancelAccountDeletionAction = authActionClient+ .metadata({ actionName: "cancel_account_deletion" })+ .use(createRateLimitMiddleware(10, "1 h"))+ .action(async ({ ctx }) => {+ await cancelAccountDeletion({ userId: ctx.user.id });+ await resumeUserSubscriptionRenewals({ userId: ctx.user.id });++ track(ctx.user, { event: "account_deletion_cancel" });+ });diff --git a/apps/web/src/app/[locale]/(space)/settings/profile/components/account-deletion-summary.tsx b/apps/web/src/app/[locale]/(space)/settings/profile/components/account-deletion-summary.tsxnew file mode 100644index 000000000..e7b47ee35--- /dev/null+++ b/apps/web/src/app/[locale]/(space)/settings/profile/components/account-deletion-summary.tsx@@ -0,0 +1,79 @@+import { Alert, AlertDescription } from "@rallly/ui/alert";+import { Icon } from "@rallly/ui/icon";+import { Skeleton } from "@rallly/ui/skeleton";+import { BarChart2Icon, CalendarIcon, InfoIcon } from "lucide-react";+import { getAccountDeletionSummary } from "@/features/user/account-deletion/data";+import { Trans } from "@/i18n/client";+import { requireUser } from "@/lib/auth";++// Streamed into the delete account dialog behind Suspense so opening the+// settings page never waits on the counts.+export async function AccountDeletionSummary() {+ const user = await requireUser();+ const { activePollCount, upcomingEventCount, hasActiveSubscription } =+ await getAccountDeletionSummary({+ userId: user.id,+ timeZone: user.timeZone ?? "UTC",+ });++ const hasResources = activePollCount > 0 || upcomingEventCount > 0;++ if (!hasResources && !hasActiveSubscription) {+ return null;+ }++ return (+ <>+ {hasResources ? (+ <ul className="space-y-2">+ {activePollCount > 0 ? (+ <li className="flex items-center gap-x-2">+ <Icon>+ <BarChart2Icon />+ </Icon>+ <Trans+ i18nKey="deleteAccountActivePolls"+ defaults="{count, plural, one {# active poll} other {# active polls}}"+ values={{ count: activePollCount }}+ />+ </li>+ ) : null}+ {upcomingEventCount > 0 ? (+ <li className="flex items-center gap-x-2">+ <Icon>+ <CalendarIcon />+ </Icon>+ <Trans+ i18nKey="deleteAccountUpcomingEvents"+ defaults="{count, plural, one {# upcoming event} other {# upcoming events}}"+ values={{ count: upcomingEventCount }}+ />+ </li>+ ) : null}+ </ul>+ ) : null}+ {hasActiveSubscription ? (+ <Alert>+ <InfoIcon />+ <AlertDescription>+ <p>+ <Trans+ i18nKey="deleteAccountSubscriptionNotice"+ defaults="Your Pro subscription will not renew and will end with your current billing period. If you cancel the deletion, your subscription will continue as normal."+ />+ </p>+ </AlertDescription>+ </Alert>+ ) : null}+ </>+ );+}++export function AccountDeletionSummarySkeleton() {+ return (+ <div className="space-y-2">+ <Skeleton className="h-5 w-40" />+ <Skeleton className="h-5 w-48" />+ </div>+ );+}diff --git a/apps/web/src/app/[locale]/(space)/settings/profile/components/cancel-account-deletion-button.tsx b/apps/web/src/app/[locale]/(space)/settings/profile/components/cancel-account-deletion-button.tsxnew file mode 100644index 000000000..adb077ee6--- /dev/null+++ b/apps/web/src/app/[locale]/(space)/settings/profile/components/cancel-account-deletion-button.tsx@@ -0,0 +1,28 @@+"use client";+import { Button } from "@rallly/ui/button";+import { toast } from "@rallly/ui/sonner";+import { Trans, useTranslation } from "@/i18n/client";+import { useSafeAction } from "@/lib/safe-action/client";+import { cancelAccountDeletionAction } from "../actions";++export function CancelAccountDeletionButton() {+ const { t } = useTranslation();+ const cancelAccountDeletion = useSafeAction(cancelAccountDeletionAction, {+ onSuccess: () => {+ toast.success(+ t("accountDeletionCancelled", {+ defaultValue: "Your account is no longer scheduled for deletion",+ }),+ );+ },+ });++ return (+ <Button+ loading={cancelAccountDeletion.isExecuting}+ onClick={() => cancelAccountDeletion.executeAsync()}+ >+ <Trans i18nKey="cancelAccountDeletion" defaults="Cancel deletion" />+ </Button>+ );+}diff --git a/apps/web/src/app/[locale]/(space)/settings/profile/components/delete-account-button.tsx b/apps/web/src/app/[locale]/(space)/settings/profile/components/delete-account-button.tsxnew file mode 100644index 000000000..61853a354--- /dev/null+++ b/apps/web/src/app/[locale]/(space)/settings/profile/components/delete-account-button.tsx@@ -0,0 +1,23 @@+"use client";++import { Button } from "@rallly/ui/button";+import { useDialog } from "@rallly/ui/dialog";++import { Trans } from "@/i18n/client";+import { DeleteAccountDialog } from "./delete-account-dialog";++export function DeleteAccountButton({+ summary,+}: {+ summary?: React.ReactNode;+}) {+ const dialog = useDialog();+ return (+ <>+ <Button className="text-destructive" {...dialog.triggerProps}>+ <Trans i18nKey="deleteAccount" defaults="Delete Account" />+ </Button>+ <DeleteAccountDialog {...dialog.dialogProps} summary={summary} />+ </>+ );+}diff --git a/apps/web/src/app/[locale]/(space)/settings/profile/components/delete-account-dialog.tsx b/apps/web/src/app/[locale]/(space)/settings/profile/components/delete-account-dialog.tsxnew file mode 100644index 000000000..516e944f4--- /dev/null+++ b/apps/web/src/app/[locale]/(space)/settings/profile/components/delete-account-dialog.tsx@@ -0,0 +1,78 @@+"use client";+import { Button } from "@rallly/ui/button";+import type { DialogProps } from "@rallly/ui/dialog";+import {+ Dialog,+ DialogClose,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@rallly/ui/dialog";+import { ACCOUNT_DELETION_GRACE_DAYS } from "@/features/user/account-deletion/constants";+import { Trans } from "@/i18n/client";+import { useSafeAction } from "@/lib/safe-action/client";+import { scheduleAccountDeletionAction } from "../actions";++export function DeleteAccountDialog({+ summary,+ ...rest+}: DialogProps & {+ summary?: React.ReactNode;+}) {+ const scheduleAccountDeletion = useSafeAction(scheduleAccountDeletionAction, {+ onSuccess: () => {+ rest.onOpenChange?.(false);+ },+ });++ return (+ <Dialog {...rest}>+ <DialogContent>+ <DialogHeader>+ <DialogTitle>+ <Trans+ i18nKey="deleteAccountDialogTitle"+ defaults="Delete Account"+ />+ </DialogTitle>+ <DialogDescription>+ <Trans+ i18nKey="deleteAccountDialogScheduleDescription"+ defaults="Your account will be scheduled for deletion."+ />+ </DialogDescription>+ </DialogHeader>+ <div className="space-y-3 text-sm">+ <p>+ <Trans+ i18nKey="deleteAccountDataWarning"+ defaults="All data associated with your account, including your polls, events, votes, and comments, will be permanently deleted."+ />+ </p>+ {summary}+ <p>+ <Trans+ i18nKey="deleteAccountRecoveryWindow"+ defaults="You can cancel the deletion within {count, plural, one {# day} other {# days}}. After that, your account and data will be permanently deleted."+ values={{ count: ACCOUNT_DELETION_GRACE_DAYS }}+ />+ </p>+ </div>+ <DialogFooter>+ <DialogClose render={<Button />}>+ <Trans i18nKey="cancel" defaults="Cancel" />+ </DialogClose>+ <Button+ variant="destructive"+ loading={scheduleAccountDeletion.isExecuting}+ onClick={() => scheduleAccountDeletion.executeAsync()}+ >+ <Trans i18nKey="deleteAccount" defaults="Delete Account" />+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+}diff --git a/apps/web/src/app/[locale]/(space)/settings/profile/components/pending-deletion-notice.tsx b/apps/web/src/app/[locale]/(space)/settings/profile/components/pending-deletion-notice.tsxnew file mode 100644index 000000000..9255affe1--- /dev/null+++ b/apps/web/src/app/[locale]/(space)/settings/profile/components/pending-deletion-notice.tsx@@ -0,0 +1,31 @@+import { getScheduledDeletionDate } from "@/features/user/account-deletion/utils";+import { Trans } from "@/i18n/client";+import { getSession } from "@/lib/auth";+import { formatDateTime } from "@/lib/datetime/format";+import { CancelAccountDeletionButton } from "./cancel-account-deletion-button";++export async function PendingDeletionNotice({+ deletedAt,+}: {+ deletedAt: Date;+}) {+ const session = await getSession();+ const deletionDate = formatDateTime(getScheduledDeletionDate(deletedAt), {+ preset: "dateLong",+ locale: session?.user.locale ?? "en",+ timeZone: session?.user.timeZone,+ });++ return (+ <div className="space-y-4">+ <p className="text-sm">+ <Trans+ i18nKey="pendingDeletionNotice"+ defaults="Your account and data will be permanently deleted on {deletionDate}."+ values={{ deletionDate }}+ />+ </p>+ <CancelAccountDeletionButton />+ </div>+ );+}diff --git a/apps/web/src/app/[locale]/(space)/settings/profile/profile-email-address.tsx b/apps/web/src/app/[locale]/(space)/settings/profile/components/profile-email-address.tsxsimilarity index 96%rename from apps/web/src/app/[locale]/(space)/settings/profile/profile-email-address.tsxrename to apps/web/src/app/[locale]/(space)/settings/profile/components/profile-email-address.tsxindex 62c13358f..7f20c7cd9 100644--- a/apps/web/src/app/[locale]/(space)/settings/profile/profile-email-address.tsx+++ b/apps/web/src/app/[locale]/(space)/settings/profile/components/profile-email-address.tsx@@ -18,7 +18,6 @@ import React from "react";import { useForm } from "react-hook-form";import * as z from "zod";import { InputOTP } from "@/components/input-otp";-import { useAuthedUser } from "@/features/user/client";import { Trans, useTranslation } from "@/i18n/client";import { authClient } from "@/lib/auth-client";@@ -150,8 +149,7 @@ function VerifyEmailChangeForm({);}-export const ProfileEmailAddress = () => {- const user = useAuthedUser();+export const ProfileEmailAddress = ({ email }: { email: string }) => {const router = useRouter();const { t } = useTranslation();@@ -160,7 +158,7 @@ export const ProfileEmailAddress = () => {const form = useForm({defaultValues: {- email: user.email,+ email,},resolver: zodResolver(emailChangeFormData),});@@ -173,7 +171,7 @@ export const ProfileEmailAddress = () => {newEmail={pendingEmail}onCancel={() => {setPendingEmail(null);- reset({ email: user.email });+ reset({ email });}}onSuccess={() => {reset({ email: pendingEmail });@@ -192,7 +190,7 @@ export const ProfileEmailAddress = () => {<Form {...form}><formonSubmit={handleSubmit(async (data) => {- if (data.email === user.email) {+ if (data.email === email) {return;}diff --git a/apps/web/src/app/[locale]/(space)/settings/profile/profile-picture.tsx b/apps/web/src/app/[locale]/(space)/settings/profile/components/profile-picture.tsxsimilarity index 100%rename from apps/web/src/app/[locale]/(space)/settings/profile/profile-picture.tsxrename to apps/web/src/app/[locale]/(space)/settings/profile/components/profile-picture.tsxdiff --git a/apps/web/src/app/[locale]/(space)/settings/profile/profile-settings.tsx b/apps/web/src/app/[locale]/(space)/settings/profile/components/profile-settings.tsxsimilarity index 88%rename from apps/web/src/app/[locale]/(space)/settings/profile/profile-settings.tsxrename to apps/web/src/app/[locale]/(space)/settings/profile/components/profile-settings.tsxindex 90dd93cb8..fbf49f8f0 100644--- a/apps/web/src/app/[locale]/(space)/settings/profile/profile-settings.tsx+++ b/apps/web/src/app/[locale]/(space)/settings/profile/components/profile-settings.tsx@@ -14,7 +14,6 @@ import { useForm } from "react-hook-form";import * as z from "zod";import { updateUserNameAction } from "@/features/user/actions";-import { useAuthedUser } from "@/features/user/client";import { Trans } from "@/i18n/client";import { useSafeAction } from "@/lib/safe-action/client";@@ -24,13 +23,17 @@ const profileSettingsFormData = z.object({name: z.string().min(1).max(100),});-export const ProfileSettings = () => {- const user = useAuthedUser();-+export const ProfileSettings = ({+ name,+ image,+}: {+ name: string;+ image?: string;+}) => {const updateUserName = useSafeAction(updateUserNameAction);const form = useForm({defaultValues: {- name: user.name,+ name,},resolver: zodResolver(profileSettingsFormData),});@@ -41,14 +44,14 @@ export const ProfileSettings = () => {<Form {...form}><formonSubmit={handleSubmit(async (data) => {- if (data.name !== user.name) {+ if (data.name !== name) {await updateUserName.executeAsync({ name: data.name });}reset(data);})}><div className="flex flex-col gap-y-4">- <ProfilePicture name={user.name} image={user.image} />+ <ProfilePicture name={name} image={image} /><FormFieldcontrol={control}name="name"diff --git a/apps/web/src/app/[locale]/(space)/settings/profile/delete-account-dialog.tsx b/apps/web/src/app/[locale]/(space)/settings/profile/delete-account-dialog.tsxdeleted file mode 100644index 2ef1962ad..000000000--- a/apps/web/src/app/[locale]/(space)/settings/profile/delete-account-dialog.tsx+++ /dev/null@@ -1,108 +0,0 @@-"use client";-import { Button } from "@rallly/ui/button";-import type { DialogProps } from "@rallly/ui/dialog";-import {- Dialog,- DialogClose,- DialogContent,- DialogDescription,- DialogFooter,- DialogHeader,- DialogTitle,-} from "@rallly/ui/dialog";-import { Form, FormField, FormItem, FormMessage } from "@rallly/ui/form";-import { Input } from "@rallly/ui/input";-import { useForm } from "react-hook-form";--import { useAuthedUser } from "@/features/user/client";-import { Trans, useTranslation } from "@/i18n/client";-import { trpc } from "@/trpc/client";--export function DeleteAccountDialog({ children, ...rest }: DialogProps & {}) {- const user = useAuthedUser();- const form = useForm<{ email: string }>({- defaultValues: {- email: "",- },- });-- const deleteUser = trpc.user.deleteMe.useMutation();- const { t } = useTranslation();-- return (- <Form {...form}>- <Dialog {...rest}>- {children}- <DialogContent>- <form- method="POST"- action="/auth/logout"- onSubmit={form.handleSubmit(async () => {- await deleteUser.mutateAsync();- })}- >- <DialogHeader>- <DialogTitle>- <Trans- i18nKey="deleteAccountDialogTitle"- defaults="Delete Account"- />- </DialogTitle>- <DialogDescription>- <Trans- i18nKey="deleteAccountDialogDescription"- defaults="Are you sure you want to delete your account?"- />- </DialogDescription>- </DialogHeader>- <div className="space-y-4 py-4">- <p className="text-sm">- <Trans- i18nKey="deleteAccountInstruction"- defaults="Please confirm your email address to delete your account"- />- </p>- <FormField- control={form.control}- name="email"- rules={{- validate: (value) => {- if (value !== user.email) {- return t("emailMismatch", {- defaultValue: "Email does not match the account email",- });- }- return true;- },- }}- render={({ field }) => (- <FormItem>- <Input- autoComplete="off"- data-1p-ignore- placeholder={user.email}- {...field}- />- <FormMessage />- </FormItem>- )}- />- </div>- <DialogFooter>- <DialogClose render={<Button />}>- <Trans i18nKey="cancel" defaults="Cancel" />- </DialogClose>- <Button- type="submit"- loading={deleteUser.isPending}- variant="destructive"- >- <Trans i18nKey="deleteAccount" defaults="Delete Account" />- </Button>- </DialogFooter>- </form>- </DialogContent>- </Dialog>- </Form>- );-}diff --git a/apps/web/src/app/[locale]/(space)/settings/profile/page.tsx b/apps/web/src/app/[locale]/(space)/settings/profile/page.tsxindex b2213f1a6..1b3a915c0 100644--- a/apps/web/src/app/[locale]/(space)/settings/profile/page.tsx+++ b/apps/web/src/app/[locale]/(space)/settings/profile/page.tsx@@ -1,11 +1,117 @@import type { Metadata } from "next";+import { redirect } from "next/navigation";+import { Suspense } from "react";import type { Params } from "@/app/[locale]/types";+import {+ PageSection,+ PageSectionContent,+ PageSectionDescription,+ PageSectionGroup,+ PageSectionHeader,+ PageSectionTitle,+} from "@/components/page-layout";+import {+ SettingsPage,+ SettingsPageContent,+ SettingsPageDescription,+ SettingsPageHeader,+ SettingsPageTitle,+} from "@/components/settings-layout";+import { getCurrentUser } from "@/features/user/data";+import { Trans } from "@/i18n/client";import { getTranslation } from "@/i18n/server";-import { ProfilePage } from "./profile-page";+import { getPathname } from "@/lib/pathname";+import { buildSafeRedirectUrl } from "@/lib/utils/redirect";+import {+ AccountDeletionSummary,+ AccountDeletionSummarySkeleton,+} from "./components/account-deletion-summary";+import { DeleteAccountButton } from "./components/delete-account-button";+import { PendingDeletionNotice } from "./components/pending-deletion-notice";+import { ProfileEmailAddress } from "./components/profile-email-address";+import { ProfileSettings } from "./components/profile-settings";-export default function Page() {- return <ProfilePage />;+export default async function Page() {+ const user = await getCurrentUser();++ if (!user) {+ redirect(+ buildSafeRedirectUrl({+ destination: "/login",+ returnUrl: await getPathname(),+ }),+ );+ }++ return (+ <SettingsPage>+ <SettingsPageHeader>+ <SettingsPageTitle>+ <Trans i18nKey="profile" defaults="Profile" />+ </SettingsPageTitle>+ <SettingsPageDescription>+ <Trans+ i18nKey="profileDescription"+ defaults="Set your public profile information"+ />+ </SettingsPageDescription>+ </SettingsPageHeader>+ <SettingsPageContent>+ <PageSectionGroup>+ <PageSection variant="card">+ <PageSectionContent>+ <ProfileSettings name={user.name} image={user.image} />+ </PageSectionContent>+ </PageSection>++ <PageSection variant="card">+ <PageSectionHeader>+ <PageSectionTitle>+ <Trans i18nKey="profileEmailAddress" defaults="Email Address" />+ </PageSectionTitle>+ <PageSectionDescription>+ <Trans+ i18nKey="profileEmailAddressDescription"+ defaults="Your email address is used to log in to your account"+ />+ </PageSectionDescription>+ </PageSectionHeader>+ <PageSectionContent>+ <ProfileEmailAddress email={user.email} />+ </PageSectionContent>+ </PageSection>++ <PageSection variant="card">+ <PageSectionHeader>+ <PageSectionTitle>+ <Trans i18nKey="dangerZone" defaults="Danger Zone" />+ </PageSectionTitle>+ <PageSectionDescription>+ <Trans+ i18nKey="dangerZoneAccountDeletion"+ defaults="Delete your account and all data associated with it"+ />+ </PageSectionDescription>+ </PageSectionHeader>+ <PageSectionContent>+ {user.deletedAt ? (+ <PendingDeletionNotice deletedAt={user.deletedAt} />+ ) : (+ <DeleteAccountButton+ summary={+ <Suspense fallback={<AccountDeletionSummarySkeleton />}>+ <AccountDeletionSummary />+ </Suspense>+ }+ />+ )}+ </PageSectionContent>+ </PageSection>+ </PageSectionGroup>+ </SettingsPageContent>+ </SettingsPage>+ );}export async function generateMetadata(props: {diff --git a/apps/web/src/app/[locale]/(space)/settings/profile/profile-page.tsx b/apps/web/src/app/[locale]/(space)/settings/profile/profile-page.tsxdeleted file mode 100644index e28b8949f..000000000--- a/apps/web/src/app/[locale]/(space)/settings/profile/profile-page.tsx+++ /dev/null@@ -1,89 +0,0 @@-"use client";--import { Button } from "@rallly/ui/button";-import { DialogTrigger } from "@rallly/ui/dialog";--import {- PageSection,- PageSectionContent,- PageSectionDescription,- PageSectionGroup,- PageSectionHeader,- PageSectionTitle,-} from "@/components/page-layout";-import {- SettingsPage,- SettingsPageContent,- SettingsPageDescription,- SettingsPageHeader,- SettingsPageTitle,-} from "@/components/settings-layout";-import { Trans } from "@/i18n/client";-import { DeleteAccountDialog } from "./delete-account-dialog";-import { ProfileEmailAddress } from "./profile-email-address";-import { ProfileSettings } from "./profile-settings";--export function ProfilePage() {- return (- <SettingsPage>- <SettingsPageHeader>- <SettingsPageTitle>- <Trans i18nKey="profile" defaults="Profile" />- </SettingsPageTitle>- <SettingsPageDescription>- <Trans- i18nKey="profileDescription"- defaults="Set your public profile information"- />- </SettingsPageDescription>- </SettingsPageHeader>- <SettingsPageContent>- <PageSectionGroup>- <PageSection variant="card">- <PageSectionContent>- <ProfileSettings />- </PageSectionContent>- </PageSection>-- <PageSection variant="card">- <PageSectionHeader>- <PageSectionTitle>- <Trans i18nKey="profileEmailAddress" defaults="Email Address" />- </PageSectionTitle>- <PageSectionDescription>- <Trans- i18nKey="profileEmailAddressDescription"- defaults="Your email address is used to log in to your account"- />- </PageSectionDescription>- </PageSectionHeader>- <PageSectionContent>- <ProfileEmailAddress />- </PageSectionContent>- </PageSection>-- <PageSection variant="card">- <PageSectionHeader>- <PageSectionTitle>- <Trans i18nKey="dangerZone" defaults="Danger Zone" />- </PageSectionTitle>- <PageSectionDescription>- <Trans- i18nKey="dangerZoneAccount"- defaults="Delete your account permanently. This action cannot be undone."- />- </PageSectionDescription>- </PageSectionHeader>- <PageSectionContent>- <DeleteAccountDialog>- <DialogTrigger render={<Button className="text-destructive" />}>- <Trans i18nKey="deleteAccount" defaults="Delete Account" />- </DialogTrigger>- </DeleteAccountDialog>- </PageSectionContent>- </PageSection>- </PageSectionGroup>- </SettingsPageContent>- </SettingsPage>- );-}diff --git a/apps/web/src/app/[locale]/control-panel/users/actions.ts b/apps/web/src/app/[locale]/control-panel/users/actions.tsnew file mode 100644index 000000000..42ad282f7--- /dev/null+++ b/apps/web/src/app/[locale]/control-panel/users/actions.ts@@ -0,0 +1,56 @@+"use server";+import * as z from "zod";+import {+ cancelUserSubscriptions,+ deleteStripeCustomer,+} from "@/features/billing/mutations";+import { getUserDeletionDetails } from "@/features/user/data";+import { hardDeleteUser } from "@/features/user/mutations";+import { AppError } from "@/lib/errors/app-error";+import { deletePostHogPerson } from "@/lib/posthog";+import { adminActionClient } from "@/lib/safe-action/server";++// Route-private because deleting a user spans features: the app layer may+// import user and billing together, the user feature may not import billing.+export const deleteUserAction = adminActionClient+ .metadata({ actionName: "delete_user" })+ .inputSchema(+ z.object({+ userId: z.string(),+ }),+ )+ .action(async ({ parsedInput }) => {+ const userId = parsedInput.userId;++ const user = await getUserDeletionDetails(userId);++ if (!user) {+ throw new AppError({+ code: "NOT_FOUND",+ message: "User not found",+ });+ }++ if (user.hasActiveSubscription) {+ throw new AppError({+ code: "FORBIDDEN",+ message: "User has active subscriptions",+ });+ }++ // Same external-store cleanup as the account deletion reaper so Stripe+ // and PostHog records don't outlive the account.+ await cancelUserSubscriptions({ userId });++ if (user.customerId) {+ await deleteStripeCustomer({ customerId: user.customerId });+ }++ await deletePostHogPerson({ distinctId: userId });++ await hardDeleteUser({ userId, email: user.email });++ return {+ success: true,+ };+ });diff --git a/apps/web/src/app/[locale]/control-panel/users/dialogs/delete-user-dialog.tsx b/apps/web/src/app/[locale]/control-panel/users/dialogs/delete-user-dialog.tsxindex 36f33f794..1800e9412 100644--- a/apps/web/src/app/[locale]/control-panel/users/dialogs/delete-user-dialog.tsx+++ b/apps/web/src/app/[locale]/control-panel/users/dialogs/delete-user-dialog.tsx@@ -22,9 +22,9 @@ import {import { Input } from "@rallly/ui/input";import { useForm } from "react-hook-form";import * as z from "zod";-import { deleteUserAction } from "@/features/user/actions";import { Trans, useTranslation } from "@/i18n/client";import { useSafeAction } from "@/lib/safe-action/client";+import { deleteUserAction } from "../actions";const useSchema = (email: string) => {const { t } = useTranslation();diff --git a/apps/web/src/app/api/house-keeping/[...method]/route.ts b/apps/web/src/app/api/house-keeping/[...method]/route.tsindex 7512bc906..e452aaaad 100644--- a/apps/web/src/app/api/house-keeping/[...method]/route.ts+++ b/apps/web/src/app/api/house-keeping/[...method]/route.ts@@ -2,11 +2,23 @@ import { createLogger } from "@rallly/logger";import { Hono } from "hono";import { bearerAuth } from "hono/bearer-auth";import { handle } from "hono/vercel";+import {+ cancelUserSubscriptions,+ deleteStripeCustomer,+} from "@/features/billing/mutations";import {autoClosePolls,deleteInactivePolls,removeDeletedPolls,} from "@/features/poll/mutations";+import { findUsersScheduledForRemoval } from "@/features/user/account-deletion/data";+import { getAccountDeletionCutoff } from "@/features/user/account-deletion/utils";+import { hardDeleteUser } from "@/features/user/mutations";+import {+ deletePostHogPerson,+ flushPostHog,+ trackSystemEvent,+} from "@/lib/posthog";const logger = createLogger("api/house-keeping");@@ -77,4 +89,94 @@ app.get("/remove-deleted-polls", async (c) => {});});+// Each user's removal makes external API calls, so give the function room+// beyond the serverless default.+export const maxDuration = 300;++const REMOVE_DELETED_USERS_BATCH_SIZE = 50;+// Backlog beyond this spills to the next daily run instead of risking a+// function timeout mid-user.+const REMOVE_DELETED_USERS_MAX_PER_RUN = 500;++// Reaper for accounts whose scheduled deletion passed the recovery window.+// Composed here because it spans features: external stores go first — Stripe+// (defensive subscription cancel, then the customer object; invoices are+// lawfully retained by Stripe) and PostHog — so a failure there leaves the+// user row in place for the next run to retry.+async function removeDeletedUsers() {+ const cutoff = getAccountDeletionCutoff();+ const failedUserIds: string[] = [];+ let deletedUsers = 0;++ while (+ deletedUsers + failedUserIds.length <+ REMOVE_DELETED_USERS_MAX_PER_RUN+ ) {+ const users = await findUsersScheduledForRemoval({+ cutoff,+ excludeUserIds: failedUserIds,+ limit: REMOVE_DELETED_USERS_BATCH_SIZE,+ });++ if (users.length === 0) {+ break;+ }++ for (const user of users) {+ try {+ await cancelUserSubscriptions({ userId: user.id });++ if (user.customerId) {+ await deleteStripeCustomer({ customerId: user.customerId });+ }++ await deletePostHogPerson({ distinctId: user.id });++ await hardDeleteUser({ userId: user.id, email: user.email });++ // Personless by design — the person this event is about was just+ // erased, so it must not create or attach to a profile.+ trackSystemEvent({ event: "account_deletion_complete" });++ deletedUsers++;+ } catch (error) {+ logger.error(+ { userId: user.id, error },+ "Failed to remove user scheduled for deletion",+ );+ failedUserIds.push(user.id);+ }+ }+ }++ if (deletedUsers + failedUserIds.length >= REMOVE_DELETED_USERS_MAX_PER_RUN) {+ logger.warn(+ { deletedUsers, failed: failedUserIds.length },+ "Reached the per-run cap for removing deleted users; remaining backlog spills to the next run",+ );+ }++ return deletedUsers;+}++app.get("/remove-deleted-users", async (c) => {+ const deletedUsers = await removeDeletedUsers();++ await flushPostHog();++ logger.info(+ { task: "remove-deleted-users", deletedUsers },+ "Removed users whose scheduled deletion passed the recovery window",+ );++ return c.json({+ success: true,+ summary: {+ deleted: {+ users: deletedUsers,+ },+ },+ });+});+export const GET = handle(app);diff --git a/apps/web/src/features/billing/actions.ts b/apps/web/src/features/billing/actions.tsindex 74de07487..137cc302c 100644--- a/apps/web/src/features/billing/actions.ts+++ b/apps/web/src/features/billing/actions.ts@@ -32,6 +32,16 @@ export const upgradeToProAction = authActionClient}),).action(async ({ ctx, parsedInput }) => {+ // The account stays fully usable during the deletion recovery window,+ // but starting a new subscription that the reaper would cancel is not+ // allowed. ctx.user is database state, not the session snapshot.+ if (ctx.user.deletedAt) {+ throw new AppError({+ code: "FORBIDDEN",+ message: "Cannot upgrade an account that is scheduled for deletion",+ });+ }+const space = await getActiveSpaceForUser(ctx.user.id);if (!space) {diff --git a/apps/web/src/features/billing/mutations.ts b/apps/web/src/features/billing/mutations.tsindex 26b576bb7..8f70b0177 100644--- a/apps/web/src/features/billing/mutations.ts+++ b/apps/web/src/features/billing/mutations.ts@@ -6,7 +6,9 @@ import {SEAT_UPDATE_PORTAL_PURPOSE,SEAT_UPDATE_PORTAL_VERSION,} from "@rallly/billing/lib/portal";+import { prisma } from "@rallly/database";import { absoluteUrl } from "@rallly/utils/absolute-url";+import { isBillingEnabled } from "@/features/billing/constants";import { getStripe } from "@/features/billing/service";export async function createStripePortalSession({@@ -155,3 +157,117 @@ export async function createStripeSubscriptionUpdateConfirmation({return portalSession.url;}++function isStripeResourceMissingError(error: unknown) {+ return (+ typeof error === "object" &&+ error !== null &&+ "code" in error &&+ (error as { code?: unknown }).code === "resource_missing"+ );+}++// Scheduling an account deletion must guarantee no further charges without+// destroying anything: cancel_at_period_end stops the renewal while keeping+// the paid-for time, and is reversible if the deletion is cancelled.+// Database state syncs via the customer.subscription.updated webhook.+async function setUserSubscriptionRenewals({+ userId,+ cancelAtPeriodEnd,+}: {+ userId: string;+ cancelAtPeriodEnd: boolean;+}) {+ if (!isBillingEnabled) {+ return 0;+ }++ const subscriptions = await prisma.subscription.findMany({+ where: { userId, active: true },+ select: { id: true },+ });++ if (subscriptions.length === 0) {+ return 0;+ }++ const stripe = getStripe();++ for (const subscription of subscriptions) {+ try {+ await stripe.subscriptions.update(subscription.id, {+ cancel_at_period_end: cancelAtPeriodEnd,+ });+ } catch (error) {+ if (!isStripeResourceMissingError(error)) {+ throw error;+ }+ }+ }++ return subscriptions.length;+}++export async function stopUserSubscriptionRenewals({+ userId,+}: {+ userId: string;+}) {+ return setUserSubscriptionRenewals({ userId, cancelAtPeriodEnd: true });+}++export async function resumeUserSubscriptionRenewals({+ userId,+}: {+ userId: string;+}) {+ return setUserSubscriptionRenewals({ userId, cancelAtPeriodEnd: false });+}++// Database state (subscription row, space tier) is synced by the+// customer.subscription.deleted webhook, the same path portal+// cancellations take.+export async function cancelUserSubscriptions({ userId }: { userId: string }) {+ if (!isBillingEnabled) {+ return;+ }++ const subscriptions = await prisma.subscription.findMany({+ where: { userId, active: true },+ select: { id: true },+ });++ if (subscriptions.length === 0) {+ return;+ }++ const stripe = getStripe();++ for (const subscription of subscriptions) {+ try {+ await stripe.subscriptions.cancel(subscription.id);+ } catch (error) {+ if (!isStripeResourceMissingError(error)) {+ throw error;+ }+ }+ }+}++export async function deleteStripeCustomer({+ customerId,+}: {+ customerId: string;+}) {+ if (!isBillingEnabled) {+ return;+ }++ try {+ await getStripe().customers.del(customerId);+ } catch (error) {+ if (!isStripeResourceMissingError(error)) {+ throw error;+ }+ }+}diff --git a/apps/web/src/features/user/ability.ts b/apps/web/src/features/user/ability.tsindex 24b60d50e..998a06a38 100644--- a/apps/web/src/features/user/ability.ts+++ b/apps/web/src/features/user/ability.ts@@ -45,22 +45,14 @@ function defineAbilityForUser(builder: AbilityBuilder<UserAbility>,user: UserAbilityContext,) {- const { can, cannot } = builder;+ const { can } = builder;// Can update their own email and namecan("update", "User", ["email", "name"], { id: user.id });- // Can delete their own account+ // Can delete their own account. An active subscription no longer blocks+ // deletion — scheduling a deletion stops the renewal instead.can("delete", "User", { id: user.id });- // Cannot delete user if they have active subscriptions- cannot("delete", "User", {- subscriptions: {- some: {- active: true,- },- },- });-// Can read their own spacescan("read", "Space", { ownerId: user.id });diff --git a/apps/web/src/features/user/account-deletion/constants.ts b/apps/web/src/features/user/account-deletion/constants.tsnew file mode 100644index 000000000..a1acffdc0--- /dev/null+++ b/apps/web/src/features/user/account-deletion/constants.ts@@ -0,0 +1 @@+export const ACCOUNT_DELETION_GRACE_DAYS = 7;diff --git a/apps/web/src/features/user/account-deletion/data.ts b/apps/web/src/features/user/account-deletion/data.tsnew file mode 100644index 000000000..a3d18b925--- /dev/null+++ b/apps/web/src/features/user/account-deletion/data.ts@@ -0,0 +1,52 @@+import "server-only";++import { prisma } from "@rallly/database";+import { upcomingScheduledEventWhere } from "@/features/scheduled-event/utils";++export async function findUsersScheduledForRemoval({+ cutoff,+ excludeUserIds,+ limit,+}: {+ cutoff: Date;+ excludeUserIds: string[];+ limit: number;+}) {+ return prisma.user.findMany({+ where: {+ deletedAt: { lt: cutoff },+ id: { notIn: excludeUserIds },+ },+ select: { id: true, email: true, customerId: true },+ take: limit,+ });+}++// Counts are limited to columns with a userId index. Vote and comment+// counts would scan participants/comments on an unindexed user_id, so the+// dialog mentions those without numbers.+export async function getAccountDeletionSummary({+ userId,+ timeZone,+}: {+ userId: string;+ timeZone: string;+}) {+ const [activePollCount, upcomingEventCount, activeSubscriptionCount] =+ await Promise.all([+ prisma.poll.count({ where: { userId, deleted: false, status: "open" } }),+ prisma.scheduledEvent.count({+ where: {+ userId,+ ...upcomingScheduledEventWhere({ now: new Date(), timeZone }),+ },+ }),+ prisma.subscription.count({ where: { userId, active: true } }),+ ]);++ return {+ activePollCount,+ upcomingEventCount,+ hasActiveSubscription: activeSubscriptionCount > 0,+ };+}diff --git a/apps/web/src/features/user/account-deletion/mutations.ts b/apps/web/src/features/user/account-deletion/mutations.tsnew file mode 100644index 000000000..dd8f3de2b--- /dev/null+++ b/apps/web/src/features/user/account-deletion/mutations.ts@@ -0,0 +1,23 @@+import "server-only";++import { prisma } from "@rallly/database";++// deletedAt is not a Better-Auth field and is never part of the session+// snapshot, so a plain Prisma write is safe here — no internalAdapter needed.+export async function scheduleAccountDeletion({ userId }: { userId: string }) {+ const deletedAt = new Date();++ await prisma.user.update({+ where: { id: userId },+ data: { deletedAt },+ });++ return deletedAt;+}++export async function cancelAccountDeletion({ userId }: { userId: string }) {+ await prisma.user.update({+ where: { id: userId },+ data: { deletedAt: null },+ });+}diff --git a/apps/web/src/features/user/account-deletion/utils.test.ts b/apps/web/src/features/user/account-deletion/utils.test.tsnew file mode 100644index 000000000..156ef238a--- /dev/null+++ b/apps/web/src/features/user/account-deletion/utils.test.ts@@ -0,0 +1,20 @@+import { describe, expect, it } from "vitest";+import { getAccountDeletionCutoff, getScheduledDeletionDate } from "./utils";++describe("getScheduledDeletionDate", () => {+ it("returns the date 7 days after deletion was requested", () => {+ const deletedAt = new Date("2026-07-19T10:00:00Z");+ expect(getScheduledDeletionDate(deletedAt)).toEqual(+ new Date("2026-07-26T10:00:00Z"),+ );+ });+});++describe("getAccountDeletionCutoff", () => {+ it("returns the instant 7 days before now", () => {+ const now = new Date("2026-07-26T10:00:00Z");+ expect(getAccountDeletionCutoff(now)).toEqual(+ new Date("2026-07-19T10:00:00Z"),+ );+ });+});diff --git a/apps/web/src/features/user/account-deletion/utils.ts b/apps/web/src/features/user/account-deletion/utils.tsnew file mode 100644index 000000000..3a5cd1265--- /dev/null+++ b/apps/web/src/features/user/account-deletion/utils.ts@@ -0,0 +1,11 @@+import { ACCOUNT_DELETION_GRACE_DAYS } from "./constants";++const GRACE_PERIOD_MS = ACCOUNT_DELETION_GRACE_DAYS * 24 * 60 * 60 * 1000;++export function getScheduledDeletionDate(deletedAt: Date) {+ return new Date(deletedAt.getTime() + GRACE_PERIOD_MS);+}++export function getAccountDeletionCutoff(now: Date = new Date()) {+ return new Date(now.getTime() - GRACE_PERIOD_MS);+}diff --git a/apps/web/src/features/user/actions.ts b/apps/web/src/features/user/actions.tsindex 8eaf74fda..8a79b72ae 100644--- a/apps/web/src/features/user/actions.ts+++ b/apps/web/src/features/user/actions.ts@@ -253,50 +253,3 @@ export const unbanUserAction = adminActionClientawait unbanUser({ userId });});--export const deleteUserAction = adminActionClient- .metadata({ actionName: "delete_user" })- .inputSchema(- z.object({- userId: z.string(),- }),- )- .action(async ({ parsedInput }) => {- const userId = parsedInput.userId;-- const user = await prisma.user.findUnique({- where: { id: userId },- include: {- subscriptions: {- select: {- active: true,- },- },- },- });-- if (!user) {- throw new AppError({- code: "NOT_FOUND",- message: "User not found",- });- }-- // Check if user has active subscriptions- if (user.subscriptions.some((subscription) => subscription.active)) {- throw new AppError({- code: "FORBIDDEN",- message: "User has active subscriptions",- });- }-- await prisma.user.delete({- where: {- id: userId,- },- });-- return {- success: true,- };- });diff --git a/apps/web/src/features/user/data.ts b/apps/web/src/features/user/data.tsindex 3b53eddf5..6919a17c2 100644--- a/apps/web/src/features/user/data.ts+++ b/apps/web/src/features/user/data.ts@@ -20,6 +20,7 @@ export const createUserDTO = (user: User): UserDTO => ({weekStart: user.weekStart ?? undefined,customerId: user.customerId ?? undefined,isGuest: user.isAnonymous,+ deletedAt: user.deletedAt ?? undefined,});/**@@ -64,6 +65,29 @@ export const getUserCount = async () => {});};+export async function getUserDeletionDetails(userId: string) {+ const user = await prisma.user.findUnique({+ where: { id: userId },+ select: {+ email: true,+ customerId: true,+ _count: {+ select: { subscriptions: { where: { active: true } } },+ },+ },+ });++ if (!user) {+ return null;+ }++ return {+ email: user.email,+ customerId: user.customerId,+ hasActiveSubscription: user._count.subscriptions > 0,+ };+}+export const getUserHasPassword = async (userId: string) => {const account = await prisma.account.findFirst({where: {diff --git a/apps/web/src/features/user/mutations.ts b/apps/web/src/features/user/mutations.tsindex 71f995e84..5ec3c75ed 100644--- a/apps/web/src/features/user/mutations.ts+++ b/apps/web/src/features/user/mutations.ts@@ -3,6 +3,7 @@ import "server-only";import type { TimeFormat } from "@rallly/database";import { prisma } from "@rallly/database";import { authLib } from "@/lib/auth";+import { deleteImageFromS3 } from "@/lib/storage/image-upload";export async function createUser({name,@@ -117,6 +118,44 @@ export async function unbanUser({ userId }: { userId: string }) {});}+// Sessions are revoked through Better-Auth's internal adapter for the same+// reason as bans: with secondary storage they live in Redis, and only+// Better-Auth's own APIs delete those keys.+export async function hardDeleteUser({+ userId,+ email,+}: {+ userId: string;+ email: string;+}) {+ const { internalAdapter } = await authLib.$context;++ await internalAdapter.deleteSessions(userId);++ // The avatar lives in object storage, outside the cascade. External URLs+ // (OAuth provider avatars) are not ours to delete.+ const user = await prisma.user.findUnique({+ where: { id: userId },+ select: { image: true },+ });++ if (user?.image && !user.image.startsWith("https://")) {+ await deleteImageFromS3(user.image);+ }++ // Cascades cover data the user owns, but their personal data also lives+ // where they took part in other users' content: participant rows carry+ // name/email (votes cascade off them, matching the promise in the delete+ // dialog) and event invites carry invitee name/email. Both relations are+ // SetNull, so the rows would otherwise outlive the account.+ await prisma.participant.deleteMany({ where: { userId } });+ await prisma.scheduledEventInvite.deleteMany({+ where: { OR: [{ inviteeId: userId }, { inviteeEmail: email }] },+ });++ await prisma.user.delete({ where: { id: userId } });+}+export async function setActiveSpace({userId,spaceId,diff --git a/apps/web/src/features/user/schema.ts b/apps/web/src/features/user/schema.tsindex 88e2a7c9e..54d22befa 100644--- a/apps/web/src/features/user/schema.ts+++ b/apps/web/src/features/user/schema.ts@@ -18,4 +18,7 @@ export type UserDTO = {locale?: string;weekStart?: number;customerId?: string;+ // Only populated on database-derived DTOs (createUserDTO); deletedAt is+ // deliberately not part of the session user object.+ deletedAt?: Date;};diff --git a/apps/web/src/lib/posthog.ts b/apps/web/src/lib/posthog.tsindex 324cdc851..cd14ebb5b 100644--- a/apps/web/src/lib/posthog.ts+++ b/apps/web/src/lib/posthog.ts@@ -101,6 +101,87 @@ export function identifyGroup(group: {});}+// System events report on flows where no person can stay attached — e.g.+// the account deletion reaper erases the very person its event is about —+// so they capture personless under a fixed server distinctId (same+// dummy-person-avoidance trick as group identify above). Never put+// user-identifying properties on these.+const SYSTEM_EVENT_DISTINCT_ID = "server_system_event";++export function trackSystemEvent(event: {+ event: string;+ properties?: Record<string, unknown>;+}) {+ posthog()?.capture({+ ...event,+ distinctId: SYSTEM_EVENT_DISTINCT_ID,+ properties: {+ ...event.properties,+ $process_person_profile: false,+ },+ });+}++/**+ * Flush buffered events before a short-lived invocation (cron) exits —+ * the client batches (flushAt/flushInterval), so a serverless function can+ * freeze before the buffer drains.+ */+export async function flushPostHog() {+ await posthog()?.flush();+}++/**+ * Erase a person from PostHog (profile plus their events) so analytics data+ * keyed to a userId does not outlive the account. PostHog is optional config+ * that can run in any deployment mode, so this guards on configuration+ * presence and no-ops when the personal API key or project id is missing.+ * Reads process.env directly (same pattern as features/billing/service.ts);+ * the personal API key needs the person:write scope.+ */+export async function deletePostHogPerson({+ distinctId,+}: {+ distinctId: string;+}) {+ const personalApiKey = process.env.POSTHOG_PERSONAL_API_KEY;+ const projectId = process.env.POSTHOG_PROJECT_ID;++ if (!personalApiKey || !projectId) {+ return;+ }++ const apiHost = process.env.POSTHOG_API_HOST ?? "https://us.posthog.com";+ const headers = { Authorization: `Bearer ${personalApiKey}` };++ const lookupRes = await fetch(+ `${apiHost}/api/projects/${projectId}/persons/?distinct_id=${encodeURIComponent(distinctId)}`,+ { headers, signal: AbortSignal.timeout(10_000) },+ );++ if (!lookupRes.ok) {+ throw new Error(`PostHog person lookup failed: ${lookupRes.status}`);+ }++ const { results } = (await lookupRes.json()) as {+ results?: Array<{ id: string | number }>;+ };+ const person = results?.[0];++ if (!person) {+ return;+ }++ const deleteRes = await fetch(+ `${apiHost}/api/projects/${projectId}/persons/${person.id}/?delete_events=true`,+ { method: "DELETE", headers, signal: AbortSignal.timeout(10_000) },+ );++ if (!deleteRes.ok && deleteRes.status !== 404) {+ throw new Error(`PostHog person deletion failed: ${deleteRes.status}`);+ }+}+export function withPostHog(handler: (req: NextRequest) => Promise<Response>,): (req: NextRequest) => Promise<Response> {diff --git a/apps/web/src/trpc/routers/user.ts b/apps/web/src/trpc/routers/user.tsindex 6dcfd6a20..73879146f 100644--- a/apps/web/src/trpc/routers/user.ts+++ b/apps/web/src/trpc/routers/user.ts@@ -1,56 +1,12 @@-import { subject } from "@casl/ability";import { prisma } from "@rallly/database";-import { TRPCError } from "@trpc/server";import * as z from "zod";import { defaultNotificationPreferences } from "@/features/notifications/constants";import { getNotificationPreferences } from "@/features/notifications/data";import { activityEventTypes } from "@/features/notifications/schema";-import { defineAbilityFor } from "@/features/user/ability";import { track } from "@/lib/posthog";import { privateProcedure, router } from "../trpc";export const user = router({- deleteMe: privateProcedure.mutation(async ({ ctx }) => {- const userId = ctx.user.id;-- const user = await prisma.user.findUnique({- where: { id: userId },- include: {- subscriptions: {- select: {- active: true,- },- },- },- });-- if (!user) {- throw new TRPCError({- code: "NOT_FOUND",- message: "User not found",- });- }-- const ability = defineAbilityFor(ctx.user);-- if (ability.cannot("delete", subject("User", user))) {- throw new TRPCError({- code: "FORBIDDEN",- message: "You are not authorized to delete this user",- });- }-- if (user.subscriptions.some((subscription) => subscription.active)) {- throw new TRPCError({- code: "FORBIDDEN",- message: "User has active subscriptions",- });- }-- await prisma.user.delete({- where: { id: userId },- });- }),getNotificationPreferences: privateProcedure.query(async ({ ctx }) => {return getNotificationPreferences(ctx.user.id);}),diff --git a/apps/web/vercel.json b/apps/web/vercel.jsonindex e9a0fcbf1..3003917fb 100644--- a/apps/web/vercel.json+++ b/apps/web/vercel.json@@ -18,6 +18,10 @@{"path": "/api/house-keeping/remove-deleted-polls","schedule": "30 6 * * *"+ },+ {+ "path": "/api/house-keeping/remove-deleted-users",+ "schedule": "0 7 * * *"}]}diff --git a/packages/database/prisma/migrations/20260719000000_add_user_deleted_at/migration.sql b/packages/database/prisma/migrations/20260719000000_add_user_deleted_at/migration.sqlnew file mode 100644index 000000000..037830331--- /dev/null+++ b/packages/database/prisma/migrations/20260719000000_add_user_deleted_at/migration.sql@@ -0,0 +1,5 @@+-- AlterTable+ALTER TABLE "users" ADD COLUMN "deleted_at" TIMESTAMP(3);++-- CreateIndex+CREATE INDEX "users_deleted_at_idx" ON "users"("deleted_at");diff --git a/packages/database/prisma/models/user.prisma b/packages/database/prisma/models/user.prismaindex 8aca8ee20..cc4d2e5f7 100644--- a/packages/database/prisma/models/user.prisma+++ b/packages/database/prisma/models/user.prisma@@ -57,6 +57,7 @@ model User {lastLoginMethod String? @map("last_login_method")isAnonymous Boolean @default(false) @map("anonymous")lastSeenAt DateTime @default(now()) @map("last_seen_at")+ deletedAt DateTime? @map("deleted_at")comments Comment[]polls Poll[]@@ -85,6 +86,7 @@ model User {sessions Session[]impersonatedSessions Session[] @relation("ImpersonatedSessions")+ @@index([deletedAt])@@map("users")}diff --git a/packages/emails/locales/en/emails.json b/packages/emails/locales/en/emails.jsonindex 5f1be0935..467694872 100644--- a/packages/emails/locales/en/emails.json+++ b/packages/emails/locales/en/emails.json@@ -1,4 +1,11 @@{+ "accountDeletionScheduled_button": "Manage Account",+ "accountDeletionScheduled_cancel": "If you change your mind, you can cancel the deletion from your <a>account settings</a> before then.",+ "accountDeletionScheduled_footer": "You're receiving this email because a request was made to delete an account on <domain />. If this wasn't you, sign in and cancel the deletion before then, or contact <a>{supportEmail}</a>.",+ "accountDeletionScheduled_heading": "Your account is scheduled for deletion",+ "accountDeletionScheduled_preview": "Your account will be deleted on {date}",+ "accountDeletionScheduled_subject": "Your account is scheduled for deletion",+ "accountDeletionScheduled_text": "Your {appName} account is scheduled for deletion on {date}. Your polls, events, votes, and comments will be permanently deleted.","allDay": "All day","changeEmail_codeValid": "This code is valid for 15 minutes","changeEmail_content2": "You're receiving this email because a request was made to change the email address of an account on <domain />. If this wasn't you contact <a>{supportEmail}</a>.",diff --git a/packages/emails/src/templates/account-deletion-scheduled.tsx b/packages/emails/src/templates/account-deletion-scheduled.tsxnew file mode 100644index 000000000..b65aad620--- /dev/null+++ b/packages/emails/src/templates/account-deletion-scheduled.tsx@@ -0,0 +1,149 @@+import { Head, Hr, Html, Img, Preview } from "@react-email/components";+import { Trans } from "react-i18next/TransWithoutContext";++import { resolveChrome } from "../chrome";+import { PoweredBy } from "../components/powered-by";+import { previewChrome } from "../components/preview-chrome";+import {+ Body,+ Button,+ Container,+ Heading,+ Link,+ Text,+} from "../components/styled-components";+import { createEmailI18n } from "../i18n";+import type { SendArgs } from "../send";+import { sendRenderedEmail } from "../send";+import type { EmailChrome } from "../types";++type AccountDeletionScheduledEmailProps = {+ locale?: string;+ chrome: EmailChrome;+ /** Preformatted, localized date (the caller owns date formatting). */+ deletionDate: string;+};++async function AccountDeletionScheduledEmail({+ deletionDate,+ locale = "en",+ chrome,+}: AccountDeletionScheduledEmailProps) {+ const { t, i18n } = await createEmailI18n(locale);+ return (+ <Html>+ <Head />+ <Preview>+ {t("accountDeletionScheduled_preview", {+ defaultValue: "Your account will be deleted on {date}",+ date: deletionDate,+ })}+ </Preview>+ <Body>+ <Container>+ <Img+ src={chrome.logoUrl}+ height="42"+ style={{ marginBottom: 32, borderRadius: 6 }}+ alt={chrome.appName}+ />+ <Heading>+ {t("accountDeletionScheduled_heading", {+ defaultValue: "Your account is scheduled for deletion",+ })}+ </Heading>+ <Text>+ {t("accountDeletionScheduled_text", {+ defaultValue:+ "Your {appName} account is scheduled for deletion on {date}. Your polls, events, votes, and comments will be permanently deleted.",+ appName: chrome.appName,+ date: deletionDate,+ })}+ </Text>+ <Text>+ <Trans+ t={t}+ i18n={i18n}+ ns="emails"+ i18nKey="accountDeletionScheduled_cancel"+ defaults="If you change your mind, you can cancel the deletion from your <a>account settings</a> before then."+ components={{+ a: (+ <Link+ color={chrome.primaryColor}+ href={`${chrome.baseUrl}/settings/profile`}+ />+ ),+ }}+ />+ </Text>+ <Button+ href={`${chrome.baseUrl}/settings/profile`}+ color={chrome.primaryColor}+ >+ {t("accountDeletionScheduled_button", {+ defaultValue: "Manage Account",+ })}+ </Button>+ <Hr />+ <Text small light={true}>+ <Trans+ t={t}+ i18n={i18n}+ ns="emails"+ i18nKey="accountDeletionScheduled_footer"+ defaults="You're receiving this email because a request was made to delete an account on <domain />. If this wasn't you, sign in and cancel the deletion before then, or contact <a>{supportEmail}</a>."+ values={{ supportEmail: chrome.supportEmail }}+ components={{+ domain: (+ <Link color={chrome.primaryColor} href={chrome.baseUrl}>+ {chrome.domain}+ </Link>+ ),+ a: (+ <Link+ color={chrome.primaryColor}+ href={`mailto:${chrome.supportEmail}`}+ />+ ),+ }}+ />+ </Text>+ <PoweredBy chrome={chrome} locale={locale} />+ </Container>+ </Body>+ </Html>+ );+}++AccountDeletionScheduledEmail.PreviewProps = {+ deletionDate: "August 2, 2026",+ locale: "en",+ chrome: previewChrome,+} as AccountDeletionScheduledEmailProps;++export default AccountDeletionScheduledEmail;++export async function sendAccountDeletionScheduledEmail({+ to,+ locale = "en",+ branding,+ props,+ ...rest+}: SendArgs<AccountDeletionScheduledEmailProps>) {+ const { t } = await createEmailI18n(locale);+ await sendRenderedEmail({+ to,+ subject: t("accountDeletionScheduled_subject", {+ defaultValue: "Your account is scheduled for deletion",+ }),+ element: (+ <AccountDeletionScheduledEmail+ {...props}+ locale={locale}+ chrome={resolveChrome(branding)}+ />+ ),+ ...rest,+ });+}