Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions apps/sim/app/api/users/me/deletion/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { deleteAccountContract, getAccountDeletionPlanContract } from '@/lib/api/contracts'
import {
defineInternalJsonRoute,
internalOrchestrationErrorPolicy,
internalRateLimits,
internalSessionAuth,
} from '@/lib/api/server/routes'
import {
deleteAccountUseCase,
previewAccountDeletionUseCase,
} from '@/lib/users/application/delete-account'
import { userAccountOperations } from '@/lib/users/application/operations'

export const dynamic = 'force-dynamic'

export const GET = defineInternalJsonRoute({
contract: getAccountDeletionPlanContract,
auth: internalSessionAuth,
operation: userAccountOperations.previewDeletion,
rateLimit: internalRateLimits.none({ reason: 'Read-only preview of the caller’s own account' }),
errorPolicy: internalOrchestrationErrorPolicy,
mapInput: () => ({}),
useCase: previewAccountDeletionUseCase,
present: (plan) => ({ plan }),
})

/**
* `AccountDeletionBlockedError` classifies itself as a conflict, so the shared
* orchestration policy renders a refused deletion as a 409 carrying the first
* blocker's sentence. The dialog lists every blocker from the GET above; this
* message covers only the race where one appears between the two calls.
*/
export const POST = defineInternalJsonRoute({
contract: deleteAccountContract,
auth: internalSessionAuth,
operation: userAccountOperations.delete,
rateLimit: internalRateLimits.none({ reason: 'Guarded by the email confirmation it requires' }),
errorPolicy: internalOrchestrationErrorPolicy,
mapInput: ({ body }) => ({ confirmEmail: body.confirmEmail }),
useCase: deleteAccountUseCase,
present: () => ({ success: true as const }),
})
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
'use client'

import { useState } from 'react'
import { ChipConfirmModal, ChipModalError, ChipModalField } from '@sim/emcn'
import { createLogger } from '@sim/logger'
import { sleep } from '@sim/utils/helpers'
import { formatQuotedNameList, normalizeEmail } from '@sim/utils/string'
import { signOut } from '@/lib/auth/auth-client'
import { useAccountDeletionPlan, useDeleteAccount } from '@/hooks/queries/account-deletion'
import { clearUserData } from '@/stores'

const logger = createLogger('DeleteAccountModal')

/** Matches the naming used in the server's blocker sentences. */
const MAX_NAMES_LISTED = 3

/** How long the post-deletion sign-out and store cleanup may take before the redirect goes anyway. */
const SIGN_OUT_TIMEOUT_MS = 3000

interface DeleteAccountModalProps {
Comment thread
waleedlatif1 marked this conversation as resolved.
open: boolean
onOpenChange: (open: boolean) => void
/** The signed-in account's email, which must be retyped to confirm. */
email: string
}

function names(workspaces: { name: string }[]): string {
return formatQuotedNameList(
workspaces.map((workspace) => workspace.name),
MAX_NAMES_LISTED
)
}

/**
* Confirms and performs account deletion.
*
* The dialog is deliberately explicit rather than alarming: it names every
* workspace that goes, every workspace that changes hands, and — when the account
* cannot be deleted yet — exactly what has to happen first. Retyping the account's
* own email address is the only guard, which is the point: the decision should
* cost a deliberate action, not a hunt for the right button.
*/
export function DeleteAccountModal({ open, onOpenChange, email }: DeleteAccountModalProps) {
const [confirmEmail, setConfirmEmail] = useState('')
const { data: plan, isFetching: isPlanFetching, error: planError } = useAccountDeletionPlan(open)
const deleteAccount = useDeleteAccount()

const blockers = plan?.blockers ?? []
const toDelete = plan?.workspacesToDelete ?? []
const toTransfer = plan?.workspacesToTransfer ?? []
const isBlocked = blockers.length > 0
const isConfirmed = normalizeEmail(confirmEmail) === normalizeEmail(email)
const isPending = deleteAccount.isPending

const close = () => {
onOpenChange(false)
setConfirmEmail('')
deleteAccount.reset()
}

const handleDelete = () => {
deleteAccount.mutate(
{ confirmEmail },
{
onSuccess: async () => {
/**
* The session row is already gone, so signing out can only fail by
* telling us so — what matters is that its cookie is dropped and no
* cached client state survives the redirect. The race bounds that
* cleanup: the account is deleted either way, so a request left hanging
* must not strand the user on "Deleting..." forever. The redirect is a
* full document load, which discards anything the cleanup missed.
*/
await Promise.race([
Promise.allSettled([signOut(), clearUserData()]),
sleep(SIGN_OUT_TIMEOUT_MS),
])
window.location.href = '/login?fromLogout=true'
},
onError: (error) => {
logger.error('Account deletion failed', { error })
},
}
)
}

const errorMessage =
deleteAccount.error?.message ??
(planError ? 'Could not check whether this account can be deleted. Try again.' : null)

return (
<ChipConfirmModal
open={open}
onOpenChange={(next) => {
if (!next) close()
}}
size='md'
title='Delete account'
confirm={{
label: 'Delete account',
pendingLabel: 'Deleting...',
onClick: handleDelete,
pending: isPending,
disabled: isBlocked || isPlanFetching || !isConfirmed || !plan,
disabledTooltip: isBlocked
? 'Resolve the items above first'
: isConfirmed
? undefined
: 'Enter your account email to confirm',
}}
>
{isBlocked ? (
<div className='flex flex-col gap-2 px-2'>
<p className='text-[var(--text-primary)] text-sm'>Your account can’t be deleted yet:</p>
<ul className='flex list-disc flex-col gap-1 pl-4'>
{blockers.map((blocker) => (
<li key={blocker.code} className='text-[var(--text-secondary)] text-sm'>
{blocker.message}
</li>
))}
</ul>
</div>
) : (
<div className='flex flex-col gap-2 px-2'>
<p className='text-[var(--text-primary)] text-sm'>
This permanently deletes <span className='font-medium'>{email}</span> along with its
workflows, chats, files, knowledge bases and credentials.{' '}
<span className='text-[var(--text-error)]'>This cannot be undone.</span>
</p>
{toDelete.length > 0 && (
<p className='text-[var(--text-secondary)] text-sm'>
{toDelete.length === 1 ? 'The workspace ' : 'The workspaces '}
<span className='text-[var(--text-primary)]'>{names(toDelete)}</span> and everything
in {toDelete.length === 1 ? 'it' : 'them'} will be deleted.
</p>
)}
{toTransfer.length > 0 && (
<p className='text-[var(--text-secondary)] text-sm'>
Billing for <span className='text-[var(--text-primary)]'>{names(toTransfer)}</span>{' '}
moves to another admin. Nothing in {toTransfer.length === 1 ? 'it' : 'them'} changes.
</p>
)}
</div>
)}
{!isBlocked && (
<ChipModalField
type='email'
title='Confirm your email'
value={confirmEmail}
onChange={setConfirmEmail}
placeholder={email}
autoComplete='off'
disabled={isPending || isPlanFetching}
required
/>
)}
<ChipModalError>{errorMessage}</ChipModalError>
</ChipConfirmModal>
)
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import { useEffect, useRef, useState } from 'react'
import {
Button,
Chip,
ChipCombobox,
ChipModal,
ChipModalBody,
Expand All @@ -26,6 +27,7 @@ import { ANONYMOUS_USER_ID } from '@/lib/auth/constants'
import { isHosted } from '@/lib/core/config/env-flags'
import { getBrowserTimezone, getTimezoneOptions } from '@/lib/core/utils/timezone'
import { getBaseUrl } from '@/lib/core/utils/urls'
import { DeleteAccountModal } from '@/app/workspace/[workspaceId]/settings/components/general/components/delete-account-modal'
import type { SettingsAction } from '@/app/workspace/[workspaceId]/settings/components/settings-header/settings-header'
import { SettingsPanel } from '@/app/workspace/[workspaceId]/settings/components/settings-panel'
import { SettingsSection } from '@/app/workspace/[workspaceId]/settings/components/settings-section/settings-section'
Expand Down Expand Up @@ -93,6 +95,8 @@ export function General() {
const [showResetPasswordModal, setShowResetPasswordModal] = useState(false)
const resetPassword = useResetPassword()

const [showDeleteAccountModal, setShowDeleteAccountModal] = useState(false)

const [uploadError, setUploadError] = useState<string | null>(null)

const snapToGridValue = settings?.snapToGridSize ?? 0
Expand Down Expand Up @@ -572,6 +576,21 @@ export function General() {
</p>
</div>
</SettingsSection>

{!isAuthDisabled && (
<SettingsSection label='Account'>
<div className='flex flex-col gap-3'>
<div className='flex items-center justify-between'>
<Label>Delete account</Label>
<Chip onClick={() => setShowDeleteAccountModal(true)}>Delete</Chip>
</div>
<p className='text-[var(--text-muted)] text-small'>
Permanently deletes your account and everything only you can reach — workflows,
chats, files, knowledge bases and credentials. This cannot be undone.
</p>
</div>
</SettingsSection>
)}
</SettingsPanel>

<ChipModal
Expand Down Expand Up @@ -604,6 +623,12 @@ export function General() {
}}
/>
</ChipModal>

<DeleteAccountModal
open={showDeleteAccountModal}
onOpenChange={setShowDeleteAccountModal}
email={profile?.email || ''}
/>
</>
)
}
54 changes: 54 additions & 0 deletions apps/sim/hooks/queries/account-deletion.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import { useMutation, useQuery } from '@tanstack/react-query'
import { requestJson } from '@/lib/api/client/request'
import {
type AccountDeletionPlan,
type DeleteAccountBody,
deleteAccountContract,
getAccountDeletionPlanContract,
} from '@/lib/api/contracts/user'

export const accountDeletionKeys = {
all: ['account-deletion'] as const,
plan: () => [...accountDeletionKeys.all, 'plan'] as const,
}

/**
* Zero: the plan is a consent disclosure, so every dialog open must refetch — its
* blockers must reflect the account as it is right now, and a workspace that
* gained an admin a minute ago changes the answer.
*
* The dialog stays mounted while closed, so the previous open's plan is still in
* the cache and `isLoading` is false during that refetch. The dialog therefore
* holds its confirm on `isFetching`, not `isLoading`, until fresh data lands;
* `gcTime: 0` only evicts once the settings panel itself unmounts.
*/
export const ACCOUNT_DELETION_PLAN_STALE_TIME = 0

async function fetchAccountDeletionPlan(signal?: AbortSignal): Promise<AccountDeletionPlan> {
const data = await requestJson(getAccountDeletionPlanContract, { signal })
return data.plan
}

export function useAccountDeletionPlan(enabled: boolean) {
return useQuery({
queryKey: accountDeletionKeys.plan(),
queryFn: ({ signal }) => fetchAccountDeletionPlan(signal),
enabled,
staleTime: ACCOUNT_DELETION_PLAN_STALE_TIME,
gcTime: 0,
retry: false,
})
}

/**
* Succeeds exactly once per account: the session that authorized it is gone by
* the time the response lands, so there is no cache left to invalidate. The
* caller is responsible for clearing local state and sending the user to sign-in.
*/
export function useDeleteAccount() {
return useMutation({
mutationFn: async (body: DeleteAccountBody) => {
await requestJson(deleteAccountContract, { body })
},
})
}
72 changes: 72 additions & 0 deletions apps/sim/lib/api/contracts/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -413,3 +413,75 @@ export const subscriptionTransferContract = defineRouteContract({
}),
},
})

/** Every reason an account cannot be erased on its own, as rendered to its owner. */
export const accountDeletionBlockerSchema = z.object({
code: z.enum([
'paid_organization_owner',
'organization_member',
'active_subscription',
'shared_workspace',
'organization_workspace',
'data_drain_owner',
]),
/** A sentence naming both the obstacle and the way out. */
message: z.string(),
})

const accountDeletionResourceSchema = z.object({
id: z.string(),
name: z.string(),
})

export type AccountDeletionResource = z.output<typeof accountDeletionResourceSchema>

export const accountDeletionPlanSchema = z.object({
blockers: z.array(accountDeletionBlockerSchema),
/** Workspaces nobody else can reach — erased along with the account. */
workspacesToDelete: z.array(accountDeletionResourceSchema),
/**
* Workspaces the account only anchors — it pays for them or is recorded as
* their owner while holding no access to them. The anchor moves to an admin
* who does; nothing inside changes hands.
*/
workspacesToTransfer: z.array(accountDeletionResourceSchema),
})

export type AccountDeletionBlocker = z.output<typeof accountDeletionBlockerSchema>
export type AccountDeletionPlan = z.output<typeof accountDeletionPlanSchema>

export const getAccountDeletionPlanContract = defineRouteContract({
method: 'GET',
path: '/api/users/me/deletion',
response: {
mode: 'json',
schema: z.object({
plan: accountDeletionPlanSchema,
}),
},
})

export const deleteAccountBodySchema = z.object({
/**
* The account's own email address, retyped. Checked server-side against the
* session's account so a mis-wired client cannot delete anything else.
*/
confirmEmail: z
.string({ error: 'Confirm your email address to delete your account' })
.min(1, 'Confirm your email address to delete your account')
.max(320, 'Email address is too long'),
})

export type DeleteAccountBody = z.input<typeof deleteAccountBodySchema>

export const deleteAccountContract = defineRouteContract({
method: 'POST',
path: '/api/users/me/deletion',
body: deleteAccountBodySchema,
response: {
mode: 'json',
schema: z.object({
success: z.literal(true),
}),
},
})
Loading
Loading