From 16e2824b9c3dd6153e2f6bcd53af4db11026a413 Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Wed, 8 Jul 2026 12:55:29 -0700 Subject: [PATCH 01/89] Add iOS account deletion and legal links --- .../AuthCoordinator+AccountDeletion.swift | 64 +++++ .../Coordinator/AuthCoordinator.swift | 2 + .../AccountDeletionClientTests.swift | 55 +++++ .../MobileSettingsView.swift | 99 ++++++++ ios/cmux/Resources/Localizable.xcstrings | 221 ++++++++++++++++++ web/app/api/account/route.ts | 117 ++++++++++ web/tests/account-route.test.ts | 132 +++++++++++ 7 files changed, 690 insertions(+) create mode 100644 Packages/Shared/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AuthCoordinator+AccountDeletion.swift create mode 100644 Packages/Shared/CmuxAuthRuntime/Tests/CmuxAuthRuntimeTests/AccountDeletionClientTests.swift create mode 100644 web/app/api/account/route.ts create mode 100644 web/tests/account-route.test.ts diff --git a/Packages/Shared/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AuthCoordinator+AccountDeletion.swift b/Packages/Shared/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AuthCoordinator+AccountDeletion.swift new file mode 100644 index 000000000000..06f825a2834d --- /dev/null +++ b/Packages/Shared/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AuthCoordinator+AccountDeletion.swift @@ -0,0 +1,64 @@ +import Foundation + +enum AccountDeletionRequestError: Error, Equatable { + case invalidAPIBaseURL + case unauthorized + case rejected(statusCode: Int) + case invalidResponse +} + +typealias AccountDeletionRequestLoader = @Sendable (URLRequest) async throws -> (Data, URLResponse) + +struct AccountDeletionClient: Sendable { + private let apiBaseURL: String + private let load: AccountDeletionRequestLoader + + init( + apiBaseURL: String, + load: @escaping AccountDeletionRequestLoader = { request in + try await URLSession.shared.data(for: request) + } + ) { + self.apiBaseURL = apiBaseURL + self.load = load + } + + func deleteAccount(accessToken: String, refreshToken: String) async throws { + guard let baseURL = URL(string: apiBaseURL), + let url = URL(string: "/api/account", relativeTo: baseURL)?.absoluteURL + else { + throw AccountDeletionRequestError.invalidAPIBaseURL + } + + var request = URLRequest(url: url) + request.httpMethod = "DELETE" + request.setValue("Bearer \(accessToken)", forHTTPHeaderField: "Authorization") + request.setValue(refreshToken, forHTTPHeaderField: "X-Stack-Refresh-Token") + + let (_, response) = try await load(request) + guard let httpResponse = response as? HTTPURLResponse else { + throw AccountDeletionRequestError.invalidResponse + } + switch httpResponse.statusCode { + case 200..<300: + return + case 401: + throw AccountDeletionRequestError.unauthorized + default: + throw AccountDeletionRequestError.rejected(statusCode: httpResponse.statusCode) + } + } +} + +extension AuthCoordinator { + /// Permanently deletes the current Stack account through cmux's backend and + /// then clears the local session using the same local-first path as sign-out. + public func deleteAccount(teardownTimeout: Duration = .seconds(5)) async throws { + let tokens = try await currentTokens() + try await AccountDeletionClient(apiBaseURL: apiBaseURL).deleteAccount( + accessToken: tokens.accessToken, + refreshToken: tokens.refreshToken + ) + await signOut(teardownTimeout: teardownTimeout) + } +} diff --git a/Packages/Shared/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AuthCoordinator.swift b/Packages/Shared/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AuthCoordinator.swift index 5c17253d88f9..63ff770c4d9c 100644 --- a/Packages/Shared/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AuthCoordinator.swift +++ b/Packages/Shared/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AuthCoordinator.swift @@ -56,6 +56,8 @@ public final class AuthCoordinator { Self.resolveTeamID(selectedTeamID: selectedTeamID, teams: availableTeams) } + var apiBaseURL: String { config.apiBaseURL } + let client: any AuthClient let sessionCache: CMUXAuthSessionCache private let userCache: CMUXAuthIdentityStore diff --git a/Packages/Shared/CmuxAuthRuntime/Tests/CmuxAuthRuntimeTests/AccountDeletionClientTests.swift b/Packages/Shared/CmuxAuthRuntime/Tests/CmuxAuthRuntimeTests/AccountDeletionClientTests.swift new file mode 100644 index 000000000000..6b94bafe345b --- /dev/null +++ b/Packages/Shared/CmuxAuthRuntime/Tests/CmuxAuthRuntimeTests/AccountDeletionClientTests.swift @@ -0,0 +1,55 @@ +import Foundation +import Testing +@testable import CmuxAuthRuntime + +struct AccountDeletionClientTests { + @Test func deleteAccountSendsNativeAuthHeaders() async throws { + let recorder = RecordedAccountDeletionRequest() + let client = AccountDeletionClient(apiBaseURL: "https://cmux.test/base") { request in + await recorder.record(request) + return ( + Data(), + HTTPURLResponse( + url: request.url!, + statusCode: 204, + httpVersion: nil, + headerFields: nil + )! + ) + } + + try await client.deleteAccount(accessToken: "access-token", refreshToken: "refresh-token") + + let request = await recorder.request + #expect(request?.url?.absoluteString == "https://cmux.test/api/account") + #expect(request?.httpMethod == "DELETE") + #expect(request?.value(forHTTPHeaderField: "Authorization") == "Bearer access-token") + #expect(request?.value(forHTTPHeaderField: "X-Stack-Refresh-Token") == "refresh-token") + } + + @Test func deleteAccountMapsUnauthorizedResponse() async { + let client = AccountDeletionClient(apiBaseURL: "https://cmux.test") { request in + ( + Data(), + HTTPURLResponse( + url: request.url!, + statusCode: 401, + httpVersion: nil, + headerFields: nil + )! + ) + } + + await #expect(throws: AccountDeletionRequestError.unauthorized) { + try await client.deleteAccount(accessToken: "access-token", refreshToken: "refresh-token") + } + } +} + +actor RecordedAccountDeletionRequest { + private(set) var request: URLRequest? + + func record(_ request: URLRequest) { + self.request = request + } +} diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsView.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsView.swift index 6555d5c45c41..95d204b2759c 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsView.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsView.swift @@ -21,6 +21,7 @@ struct MobileSettingsView: View { var store: CMUXMobileShellStore? @Environment(\.dismiss) private var dismiss + @Environment(\.openURL) private var openURL @State private var showingShortcuts = false /// Mirrors ``MobilePushCoordinator/isEnabled`` so the toggle's label/icon /// update after the async enable/disable. The coordinator exposes @@ -30,6 +31,9 @@ struct MobileSettingsView: View { @State private var showingHostPicker = false @State private var showingOnboarding = false @State private var showingSetupHelp = false + @State private var showingDeleteAccountConfirmation = false + @State private var showingDeleteAccountFailure = false + @State private var deletingAccount = false #if DEBUG @State private var showingChatDemo = false @State private var showingTerminalDemo = false @@ -61,6 +65,19 @@ struct MobileSettingsView: View { } .accessibilityIdentifier("MobileSettingsSignOut") } + + Button(role: .destructive) { + showingDeleteAccountConfirmation = true + } label: { + Label( + deletingAccount + ? L10n.string("mobile.settings.deletingAccount", defaultValue: "Deleting Account...") + : L10n.string("mobile.settings.deleteAccount", defaultValue: "Delete Account"), + systemImage: deletingAccount ? "hourglass" : "trash" + ) + } + .disabled(deletingAccount) + .accessibilityIdentifier("MobileSettingsDeleteAccount") } header: { Text(L10n.string("mobile.settings.account", defaultValue: "Account")) } footer: { @@ -257,6 +274,27 @@ struct MobileSettingsView: View { .accessibilityIdentifier("MobileSettingsNotifications") } + Section(L10n.string("mobile.settings.legalSupport", defaultValue: "Legal & Support")) { + externalLinkRow( + title: L10n.string("mobile.settings.privacyPolicy", defaultValue: "Privacy Policy"), + systemImage: "hand.raised", + url: Self.privacyPolicyURL, + identifier: "MobileSettingsPrivacyPolicy" + ) + externalLinkRow( + title: L10n.string("mobile.settings.termsOfService", defaultValue: "Terms of Service"), + systemImage: "doc.text", + url: Self.termsOfServiceURL, + identifier: "MobileSettingsTermsOfService" + ) + externalLinkRow( + title: L10n.string("mobile.settings.support", defaultValue: "Support"), + systemImage: "envelope", + url: Self.supportURL, + identifier: "MobileSettingsSupport" + ) + } + Section(L10n.string("mobile.settings.about", defaultValue: "About")) { LabeledContent { Text(AppVersionInfo.current().displayString) @@ -315,10 +353,71 @@ struct MobileSettingsView: View { // mark "You are here". SetupHelpView(highlight: setupHelpHighlight) { showingSetupHelp = false } } + .alert( + L10n.string("mobile.settings.deleteAccountTitle", defaultValue: "Delete Account?"), + isPresented: $showingDeleteAccountConfirmation + ) { + Button(L10n.string("mobile.settings.deleteAccountCancel", defaultValue: "Cancel"), role: .cancel) {} + Button( + L10n.string("mobile.settings.deleteAccountConfirm", defaultValue: "Delete Account"), + role: .destructive + ) { + deleteAccount() + } + } message: { + Text(L10n.string( + "mobile.settings.deleteAccountMessage", + defaultValue: "This permanently deletes your cmux account and cmux data. You will be signed out on this device." + )) + } + .alert( + L10n.string("mobile.settings.deleteAccountFailedTitle", defaultValue: "Couldn't Delete Account"), + isPresented: $showingDeleteAccountFailure + ) { + Button(L10n.string("mobile.settings.deleteAccountFailureOK", defaultValue: "OK"), role: .cancel) {} + } message: { + Text(L10n.string( + "mobile.settings.deleteAccountFailedMessage", + defaultValue: "Try again later or contact support." + )) + } } .accessibilityIdentifier("MobileSettingsView") } + private static let privacyPolicyURL = URL(string: "https://cmux.com/privacy-policy")! + private static let termsOfServiceURL = URL(string: "https://cmux.com/terms-of-service")! + private static let supportURL = URL(string: "mailto:feedback@manaflow.com?subject=cmux%20iOS%20support")! + + private func externalLinkRow( + title: String, + systemImage: String, + url: URL, + identifier: String + ) -> some View { + Button { + openURL(url) + } label: { + Label(title, systemImage: systemImage) + } + .accessibilityIdentifier(identifier) + } + + private func deleteAccount() { + guard !deletingAccount else { return } + deletingAccount = true + Task { + do { + try await authManager.deleteAccount() + store?.signOut() + dismiss() + } catch { + showingDeleteAccountFailure = true + } + deletingAccount = false + } + } + /// Which setup gate to mark as the user's current blocker. Settings is reached /// only from the connected workspace list, so the user has cleared every gate /// and there is no "You are here" step; the help is a plain reference. `nil` diff --git a/ios/cmux/Resources/Localizable.xcstrings b/ios/cmux/Resources/Localizable.xcstrings index ce94462ee18b..4b0dde93a8b5 100644 --- a/ios/cmux/Resources/Localizable.xcstrings +++ b/ios/cmux/Resources/Localizable.xcstrings @@ -3962,6 +3962,159 @@ } } }, + "mobile.settings.deleteAccount": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Delete Account" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "アカウントを削除" + } + } + } + }, + "mobile.settings.deleteAccountCancel": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Cancel" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "キャンセル" + } + } + } + }, + "mobile.settings.deleteAccountConfirm": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Delete Account" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "アカウントを削除" + } + } + } + }, + "mobile.settings.deleteAccountFailedMessage": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Try again later or contact support." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "しばらくしてからもう一度お試しいただくか、サポートにお問い合わせください。" + } + } + } + }, + "mobile.settings.deleteAccountFailedTitle": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Couldn't Delete Account" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "アカウントを削除できませんでした" + } + } + } + }, + "mobile.settings.deleteAccountFailureOK": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "OK" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "OK" + } + } + } + }, + "mobile.settings.deleteAccountMessage": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "This permanently deletes your cmux account and cmux data. You will be signed out on this device." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "cmux アカウントと cmux のデータを完全に削除します。このデバイスではサインアウトされます。" + } + } + } + }, + "mobile.settings.deleteAccountTitle": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Delete Account?" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "アカウントを削除しますか?" + } + } + } + }, + "mobile.settings.deletingAccount": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Deleting Account..." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "アカウントを削除中..." + } + } + } + }, "mobile.settings.agentChatDemo": { "extractionState": "manual", "localizations": { @@ -4064,6 +4217,23 @@ } } }, + "mobile.settings.legalSupport": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Legal & Support" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "法務とサポート" + } + } + } + }, "mobile.settings.mac": { "extractionState": "manual", "localizations": { @@ -4081,6 +4251,23 @@ } } }, + "mobile.settings.privacyPolicy": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Privacy Policy" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "プライバシーポリシー" + } + } + } + }, "mobile.settings.pointsFormat": { "extractionState": "manual", "localizations": { @@ -4200,6 +4387,23 @@ } } }, + "mobile.settings.support": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Support" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "サポート" + } + } + } + }, "mobile.settings.switchMac": { "extractionState": "manual", "localizations": { @@ -4251,6 +4455,23 @@ } } }, + "mobile.settings.termsOfService": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Terms of Service" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "利用規約" + } + } + } + }, "mobile.settings.terminalLogDemo": { "extractionState": "manual", "localizations": { diff --git a/web/app/api/account/route.ts b/web/app/api/account/route.ts new file mode 100644 index 000000000000..d2d888cccb5e --- /dev/null +++ b/web/app/api/account/route.ts @@ -0,0 +1,117 @@ +import { and, eq, isNull, or } from "drizzle-orm"; + +import { getStackServerApp, isStackConfigured } from "../../lib/stack"; +import { cloudDb } from "../../../db/client"; +import { + cloudVmBaseEvents, + cloudVmBases, + cloudVmLeases, + cloudVmNotificationDeliveries, + cloudVmNotificationEvents, + cloudVmSessions, + cloudVmUsageEvents, + cloudVms, + deviceTokens, + devices, + notificationSendEvents, + vaultCliAuthRequests, + vaultSessions, + vaultUploadGrants, + vaultUploadTombstones, +} from "../../../db/schema"; +import { unauthorized, verifyRequest } from "../../../services/vms/auth"; +import { jsonResponse } from "../../../services/vms/routeHelpers"; +import { destroyVm, listUserVms, runVmWorkflow } from "../../../services/vms/workflows"; + +export const runtime = "nodejs"; +export const dynamic = "force-dynamic"; + +type DeletableStackUser = { + readonly id: string; + readonly delete: () => Promise; +}; + +export async function DELETE(request: Request): Promise { + const user = await verifyRequest(request, { allowCookie: false }); + if (!user) return unauthorized(); + + const stackUser = await currentDeletableStackUser(request); + if (!stackUser || stackUser.id !== user.id) return unauthorized(); + + try { + const destroyedVms = await destroyPersonalCloudVms(user.id); + await deleteCmuxOwnedAccountRows(user.id); + await stackUser.delete(); + return jsonResponse({ ok: true, destroyedVms }); + } catch (error) { + console.error("account.delete.failed", error); + return jsonResponse({ error: "account_delete_failed" }, 500); + } +} + +async function currentDeletableStackUser(request: Request): Promise { + if (!isStackConfigured()) return null; + + const authHeader = request.headers.get("authorization"); + const refreshHeader = request.headers.get("x-stack-refresh-token"); + if (!authHeader?.toLowerCase().startsWith("bearer ") || !refreshHeader) return null; + + const accessToken = authHeader.slice("bearer ".length).trim(); + const refreshToken = refreshHeader.trim(); + if (!accessToken || !refreshToken) return null; + + const user = await getStackServerApp().getUser({ + tokenStore: { accessToken, refreshToken }, + }); + if (!user || typeof (user as Partial).delete !== "function") return null; + return user as DeletableStackUser; +} + +async function destroyPersonalCloudVms(userId: string): Promise { + const vms = await runVmWorkflow(listUserVms(userId)); + for (const vm of vms) { + await runVmWorkflow(destroyVm({ userId, providerVmId: vm.providerVmId })); + } + return vms.length; +} + +async function deleteCmuxOwnedAccountRows(userId: string): Promise { + const db = cloudDb(); + await db.transaction(async (tx) => { + await tx.delete(deviceTokens).where(eq(deviceTokens.userId, userId)); + await tx.delete(notificationSendEvents).where(eq(notificationSendEvents.userId, userId)); + + await tx.delete(cloudVmNotificationDeliveries).where(eq(cloudVmNotificationDeliveries.userId, userId)); + await tx.delete(cloudVmNotificationEvents).where(eq(cloudVmNotificationEvents.userId, userId)); + await tx.delete(cloudVmUsageEvents).where(personalUsageScope(userId)); + await tx.delete(cloudVmLeases).where(eq(cloudVmLeases.userId, userId)); + await tx.delete(cloudVmSessions).where(eq(cloudVmSessions.userId, userId)); + await tx.delete(cloudVms).where(personalVmScope(userId)); + await tx.delete(cloudVmBaseEvents).where(eq(cloudVmBaseEvents.userId, userId)); + await tx.delete(cloudVmBases).where(and( + eq(cloudVmBases.scopeType, "user"), + eq(cloudVmBases.scopeId, userId), + )); + + await tx.delete(devices).where(eq(devices.userId, userId)); + + await tx.delete(vaultUploadGrants).where(eq(vaultUploadGrants.userId, userId)); + await tx.delete(vaultUploadTombstones).where(eq(vaultUploadTombstones.userId, userId)); + await tx.delete(vaultCliAuthRequests).where(eq(vaultCliAuthRequests.userId, userId)); + await tx.delete(vaultSessions).where(eq(vaultSessions.userId, userId)); + }); +} + +function personalVmScope(userId: string) { + return and( + eq(cloudVms.userId, userId), + or(isNull(cloudVms.billingTeamId), eq(cloudVms.billingTeamId, userId)), + ); +} + +function personalUsageScope(userId: string) { + return and( + eq(cloudVmUsageEvents.userId, userId), + or(isNull(cloudVmUsageEvents.billingTeamId), eq(cloudVmUsageEvents.billingTeamId, userId)), + ); +} diff --git a/web/tests/account-route.test.ts b/web/tests/account-route.test.ts new file mode 100644 index 000000000000..8348642aabc5 --- /dev/null +++ b/web/tests/account-route.test.ts @@ -0,0 +1,132 @@ +import { beforeEach, describe, expect, mock, test } from "bun:test"; + +const deleteStackUser = mock(async () => {}); +const getUser = mock(async () => stackUser(stackUserIds.shift())); +const transaction = mock(async (...args: unknown[]) => { + const [callback] = args as [(tx: MockTransaction) => Promise]; + await callback(mockTransaction); +}); +const listUserVms = mock((...args: unknown[]) => { + const [userId] = args as [string]; + return { kind: "listUserVms" as const, userId }; +}); +const destroyVm = mock((...args: unknown[]) => { + const [input] = args as [{ readonly userId: string; readonly providerVmId: string }]; + return { + kind: "destroyVm" as const, + input, + }; +}); +const runVmWorkflow = mock(async (...args: unknown[]) => { + const [program] = args as [WorkflowProgram]; + if (program.kind === "listUserVms") { + return [ + { providerVmId: "personal-vm-1" }, + { providerVmId: "personal-vm-2" }, + ]; + } + return undefined; +}); + +let deletedTableCount = 0; +let stackUserIds: Array = []; + +type WorkflowProgram = + | { readonly kind: "listUserVms"; readonly userId: string } + | { readonly kind: "destroyVm"; readonly input: { readonly userId: string; readonly providerVmId: string } }; + +type MockTransaction = { + readonly delete: (table: unknown) => { readonly where: (condition: unknown) => Promise }; +}; + +const mockTransaction: MockTransaction = { + delete: () => { + deletedTableCount += 1; + return { where: async () => {} }; + }, +}; + +mock.module("../app/lib/stack", () => ({ + getStackServerApp: () => ({ getUser }), + isStackConfigured: () => true, + stackServerApp: { getUser }, +})); + +mock.module("../db/client", () => ({ + cloudDb: () => ({ transaction }), + closeCloudDbForTests: async () => {}, +})); + +mock.module("../services/vms/workflows", () => ({ + destroyVm, + listUserVms, + runVmWorkflow, +})); + +const { DELETE } = await import("../app/api/account/route"); + +beforeEach(() => { + deleteStackUser.mockClear(); + getUser.mockClear(); + transaction.mockClear(); + listUserVms.mockClear(); + destroyVm.mockClear(); + runVmWorkflow.mockClear(); + deletedTableCount = 0; + stackUserIds = []; +}); + +describe("account deletion route", () => { + test("requires native auth headers", async () => { + const response = await DELETE(new Request("https://cmux.test/api/account", { method: "DELETE" })); + + expect(response.status).toBe(401); + expect(deleteStackUser).not.toHaveBeenCalled(); + expect(transaction).not.toHaveBeenCalled(); + }); + + test("destroys personal VMs, deletes cmux rows, then deletes the Stack user", async () => { + const response = await DELETE(accountDeletionRequest()); + + expect(response.status).toBe(200); + expect(await response.json()).toEqual({ ok: true, destroyedVms: 2 }); + expect(listUserVms).toHaveBeenCalledWith("account-user-1"); + expect(destroyVm).toHaveBeenCalledTimes(2); + expect(destroyVm).toHaveBeenCalledWith({ userId: "account-user-1", providerVmId: "personal-vm-1" }); + expect(destroyVm).toHaveBeenCalledWith({ userId: "account-user-1", providerVmId: "personal-vm-2" }); + expect(transaction).toHaveBeenCalledTimes(1); + expect(deletedTableCount).toBeGreaterThan(10); + expect(deleteStackUser).toHaveBeenCalledTimes(1); + }); + + test("rejects a Stack user mismatch before deleting data", async () => { + stackUserIds = ["account-user-1", "other-user"]; + + const response = await DELETE(accountDeletionRequest()); + + expect(response.status).toBe(401); + expect(deleteStackUser).not.toHaveBeenCalled(); + expect(transaction).not.toHaveBeenCalled(); + }); +}); + +function accountDeletionRequest(): Request { + return new Request("https://cmux.test/api/account", { + method: "DELETE", + headers: { + authorization: "Bearer access-token", + "x-stack-refresh-token": "refresh-token", + }, + }); +} + +function stackUser(id = "account-user-1") { + return { + id, + displayName: null, + primaryEmail: "account@example.com", + selectedTeam: null, + listTeams: async () => [], + delete: deleteStackUser, + }; +} From 0f88b979f9939651da37a15340108e0ccfe89fbb Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Wed, 8 Jul 2026 13:22:41 -0700 Subject: [PATCH 02/89] Fix account deletion review issues --- .../AuthCoordinator+AccountDeletion.swift | 30 +++++++++---- .../AccountDeletionClientTests.swift | 20 ++++++++- .../MobileSettingsView.swift | 37 +++++++++++++--- ios/cmux/Resources/Localizable.xcstrings | 17 ++++++++ web/app/api/account/route.ts | 36 +++++++++++++++- web/tests/account-route.test.ts | 42 ++++++++++++++++++- 6 files changed, 163 insertions(+), 19 deletions(-) diff --git a/Packages/Shared/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AuthCoordinator+AccountDeletion.swift b/Packages/Shared/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AuthCoordinator+AccountDeletion.swift index 06f825a2834d..d923ed24fc85 100644 --- a/Packages/Shared/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AuthCoordinator+AccountDeletion.swift +++ b/Packages/Shared/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AuthCoordinator+AccountDeletion.swift @@ -1,14 +1,19 @@ import Foundation -enum AccountDeletionRequestError: Error, Equatable { +public enum AccountDeletionRequestError: Error, Equatable { case invalidAPIBaseURL case unauthorized + case stackDeleteIncomplete case rejected(statusCode: Int) case invalidResponse } typealias AccountDeletionRequestLoader = @Sendable (URLRequest) async throws -> (Data, URLResponse) +nonisolated private struct AccountDeletionErrorResponse: Decodable { + let error: String +} + struct AccountDeletionClient: Sendable { private let apiBaseURL: String private let load: AccountDeletionRequestLoader @@ -24,9 +29,8 @@ struct AccountDeletionClient: Sendable { } func deleteAccount(accessToken: String, refreshToken: String) async throws { - guard let baseURL = URL(string: apiBaseURL), - let url = URL(string: "/api/account", relativeTo: baseURL)?.absoluteURL - else { + let trimmedBaseURL = apiBaseURL.hasSuffix("/") ? String(apiBaseURL.dropLast()) : apiBaseURL + guard let url = URL(string: trimmedBaseURL + "/api/account") else { throw AccountDeletionRequestError.invalidAPIBaseURL } @@ -35,7 +39,7 @@ struct AccountDeletionClient: Sendable { request.setValue("Bearer \(accessToken)", forHTTPHeaderField: "Authorization") request.setValue(refreshToken, forHTTPHeaderField: "X-Stack-Refresh-Token") - let (_, response) = try await load(request) + let (data, response) = try await load(request) guard let httpResponse = response as? HTTPURLResponse else { throw AccountDeletionRequestError.invalidResponse } @@ -45,20 +49,28 @@ struct AccountDeletionClient: Sendable { case 401: throw AccountDeletionRequestError.unauthorized default: + if Self.errorCode(in: data) == "account_stack_delete_failed_after_data_delete" { + throw AccountDeletionRequestError.stackDeleteIncomplete + } throw AccountDeletionRequestError.rejected(statusCode: httpResponse.statusCode) } } + + private static func errorCode(in data: Data) -> String? { + try? JSONDecoder().decode(AccountDeletionErrorResponse.self, from: data).error + } } extension AuthCoordinator { - /// Permanently deletes the current Stack account through cmux's backend and - /// then clears the local session using the same local-first path as sign-out. - public func deleteAccount(teardownTimeout: Duration = .seconds(5)) async throws { + /// Permanently deletes the current Stack account through cmux's backend. + /// + /// Callers clear local shell/auth state through their normal sign-out owner + /// after this succeeds so app-level teardown hooks run in the right order. + public func deleteAccount() async throws { let tokens = try await currentTokens() try await AccountDeletionClient(apiBaseURL: apiBaseURL).deleteAccount( accessToken: tokens.accessToken, refreshToken: tokens.refreshToken ) - await signOut(teardownTimeout: teardownTimeout) } } diff --git a/Packages/Shared/CmuxAuthRuntime/Tests/CmuxAuthRuntimeTests/AccountDeletionClientTests.swift b/Packages/Shared/CmuxAuthRuntime/Tests/CmuxAuthRuntimeTests/AccountDeletionClientTests.swift index 6b94bafe345b..6ce48bc9d876 100644 --- a/Packages/Shared/CmuxAuthRuntime/Tests/CmuxAuthRuntimeTests/AccountDeletionClientTests.swift +++ b/Packages/Shared/CmuxAuthRuntime/Tests/CmuxAuthRuntimeTests/AccountDeletionClientTests.swift @@ -21,7 +21,7 @@ struct AccountDeletionClientTests { try await client.deleteAccount(accessToken: "access-token", refreshToken: "refresh-token") let request = await recorder.request - #expect(request?.url?.absoluteString == "https://cmux.test/api/account") + #expect(request?.url?.absoluteString == "https://cmux.test/base/api/account") #expect(request?.httpMethod == "DELETE") #expect(request?.value(forHTTPHeaderField: "Authorization") == "Bearer access-token") #expect(request?.value(forHTTPHeaderField: "X-Stack-Refresh-Token") == "refresh-token") @@ -44,6 +44,24 @@ struct AccountDeletionClientTests { try await client.deleteAccount(accessToken: "access-token", refreshToken: "refresh-token") } } + + @Test func deleteAccountMapsStackDeleteIncompleteResponse() async { + let client = AccountDeletionClient(apiBaseURL: "https://cmux.test") { request in + ( + Data(#"{"error":"account_stack_delete_failed_after_data_delete"}"#.utf8), + HTTPURLResponse( + url: request.url!, + statusCode: 500, + httpVersion: nil, + headerFields: nil + )! + ) + } + + await #expect(throws: AccountDeletionRequestError.stackDeleteIncomplete) { + try await client.deleteAccount(accessToken: "access-token", refreshToken: "refresh-token") + } + } } actor RecordedAccountDeletionRequest { diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsView.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsView.swift index 95d204b2759c..280d4329932b 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsView.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsView.swift @@ -33,6 +33,7 @@ struct MobileSettingsView: View { @State private var showingSetupHelp = false @State private var showingDeleteAccountConfirmation = false @State private var showingDeleteAccountFailure = false + @State private var deleteAccountFailureKind = DeleteAccountFailureKind.generic @State private var deletingAccount = false #if DEBUG @State private var showingChatDemo = false @@ -376,10 +377,7 @@ struct MobileSettingsView: View { ) { Button(L10n.string("mobile.settings.deleteAccountFailureOK", defaultValue: "OK"), role: .cancel) {} } message: { - Text(L10n.string( - "mobile.settings.deleteAccountFailedMessage", - defaultValue: "Try again later or contact support." - )) + Text(deleteAccountFailureKind.localizedMessage) } } .accessibilityIdentifier("MobileSettingsView") @@ -409,9 +407,18 @@ struct MobileSettingsView: View { Task { do { try await authManager.deleteAccount() - store?.signOut() + if let signOut { + signOut() + } else { + await authManager.signOut() + } dismiss() } catch { + if case AccountDeletionRequestError.stackDeleteIncomplete = error { + deleteAccountFailureKind = .stackDeleteIncomplete + } else { + deleteAccountFailureKind = .generic + } showingDeleteAccountFailure = true } deletingAccount = false @@ -489,4 +496,24 @@ struct MobileSettingsView: View { #endif } + +private enum DeleteAccountFailureKind { + case generic + case stackDeleteIncomplete + + var localizedMessage: String { + switch self { + case .generic: + return L10n.string( + "mobile.settings.deleteAccountFailedMessage", + defaultValue: "Try again later or contact support." + ) + case .stackDeleteIncomplete: + return L10n.string( + "mobile.settings.deleteAccountPartialFailureMessage", + defaultValue: "Your cmux data was deleted, but account sign-in cleanup did not finish. Try Delete Account again to complete deletion." + ) + } + } +} #endif diff --git a/ios/cmux/Resources/Localizable.xcstrings b/ios/cmux/Resources/Localizable.xcstrings index 4b0dde93a8b5..7935f75991b0 100644 --- a/ios/cmux/Resources/Localizable.xcstrings +++ b/ios/cmux/Resources/Localizable.xcstrings @@ -4064,6 +4064,23 @@ } } }, + "mobile.settings.deleteAccountPartialFailureMessage": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Your cmux data was deleted, but account sign-in cleanup did not finish. Try Delete Account again to complete deletion." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "cmux のデータは削除されましたが、アカウントのサインイン情報のクリーンアップは完了しませんでした。削除を完了するには、もう一度「アカウントを削除」をお試しください。" + } + } + } + }, "mobile.settings.deleteAccountMessage": { "extractionState": "manual", "localizations": { diff --git a/web/app/api/account/route.ts b/web/app/api/account/route.ts index d2d888cccb5e..04b137262f09 100644 --- a/web/app/api/account/route.ts +++ b/web/app/api/account/route.ts @@ -40,11 +40,24 @@ export async function DELETE(request: Request): Promise { try { const destroyedVms = await destroyPersonalCloudVms(user.id); + // Delete cmux-owned data before the Stack user so a Stack-side failure does + // not strand retained app data behind an account the user can no longer use. + // These deletes are idempotent, so the same signed-in user can retry the + // final Stack deletion when the distinct response below is returned. await deleteCmuxOwnedAccountRows(user.id); - await stackUser.delete(); + try { + await stackUser.delete(); + } catch (error) { + logAccountDeleteError("account.delete.stack_user_failed_after_data_delete", error); + return jsonResponse({ + error: "account_stack_delete_failed_after_data_delete", + retryable: true, + destroyedVms, + }, 500); + } return jsonResponse({ ok: true, destroyedVms }); } catch (error) { - console.error("account.delete.failed", error); + logAccountDeleteError("account.delete.failed", error); return jsonResponse({ error: "account_delete_failed" }, 500); } } @@ -115,3 +128,22 @@ function personalUsageScope(userId: string) { or(isNull(cloudVmUsageEvents.billingTeamId), eq(cloudVmUsageEvents.billingTeamId, userId)), ); } + +const SENSITIVE_ERROR_TEXT = + /(srt_[A-Za-z0-9_-]+|sk-[A-Za-z0-9_-]{8,}|Bearer\s+\S+|eyJ[A-Za-z0-9_-]{10,})/g; + +function logAccountDeleteError(label: string, error: unknown): void { + console.error(label, sanitizedErrorSummary(error)); +} + +function sanitizedErrorSummary(error: unknown): string { + const name = + error && typeof error === "object" && typeof (error as { name?: unknown }).name === "string" + ? (error as { name: string }).name + : typeof error; + const message = + error && typeof error === "object" && typeof (error as { message?: unknown }).message === "string" + ? (error as { message: string }).message + : String(error); + return `${name}: ${message.replace(SENSITIVE_ERROR_TEXT, "[redacted]")}`; +} diff --git a/web/tests/account-route.test.ts b/web/tests/account-route.test.ts index 8348642aabc5..a7ce16f2bc18 100644 --- a/web/tests/account-route.test.ts +++ b/web/tests/account-route.test.ts @@ -1,9 +1,13 @@ -import { beforeEach, describe, expect, mock, test } from "bun:test"; +import { afterEach, beforeEach, describe, expect, mock, test } from "bun:test"; -const deleteStackUser = mock(async () => {}); +const deleteStackUser = mock(async () => { + routeEvents.push("stack-delete"); + if (stackDeleteError) throw stackDeleteError; +}); const getUser = mock(async () => stackUser(stackUserIds.shift())); const transaction = mock(async (...args: unknown[]) => { const [callback] = args as [(tx: MockTransaction) => Promise]; + routeEvents.push("transaction"); await callback(mockTransaction); }); const listUserVms = mock((...args: unknown[]) => { @@ -29,7 +33,11 @@ const runVmWorkflow = mock(async (...args: unknown[]) => { }); let deletedTableCount = 0; +let routeEvents: string[] = []; +let stackDeleteError: unknown = null; let stackUserIds: Array = []; +const originalConsoleError = console.error; +const consoleError = mock(() => {}); type WorkflowProgram = | { readonly kind: "listUserVms"; readonly userId: string } @@ -66,6 +74,8 @@ mock.module("../services/vms/workflows", () => ({ const { DELETE } = await import("../app/api/account/route"); beforeEach(() => { + console.error = consoleError as typeof console.error; + consoleError.mockClear(); deleteStackUser.mockClear(); getUser.mockClear(); transaction.mockClear(); @@ -73,9 +83,15 @@ beforeEach(() => { destroyVm.mockClear(); runVmWorkflow.mockClear(); deletedTableCount = 0; + routeEvents = []; + stackDeleteError = null; stackUserIds = []; }); +afterEach(() => { + console.error = originalConsoleError; +}); + describe("account deletion route", () => { test("requires native auth headers", async () => { const response = await DELETE(new Request("https://cmux.test/api/account", { method: "DELETE" })); @@ -97,6 +113,28 @@ describe("account deletion route", () => { expect(transaction).toHaveBeenCalledTimes(1); expect(deletedTableCount).toBeGreaterThan(10); expect(deleteStackUser).toHaveBeenCalledTimes(1); + expect(routeEvents).toEqual(["transaction", "stack-delete"]); + }); + + test("returns a retryable partial-failure response when Stack deletion fails after cmux data deletion", async () => { + stackDeleteError = new Error("Bearer access-token leaked by upstream"); + + const response = await DELETE(accountDeletionRequest()); + + expect(response.status).toBe(500); + expect(await response.json()).toEqual({ + error: "account_stack_delete_failed_after_data_delete", + retryable: true, + destroyedVms: 2, + }); + expect(transaction).toHaveBeenCalledTimes(1); + expect(deletedTableCount).toBeGreaterThan(10); + expect(deleteStackUser).toHaveBeenCalledTimes(1); + expect(routeEvents).toEqual(["transaction", "stack-delete"]); + expect(consoleError).toHaveBeenCalledWith( + "account.delete.stack_user_failed_after_data_delete", + "Error: [redacted] leaked by upstream", + ); }); test("rejects a Stack user mismatch before deleting data", async () => { From 760c4d9530cbec20dd609ba46a251334ded7a3b5 Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Wed, 8 Jul 2026 13:31:21 -0700 Subject: [PATCH 03/89] Complete account deletion cleanup --- web/app/api/account/route.ts | 104 +++++++++++++++++++++++++++- web/tests/account-route.test.ts | 117 +++++++++++++++++++++++++++++++- 2 files changed, 219 insertions(+), 2 deletions(-) diff --git a/web/app/api/account/route.ts b/web/app/api/account/route.ts index 04b137262f09..8443d27ab2de 100644 --- a/web/app/api/account/route.ts +++ b/web/app/api/account/route.ts @@ -1,8 +1,9 @@ -import { and, eq, isNull, or } from "drizzle-orm"; +import { and, eq, inArray, isNull, or } from "drizzle-orm"; import { getStackServerApp, isStackConfigured } from "../../lib/stack"; import { cloudDb } from "../../../db/client"; import { + billingEmailClaims, cloudVmBaseEvents, cloudVmBases, cloudVmLeases, @@ -14,11 +15,17 @@ import { deviceTokens, devices, notificationSendEvents, + stripeCustomers, + stripeSubscriptions, vaultCliAuthRequests, vaultSessions, + vaultSnapshots, vaultUploadGrants, vaultUploadTombstones, } from "../../../db/schema"; +import { ACTIVE_STRIPE_PRO_STATUSES } from "../../../services/billing/pro"; +import { isStripeBillingConfigured, stripe } from "../../../services/billing/stripe"; +import { deleteObject } from "../../../services/vault/storage"; import { unauthorized, verifyRequest } from "../../../services/vms/auth"; import { jsonResponse } from "../../../services/vms/routeHelpers"; import { destroyVm, listUserVms, runVmWorkflow } from "../../../services/vms/workflows"; @@ -40,6 +47,8 @@ export async function DELETE(request: Request): Promise { try { const destroyedVms = await destroyPersonalCloudVms(user.id); + await deleteVaultObjectsForAccount(user.id); + await resolveUserBillingForAccountDeletion(user.id); // Delete cmux-owned data before the Stack user so a Stack-side failure does // not strand retained app data behind an account the user can no longer use. // These deletes are idempotent, so the same signed-in user can retry the @@ -88,12 +97,105 @@ async function destroyPersonalCloudVms(userId: string): Promise { return vms.length; } +async function deleteVaultObjectsForAccount(userId: string): Promise { + const db = cloudDb(); + const objectKeys = new Set(); + + const sessions = await db + .select({ latestObjectKey: vaultSessions.latestObjectKey }) + .from(vaultSessions) + .where(eq(vaultSessions.userId, userId)); + for (const session of sessions) objectKeys.add(session.latestObjectKey); + + const snapshots = await db + .select({ objectKey: vaultSnapshots.objectKey }) + .from(vaultSnapshots) + .innerJoin(vaultSessions, eq(vaultSnapshots.sessionId, vaultSessions.id)) + .where(eq(vaultSessions.userId, userId)); + for (const snapshot of snapshots) objectKeys.add(snapshot.objectKey); + + const grants = await db + .select({ + objectKey: vaultUploadGrants.objectKey, + uploadObjectKey: vaultUploadGrants.uploadObjectKey, + }) + .from(vaultUploadGrants) + .where(eq(vaultUploadGrants.userId, userId)); + for (const grant of grants) { + objectKeys.add(grant.objectKey); + objectKeys.add(grant.uploadObjectKey); + } + + const tombstones = await db + .select({ + objectKey: vaultUploadTombstones.objectKey, + uploadObjectKey: vaultUploadTombstones.uploadObjectKey, + }) + .from(vaultUploadTombstones) + .where(eq(vaultUploadTombstones.userId, userId)); + for (const tombstone of tombstones) { + objectKeys.add(tombstone.objectKey); + objectKeys.add(tombstone.uploadObjectKey); + } + + for (const objectKey of objectKeys) { + await deleteObject(objectKey); + } +} + +async function resolveUserBillingForAccountDeletion(userId: string): Promise { + const db = cloudDb(); + const activeSubscriptions = await db + .select({ id: stripeSubscriptions.id }) + .from(stripeSubscriptions) + .where(and( + eq(stripeSubscriptions.stackUserId, userId), + eq(stripeSubscriptions.scope, "user"), + isNull(stripeSubscriptions.stackTeamId), + inArray(stripeSubscriptions.status, ACTIVE_STRIPE_PRO_STATUSES), + )); + const customers = await db + .select({ id: stripeCustomers.id }) + .from(stripeCustomers) + .where(and( + eq(stripeCustomers.stackUserId, userId), + isNull(stripeCustomers.stackTeamId), + )); + + if (activeSubscriptions.length === 0 && customers.length === 0) return; + if (!isStripeBillingConfigured()) { + throw new Error("Stripe billing cleanup is not configured"); + } + + const client = stripe(); + for (const subscription of activeSubscriptions) { + await client.subscriptions.cancel(subscription.id); + } + for (const customer of customers) { + await client.customers.del(customer.id); + } +} + async function deleteCmuxOwnedAccountRows(userId: string): Promise { const db = cloudDb(); await db.transaction(async (tx) => { await tx.delete(deviceTokens).where(eq(deviceTokens.userId, userId)); await tx.delete(notificationSendEvents).where(eq(notificationSendEvents.userId, userId)); + await tx.delete(billingEmailClaims).where(or( + eq(billingEmailClaims.stackUserId, userId), + eq(billingEmailClaims.claimedByUserId, userId), + )); + await tx.delete(stripeSubscriptions).where(and( + eq(stripeSubscriptions.stackUserId, userId), + eq(stripeSubscriptions.scope, "user"), + isNull(stripeSubscriptions.stackTeamId), + )); + await tx.delete(stripeCustomers).where(and( + eq(stripeCustomers.stackUserId, userId), + isNull(stripeCustomers.stackTeamId), + )); + await tx.delete(cloudVmNotificationDeliveries).where(eq(cloudVmNotificationDeliveries.userId, userId)); await tx.delete(cloudVmNotificationEvents).where(eq(cloudVmNotificationEvents.userId, userId)); await tx.delete(cloudVmUsageEvents).where(personalUsageScope(userId)); diff --git a/web/tests/account-route.test.ts b/web/tests/account-route.test.ts index a7ce16f2bc18..395f0190bd61 100644 --- a/web/tests/account-route.test.ts +++ b/web/tests/account-route.test.ts @@ -31,11 +31,30 @@ const runVmWorkflow = mock(async (...args: unknown[]) => { } return undefined; }); +const deleteObject = mock(async (...args: unknown[]) => { + const [objectKey] = args as [string]; + deletedVaultObjects.push(objectKey); + if (vaultDeleteError) throw vaultDeleteError; +}); +const cancelSubscription = mock(async (...args: unknown[]) => { + const [subscriptionId] = args as [string]; + cancelledStripeSubscriptions.push(subscriptionId); +}); +const deleteCustomer = mock(async (...args: unknown[]) => { + const [customerId] = args as [string]; + deletedStripeCustomers.push(customerId); +}); let deletedTableCount = 0; let routeEvents: string[] = []; let stackDeleteError: unknown = null; let stackUserIds: Array = []; +let selectResults: unknown[][] = []; +let deletedVaultObjects: string[] = []; +let vaultDeleteError: unknown = null; +let stripeConfigured = true; +let cancelledStripeSubscriptions: string[] = []; +let deletedStripeCustomers: string[] = []; const originalConsoleError = console.error; const consoleError = mock(() => {}); @@ -54,6 +73,22 @@ const mockTransaction: MockTransaction = { }, }; +function nextSelectResult(): unknown[] { + return selectResults.shift() ?? []; +} + +const mockDb = { + select: mock(() => ({ + from: () => ({ + where: async () => nextSelectResult(), + innerJoin: () => ({ + where: async () => nextSelectResult(), + }), + }), + })), + transaction, +}; + mock.module("../app/lib/stack", () => ({ getStackServerApp: () => ({ getUser }), isStackConfigured: () => true, @@ -61,10 +96,22 @@ mock.module("../app/lib/stack", () => ({ })); mock.module("../db/client", () => ({ - cloudDb: () => ({ transaction }), + cloudDb: () => mockDb, closeCloudDbForTests: async () => {}, })); +mock.module("../services/vault/storage", () => ({ + deleteObject, +})); + +mock.module("../services/billing/stripe", () => ({ + isStripeBillingConfigured: () => stripeConfigured, + stripe: () => ({ + subscriptions: { cancel: cancelSubscription }, + customers: { del: deleteCustomer }, + }), +})); + mock.module("../services/vms/workflows", () => ({ destroyVm, listUserVms, @@ -79,13 +126,23 @@ beforeEach(() => { deleteStackUser.mockClear(); getUser.mockClear(); transaction.mockClear(); + mockDb.select.mockClear(); listUserVms.mockClear(); destroyVm.mockClear(); runVmWorkflow.mockClear(); + deleteObject.mockClear(); + cancelSubscription.mockClear(); + deleteCustomer.mockClear(); deletedTableCount = 0; routeEvents = []; stackDeleteError = null; stackUserIds = []; + selectResults = [[], [], [], [], [], []]; + deletedVaultObjects = []; + vaultDeleteError = null; + stripeConfigured = true; + cancelledStripeSubscriptions = []; + deletedStripeCustomers = []; }); afterEach(() => { @@ -102,6 +159,15 @@ describe("account deletion route", () => { }); test("destroys personal VMs, deletes cmux rows, then deletes the Stack user", async () => { + selectResults = [ + [{ latestObjectKey: "vault/u/account-user-1/latest.jsonl.zst" }], + [{ objectKey: "vault/u/account-user-1/snapshot.jsonl.zst" }], + [{ objectKey: "vault/u/account-user-1/grant.jsonl.zst", uploadObjectKey: "vault/uploads/grant" }], + [{ objectKey: "vault/u/account-user-1/tombstone.jsonl.zst", uploadObjectKey: "vault/uploads/tombstone" }], + [{ id: "sub_user_active" }], + [{ id: "cus_user" }], + ]; + const response = await DELETE(accountDeletionRequest()); expect(response.status).toBe(200); @@ -112,10 +178,59 @@ describe("account deletion route", () => { expect(destroyVm).toHaveBeenCalledWith({ userId: "account-user-1", providerVmId: "personal-vm-2" }); expect(transaction).toHaveBeenCalledTimes(1); expect(deletedTableCount).toBeGreaterThan(10); + expect(deletedVaultObjects).toEqual([ + "vault/u/account-user-1/latest.jsonl.zst", + "vault/u/account-user-1/snapshot.jsonl.zst", + "vault/u/account-user-1/grant.jsonl.zst", + "vault/uploads/grant", + "vault/u/account-user-1/tombstone.jsonl.zst", + "vault/uploads/tombstone", + ]); + expect(cancelledStripeSubscriptions).toEqual(["sub_user_active"]); + expect(deletedStripeCustomers).toEqual(["cus_user"]); expect(deleteStackUser).toHaveBeenCalledTimes(1); expect(routeEvents).toEqual(["transaction", "stack-delete"]); }); + test("does not delete rows or Stack user when vault object cleanup fails", async () => { + selectResults = [ + [{ latestObjectKey: "vault/u/account-user-1/latest.jsonl.zst" }], + [], + [], + [], + [], + [], + ]; + vaultDeleteError = new Error("vault unavailable"); + + const response = await DELETE(accountDeletionRequest()); + + expect(response.status).toBe(500); + expect(await response.json()).toEqual({ error: "account_delete_failed" }); + expect(transaction).not.toHaveBeenCalled(); + expect(deleteStackUser).not.toHaveBeenCalled(); + }); + + test("does not delete rows or Stack user when active billing cleanup cannot run", async () => { + selectResults = [ + [], + [], + [], + [], + [{ id: "sub_user_active" }], + [], + ]; + stripeConfigured = false; + + const response = await DELETE(accountDeletionRequest()); + + expect(response.status).toBe(500); + expect(await response.json()).toEqual({ error: "account_delete_failed" }); + expect(cancelSubscription).not.toHaveBeenCalled(); + expect(transaction).not.toHaveBeenCalled(); + expect(deleteStackUser).not.toHaveBeenCalled(); + }); + test("returns a retryable partial-failure response when Stack deletion fails after cmux data deletion", async () => { stackDeleteError = new Error("Bearer access-token leaked by upstream"); From aeedf886267925568b5b621e75062ac89a92f10d Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Wed, 8 Jul 2026 13:42:03 -0700 Subject: [PATCH 04/89] Guard deleted account billing webhooks --- web/app/api/account/route.ts | 5 ++ web/services/billing/purchase.ts | 134 +++++++++++++++++++++-------- web/tests/account-route.test.ts | 8 +- web/tests/billing-purchase.test.ts | 52 ++++++++++- 4 files changed, 158 insertions(+), 41 deletions(-) diff --git a/web/app/api/account/route.ts b/web/app/api/account/route.ts index 8443d27ab2de..87201449b6f1 100644 --- a/web/app/api/account/route.ts +++ b/web/app/api/account/route.ts @@ -6,6 +6,7 @@ import { billingEmailClaims, cloudVmBaseEvents, cloudVmBases, + cloudVmBillingGrants, cloudVmLeases, cloudVmNotificationDeliveries, cloudVmNotificationEvents, @@ -196,6 +197,10 @@ async function deleteCmuxOwnedAccountRows(userId: string): Promise { isNull(stripeCustomers.stackTeamId), )); + await tx.delete(cloudVmBillingGrants).where(and( + eq(cloudVmBillingGrants.billingCustomerType, "user"), + eq(cloudVmBillingGrants.billingCustomerId, userId), + )); await tx.delete(cloudVmNotificationDeliveries).where(eq(cloudVmNotificationDeliveries.userId, userId)); await tx.delete(cloudVmNotificationEvents).where(eq(cloudVmNotificationEvents.userId, userId)); await tx.delete(cloudVmUsageEvents).where(personalUsageScope(userId)); diff --git a/web/services/billing/purchase.ts b/web/services/billing/purchase.ts index fd0949a2f545..9e6b9a5cfb85 100644 --- a/web/services/billing/purchase.ts +++ b/web/services/billing/purchase.ts @@ -180,20 +180,29 @@ export async function applySubscriptionUpdate( return { scope: "team", stackTeamId: teamScope.stackTeamId, isActive }; } - const stackUserId = - subscription.metadata?.stackUserId ?? - (await stackUserIdForStripeCustomer(db, customerId)); + const mappedStackUserId = await stackUserIdForStripeCustomer(db, customerId); + const stackUserId = subscription.metadata?.stackUserId ?? mappedStackUserId; if (!stackUserId) return { skipped: true }; - await upsertStripeSubscription(db, { + const isActive = isActiveStripeSubscriptionStatus(subscription.status); + const hasLocalBillingRecord = + mappedStackUserId === stackUserId || + (await userStripeSubscriptionExists(db, { + subscriptionId: subscription.id, + stackUserId, + })); + if (!hasLocalBillingRecord) return { skipped: true }; + + const user = await loadOptionalStackUser(stackUserId, dependencies.stackApp); + if (!user) return { skipped: true }; + + await updateExistingStripeSubscription(db, { subscription, customerId, stackUserId, scope: "user", }); - const isActive = isActiveStripeSubscriptionStatus(subscription.status); - const user = await loadStackUser(stackUserId, dependencies.stackApp); await syncProPlanMetadata(user, isActive); if (!isActive) { await removeUserFromTestflightOnLapse(user, stackUserId, dependencies); @@ -232,13 +241,20 @@ async function loadStackUser( stackUserId: string, stackApp: StackBillingApp | null | undefined, ): Promise { - const app = stackApp ?? stackServerApp; - if (!app) throw new Error("Stack Auth is not configured"); - const user = await app.getUser(stackUserId); + const user = await loadOptionalStackUser(stackUserId, stackApp); if (!user) throw new Error(`Stack user not found for Stripe purchase: ${stackUserId}`); return user; } +async function loadOptionalStackUser( + stackUserId: string, + stackApp: StackBillingApp | null | undefined, +): Promise { + const app = stackApp ?? stackServerApp; + if (!app) throw new Error("Stack Auth is not configured"); + return app.getUser(stackUserId); +} + async function loadStackTeam( stackTeamId: string, stackApp: StackBillingApp | null | undefined, @@ -441,43 +457,89 @@ async function upsertStripeSubscription( scope: "user" | "team"; }, ): Promise { - const { subscription } = input; - const plan = input.scope === "team" ? TEAM_PLAN_ID : PRO_PLAN_ID; + const values = stripeSubscriptionValues(input); await db .insert(stripeSubscriptions) - .values({ - id: subscription.id, - customerId: input.customerId, - stackUserId: input.stackUserId, - stackTeamId: input.stackTeamId ?? null, - status: subscription.status, - priceId: subscriptionPriceId(subscription), - plan, - seats: input.scope === "team" ? subscriptionSeats(subscription) : null, - scope: input.scope, - currentPeriodEnd: subscriptionCurrentPeriodEnd(subscription), - cancelAtPeriodEnd: subscription.cancel_at_period_end, - raw: JSON.parse(JSON.stringify(subscription)) as Record, - }) + .values(values) .onConflictDoUpdate({ target: stripeSubscriptions.id, set: { - customerId: input.customerId, - stackUserId: input.stackUserId, - stackTeamId: input.stackTeamId ?? null, - status: subscription.status, - priceId: subscriptionPriceId(subscription), - plan, - seats: input.scope === "team" ? subscriptionSeats(subscription) : null, - scope: input.scope, - currentPeriodEnd: subscriptionCurrentPeriodEnd(subscription), - cancelAtPeriodEnd: subscription.cancel_at_period_end, - raw: JSON.parse(JSON.stringify(subscription)) as Record, + ...values, updatedAt: sql`now()`, }, }); } +async function updateExistingStripeSubscription( + db: BillingDb, + input: { + subscription: Stripe.Subscription; + customerId: string; + stackUserId: string; + stackTeamId?: string | null; + scope: "user" | "team"; + }, +): Promise { + await db + .update(stripeSubscriptions) + .set({ + ...stripeSubscriptionValues(input), + updatedAt: sql`now()`, + }) + .where( + and( + eq(stripeSubscriptions.id, input.subscription.id), + eq(stripeSubscriptions.stackUserId, input.stackUserId), + eq(stripeSubscriptions.scope, input.scope), + isNull(stripeSubscriptions.stackTeamId), + ), + ); +} + +function stripeSubscriptionValues(input: { + subscription: Stripe.Subscription; + customerId: string; + stackUserId: string; + stackTeamId?: string | null; + scope: "user" | "team"; +}) { + const { subscription } = input; + const plan = input.scope === "team" ? TEAM_PLAN_ID : PRO_PLAN_ID; + return { + id: subscription.id, + customerId: input.customerId, + stackUserId: input.stackUserId, + stackTeamId: input.stackTeamId ?? null, + status: subscription.status, + priceId: subscriptionPriceId(subscription), + plan, + seats: input.scope === "team" ? subscriptionSeats(subscription) : null, + scope: input.scope, + currentPeriodEnd: subscriptionCurrentPeriodEnd(subscription), + cancelAtPeriodEnd: subscription.cancel_at_period_end, + raw: JSON.parse(JSON.stringify(subscription)) as Record, + }; +} + +async function userStripeSubscriptionExists( + db: BillingDb, + input: { subscriptionId: string; stackUserId: string }, +): Promise { + const [row] = await db + .select({ id: stripeSubscriptions.id }) + .from(stripeSubscriptions) + .where( + and( + eq(stripeSubscriptions.id, input.subscriptionId), + eq(stripeSubscriptions.stackUserId, input.stackUserId), + eq(stripeSubscriptions.scope, "user"), + isNull(stripeSubscriptions.stackTeamId), + ), + ) + .limit(1); + return Boolean(row); +} + async function attachPurchaseEmailOrRecordClaim( db: BillingDb, input: { diff --git a/web/tests/account-route.test.ts b/web/tests/account-route.test.ts index 395f0190bd61..961079b64c33 100644 --- a/web/tests/account-route.test.ts +++ b/web/tests/account-route.test.ts @@ -1,5 +1,7 @@ import { afterEach, beforeEach, describe, expect, mock, test } from "bun:test"; +import { cloudVmBillingGrants } from "../db/schema"; + const deleteStackUser = mock(async () => { routeEvents.push("stack-delete"); if (stackDeleteError) throw stackDeleteError; @@ -46,6 +48,7 @@ const deleteCustomer = mock(async (...args: unknown[]) => { }); let deletedTableCount = 0; +let deletedTables: unknown[] = []; let routeEvents: string[] = []; let stackDeleteError: unknown = null; let stackUserIds: Array = []; @@ -67,7 +70,8 @@ type MockTransaction = { }; const mockTransaction: MockTransaction = { - delete: () => { + delete: (table: unknown) => { + deletedTables.push(table); deletedTableCount += 1; return { where: async () => {} }; }, @@ -134,6 +138,7 @@ beforeEach(() => { cancelSubscription.mockClear(); deleteCustomer.mockClear(); deletedTableCount = 0; + deletedTables = []; routeEvents = []; stackDeleteError = null; stackUserIds = []; @@ -178,6 +183,7 @@ describe("account deletion route", () => { expect(destroyVm).toHaveBeenCalledWith({ userId: "account-user-1", providerVmId: "personal-vm-2" }); expect(transaction).toHaveBeenCalledTimes(1); expect(deletedTableCount).toBeGreaterThan(10); + expect(deletedTables).toContain(cloudVmBillingGrants); expect(deletedVaultObjects).toEqual([ "vault/u/account-user-1/latest.jsonl.zst", "vault/u/account-user-1/snapshot.jsonl.zst", diff --git a/web/tests/billing-purchase.test.ts b/web/tests/billing-purchase.test.ts index 7897acb3951c..41e25b725d72 100644 --- a/web/tests/billing-purchase.test.ts +++ b/web/tests/billing-purchase.test.ts @@ -1,10 +1,28 @@ import { beforeEach, describe, expect, mock, test } from "bun:test"; import { billingEmailClaims, stripeCustomers, stripeSubscriptions } from "../db/schema"; -import { - applySubscriptionUpdate, - recordCheckoutCompletion, -} from "../services/billing/purchase"; + +mock.module("../app/lib/stack", () => ({ + stackServerApp: null, +})); +mock.module("../db/client", () => ({ + cloudDb: () => { + throw new Error("test must inject a billing DB"); + }, +})); +mock.module("../services/asc/client", () => ({ + isAscConfigured: () => false, +})); +mock.module("../services/asc/testflight", () => ({ + removeTester: async () => {}, +})); +mock.module("../services/errors", () => ({ + captureAscError: () => {}, +})); + +const { applySubscriptionUpdate, recordCheckoutCompletion } = await import( + "../services/billing/purchase" +); const inserts: Array<{ table: unknown; values: Record }> = []; const updates: Array<{ table: unknown; values: Record }> = []; @@ -469,6 +487,7 @@ describe("recordCheckoutCompletion", () => { clientReadOnlyMetadata: { cmuxPlan: "pro" }, update, }; + selectResults = [[{ stackUserId: "user_123" }]]; const result = await applySubscriptionUpdate( userSubscriptionUpdate({ status: "canceled" }) as never, @@ -495,6 +514,7 @@ describe("recordCheckoutCompletion", () => { clientReadOnlyMetadata: { cmuxPlan: "pro" }, update: mock(async () => undefined), }; + selectResults = [[{ stackUserId: "user_123" }]]; const result = await applySubscriptionUpdate( userSubscriptionUpdate({ status: "canceled" }) as never, @@ -530,6 +550,7 @@ describe("recordCheckoutCompletion", () => { clientReadOnlyMetadata: { cmuxPlan: "pro" }, update: mock(async () => undefined), }; + selectResults = [[{ stackUserId: "user_123" }]]; await applySubscriptionUpdate( userSubscriptionUpdate({ status: "canceled" }) as never, @@ -546,6 +567,29 @@ describe("recordCheckoutCompletion", () => { expect(removeTester).not.toHaveBeenCalled(); }); + test("skips user subscription webhooks after local billing rows are gone", async () => { + const getUser = mock(async () => ({ + id: "user_123", + primaryEmail: "buyer@example.com", + clientReadOnlyMetadata: { cmuxPlan: "pro" }, + update: mock(async () => undefined), + })); + selectResults = [[], []]; + + const result = await applySubscriptionUpdate( + userSubscriptionUpdate({ status: "canceled" }) as never, + { + db: fakeDb() as never, + stackApp: { getUser } as never, + }, + ); + + expect(result).toEqual({ skipped: true }); + expect(getUser).not.toHaveBeenCalled(); + expect(inserts.some((insert) => insert.table === stripeSubscriptions)).toBe(false); + expect(updates.some((update) => update.table === stripeSubscriptions)).toBe(false); + }); + test("does not remove TestFlight access when a Team subscription lapses", async () => { const removeTester = mock(async () => undefined); const team = { From ebaf859f3b29e7a3f863a37cc9f50d42d479d033 Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Wed, 8 Jul 2026 13:46:22 -0700 Subject: [PATCH 05/89] Split mobile settings account review sections --- .../MobileSettingsAccountSection.swift | 142 +++++++++++++++ .../MobileSettingsLegalSupportSection.swift | 48 +++++ .../MobileSettingsView.swift | 170 +----------------- ios/cmux/Resources/Localizable.xcstrings | 34 ++++ 4 files changed, 226 insertions(+), 168 deletions(-) create mode 100644 Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsAccountSection.swift create mode 100644 Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsLegalSupportSection.swift diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsAccountSection.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsAccountSection.swift new file mode 100644 index 000000000000..7580496ac643 --- /dev/null +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsAccountSection.swift @@ -0,0 +1,142 @@ +#if os(iOS) +import CmuxAuthRuntime +import SwiftUI + +struct MobileSettingsAccountSection: View { + @Environment(AuthCoordinator.self) private var authManager + @Environment(\.dismiss) private var dismiss + let signOut: (() -> Void)? + + @State private var showingDeleteAccountConfirmation = false + @State private var showingDeleteAccountFailure = false + @State private var deleteAccountFailureKind = DeleteAccountFailureKind.generic + @State private var deletingAccount = false + + var body: some View { + Section { + LabeledContent { + Text(accountEmail) + .foregroundStyle(.secondary) + .textSelection(.enabled) + } label: { + Label(accountDisplayName, systemImage: "person.crop.circle") + } + .accessibilityIdentifier("MobileSettingsAccountRow") + + if let signOut { + Button(role: .destructive) { + signOut() + dismiss() + } label: { + Label( + L10n.string("mobile.signOut", defaultValue: "Sign Out"), + systemImage: "rectangle.portrait.and.arrow.right" + ) + } + .accessibilityIdentifier("MobileSettingsSignOut") + } + + Button(role: .destructive) { + showingDeleteAccountConfirmation = true + } label: { + Label( + deletingAccount + ? L10n.string("mobile.settings.deletingAccount", defaultValue: "Deleting Account...") + : L10n.string("mobile.settings.deleteAccount", defaultValue: "Delete Account"), + systemImage: deletingAccount ? "hourglass" : "trash" + ) + } + .disabled(deletingAccount) + .accessibilityIdentifier("MobileSettingsDeleteAccount") + } header: { + Text(L10n.string("mobile.settings.account", defaultValue: "Account")) + } footer: { + Text(L10n.string( + "mobile.settings.accountFooter", + defaultValue: "This device must be signed in to the same cmux account as the computer you pair with." + )) + } + .alert( + L10n.string("mobile.settings.deleteAccountTitle", defaultValue: "Delete Account?"), + isPresented: $showingDeleteAccountConfirmation + ) { + Button(L10n.string("mobile.settings.deleteAccountCancel", defaultValue: "Cancel"), role: .cancel) {} + Button( + L10n.string("mobile.settings.deleteAccountConfirm", defaultValue: "Delete Account"), + role: .destructive + ) { + deleteAccount() + } + } message: { + Text(L10n.string( + "mobile.settings.deleteAccountMessage", + defaultValue: "This permanently deletes your cmux account and cmux data. You will be signed out on this device." + )) + } + .alert( + L10n.string("mobile.settings.deleteAccountFailedTitle", defaultValue: "Couldn't Delete Account"), + isPresented: $showingDeleteAccountFailure + ) { + Button(L10n.string("mobile.settings.deleteAccountFailureOK", defaultValue: "OK"), role: .cancel) {} + } message: { + Text(deleteAccountFailureKind.localizedMessage) + } + } + + private func deleteAccount() { + guard !deletingAccount else { return } + deletingAccount = true + Task { + do { + try await authManager.deleteAccount() + if let signOut { + signOut() + } else { + await authManager.signOut() + } + dismiss() + } catch { + if case AccountDeletionRequestError.stackDeleteIncomplete = error { + deleteAccountFailureKind = .stackDeleteIncomplete + } else { + deleteAccountFailureKind = .generic + } + showingDeleteAccountFailure = true + } + deletingAccount = false + } + } + + private var accountEmail: String { + let email = authManager.currentUser?.primaryEmail?.trimmingCharacters(in: .whitespacesAndNewlines) + if let email, !email.isEmpty { return email } + return L10n.string("mobile.settings.notSignedIn", defaultValue: "Not signed in") + } + + private var accountDisplayName: String { + let name = authManager.currentUser?.displayName?.trimmingCharacters(in: .whitespacesAndNewlines) + if let name, !name.isEmpty { return name } + return L10n.string("mobile.settings.account", defaultValue: "Account") + } +} + +private enum DeleteAccountFailureKind { + case generic + case stackDeleteIncomplete + + var localizedMessage: String { + switch self { + case .generic: + return L10n.string( + "mobile.settings.deleteAccountFailedMessage", + defaultValue: "Try again later or contact support." + ) + case .stackDeleteIncomplete: + return L10n.string( + "mobile.settings.deleteAccountPartialFailureMessage", + defaultValue: "Your cmux data was deleted, but account sign-in cleanup did not finish. Try Delete Account again to complete deletion." + ) + } + } +} +#endif diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsLegalSupportSection.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsLegalSupportSection.swift new file mode 100644 index 000000000000..1b61b9cc6251 --- /dev/null +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsLegalSupportSection.swift @@ -0,0 +1,48 @@ +#if os(iOS) +import SwiftUI + +struct MobileSettingsLegalSupportSection: View { + @Environment(\.openURL) private var openURL + + var body: some View { + Section(L10n.string("mobile.settings.legalSupport", defaultValue: "Legal & Support")) { + externalLinkRow( + title: L10n.string("mobile.settings.privacyPolicy", defaultValue: "Privacy Policy"), + systemImage: "hand.raised", + url: Self.privacyPolicyURL, + identifier: "MobileSettingsPrivacyPolicy" + ) + externalLinkRow( + title: L10n.string("mobile.settings.termsOfService", defaultValue: "Terms of Service"), + systemImage: "doc.text", + url: Self.termsOfServiceURL, + identifier: "MobileSettingsTermsOfService" + ) + externalLinkRow( + title: L10n.string("mobile.settings.support", defaultValue: "Support"), + systemImage: "envelope", + url: Self.supportURL, + identifier: "MobileSettingsSupport" + ) + } + } + + private static let privacyPolicyURL = URL(string: "https://cmux.com/privacy-policy")! + private static let termsOfServiceURL = URL(string: "https://cmux.com/terms-of-service")! + private static let supportURL = URL(string: "mailto:feedback@manaflow.com?subject=cmux%20iOS%20support")! + + private func externalLinkRow( + title: String, + systemImage: String, + url: URL, + identifier: String + ) -> some View { + Button { + openURL(url) + } label: { + Label(title, systemImage: systemImage) + } + .accessibilityIdentifier(identifier) + } +} +#endif diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsView.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsView.swift index 280d4329932b..5d45be6527ed 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsView.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsView.swift @@ -21,7 +21,6 @@ struct MobileSettingsView: View { var store: CMUXMobileShellStore? @Environment(\.dismiss) private var dismiss - @Environment(\.openURL) private var openURL @State private var showingShortcuts = false /// Mirrors ``MobilePushCoordinator/isEnabled`` so the toggle's label/icon /// update after the async enable/disable. The coordinator exposes @@ -31,10 +30,6 @@ struct MobileSettingsView: View { @State private var showingHostPicker = false @State private var showingOnboarding = false @State private var showingSetupHelp = false - @State private var showingDeleteAccountConfirmation = false - @State private var showingDeleteAccountFailure = false - @State private var deleteAccountFailureKind = DeleteAccountFailureKind.generic - @State private var deletingAccount = false #if DEBUG @State private var showingChatDemo = false @State private var showingTerminalDemo = false @@ -44,49 +39,7 @@ struct MobileSettingsView: View { @Bindable var displaySettings = displaySettings return NavigationStack { Form { - Section { - LabeledContent { - Text(accountEmail) - .foregroundStyle(.secondary) - .textSelection(.enabled) - } label: { - Label(accountDisplayName, systemImage: "person.crop.circle") - } - .accessibilityIdentifier("MobileSettingsAccountRow") - - if let signOut { - Button(role: .destructive) { - signOut() - dismiss() - } label: { - Label( - L10n.string("mobile.signOut", defaultValue: "Sign Out"), - systemImage: "rectangle.portrait.and.arrow.right" - ) - } - .accessibilityIdentifier("MobileSettingsSignOut") - } - - Button(role: .destructive) { - showingDeleteAccountConfirmation = true - } label: { - Label( - deletingAccount - ? L10n.string("mobile.settings.deletingAccount", defaultValue: "Deleting Account...") - : L10n.string("mobile.settings.deleteAccount", defaultValue: "Delete Account"), - systemImage: deletingAccount ? "hourglass" : "trash" - ) - } - .disabled(deletingAccount) - .accessibilityIdentifier("MobileSettingsDeleteAccount") - } header: { - Text(L10n.string("mobile.settings.account", defaultValue: "Account")) - } footer: { - Text(L10n.string( - "mobile.settings.accountFooter", - defaultValue: "This device must be signed in to the same cmux account as the computer you pair with." - )) - } + MobileSettingsAccountSection(signOut: signOut) // Stack team switcher. Only shown when the user belongs to more than // one team. Rendered as an INLINE picker — each team is a row with a @@ -275,26 +228,7 @@ struct MobileSettingsView: View { .accessibilityIdentifier("MobileSettingsNotifications") } - Section(L10n.string("mobile.settings.legalSupport", defaultValue: "Legal & Support")) { - externalLinkRow( - title: L10n.string("mobile.settings.privacyPolicy", defaultValue: "Privacy Policy"), - systemImage: "hand.raised", - url: Self.privacyPolicyURL, - identifier: "MobileSettingsPrivacyPolicy" - ) - externalLinkRow( - title: L10n.string("mobile.settings.termsOfService", defaultValue: "Terms of Service"), - systemImage: "doc.text", - url: Self.termsOfServiceURL, - identifier: "MobileSettingsTermsOfService" - ) - externalLinkRow( - title: L10n.string("mobile.settings.support", defaultValue: "Support"), - systemImage: "envelope", - url: Self.supportURL, - identifier: "MobileSettingsSupport" - ) - } + MobileSettingsLegalSupportSection() Section(L10n.string("mobile.settings.about", defaultValue: "About")) { LabeledContent { @@ -354,77 +288,10 @@ struct MobileSettingsView: View { // mark "You are here". SetupHelpView(highlight: setupHelpHighlight) { showingSetupHelp = false } } - .alert( - L10n.string("mobile.settings.deleteAccountTitle", defaultValue: "Delete Account?"), - isPresented: $showingDeleteAccountConfirmation - ) { - Button(L10n.string("mobile.settings.deleteAccountCancel", defaultValue: "Cancel"), role: .cancel) {} - Button( - L10n.string("mobile.settings.deleteAccountConfirm", defaultValue: "Delete Account"), - role: .destructive - ) { - deleteAccount() - } - } message: { - Text(L10n.string( - "mobile.settings.deleteAccountMessage", - defaultValue: "This permanently deletes your cmux account and cmux data. You will be signed out on this device." - )) - } - .alert( - L10n.string("mobile.settings.deleteAccountFailedTitle", defaultValue: "Couldn't Delete Account"), - isPresented: $showingDeleteAccountFailure - ) { - Button(L10n.string("mobile.settings.deleteAccountFailureOK", defaultValue: "OK"), role: .cancel) {} - } message: { - Text(deleteAccountFailureKind.localizedMessage) - } } .accessibilityIdentifier("MobileSettingsView") } - private static let privacyPolicyURL = URL(string: "https://cmux.com/privacy-policy")! - private static let termsOfServiceURL = URL(string: "https://cmux.com/terms-of-service")! - private static let supportURL = URL(string: "mailto:feedback@manaflow.com?subject=cmux%20iOS%20support")! - - private func externalLinkRow( - title: String, - systemImage: String, - url: URL, - identifier: String - ) -> some View { - Button { - openURL(url) - } label: { - Label(title, systemImage: systemImage) - } - .accessibilityIdentifier(identifier) - } - - private func deleteAccount() { - guard !deletingAccount else { return } - deletingAccount = true - Task { - do { - try await authManager.deleteAccount() - if let signOut { - signOut() - } else { - await authManager.signOut() - } - dismiss() - } catch { - if case AccountDeletionRequestError.stackDeleteIncomplete = error { - deleteAccountFailureKind = .stackDeleteIncomplete - } else { - deleteAccountFailureKind = .generic - } - showingDeleteAccountFailure = true - } - deletingAccount = false - } - } - /// Which setup gate to mark as the user's current blocker. Settings is reached /// only from the connected workspace list, so the user has cleared every gate /// and there is no "You are here" step; the help is a plain reference. `nil` @@ -455,18 +322,6 @@ struct MobileSettingsView: View { ) } - private var accountEmail: String { - let email = authManager.currentUser?.primaryEmail?.trimmingCharacters(in: .whitespacesAndNewlines) - if let email, !email.isEmpty { return email } - return L10n.string("mobile.settings.notSignedIn", defaultValue: "Not signed in") - } - - private var accountDisplayName: String { - let name = authManager.currentUser?.displayName?.trimmingCharacters(in: .whitespacesAndNewlines) - if let name, !name.isEmpty { return name } - return L10n.string("mobile.settings.account", defaultValue: "Account") - } - #if DEBUG private func debugLayoutSlider( title: String, @@ -494,26 +349,5 @@ struct MobileSettingsView: View { ) } #endif - -} - -private enum DeleteAccountFailureKind { - case generic - case stackDeleteIncomplete - - var localizedMessage: String { - switch self { - case .generic: - return L10n.string( - "mobile.settings.deleteAccountFailedMessage", - defaultValue: "Try again later or contact support." - ) - case .stackDeleteIncomplete: - return L10n.string( - "mobile.settings.deleteAccountPartialFailureMessage", - defaultValue: "Your cmux data was deleted, but account sign-in cleanup did not finish. Try Delete Account again to complete deletion." - ) - } - } } #endif diff --git a/ios/cmux/Resources/Localizable.xcstrings b/ios/cmux/Resources/Localizable.xcstrings index 7935f75991b0..8ac0555a1172 100644 --- a/ios/cmux/Resources/Localizable.xcstrings +++ b/ios/cmux/Resources/Localizable.xcstrings @@ -3945,6 +3945,23 @@ } } }, + "mobile.settings.account": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Account" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "アカウント" + } + } + } + }, "mobile.settings.accountFooter": { "extractionState": "manual", "localizations": { @@ -4268,6 +4285,23 @@ } } }, + "mobile.settings.notSignedIn": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Not signed in" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "サインインしていません" + } + } + } + }, "mobile.settings.privacyPolicy": { "extractionState": "manual", "localizations": { From 31808e1d0b438ff559dd30eeec15fb2adeb09b8e Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Wed, 8 Jul 2026 13:47:55 -0700 Subject: [PATCH 06/89] Fix mobile settings section imports --- .../Sources/CmuxMobileShellUI/MobileSettingsAccountSection.swift | 1 + .../CmuxMobileShellUI/MobileSettingsLegalSupportSection.swift | 1 + 2 files changed, 2 insertions(+) diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsAccountSection.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsAccountSection.swift index 7580496ac643..dbc89c320e44 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsAccountSection.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsAccountSection.swift @@ -1,5 +1,6 @@ #if os(iOS) import CmuxAuthRuntime +import CmuxMobileSupport import SwiftUI struct MobileSettingsAccountSection: View { diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsLegalSupportSection.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsLegalSupportSection.swift index 1b61b9cc6251..3ae8f3221ad1 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsLegalSupportSection.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsLegalSupportSection.swift @@ -1,4 +1,5 @@ #if os(iOS) +import CmuxMobileSupport import SwiftUI struct MobileSettingsLegalSupportSection: View { From 0f3771740593a35984874039aebbc0d814296d57 Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Wed, 8 Jul 2026 13:53:42 -0700 Subject: [PATCH 07/89] Bound account deletion cleanup failures --- .../AuthCoordinator+AccountDeletion.swift | 26 +++++-- .../Coordinator/AuthPhase.swift | 1 + .../AccountDeletionClientTests.swift | 13 +++- .../MobileSettingsAccountSection.swift | 10 +++ ios/cmux/Resources/Localizable.xcstrings | 17 +++++ web/app/api/account/route.ts | 18 ++++- web/tests/account-route.test.ts | 74 +++++++++++++++++-- 7 files changed, 140 insertions(+), 19 deletions(-) diff --git a/Packages/Shared/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AuthCoordinator+AccountDeletion.swift b/Packages/Shared/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AuthCoordinator+AccountDeletion.swift index d923ed24fc85..dc9d126cad3f 100644 --- a/Packages/Shared/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AuthCoordinator+AccountDeletion.swift +++ b/Packages/Shared/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AuthCoordinator+AccountDeletion.swift @@ -4,6 +4,7 @@ public enum AccountDeletionRequestError: Error, Equatable { case invalidAPIBaseURL case unauthorized case stackDeleteIncomplete + case timedOut case rejected(statusCode: Int) case invalidResponse } @@ -16,15 +17,18 @@ nonisolated private struct AccountDeletionErrorResponse: Decodable { struct AccountDeletionClient: Sendable { private let apiBaseURL: String + private let requestTimeout: TimeInterval private let load: AccountDeletionRequestLoader init( apiBaseURL: String, + requestTimeout: TimeInterval = 60, load: @escaping AccountDeletionRequestLoader = { request in try await URLSession.shared.data(for: request) } ) { self.apiBaseURL = apiBaseURL + self.requestTimeout = requestTimeout self.load = load } @@ -34,12 +38,18 @@ struct AccountDeletionClient: Sendable { throw AccountDeletionRequestError.invalidAPIBaseURL } - var request = URLRequest(url: url) + var request = URLRequest(url: url, timeoutInterval: requestTimeout) request.httpMethod = "DELETE" request.setValue("Bearer \(accessToken)", forHTTPHeaderField: "Authorization") request.setValue(refreshToken, forHTTPHeaderField: "X-Stack-Refresh-Token") - let (data, response) = try await load(request) + let data: Data + let response: URLResponse + do { + (data, response) = try await load(request) + } catch let error as URLError where error.code == .timedOut { + throw AccountDeletionRequestError.timedOut + } guard let httpResponse = response as? HTTPURLResponse else { throw AccountDeletionRequestError.invalidResponse } @@ -68,9 +78,13 @@ extension AuthCoordinator { /// after this succeeds so app-level teardown hooks run in the right order. public func deleteAccount() async throws { let tokens = try await currentTokens() - try await AccountDeletionClient(apiBaseURL: apiBaseURL).deleteAccount( - accessToken: tokens.accessToken, - refreshToken: tokens.refreshToken - ) + let apiBaseURL = apiBaseURL + let timeout = timeouts.network + try await runPhase(.accountDeletion, timeout: timeout) { + try await AccountDeletionClient(apiBaseURL: apiBaseURL).deleteAccount( + accessToken: tokens.accessToken, + refreshToken: tokens.refreshToken + ) + } } } diff --git a/Packages/Shared/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AuthPhase.swift b/Packages/Shared/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AuthPhase.swift index cb4571f13e0e..602513bafbe6 100644 --- a/Packages/Shared/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AuthPhase.swift +++ b/Packages/Shared/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AuthPhase.swift @@ -13,4 +13,5 @@ enum AuthPhase: String, Sendable, Hashable { case validateSession = "validate_session" case listTeams = "list_teams" case postSignIn = "post_sign_in" + case accountDeletion = "account_deletion" } diff --git a/Packages/Shared/CmuxAuthRuntime/Tests/CmuxAuthRuntimeTests/AccountDeletionClientTests.swift b/Packages/Shared/CmuxAuthRuntime/Tests/CmuxAuthRuntimeTests/AccountDeletionClientTests.swift index 6ce48bc9d876..8112449b3c2d 100644 --- a/Packages/Shared/CmuxAuthRuntime/Tests/CmuxAuthRuntimeTests/AccountDeletionClientTests.swift +++ b/Packages/Shared/CmuxAuthRuntime/Tests/CmuxAuthRuntimeTests/AccountDeletionClientTests.swift @@ -5,7 +5,7 @@ import Testing struct AccountDeletionClientTests { @Test func deleteAccountSendsNativeAuthHeaders() async throws { let recorder = RecordedAccountDeletionRequest() - let client = AccountDeletionClient(apiBaseURL: "https://cmux.test/base") { request in + let client = AccountDeletionClient(apiBaseURL: "https://cmux.test/base", requestTimeout: 12) { request in await recorder.record(request) return ( Data(), @@ -23,6 +23,7 @@ struct AccountDeletionClientTests { let request = await recorder.request #expect(request?.url?.absoluteString == "https://cmux.test/base/api/account") #expect(request?.httpMethod == "DELETE") + #expect(request?.timeoutInterval == 12) #expect(request?.value(forHTTPHeaderField: "Authorization") == "Bearer access-token") #expect(request?.value(forHTTPHeaderField: "X-Stack-Refresh-Token") == "refresh-token") } @@ -62,6 +63,16 @@ struct AccountDeletionClientTests { try await client.deleteAccount(accessToken: "access-token", refreshToken: "refresh-token") } } + + @Test func deleteAccountMapsTransportTimeout() async { + let client = AccountDeletionClient(apiBaseURL: "https://cmux.test") { _ in + throw URLError(.timedOut) + } + + await #expect(throws: AccountDeletionRequestError.timedOut) { + try await client.deleteAccount(accessToken: "access-token", refreshToken: "refresh-token") + } + } } actor RecordedAccountDeletionRequest { diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsAccountSection.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsAccountSection.swift index dbc89c320e44..8fd781b213fa 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsAccountSection.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsAccountSection.swift @@ -99,6 +99,10 @@ struct MobileSettingsAccountSection: View { } catch { if case AccountDeletionRequestError.stackDeleteIncomplete = error { deleteAccountFailureKind = .stackDeleteIncomplete + } else if case AccountDeletionRequestError.timedOut = error { + deleteAccountFailureKind = .timedOut + } else if case AuthError.timedOut = error { + deleteAccountFailureKind = .timedOut } else { deleteAccountFailureKind = .generic } @@ -124,6 +128,7 @@ struct MobileSettingsAccountSection: View { private enum DeleteAccountFailureKind { case generic case stackDeleteIncomplete + case timedOut var localizedMessage: String { switch self { @@ -137,6 +142,11 @@ private enum DeleteAccountFailureKind { "mobile.settings.deleteAccountPartialFailureMessage", defaultValue: "Your cmux data was deleted, but account sign-in cleanup did not finish. Try Delete Account again to complete deletion." ) + case .timedOut: + return L10n.string( + "mobile.settings.deleteAccountTimedOutMessage", + defaultValue: "Account deletion timed out. Check your connection and try again." + ) } } } diff --git a/ios/cmux/Resources/Localizable.xcstrings b/ios/cmux/Resources/Localizable.xcstrings index 8ac0555a1172..5ed4381cd2f4 100644 --- a/ios/cmux/Resources/Localizable.xcstrings +++ b/ios/cmux/Resources/Localizable.xcstrings @@ -4098,6 +4098,23 @@ } } }, + "mobile.settings.deleteAccountTimedOutMessage": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Account deletion timed out. Check your connection and try again." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "アカウントの削除がタイムアウトしました。接続を確認してからもう一度お試しください。" + } + } + } + }, "mobile.settings.deleteAccountMessage": { "extractionState": "manual", "localizations": { diff --git a/web/app/api/account/route.ts b/web/app/api/account/route.ts index 87201449b6f1..d233f16b7706 100644 --- a/web/app/api/account/route.ts +++ b/web/app/api/account/route.ts @@ -24,7 +24,11 @@ import { vaultUploadGrants, vaultUploadTombstones, } from "../../../db/schema"; -import { ACTIVE_STRIPE_PRO_STATUSES } from "../../../services/billing/pro"; +import { + ACTIVE_STRIPE_PRO_STATUSES, + syncProPlanMetadata, + type ProMetadataCustomer, +} from "../../../services/billing/pro"; import { isStripeBillingConfigured, stripe } from "../../../services/billing/stripe"; import { deleteObject } from "../../../services/vault/storage"; import { unauthorized, verifyRequest } from "../../../services/vms/auth"; @@ -37,7 +41,7 @@ export const dynamic = "force-dynamic"; type DeletableStackUser = { readonly id: string; readonly delete: () => Promise; -}; +} & ProMetadataCustomer; export async function DELETE(request: Request): Promise { const user = await verifyRequest(request, { allowCookie: false }); @@ -50,6 +54,7 @@ export async function DELETE(request: Request): Promise { const destroyedVms = await destroyPersonalCloudVms(user.id); await deleteVaultObjectsForAccount(user.id); await resolveUserBillingForAccountDeletion(user.id); + await clearUserBillingEntitlementsForAccountDeletion(stackUser); // Delete cmux-owned data before the Stack user so a Stack-side failure does // not strand retained app data behind an account the user can no longer use. // These deletes are idempotent, so the same signed-in user can retry the @@ -86,7 +91,8 @@ async function currentDeletableStackUser(request: Request): Promise).delete !== "function") return null; + const candidate = user as Partial; + if (!user || typeof candidate.delete !== "function" || typeof candidate.update !== "function") return null; return user as DeletableStackUser; } @@ -177,6 +183,10 @@ async function resolveUserBillingForAccountDeletion(userId: string): Promise { + await syncProPlanMetadata(user, false); +} + async function deleteCmuxOwnedAccountRows(userId: string): Promise { const db = cloudDb(); await db.transaction(async (tx) => { @@ -237,7 +247,7 @@ function personalUsageScope(userId: string) { } const SENSITIVE_ERROR_TEXT = - /(srt_[A-Za-z0-9_-]+|sk-[A-Za-z0-9_-]{8,}|Bearer\s+\S+|eyJ[A-Za-z0-9_-]{10,})/g; + /(Bearer\s+\S+|eyJ[A-Za-z0-9_-]*\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+|srt_[A-Za-z0-9_-]+|sk-[A-Za-z0-9_-]{8,})/g; function logAccountDeleteError(label: string, error: unknown): void { console.error(label, sanitizedErrorSummary(error)); diff --git a/web/tests/account-route.test.ts b/web/tests/account-route.test.ts index 961079b64c33..b5228e62e1b8 100644 --- a/web/tests/account-route.test.ts +++ b/web/tests/account-route.test.ts @@ -2,10 +2,21 @@ import { afterEach, beforeEach, describe, expect, mock, test } from "bun:test"; import { cloudVmBillingGrants } from "../db/schema"; +const ACCOUNT_USER_ID = "account-user-1"; +const storageModule = await import("../services/vault/storage"); +const realDeleteObject = storageModule.deleteObject; +const workflowsModule = await import("../services/vms/workflows"); +const realDestroyVm = workflowsModule.destroyVm; +const realListUserVms = workflowsModule.listUserVms; +const realRunVmWorkflow = workflowsModule.runVmWorkflow as (...args: unknown[]) => unknown; + const deleteStackUser = mock(async () => { routeEvents.push("stack-delete"); if (stackDeleteError) throw stackDeleteError; }); +const updateStackUser = mock(async () => { + routeEvents.push("metadata-update"); +}); const getUser = mock(async () => stackUser(stackUserIds.shift())); const transaction = mock(async (...args: unknown[]) => { const [callback] = args as [(tx: MockTransaction) => Promise]; @@ -105,7 +116,12 @@ mock.module("../db/client", () => ({ })); mock.module("../services/vault/storage", () => ({ - deleteObject, + ...storageModule, + deleteObject: ((...args: Parameters) => { + const [objectKey] = args; + if (isAccountDeletionVaultObject(objectKey)) return deleteObject(...args); + return realDeleteObject(...args); + }) as typeof realDeleteObject, })); mock.module("../services/billing/stripe", () => ({ @@ -117,9 +133,22 @@ mock.module("../services/billing/stripe", () => ({ })); mock.module("../services/vms/workflows", () => ({ - destroyVm, - listUserVms, - runVmWorkflow, + ...workflowsModule, + destroyVm: ((...args: Parameters) => { + const [input] = args; + if (input.userId === ACCOUNT_USER_ID) return destroyVm(...args); + return realDestroyVm(...args); + }) as typeof realDestroyVm, + listUserVms: ((...args: Parameters) => { + const [userId] = args; + if (userId === ACCOUNT_USER_ID) return listUserVms(...args); + return realListUserVms(...args); + }) as typeof realListUserVms, + runVmWorkflow: ((...args: unknown[]) => { + const [program] = args; + if (isAccountDeletionWorkflowProgram(program)) return runVmWorkflow(...args); + return realRunVmWorkflow(...args); + }) as typeof workflowsModule.runVmWorkflow, })); const { DELETE } = await import("../app/api/account/route"); @@ -128,6 +157,7 @@ beforeEach(() => { console.error = consoleError as typeof console.error; consoleError.mockClear(); deleteStackUser.mockClear(); + updateStackUser.mockClear(); getUser.mockClear(); transaction.mockClear(); mockDb.select.mockClear(); @@ -194,8 +224,11 @@ describe("account deletion route", () => { ]); expect(cancelledStripeSubscriptions).toEqual(["sub_user_active"]); expect(deletedStripeCustomers).toEqual(["cus_user"]); + expect(updateStackUser).toHaveBeenCalledWith({ + clientReadOnlyMetadata: {}, + }); expect(deleteStackUser).toHaveBeenCalledTimes(1); - expect(routeEvents).toEqual(["transaction", "stack-delete"]); + expect(routeEvents).toEqual(["metadata-update", "transaction", "stack-delete"]); }); test("does not delete rows or Stack user when vault object cleanup fails", async () => { @@ -238,7 +271,9 @@ describe("account deletion route", () => { }); test("returns a retryable partial-failure response when Stack deletion fails after cmux data deletion", async () => { - stackDeleteError = new Error("Bearer access-token leaked by upstream"); + stackDeleteError = new Error( + "raw eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJhY2NvdW50LXVzZXItMSJ9.signaturePart leaked by upstream", + ); const response = await DELETE(accountDeletionRequest()); @@ -250,11 +285,14 @@ describe("account deletion route", () => { }); expect(transaction).toHaveBeenCalledTimes(1); expect(deletedTableCount).toBeGreaterThan(10); + expect(updateStackUser).toHaveBeenCalledWith({ + clientReadOnlyMetadata: {}, + }); expect(deleteStackUser).toHaveBeenCalledTimes(1); - expect(routeEvents).toEqual(["transaction", "stack-delete"]); + expect(routeEvents).toEqual(["metadata-update", "transaction", "stack-delete"]); expect(consoleError).toHaveBeenCalledWith( "account.delete.stack_user_failed_after_data_delete", - "Error: [redacted] leaked by upstream", + "Error: raw [redacted] leaked by upstream", ); }); @@ -284,8 +322,28 @@ function stackUser(id = "account-user-1") { id, displayName: null, primaryEmail: "account@example.com", + clientReadOnlyMetadata: { cmuxPlan: "pro" }, selectedTeam: null, listTeams: async () => [], + update: updateStackUser, delete: deleteStackUser, }; } + +function isAccountDeletionVaultObject(objectKey: string): boolean { + return objectKey.startsWith(`vault/u/${ACCOUNT_USER_ID}/`) || + objectKey === "vault/uploads/grant" || + objectKey === "vault/uploads/tombstone"; +} + +function isAccountDeletionWorkflowProgram(program: unknown): boolean { + if (!program || typeof program !== "object") return false; + const candidate = program as { + readonly kind?: unknown; + readonly userId?: unknown; + readonly input?: { readonly userId?: unknown }; + }; + if (candidate.kind === "listUserVms") return candidate.userId === ACCOUNT_USER_ID; + if (candidate.kind === "destroyVm") return candidate.input?.userId === ACCOUNT_USER_ID; + return false; +} From b4262705a43351789c0488e0819e653022148047 Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Wed, 8 Jul 2026 13:57:50 -0700 Subject: [PATCH 08/89] Harden account deletion retries --- .../AuthCoordinator+AccountDeletion.swift | 8 +++- .../AccountDeletionClientTests.swift | 18 ++++++++ .../MobileSettingsAccountSection.swift | 10 +++-- web/app/api/account/route.ts | 45 +++++++++++++++++-- web/tests/account-route.test.ts | 30 ++++++++++++- 5 files changed, 103 insertions(+), 8 deletions(-) diff --git a/Packages/Shared/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AuthCoordinator+AccountDeletion.swift b/Packages/Shared/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AuthCoordinator+AccountDeletion.swift index dc9d126cad3f..2e6f8cbe0991 100644 --- a/Packages/Shared/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AuthCoordinator+AccountDeletion.swift +++ b/Packages/Shared/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AuthCoordinator+AccountDeletion.swift @@ -32,6 +32,7 @@ struct AccountDeletionClient: Sendable { self.load = load } + @concurrent func deleteAccount(accessToken: String, refreshToken: String) async throws { let trimmedBaseURL = apiBaseURL.hasSuffix("/") ? String(apiBaseURL.dropLast()) : apiBaseURL guard let url = URL(string: trimmedBaseURL + "/api/account") else { @@ -59,7 +60,7 @@ struct AccountDeletionClient: Sendable { case 401: throw AccountDeletionRequestError.unauthorized default: - if Self.errorCode(in: data) == "account_stack_delete_failed_after_data_delete" { + if Self.isRetryablePartialDeletionError(Self.errorCode(in: data)) { throw AccountDeletionRequestError.stackDeleteIncomplete } throw AccountDeletionRequestError.rejected(statusCode: httpResponse.statusCode) @@ -69,6 +70,11 @@ struct AccountDeletionClient: Sendable { private static func errorCode(in data: Data) -> String? { try? JSONDecoder().decode(AccountDeletionErrorResponse.self, from: data).error } + + private static func isRetryablePartialDeletionError(_ code: String?) -> Bool { + code == "account_delete_retryable" || + code == "account_stack_delete_failed_after_data_delete" + } } extension AuthCoordinator { diff --git a/Packages/Shared/CmuxAuthRuntime/Tests/CmuxAuthRuntimeTests/AccountDeletionClientTests.swift b/Packages/Shared/CmuxAuthRuntime/Tests/CmuxAuthRuntimeTests/AccountDeletionClientTests.swift index 8112449b3c2d..70178fd0b966 100644 --- a/Packages/Shared/CmuxAuthRuntime/Tests/CmuxAuthRuntimeTests/AccountDeletionClientTests.swift +++ b/Packages/Shared/CmuxAuthRuntime/Tests/CmuxAuthRuntimeTests/AccountDeletionClientTests.swift @@ -47,6 +47,24 @@ struct AccountDeletionClientTests { } @Test func deleteAccountMapsStackDeleteIncompleteResponse() async { + let client = AccountDeletionClient(apiBaseURL: "https://cmux.test") { request in + ( + Data(#"{"error":"account_delete_retryable"}"#.utf8), + HTTPURLResponse( + url: request.url!, + statusCode: 500, + httpVersion: nil, + headerFields: nil + )! + ) + } + + await #expect(throws: AccountDeletionRequestError.stackDeleteIncomplete) { + try await client.deleteAccount(accessToken: "access-token", refreshToken: "refresh-token") + } + } + + @Test func deleteAccountMapsLegacyPartialDeletionResponse() async { let client = AccountDeletionClient(apiBaseURL: "https://cmux.test") { request in ( Data(#"{"error":"account_stack_delete_failed_after_data_delete"}"#.utf8), diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsAccountSection.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsAccountSection.swift index 8fd781b213fa..44da9a91e6f5 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsAccountSection.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsAccountSection.swift @@ -12,6 +12,7 @@ struct MobileSettingsAccountSection: View { @State private var showingDeleteAccountFailure = false @State private var deleteAccountFailureKind = DeleteAccountFailureKind.generic @State private var deletingAccount = false + @State private var deleteAccountTask: Task? var body: some View { Section { @@ -85,9 +86,13 @@ struct MobileSettingsAccountSection: View { } private func deleteAccount() { - guard !deletingAccount else { return } + guard !deletingAccount, deleteAccountTask == nil else { return } deletingAccount = true - Task { + deleteAccountTask = Task { + defer { + deleteAccountTask = nil + deletingAccount = false + } do { try await authManager.deleteAccount() if let signOut { @@ -108,7 +113,6 @@ struct MobileSettingsAccountSection: View { } showingDeleteAccountFailure = true } - deletingAccount = false } } diff --git a/web/app/api/account/route.ts b/web/app/api/account/route.ts index d233f16b7706..bf97bae4709a 100644 --- a/web/app/api/account/route.ts +++ b/web/app/api/account/route.ts @@ -65,7 +65,7 @@ export async function DELETE(request: Request): Promise { } catch (error) { logAccountDeleteError("account.delete.stack_user_failed_after_data_delete", error); return jsonResponse({ - error: "account_stack_delete_failed_after_data_delete", + error: "account_delete_retryable", retryable: true, destroyedVms, }, 500); @@ -176,10 +176,10 @@ async function resolveUserBillingForAccountDeletion(userId: string): Promise, + subscriptionId: string, +): Promise { + try { + await client.subscriptions.cancel(subscriptionId); + } catch (error) { + if (isStripeAlreadyInDeletionTargetState(error, [/already been canceled/i])) return; + throw error; + } +} + +async function deleteStripeCustomerForAccountDeletion( + client: ReturnType, + customerId: string, +): Promise { + try { + await client.customers.del(customerId); + } catch (error) { + if (isStripeAlreadyInDeletionTargetState(error, [/already deleted/i])) return; + throw error; + } +} + +function isStripeAlreadyInDeletionTargetState(error: unknown, messagePatterns: readonly RegExp[]): boolean { + const statusCode = + error && typeof error === "object" + ? (error as { statusCode?: unknown; raw?: { statusCode?: unknown } }).statusCode ?? + (error as { raw?: { statusCode?: unknown } }).raw?.statusCode + : undefined; + if (statusCode === 404) return true; + + const message = + error && typeof error === "object" && typeof (error as { message?: unknown }).message === "string" + ? (error as { message: string }).message + : String(error); + return messagePatterns.some((pattern) => pattern.test(message)); +} + async function deleteCmuxOwnedAccountRows(userId: string): Promise { const db = cloudDb(); await db.transaction(async (tx) => { diff --git a/web/tests/account-route.test.ts b/web/tests/account-route.test.ts index b5228e62e1b8..544f436c1199 100644 --- a/web/tests/account-route.test.ts +++ b/web/tests/account-route.test.ts @@ -52,10 +52,12 @@ const deleteObject = mock(async (...args: unknown[]) => { const cancelSubscription = mock(async (...args: unknown[]) => { const [subscriptionId] = args as [string]; cancelledStripeSubscriptions.push(subscriptionId); + if (stripeCancelError) throw stripeCancelError; }); const deleteCustomer = mock(async (...args: unknown[]) => { const [customerId] = args as [string]; deletedStripeCustomers.push(customerId); + if (stripeDeleteCustomerError) throw stripeDeleteCustomerError; }); let deletedTableCount = 0; @@ -69,6 +71,8 @@ let vaultDeleteError: unknown = null; let stripeConfigured = true; let cancelledStripeSubscriptions: string[] = []; let deletedStripeCustomers: string[] = []; +let stripeCancelError: unknown = null; +let stripeDeleteCustomerError: unknown = null; const originalConsoleError = console.error; const consoleError = mock(() => {}); @@ -178,6 +182,8 @@ beforeEach(() => { stripeConfigured = true; cancelledStripeSubscriptions = []; deletedStripeCustomers = []; + stripeCancelError = null; + stripeDeleteCustomerError = null; }); afterEach(() => { @@ -279,7 +285,7 @@ describe("account deletion route", () => { expect(response.status).toBe(500); expect(await response.json()).toEqual({ - error: "account_stack_delete_failed_after_data_delete", + error: "account_delete_retryable", retryable: true, destroyedVms: 2, }); @@ -296,6 +302,28 @@ describe("account deletion route", () => { ); }); + test("continues when Stripe resources are already in the deletion target state", async () => { + selectResults = [ + [], + [], + [], + [], + [{ id: "sub_user_active" }], + [{ id: "cus_user" }], + ]; + stripeCancelError = new Error("This subscription has already been canceled"); + stripeDeleteCustomerError = { statusCode: 404, message: "No such customer" }; + + const response = await DELETE(accountDeletionRequest()); + + expect(response.status).toBe(200); + expect(await response.json()).toEqual({ ok: true, destroyedVms: 2 }); + expect(cancelledStripeSubscriptions).toEqual(["sub_user_active"]); + expect(deletedStripeCustomers).toEqual(["cus_user"]); + expect(transaction).toHaveBeenCalledTimes(1); + expect(deleteStackUser).toHaveBeenCalledTimes(1); + }); + test("rejects a Stack user mismatch before deleting data", async () => { stackUserIds = ["account-user-1", "other-user"]; From 79edd76e7d8ebc06692202ea3ae83615db608ce4 Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Wed, 8 Jul 2026 13:58:24 -0700 Subject: [PATCH 09/89] Avoid billing purchase test mock leakage --- web/tests/billing-purchase.test.ts | 23 ++++++----------------- 1 file changed, 6 insertions(+), 17 deletions(-) diff --git a/web/tests/billing-purchase.test.ts b/web/tests/billing-purchase.test.ts index 41e25b725d72..19a7db4632f1 100644 --- a/web/tests/billing-purchase.test.ts +++ b/web/tests/billing-purchase.test.ts @@ -2,23 +2,12 @@ import { beforeEach, describe, expect, mock, test } from "bun:test"; import { billingEmailClaims, stripeCustomers, stripeSubscriptions } from "../db/schema"; -mock.module("../app/lib/stack", () => ({ - stackServerApp: null, -})); -mock.module("../db/client", () => ({ - cloudDb: () => { - throw new Error("test must inject a billing DB"); - }, -})); -mock.module("../services/asc/client", () => ({ - isAscConfigured: () => false, -})); -mock.module("../services/asc/testflight", () => ({ - removeTester: async () => {}, -})); -mock.module("../services/errors", () => ({ - captureAscError: () => {}, -})); +process.env.RESEND_API_KEY ??= "test-resend-key"; +process.env.CMUX_FEEDBACK_FROM_EMAIL ??= "feedback@example.com"; +process.env.CMUX_FEEDBACK_RATE_LIMIT_ID ??= "test-feedback-rate-limit"; +process.env.STACK_SECRET_SERVER_KEY ??= "test-stack-secret"; +process.env.NEXT_PUBLIC_STACK_PROJECT_ID ??= "test-stack-project"; +process.env.NEXT_PUBLIC_STACK_PUBLISHABLE_CLIENT_KEY ??= "test-stack-publishable"; const { applySubscriptionUpdate, recordCheckoutCompletion } = await import( "../services/billing/purchase" From d6e7ec5c8e2667432c1a1b57af67b046426164bf Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Wed, 8 Jul 2026 14:11:20 -0700 Subject: [PATCH 10/89] Block account deletion race windows --- .../AuthCoordinator+AccountDeletion.swift | 2 +- web/app/api/account/route.ts | 19 +++-- web/services/vms/auth.ts | 21 +++++- web/tests/account-route.test.ts | 74 ++++++++++++++----- web/tests/vm-route-auth.test.ts | 26 +++++++ 5 files changed, 116 insertions(+), 26 deletions(-) diff --git a/Packages/Shared/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AuthCoordinator+AccountDeletion.swift b/Packages/Shared/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AuthCoordinator+AccountDeletion.swift index 2e6f8cbe0991..ed5b0dbcb3a4 100644 --- a/Packages/Shared/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AuthCoordinator+AccountDeletion.swift +++ b/Packages/Shared/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AuthCoordinator+AccountDeletion.swift @@ -83,10 +83,10 @@ extension AuthCoordinator { /// Callers clear local shell/auth state through their normal sign-out owner /// after this succeeds so app-level teardown hooks run in the right order. public func deleteAccount() async throws { - let tokens = try await currentTokens() let apiBaseURL = apiBaseURL let timeout = timeouts.network try await runPhase(.accountDeletion, timeout: timeout) { + let tokens = try await self.currentTokens() try await AccountDeletionClient(apiBaseURL: apiBaseURL).deleteAccount( accessToken: tokens.accessToken, refreshToken: tokens.refreshToken diff --git a/web/app/api/account/route.ts b/web/app/api/account/route.ts index bf97bae4709a..793dfb16bbaf 100644 --- a/web/app/api/account/route.ts +++ b/web/app/api/account/route.ts @@ -26,7 +26,7 @@ import { } from "../../../db/schema"; import { ACTIVE_STRIPE_PRO_STATUSES, - syncProPlanMetadata, + type ProMetadataJson, type ProMetadataCustomer, } from "../../../services/billing/pro"; import { isStripeBillingConfigured, stripe } from "../../../services/billing/stripe"; @@ -44,7 +44,7 @@ type DeletableStackUser = { } & ProMetadataCustomer; export async function DELETE(request: Request): Promise { - const user = await verifyRequest(request, { allowCookie: false }); + const user = await verifyRequest(request, { allowCookie: false, allowDeletingAccount: true }); if (!user) return unauthorized(); const stackUser = await currentDeletableStackUser(request); @@ -54,7 +54,7 @@ export async function DELETE(request: Request): Promise { const destroyedVms = await destroyPersonalCloudVms(user.id); await deleteVaultObjectsForAccount(user.id); await resolveUserBillingForAccountDeletion(user.id); - await clearUserBillingEntitlementsForAccountDeletion(stackUser); + await markAccountDeletingAndClearBillingEntitlements(stackUser); // Delete cmux-owned data before the Stack user so a Stack-side failure does // not strand retained app data behind an account the user can no longer use. // These deletes are idempotent, so the same signed-in user can retry the @@ -70,6 +70,8 @@ export async function DELETE(request: Request): Promise { destroyedVms, }, 500); } + await deleteVaultObjectsForAccount(user.id); + await deleteCmuxOwnedAccountRows(user.id); return jsonResponse({ ok: true, destroyedVms }); } catch (error) { logAccountDeleteError("account.delete.failed", error); @@ -183,8 +185,15 @@ async function resolveUserBillingForAccountDeletion(userId: string): Promise { - await syncProPlanMetadata(user, false); +async function markAccountDeletingAndClearBillingEntitlements(user: DeletableStackUser): Promise { + const raw = user.clientReadOnlyMetadata; + const metadata: Record = + raw && typeof raw === "object" && !Array.isArray(raw) + ? { ...(raw as Record) } + : {}; + delete metadata.cmuxPlan; + metadata.cmuxAccountDeleting = true; + await user.update({ clientReadOnlyMetadata: metadata as ProMetadataJson }); } async function cancelStripeSubscriptionForAccountDeletion( diff --git a/web/services/vms/auth.ts b/web/services/vms/auth.ts index 1d1b18039a02..b0363b2a89e4 100644 --- a/web/services/vms/auth.ts +++ b/web/services/vms/auth.ts @@ -34,7 +34,11 @@ export type AuthedTeam = { */ export async function verifyRequest( request: Request, - options: { readonly requestedTeamId?: string | null; readonly allowCookie?: boolean } = {}, + options: { + readonly requestedTeamId?: string | null; + readonly allowCookie?: boolean; + readonly allowDeletingAccount?: boolean; + } = {}, ): Promise { if (!isStackConfigured()) { return null; @@ -71,8 +75,12 @@ export async function verifyRequest( async function authedUserFromStackUser( user: StackUserLike, - options: { readonly requestedTeamId?: string | null }, -): Promise { + options: { readonly requestedTeamId?: string | null; readonly allowDeletingAccount?: boolean }, +): Promise { + if (!options.allowDeletingAccount && isAccountDeletionInProgress(user.clientReadOnlyMetadata)) { + return null; + } + const selectedTeam = billingTeamFromUnknown(user.selectedTeam); const requestedTeamId = normalizedOptionalString(options.requestedTeamId); // When the selected team is enough, entitlements resolve from it before any @@ -111,6 +119,13 @@ async function authedUserFromStackUser( }; } +function isAccountDeletionInProgress(metadata: unknown): boolean { + return !!metadata && + typeof metadata === "object" && + !Array.isArray(metadata) && + (metadata as { cmuxAccountDeleting?: unknown }).cmuxAccountDeleting === true; +} + type StackUserLike = { readonly id: string; readonly displayName: string | null; diff --git a/web/tests/account-route.test.ts b/web/tests/account-route.test.ts index 544f436c1199..8f1d05c1af58 100644 --- a/web/tests/account-route.test.ts +++ b/web/tests/account-route.test.ts @@ -1,8 +1,24 @@ -import { afterEach, beforeEach, describe, expect, mock, test } from "bun:test"; +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, mock, test } from "bun:test"; import { cloudVmBillingGrants } from "../db/schema"; +process.env.RESEND_API_KEY ??= "test-resend-key"; +process.env.CMUX_FEEDBACK_FROM_EMAIL ??= "feedback@example.com"; +process.env.CMUX_FEEDBACK_RATE_LIMIT_ID ??= "test-feedback-rate-limit"; +process.env.STACK_SECRET_SERVER_KEY ??= "test-stack-secret"; +process.env.NEXT_PUBLIC_STACK_PROJECT_ID ??= "test-stack-project"; +process.env.NEXT_PUBLIC_STACK_PUBLISHABLE_CLIENT_KEY ??= "test-stack-publishable"; + const ACCOUNT_USER_ID = "account-user-1"; +const stackModule = await import("../app/lib/stack"); +const realGetStackServerApp = stackModule.getStackServerApp; +const realIsStackConfigured = stackModule.isStackConfigured; +const dbClientModule = await import("../db/client"); +const realCloudDb = dbClientModule.cloudDb; +const realCloseCloudDbForTests = dbClientModule.closeCloudDbForTests; +const stripeModule = await import("../services/billing/stripe"); +const realIsStripeBillingConfigured = stripeModule.isStripeBillingConfigured; +const realStripe = stripeModule.stripe; const storageModule = await import("../services/vault/storage"); const realDeleteObject = storageModule.deleteObject; const workflowsModule = await import("../services/vms/workflows"); @@ -73,6 +89,7 @@ let cancelledStripeSubscriptions: string[] = []; let deletedStripeCustomers: string[] = []; let stripeCancelError: unknown = null; let stripeDeleteCustomerError: unknown = null; +let useAccountRouteStubs = false; const originalConsoleError = console.error; const consoleError = mock(() => {}); @@ -109,14 +126,15 @@ const mockDb = { }; mock.module("../app/lib/stack", () => ({ - getStackServerApp: () => ({ getUser }), - isStackConfigured: () => true, - stackServerApp: { getUser }, + ...stackModule, + getStackServerApp: () => useAccountRouteStubs ? { getUser } : realGetStackServerApp(), + isStackConfigured: () => useAccountRouteStubs ? true : realIsStackConfigured(), })); mock.module("../db/client", () => ({ - cloudDb: () => mockDb, - closeCloudDbForTests: async () => {}, + ...dbClientModule, + cloudDb: () => useAccountRouteStubs ? mockDb : realCloudDb(), + closeCloudDbForTests: () => useAccountRouteStubs ? Promise.resolve() : realCloseCloudDbForTests(), })); mock.module("../services/vault/storage", () => ({ @@ -129,11 +147,16 @@ mock.module("../services/vault/storage", () => ({ })); mock.module("../services/billing/stripe", () => ({ - isStripeBillingConfigured: () => stripeConfigured, - stripe: () => ({ - subscriptions: { cancel: cancelSubscription }, - customers: { del: deleteCustomer }, - }), + ...stripeModule, + isStripeBillingConfigured: () => useAccountRouteStubs + ? stripeConfigured + : realIsStripeBillingConfigured(), + stripe: () => useAccountRouteStubs + ? { + subscriptions: { cancel: cancelSubscription }, + customers: { del: deleteCustomer }, + } + : realStripe(), })); mock.module("../services/vms/workflows", () => ({ @@ -157,6 +180,14 @@ mock.module("../services/vms/workflows", () => ({ const { DELETE } = await import("../app/api/account/route"); +beforeAll(() => { + useAccountRouteStubs = true; +}); + +afterAll(() => { + useAccountRouteStubs = false; +}); + beforeEach(() => { console.error = consoleError as typeof console.error; consoleError.mockClear(); @@ -217,7 +248,7 @@ describe("account deletion route", () => { expect(destroyVm).toHaveBeenCalledTimes(2); expect(destroyVm).toHaveBeenCalledWith({ userId: "account-user-1", providerVmId: "personal-vm-1" }); expect(destroyVm).toHaveBeenCalledWith({ userId: "account-user-1", providerVmId: "personal-vm-2" }); - expect(transaction).toHaveBeenCalledTimes(1); + expect(transaction).toHaveBeenCalledTimes(2); expect(deletedTableCount).toBeGreaterThan(10); expect(deletedTables).toContain(cloudVmBillingGrants); expect(deletedVaultObjects).toEqual([ @@ -231,10 +262,15 @@ describe("account deletion route", () => { expect(cancelledStripeSubscriptions).toEqual(["sub_user_active"]); expect(deletedStripeCustomers).toEqual(["cus_user"]); expect(updateStackUser).toHaveBeenCalledWith({ - clientReadOnlyMetadata: {}, + clientReadOnlyMetadata: { cmuxAccountDeleting: true }, }); expect(deleteStackUser).toHaveBeenCalledTimes(1); - expect(routeEvents).toEqual(["metadata-update", "transaction", "stack-delete"]); + expect(routeEvents).toEqual([ + "metadata-update", + "transaction", + "stack-delete", + "transaction", + ]); }); test("does not delete rows or Stack user when vault object cleanup fails", async () => { @@ -292,10 +328,14 @@ describe("account deletion route", () => { expect(transaction).toHaveBeenCalledTimes(1); expect(deletedTableCount).toBeGreaterThan(10); expect(updateStackUser).toHaveBeenCalledWith({ - clientReadOnlyMetadata: {}, + clientReadOnlyMetadata: { cmuxAccountDeleting: true }, }); expect(deleteStackUser).toHaveBeenCalledTimes(1); - expect(routeEvents).toEqual(["metadata-update", "transaction", "stack-delete"]); + expect(routeEvents).toEqual([ + "metadata-update", + "transaction", + "stack-delete", + ]); expect(consoleError).toHaveBeenCalledWith( "account.delete.stack_user_failed_after_data_delete", "Error: raw [redacted] leaked by upstream", @@ -320,7 +360,7 @@ describe("account deletion route", () => { expect(await response.json()).toEqual({ ok: true, destroyedVms: 2 }); expect(cancelledStripeSubscriptions).toEqual(["sub_user_active"]); expect(deletedStripeCustomers).toEqual(["cus_user"]); - expect(transaction).toHaveBeenCalledTimes(1); + expect(transaction).toHaveBeenCalledTimes(2); expect(deleteStackUser).toHaveBeenCalledTimes(1); }); diff --git a/web/tests/vm-route-auth.test.ts b/web/tests/vm-route-auth.test.ts index 365781bb5847..81d26de58b43 100644 --- a/web/tests/vm-route-auth.test.ts +++ b/web/tests/vm-route-auth.test.ts @@ -200,6 +200,32 @@ describe("VM REST auth", () => { expect(runVmWorkflow).not.toHaveBeenCalled(); }); + test("rejects account-deleting users before reaching workflows", async () => { + getUser.mockResolvedValue({ + id: "user-1", + displayName: null, + primaryEmail: "user@example.com", + clientReadOnlyMetadata: { cmuxAccountDeleting: true }, + selectedTeam: null, + listTeams: async () => [], + }); + + const response = await POST( + new Request("https://cmux.test/api/vm", { + method: "POST", + headers: { + authorization: "Bearer access-token", + "x-stack-refresh-token": "refresh-token", + }, + body: JSON.stringify({ provider: "freestyle" }), + }), + ); + + expect(response.status).toBe(401); + expect(await response.json()).toEqual({ error: "unauthorized" }); + expect(runVmWorkflow).not.toHaveBeenCalled(); + }); + test("rejects unauthenticated VM mutations before reaching workflows", async () => { const context = { params: Promise.resolve({ id: "provider-vm-1" }) }; const responses = await Promise.all([ From 7150941eed78e1c9641376d6ca76c18265b8b4b5 Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Wed, 8 Jul 2026 14:25:52 -0700 Subject: [PATCH 11/89] Close account deletion race windows --- .../AuthCoordinator+AccountDeletion.swift | 15 ++- .../MobileSettingsAccountSection.swift | 8 +- web/app/api/account/route.ts | 66 ++++++++- web/tests/account-route.test.ts | 126 +++++++++++++++++- 4 files changed, 196 insertions(+), 19 deletions(-) diff --git a/Packages/Shared/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AuthCoordinator+AccountDeletion.swift b/Packages/Shared/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AuthCoordinator+AccountDeletion.swift index ed5b0dbcb3a4..0c383b39a86e 100644 --- a/Packages/Shared/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AuthCoordinator+AccountDeletion.swift +++ b/Packages/Shared/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AuthCoordinator+AccountDeletion.swift @@ -4,6 +4,9 @@ public enum AccountDeletionRequestError: Error, Equatable { case invalidAPIBaseURL case unauthorized case stackDeleteIncomplete + /// The DELETE request reached the transport layer and timed out before a + /// definitive response. The backend may still complete account deletion, so + /// callers must treat the local session as no longer trustworthy. case timedOut case rejected(statusCode: Int) case invalidResponse @@ -85,12 +88,12 @@ extension AuthCoordinator { public func deleteAccount() async throws { let apiBaseURL = apiBaseURL let timeout = timeouts.network - try await runPhase(.accountDeletion, timeout: timeout) { - let tokens = try await self.currentTokens() - try await AccountDeletionClient(apiBaseURL: apiBaseURL).deleteAccount( - accessToken: tokens.accessToken, - refreshToken: tokens.refreshToken - ) + let tokens = try await runTokenTouchingPhase(.accountDeletion, timeout: timeout) { + try await self.currentTokens() } + try await AccountDeletionClient(apiBaseURL: apiBaseURL).deleteAccount( + accessToken: tokens.accessToken, + refreshToken: tokens.refreshToken + ) } } diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsAccountSection.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsAccountSection.swift index 44da9a91e6f5..b1c1de1901fc 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsAccountSection.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsAccountSection.swift @@ -105,7 +105,13 @@ struct MobileSettingsAccountSection: View { if case AccountDeletionRequestError.stackDeleteIncomplete = error { deleteAccountFailureKind = .stackDeleteIncomplete } else if case AccountDeletionRequestError.timedOut = error { - deleteAccountFailureKind = .timedOut + if let signOut { + signOut() + } else { + await authManager.signOut() + } + dismiss() + return } else if case AuthError.timedOut = error { deleteAccountFailureKind = .timedOut } else { diff --git a/web/app/api/account/route.ts b/web/app/api/account/route.ts index 793dfb16bbaf..0e798208d291 100644 --- a/web/app/api/account/route.ts +++ b/web/app/api/account/route.ts @@ -51,15 +51,15 @@ export async function DELETE(request: Request): Promise { if (!stackUser || stackUser.id !== user.id) return unauthorized(); try { + await markAccountDeletingAndClearBillingEntitlements(stackUser); const destroyedVms = await destroyPersonalCloudVms(user.id); await deleteVaultObjectsForAccount(user.id); await resolveUserBillingForAccountDeletion(user.id); - await markAccountDeletingAndClearBillingEntitlements(stackUser); // Delete cmux-owned data before the Stack user so a Stack-side failure does // not strand retained app data behind an account the user can no longer use. // These deletes are idempotent, so the same signed-in user can retry the // final Stack deletion when the distinct response below is returned. - await deleteCmuxOwnedAccountRows(user.id); + await deleteCollectedVaultObjects(await deleteCmuxOwnedAccountRows(user.id)); try { await stackUser.delete(); } catch (error) { @@ -71,7 +71,7 @@ export async function DELETE(request: Request): Promise { }, 500); } await deleteVaultObjectsForAccount(user.id); - await deleteCmuxOwnedAccountRows(user.id); + await deleteCollectedVaultObjects(await deleteCmuxOwnedAccountRows(user.id)); return jsonResponse({ ok: true, destroyedVms }); } catch (error) { logAccountDeleteError("account.delete.failed", error); @@ -152,6 +152,12 @@ async function deleteVaultObjectsForAccount(userId: string): Promise { } } +async function deleteCollectedVaultObjects(rows: DeletedAccountRows): Promise { + for (const objectKey of rows.vaultObjectKeys) { + await deleteObject(objectKey); + } +} + async function resolveUserBillingForAccountDeletion(userId: string): Promise { const db = cloudDb(); const activeSubscriptions = await db @@ -235,8 +241,13 @@ function isStripeAlreadyInDeletionTargetState(error: unknown, messagePatterns: r return messagePatterns.some((pattern) => pattern.test(message)); } -async function deleteCmuxOwnedAccountRows(userId: string): Promise { +type DeletedAccountRows = { + readonly vaultObjectKeys: readonly string[]; +}; + +async function deleteCmuxOwnedAccountRows(userId: string): Promise { const db = cloudDb(); + const vaultObjectKeys = new Set(); await db.transaction(async (tx) => { await tx.delete(deviceTokens).where(eq(deviceTokens.userId, userId)); await tx.delete(notificationSendEvents).where(eq(notificationSendEvents.userId, userId)); @@ -273,11 +284,52 @@ async function deleteCmuxOwnedAccountRows(userId: string): Promise { await tx.delete(devices).where(eq(devices.userId, userId)); - await tx.delete(vaultUploadGrants).where(eq(vaultUploadGrants.userId, userId)); - await tx.delete(vaultUploadTombstones).where(eq(vaultUploadTombstones.userId, userId)); + const deletedGrants = await tx + .delete(vaultUploadGrants) + .where(eq(vaultUploadGrants.userId, userId)) + .returning({ + objectKey: vaultUploadGrants.objectKey, + uploadObjectKey: vaultUploadGrants.uploadObjectKey, + }); + for (const grant of deletedGrants) { + vaultObjectKeys.add(grant.objectKey); + vaultObjectKeys.add(grant.uploadObjectKey); + } + + const deletedTombstones = await tx + .delete(vaultUploadTombstones) + .where(eq(vaultUploadTombstones.userId, userId)) + .returning({ + objectKey: vaultUploadTombstones.objectKey, + uploadObjectKey: vaultUploadTombstones.uploadObjectKey, + }); + for (const tombstone of deletedTombstones) { + vaultObjectKeys.add(tombstone.objectKey); + vaultObjectKeys.add(tombstone.uploadObjectKey); + } + await tx.delete(vaultCliAuthRequests).where(eq(vaultCliAuthRequests.userId, userId)); - await tx.delete(vaultSessions).where(eq(vaultSessions.userId, userId)); + + const sessions = await tx + .select({ id: vaultSessions.id }) + .from(vaultSessions) + .where(eq(vaultSessions.userId, userId)); + const sessionIds = sessions.map((session) => session.id); + if (sessionIds.length > 0) { + const deletedSnapshots = await tx + .delete(vaultSnapshots) + .where(inArray(vaultSnapshots.sessionId, sessionIds)) + .returning({ objectKey: vaultSnapshots.objectKey }); + for (const snapshot of deletedSnapshots) vaultObjectKeys.add(snapshot.objectKey); + } + + const deletedSessions = await tx + .delete(vaultSessions) + .where(eq(vaultSessions.userId, userId)) + .returning({ latestObjectKey: vaultSessions.latestObjectKey }); + for (const session of deletedSessions) vaultObjectKeys.add(session.latestObjectKey); }); + return { vaultObjectKeys: [...vaultObjectKeys] }; } function personalVmScope(userId: string) { diff --git a/web/tests/account-route.test.ts b/web/tests/account-route.test.ts index 8f1d05c1af58..e173cab14c83 100644 --- a/web/tests/account-route.test.ts +++ b/web/tests/account-route.test.ts @@ -1,6 +1,12 @@ import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, mock, test } from "bun:test"; -import { cloudVmBillingGrants } from "../db/schema"; +import { + cloudVmBillingGrants, + vaultSessions, + vaultSnapshots, + vaultUploadGrants, + vaultUploadTombstones, +} from "../db/schema"; process.env.RESEND_API_KEY ??= "test-resend-key"; process.env.CMUX_FEEDBACK_FROM_EMAIL ??= "feedback@example.com"; @@ -53,25 +59,30 @@ const destroyVm = mock((...args: unknown[]) => { const runVmWorkflow = mock(async (...args: unknown[]) => { const [program] = args as [WorkflowProgram]; if (program.kind === "listUserVms") { + routeEvents.push("list-vms"); return [ { providerVmId: "personal-vm-1" }, { providerVmId: "personal-vm-2" }, ]; } + routeEvents.push("destroy-vm"); return undefined; }); const deleteObject = mock(async (...args: unknown[]) => { const [objectKey] = args as [string]; + routeEvents.push("vault-delete"); deletedVaultObjects.push(objectKey); if (vaultDeleteError) throw vaultDeleteError; }); const cancelSubscription = mock(async (...args: unknown[]) => { const [subscriptionId] = args as [string]; + routeEvents.push("stripe-cancel"); cancelledStripeSubscriptions.push(subscriptionId); if (stripeCancelError) throw stripeCancelError; }); const deleteCustomer = mock(async (...args: unknown[]) => { const [customerId] = args as [string]; + routeEvents.push("stripe-delete-customer"); deletedStripeCustomers.push(customerId); if (stripeDeleteCustomerError) throw stripeDeleteCustomerError; }); @@ -89,6 +100,7 @@ let cancelledStripeSubscriptions: string[] = []; let deletedStripeCustomers: string[] = []; let stripeCancelError: unknown = null; let stripeDeleteCustomerError: unknown = null; +let transactionVaultRows: TransactionVaultRows = emptyTransactionVaultRows(); let useAccountRouteStubs = false; const originalConsoleError = console.error; const consoleError = mock(() => {}); @@ -98,21 +110,76 @@ type WorkflowProgram = | { readonly kind: "destroyVm"; readonly input: { readonly userId: string; readonly providerVmId: string } }; type MockTransaction = { - readonly delete: (table: unknown) => { readonly where: (condition: unknown) => Promise }; + readonly delete: (table: unknown) => { readonly where: (condition: unknown) => ReturningDeleteResult }; + readonly select: (shape: unknown) => { + readonly from: (table: unknown) => { readonly where: (condition: unknown) => Promise }; + }; +}; + +type ReturningDeleteResult = Promise & { + readonly returning: (shape: unknown) => Promise; }; +type TransactionVaultRows = { + readonly sessions: unknown[]; + readonly deletedSessions: unknown[]; + readonly deletedSnapshots: unknown[]; + readonly deletedGrants: unknown[]; + readonly deletedTombstones: unknown[]; +}; + +const selectTransactionRows = mock(() => ({ + from: (table: unknown) => ({ + where: async () => selectedRowsForTransactionTable(table), + }), +})); + const mockTransaction: MockTransaction = { delete: (table: unknown) => { deletedTables.push(table); deletedTableCount += 1; - return { where: async () => {} }; + return { + where: () => returningDeleteResult(table), + }; }, + select: selectTransactionRows, }; function nextSelectResult(): unknown[] { return selectResults.shift() ?? []; } +function emptyTransactionVaultRows(): TransactionVaultRows { + return { + sessions: [], + deletedSessions: [], + deletedSnapshots: [], + deletedGrants: [], + deletedTombstones: [], + }; +} + +function returningDeleteResult(table: unknown): ReturningDeleteResult { + const result = Promise.resolve() as ReturningDeleteResult; + Object.defineProperty(result, "returning", { + value: async () => deletedRowsForTransactionTable(table), + }); + return result; +} + +function selectedRowsForTransactionTable(table: unknown): unknown[] { + if (table === vaultSessions) return transactionVaultRows.sessions; + return []; +} + +function deletedRowsForTransactionTable(table: unknown): unknown[] { + if (table === vaultSessions) return transactionVaultRows.deletedSessions; + if (table === vaultSnapshots) return transactionVaultRows.deletedSnapshots; + if (table === vaultUploadGrants) return transactionVaultRows.deletedGrants; + if (table === vaultUploadTombstones) return transactionVaultRows.deletedTombstones; + return []; +} + const mockDb = { select: mock(() => ({ from: () => ({ @@ -202,6 +269,7 @@ beforeEach(() => { deleteObject.mockClear(); cancelSubscription.mockClear(); deleteCustomer.mockClear(); + selectTransactionRows.mockClear(); deletedTableCount = 0; deletedTables = []; routeEvents = []; @@ -215,6 +283,7 @@ beforeEach(() => { deletedStripeCustomers = []; stripeCancelError = null; stripeDeleteCustomerError = null; + transactionVaultRows = emptyTransactionVaultRows(); }); afterEach(() => { @@ -267,12 +336,57 @@ describe("account deletion route", () => { expect(deleteStackUser).toHaveBeenCalledTimes(1); expect(routeEvents).toEqual([ "metadata-update", + "list-vms", + "destroy-vm", + "destroy-vm", + "vault-delete", + "vault-delete", + "vault-delete", + "vault-delete", + "vault-delete", + "vault-delete", + "stripe-cancel", + "stripe-delete-customer", "transaction", "stack-delete", "transaction", ]); }); + test("deletes vault objects collected from rows removed during account cleanup", async () => { + transactionVaultRows = { + sessions: [{ id: "late-session" }], + deletedSessions: [{ latestObjectKey: "vault/u/account-user-1/late-latest.jsonl.zst" }], + deletedSnapshots: [{ objectKey: "vault/u/account-user-1/late-snapshot.jsonl.zst" }], + deletedGrants: [{ + objectKey: "vault/u/account-user-1/late-grant.jsonl.zst", + uploadObjectKey: "vault/uploads/late-grant", + }], + deletedTombstones: [{ + objectKey: "vault/u/account-user-1/late-tombstone.jsonl.zst", + uploadObjectKey: "vault/uploads/late-tombstone", + }], + }; + + const response = await DELETE(accountDeletionRequest()); + + expect(response.status).toBe(200); + expect(deletedVaultObjects).toEqual([ + "vault/u/account-user-1/late-grant.jsonl.zst", + "vault/uploads/late-grant", + "vault/u/account-user-1/late-tombstone.jsonl.zst", + "vault/uploads/late-tombstone", + "vault/u/account-user-1/late-snapshot.jsonl.zst", + "vault/u/account-user-1/late-latest.jsonl.zst", + "vault/u/account-user-1/late-grant.jsonl.zst", + "vault/uploads/late-grant", + "vault/u/account-user-1/late-tombstone.jsonl.zst", + "vault/uploads/late-tombstone", + "vault/u/account-user-1/late-snapshot.jsonl.zst", + "vault/u/account-user-1/late-latest.jsonl.zst", + ]); + }); + test("does not delete rows or Stack user when vault object cleanup fails", async () => { selectResults = [ [{ latestObjectKey: "vault/u/account-user-1/latest.jsonl.zst" }], @@ -333,6 +447,9 @@ describe("account deletion route", () => { expect(deleteStackUser).toHaveBeenCalledTimes(1); expect(routeEvents).toEqual([ "metadata-update", + "list-vms", + "destroy-vm", + "destroy-vm", "transaction", "stack-delete", ]); @@ -400,8 +517,7 @@ function stackUser(id = "account-user-1") { function isAccountDeletionVaultObject(objectKey: string): boolean { return objectKey.startsWith(`vault/u/${ACCOUNT_USER_ID}/`) || - objectKey === "vault/uploads/grant" || - objectKey === "vault/uploads/tombstone"; + objectKey.startsWith("vault/uploads/"); } function isAccountDeletionWorkflowProgram(program: unknown): boolean { From 02ce6e4c66c9844812d1d72d05b088ff678ca439 Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Wed, 8 Jul 2026 14:32:42 -0700 Subject: [PATCH 12/89] Treat post-delete cleanup as terminal --- web/app/api/account/route.ts | 12 ++++++++++-- web/tests/account-route.test.ts | 26 ++++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 2 deletions(-) diff --git a/web/app/api/account/route.ts b/web/app/api/account/route.ts index 0e798208d291..04e436b58c7a 100644 --- a/web/app/api/account/route.ts +++ b/web/app/api/account/route.ts @@ -70,8 +70,7 @@ export async function DELETE(request: Request): Promise { destroyedVms, }, 500); } - await deleteVaultObjectsForAccount(user.id); - await deleteCollectedVaultObjects(await deleteCmuxOwnedAccountRows(user.id)); + await finishPostStackAccountCleanup(user.id); return jsonResponse({ ok: true, destroyedVms }); } catch (error) { logAccountDeleteError("account.delete.failed", error); @@ -158,6 +157,15 @@ async function deleteCollectedVaultObjects(rows: DeletedAccountRows): Promise { + try { + await deleteVaultObjectsForAccount(userId); + await deleteCollectedVaultObjects(await deleteCmuxOwnedAccountRows(userId)); + } catch (error) { + logAccountDeleteError("account.delete.post_stack_cleanup_failed", error); + } +} + async function resolveUserBillingForAccountDeletion(userId: string): Promise { const db = cloudDb(); const activeSubscriptions = await db diff --git a/web/tests/account-route.test.ts b/web/tests/account-route.test.ts index e173cab14c83..ce8bc954ca77 100644 --- a/web/tests/account-route.test.ts +++ b/web/tests/account-route.test.ts @@ -73,6 +73,9 @@ const deleteObject = mock(async (...args: unknown[]) => { routeEvents.push("vault-delete"); deletedVaultObjects.push(objectKey); if (vaultDeleteError) throw vaultDeleteError; + if (postStackVaultDeleteError && routeEvents.includes("stack-delete")) { + throw postStackVaultDeleteError; + } }); const cancelSubscription = mock(async (...args: unknown[]) => { const [subscriptionId] = args as [string]; @@ -95,6 +98,7 @@ let stackUserIds: Array = []; let selectResults: unknown[][] = []; let deletedVaultObjects: string[] = []; let vaultDeleteError: unknown = null; +let postStackVaultDeleteError: unknown = null; let stripeConfigured = true; let cancelledStripeSubscriptions: string[] = []; let deletedStripeCustomers: string[] = []; @@ -278,6 +282,7 @@ beforeEach(() => { selectResults = [[], [], [], [], [], []]; deletedVaultObjects = []; vaultDeleteError = null; + postStackVaultDeleteError = null; stripeConfigured = true; cancelledStripeSubscriptions = []; deletedStripeCustomers = []; @@ -459,6 +464,27 @@ describe("account deletion route", () => { ); }); + test("returns success when post-Stack cleanup fails after the account is deleted", async () => { + postStackVaultDeleteError = new Error("post-delete vault unavailable"); + transactionVaultRows = { + sessions: [], + deletedSessions: [{ latestObjectKey: "vault/u/account-user-1/post-stack-latest.jsonl.zst" }], + deletedSnapshots: [], + deletedGrants: [], + deletedTombstones: [], + }; + + const response = await DELETE(accountDeletionRequest()); + + expect(response.status).toBe(200); + expect(await response.json()).toEqual({ ok: true, destroyedVms: 2 }); + expect(deleteStackUser).toHaveBeenCalledTimes(1); + expect(consoleError).toHaveBeenCalledWith( + "account.delete.post_stack_cleanup_failed", + "Error: post-delete vault unavailable", + ); + }); + test("continues when Stripe resources are already in the deletion target state", async () => { selectResults = [ [], From ffce0acc68fcb5d800255b717b94203997befb00 Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Wed, 8 Jul 2026 14:42:51 -0700 Subject: [PATCH 13/89] Handle out-of-order subscription updates --- web/services/billing/purchase.ts | 44 ++++++++++++++++++------------ web/tests/billing-purchase.test.ts | 38 +++++++++++++++++++++++--- 2 files changed, 60 insertions(+), 22 deletions(-) diff --git a/web/services/billing/purchase.ts b/web/services/billing/purchase.ts index 9e6b9a5cfb85..a755e84c05f6 100644 --- a/web/services/billing/purchase.ts +++ b/web/services/billing/purchase.ts @@ -185,23 +185,29 @@ export async function applySubscriptionUpdate( if (!stackUserId) return { skipped: true }; const isActive = isActiveStripeSubscriptionStatus(subscription.status); - const hasLocalBillingRecord = - mappedStackUserId === stackUserId || - (await userStripeSubscriptionExists(db, { - subscriptionId: subscription.id, - stackUserId, - })); - if (!hasLocalBillingRecord) return { skipped: true }; + const hasUserSubscription = await userStripeSubscriptionExists(db, { + subscriptionId: subscription.id, + stackUserId, + }); + if (!hasUserSubscription && mappedStackUserId !== stackUserId) return { skipped: true }; const user = await loadOptionalStackUser(stackUserId, dependencies.stackApp); if (!user) return { skipped: true }; - await updateExistingStripeSubscription(db, { - subscription, - customerId, - stackUserId, - scope: "user", - }); + if (hasUserSubscription) { + await updateExistingUserStripeSubscription(db, { + subscription, + customerId, + stackUserId, + }); + } else { + await upsertStripeSubscription(db, { + subscription, + customerId, + stackUserId, + scope: "user", + }); + } await syncProPlanMetadata(user, isActive); if (!isActive) { @@ -470,27 +476,29 @@ async function upsertStripeSubscription( }); } -async function updateExistingStripeSubscription( +async function updateExistingUserStripeSubscription( db: BillingDb, input: { subscription: Stripe.Subscription; customerId: string; stackUserId: string; - stackTeamId?: string | null; - scope: "user" | "team"; }, ): Promise { + const values = stripeSubscriptionValues({ + ...input, + scope: "user", + }); await db .update(stripeSubscriptions) .set({ - ...stripeSubscriptionValues(input), + ...values, updatedAt: sql`now()`, }) .where( and( eq(stripeSubscriptions.id, input.subscription.id), eq(stripeSubscriptions.stackUserId, input.stackUserId), - eq(stripeSubscriptions.scope, input.scope), + eq(stripeSubscriptions.scope, "user"), isNull(stripeSubscriptions.stackTeamId), ), ); diff --git a/web/tests/billing-purchase.test.ts b/web/tests/billing-purchase.test.ts index 19a7db4632f1..024dd658d61b 100644 --- a/web/tests/billing-purchase.test.ts +++ b/web/tests/billing-purchase.test.ts @@ -6,7 +6,7 @@ process.env.RESEND_API_KEY ??= "test-resend-key"; process.env.CMUX_FEEDBACK_FROM_EMAIL ??= "feedback@example.com"; process.env.CMUX_FEEDBACK_RATE_LIMIT_ID ??= "test-feedback-rate-limit"; process.env.STACK_SECRET_SERVER_KEY ??= "test-stack-secret"; -process.env.NEXT_PUBLIC_STACK_PROJECT_ID ??= "test-stack-project"; +process.env.NEXT_PUBLIC_STACK_PROJECT_ID ??= "00000000-0000-4000-8000-000000000000"; process.env.NEXT_PUBLIC_STACK_PUBLISHABLE_CLIENT_KEY ??= "test-stack-publishable"; const { applySubscriptionUpdate, recordCheckoutCompletion } = await import( @@ -476,7 +476,7 @@ describe("recordCheckoutCompletion", () => { clientReadOnlyMetadata: { cmuxPlan: "pro" }, update, }; - selectResults = [[{ stackUserId: "user_123" }]]; + selectResults = [[{ stackUserId: "user_123" }], [{ id: "sub_user" }]]; const result = await applySubscriptionUpdate( userSubscriptionUpdate({ status: "canceled" }) as never, @@ -503,7 +503,7 @@ describe("recordCheckoutCompletion", () => { clientReadOnlyMetadata: { cmuxPlan: "pro" }, update: mock(async () => undefined), }; - selectResults = [[{ stackUserId: "user_123" }]]; + selectResults = [[{ stackUserId: "user_123" }], [{ id: "sub_user" }]]; const result = await applySubscriptionUpdate( userSubscriptionUpdate({ status: "canceled" }) as never, @@ -539,7 +539,7 @@ describe("recordCheckoutCompletion", () => { clientReadOnlyMetadata: { cmuxPlan: "pro" }, update: mock(async () => undefined), }; - selectResults = [[{ stackUserId: "user_123" }]]; + selectResults = [[{ stackUserId: "user_123" }], [{ id: "sub_user" }]]; await applySubscriptionUpdate( userSubscriptionUpdate({ status: "canceled" }) as never, @@ -579,6 +579,36 @@ describe("recordCheckoutCompletion", () => { expect(updates.some((update) => update.table === stripeSubscriptions)).toBe(false); }); + test("creates a missing user subscription row when the customer mapping already exists", async () => { + const user = { + id: "user_123", + primaryEmail: "buyer@example.com", + clientReadOnlyMetadata: {}, + update: mock(async () => undefined), + }; + selectResults = [[{ stackUserId: "user_123" }], []]; + + const result = await applySubscriptionUpdate( + userSubscriptionUpdate({ status: "active" }) as never, + { + db: fakeDb() as never, + stackApp: { getUser: async () => user } as never, + }, + ); + + expect(result).toEqual({ scope: "user", stackUserId: "user_123", isActive: true }); + expect( + inserts.some( + (insert) => + insert.table === stripeSubscriptions && + insert.values.id === "sub_user" && + insert.values.scope === "user" && + insert.values.stackUserId === "user_123", + ), + ).toBe(true); + expect(updates.some((update) => update.table === stripeSubscriptions)).toBe(false); + }); + test("does not remove TestFlight access when a Team subscription lapses", async () => { const removeTester = mock(async () => undefined); const team = { From d5e097119b380766148f052b718c3c20a8ec33fb Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Wed, 8 Jul 2026 14:43:02 -0700 Subject: [PATCH 14/89] Order account deletion cleanup safely --- web/app/api/account/route.ts | 103 ++++++++++++++++++++------------ web/tests/account-route.test.ts | 36 +++++++---- 2 files changed, 90 insertions(+), 49 deletions(-) diff --git a/web/app/api/account/route.ts b/web/app/api/account/route.ts index 04e436b58c7a..6bcf8ae6e812 100644 --- a/web/app/api/account/route.ts +++ b/web/app/api/account/route.ts @@ -1,4 +1,4 @@ -import { and, eq, inArray, isNull, or } from "drizzle-orm"; +import { and, asc, eq, inArray, isNull, or } from "drizzle-orm"; import { getStackServerApp, isStackConfigured } from "../../lib/stack"; import { cloudDb } from "../../../db/client"; @@ -38,6 +38,8 @@ import { destroyVm, listUserVms, runVmWorkflow } from "../../../services/vms/wor export const runtime = "nodejs"; export const dynamic = "force-dynamic"; +const VAULT_OBJECT_DELETE_BATCH_SIZE = 100; + type DeletableStackUser = { readonly id: string; readonly delete: () => Promise; @@ -51,10 +53,10 @@ export async function DELETE(request: Request): Promise { if (!stackUser || stackUser.id !== user.id) return unauthorized(); try { + await resolveUserBillingForAccountDeletion(user.id); await markAccountDeletingAndClearBillingEntitlements(stackUser); const destroyedVms = await destroyPersonalCloudVms(user.id); await deleteVaultObjectsForAccount(user.id); - await resolveUserBillingForAccountDeletion(user.id); // Delete cmux-owned data before the Stack user so a Stack-side failure does // not strand retained app data behind an account the user can no longer use. // These deletes are idempotent, so the same signed-in user can retry the @@ -107,47 +109,70 @@ async function destroyPersonalCloudVms(userId: string): Promise { async function deleteVaultObjectsForAccount(userId: string): Promise { const db = cloudDb(); - const objectKeys = new Set(); - - const sessions = await db - .select({ latestObjectKey: vaultSessions.latestObjectKey }) - .from(vaultSessions) - .where(eq(vaultSessions.userId, userId)); - for (const session of sessions) objectKeys.add(session.latestObjectKey); - - const snapshots = await db - .select({ objectKey: vaultSnapshots.objectKey }) - .from(vaultSnapshots) - .innerJoin(vaultSessions, eq(vaultSnapshots.sessionId, vaultSessions.id)) - .where(eq(vaultSessions.userId, userId)); - for (const snapshot of snapshots) objectKeys.add(snapshot.objectKey); - - const grants = await db - .select({ - objectKey: vaultUploadGrants.objectKey, - uploadObjectKey: vaultUploadGrants.uploadObjectKey, - }) - .from(vaultUploadGrants) - .where(eq(vaultUploadGrants.userId, userId)); - for (const grant of grants) { - objectKeys.add(grant.objectKey); - objectKeys.add(grant.uploadObjectKey); + + for (let offset = 0; ; offset += VAULT_OBJECT_DELETE_BATCH_SIZE) { + const sessions = await db + .select({ latestObjectKey: vaultSessions.latestObjectKey }) + .from(vaultSessions) + .where(eq(vaultSessions.userId, userId)) + .orderBy(asc(vaultSessions.id)) + .limit(VAULT_OBJECT_DELETE_BATCH_SIZE) + .offset(offset); + if (sessions.length === 0) break; + for (const session of sessions) await deleteObject(session.latestObjectKey); + if (sessions.length < VAULT_OBJECT_DELETE_BATCH_SIZE) break; } - const tombstones = await db - .select({ - objectKey: vaultUploadTombstones.objectKey, - uploadObjectKey: vaultUploadTombstones.uploadObjectKey, - }) - .from(vaultUploadTombstones) - .where(eq(vaultUploadTombstones.userId, userId)); - for (const tombstone of tombstones) { - objectKeys.add(tombstone.objectKey); - objectKeys.add(tombstone.uploadObjectKey); + for (let offset = 0; ; offset += VAULT_OBJECT_DELETE_BATCH_SIZE) { + const snapshots = await db + .select({ objectKey: vaultSnapshots.objectKey }) + .from(vaultSnapshots) + .innerJoin(vaultSessions, eq(vaultSnapshots.sessionId, vaultSessions.id)) + .where(eq(vaultSessions.userId, userId)) + .orderBy(asc(vaultSnapshots.id)) + .limit(VAULT_OBJECT_DELETE_BATCH_SIZE) + .offset(offset); + if (snapshots.length === 0) break; + for (const snapshot of snapshots) await deleteObject(snapshot.objectKey); + if (snapshots.length < VAULT_OBJECT_DELETE_BATCH_SIZE) break; } - for (const objectKey of objectKeys) { - await deleteObject(objectKey); + for (let offset = 0; ; offset += VAULT_OBJECT_DELETE_BATCH_SIZE) { + const grants = await db + .select({ + objectKey: vaultUploadGrants.objectKey, + uploadObjectKey: vaultUploadGrants.uploadObjectKey, + }) + .from(vaultUploadGrants) + .where(eq(vaultUploadGrants.userId, userId)) + .orderBy(asc(vaultUploadGrants.id)) + .limit(VAULT_OBJECT_DELETE_BATCH_SIZE) + .offset(offset); + if (grants.length === 0) break; + for (const grant of grants) { + await deleteObject(grant.objectKey); + await deleteObject(grant.uploadObjectKey); + } + if (grants.length < VAULT_OBJECT_DELETE_BATCH_SIZE) break; + } + + for (let offset = 0; ; offset += VAULT_OBJECT_DELETE_BATCH_SIZE) { + const tombstones = await db + .select({ + objectKey: vaultUploadTombstones.objectKey, + uploadObjectKey: vaultUploadTombstones.uploadObjectKey, + }) + .from(vaultUploadTombstones) + .where(eq(vaultUploadTombstones.userId, userId)) + .orderBy(asc(vaultUploadTombstones.id)) + .limit(VAULT_OBJECT_DELETE_BATCH_SIZE) + .offset(offset); + if (tombstones.length === 0) break; + for (const tombstone of tombstones) { + await deleteObject(tombstone.objectKey); + await deleteObject(tombstone.uploadObjectKey); + } + if (tombstones.length < VAULT_OBJECT_DELETE_BATCH_SIZE) break; } } diff --git a/web/tests/account-route.test.ts b/web/tests/account-route.test.ts index ce8bc954ca77..e6d3eaba2eae 100644 --- a/web/tests/account-route.test.ts +++ b/web/tests/account-route.test.ts @@ -124,6 +124,12 @@ type ReturningDeleteResult = Promise & { readonly returning: (shape: unknown) => Promise; }; +type SelectResult = Promise & { + readonly orderBy: (order: unknown) => SelectResult; + readonly limit: (limit: number) => SelectResult; + readonly offset: (offset: number) => SelectResult; +}; + type TransactionVaultRows = { readonly sessions: unknown[]; readonly deletedSessions: unknown[]; @@ -153,6 +159,16 @@ function nextSelectResult(): unknown[] { return selectResults.shift() ?? []; } +function chainableSelectResult(rows: unknown[]): SelectResult { + const result = Promise.resolve(rows) as SelectResult; + Object.defineProperties(result, { + orderBy: { value: () => result }, + limit: { value: () => result }, + offset: { value: () => result }, + }); + return result; +} + function emptyTransactionVaultRows(): TransactionVaultRows { return { sessions: [], @@ -187,9 +203,9 @@ function deletedRowsForTransactionTable(table: unknown): unknown[] { const mockDb = { select: mock(() => ({ from: () => ({ - where: async () => nextSelectResult(), + where: () => chainableSelectResult(nextSelectResult()), innerJoin: () => ({ - where: async () => nextSelectResult(), + where: () => chainableSelectResult(nextSelectResult()), }), }), })), @@ -306,12 +322,12 @@ describe("account deletion route", () => { test("destroys personal VMs, deletes cmux rows, then deletes the Stack user", async () => { selectResults = [ + [{ id: "sub_user_active" }], + [{ id: "cus_user" }], [{ latestObjectKey: "vault/u/account-user-1/latest.jsonl.zst" }], [{ objectKey: "vault/u/account-user-1/snapshot.jsonl.zst" }], [{ objectKey: "vault/u/account-user-1/grant.jsonl.zst", uploadObjectKey: "vault/uploads/grant" }], [{ objectKey: "vault/u/account-user-1/tombstone.jsonl.zst", uploadObjectKey: "vault/uploads/tombstone" }], - [{ id: "sub_user_active" }], - [{ id: "cus_user" }], ]; const response = await DELETE(accountDeletionRequest()); @@ -340,6 +356,8 @@ describe("account deletion route", () => { }); expect(deleteStackUser).toHaveBeenCalledTimes(1); expect(routeEvents).toEqual([ + "stripe-cancel", + "stripe-delete-customer", "metadata-update", "list-vms", "destroy-vm", @@ -350,8 +368,6 @@ describe("account deletion route", () => { "vault-delete", "vault-delete", "vault-delete", - "stripe-cancel", - "stripe-delete-customer", "transaction", "stack-delete", "transaction", @@ -394,9 +410,9 @@ describe("account deletion route", () => { test("does not delete rows or Stack user when vault object cleanup fails", async () => { selectResults = [ - [{ latestObjectKey: "vault/u/account-user-1/latest.jsonl.zst" }], [], [], + [{ latestObjectKey: "vault/u/account-user-1/latest.jsonl.zst" }], [], [], [], @@ -413,11 +429,11 @@ describe("account deletion route", () => { test("does not delete rows or Stack user when active billing cleanup cannot run", async () => { selectResults = [ + [{ id: "sub_user_active" }], [], [], [], [], - [{ id: "sub_user_active" }], [], ]; stripeConfigured = false; @@ -487,12 +503,12 @@ describe("account deletion route", () => { test("continues when Stripe resources are already in the deletion target state", async () => { selectResults = [ + [{ id: "sub_user_active" }], + [{ id: "cus_user" }], [], [], [], [], - [{ id: "sub_user_active" }], - [{ id: "cus_user" }], ]; stripeCancelError = new Error("This subscription has already been canceled"); stripeDeleteCustomerError = { statusCode: 404, message: "No such customer" }; From f7c181c9a49320c1a468fff137dbf4c4581ad1cb Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Wed, 8 Jul 2026 14:45:59 -0700 Subject: [PATCH 15/89] Avoid subscription primary key updates --- web/services/billing/purchase.ts | 48 +++++++++++++++++++----------- web/tests/billing-purchase.test.ts | 11 ++++++- 2 files changed, 41 insertions(+), 18 deletions(-) diff --git a/web/services/billing/purchase.ts b/web/services/billing/purchase.ts index a755e84c05f6..0e7c818273b1 100644 --- a/web/services/billing/purchase.ts +++ b/web/services/billing/purchase.ts @@ -27,6 +27,14 @@ export const ACTIVE_STRIPE_SUBSCRIPTION_STATUSES = new Set([ type BillingDb = ReturnType; +type StripeSubscriptionValuesInput = { + subscription: Stripe.Subscription; + customerId: string; + stackUserId: string; + stackTeamId?: string | null; + scope: "user" | "team"; +}; + type StackBillingUser = { readonly id: string; readonly primaryEmail?: string | null; @@ -455,22 +463,17 @@ async function upsertTeamStripeCustomer( async function upsertStripeSubscription( db: BillingDb, - input: { - subscription: Stripe.Subscription; - customerId: string; - stackUserId: string; - stackTeamId?: string | null; - scope: "user" | "team"; - }, + input: StripeSubscriptionValuesInput, ): Promise { const values = stripeSubscriptionValues(input); + const updateValues = mutableStripeSubscriptionValues(input); await db .insert(stripeSubscriptions) .values(values) .onConflictDoUpdate({ target: stripeSubscriptions.id, set: { - ...values, + ...updateValues, updatedAt: sql`now()`, }, }); @@ -484,14 +487,14 @@ async function updateExistingUserStripeSubscription( stackUserId: string; }, ): Promise { - const values = stripeSubscriptionValues({ + const updateValues = mutableStripeSubscriptionValues({ ...input, scope: "user", }); await db .update(stripeSubscriptions) .set({ - ...values, + ...updateValues, updatedAt: sql`now()`, }) .where( @@ -504,13 +507,7 @@ async function updateExistingUserStripeSubscription( ); } -function stripeSubscriptionValues(input: { - subscription: Stripe.Subscription; - customerId: string; - stackUserId: string; - stackTeamId?: string | null; - scope: "user" | "team"; -}) { +function stripeSubscriptionValues(input: StripeSubscriptionValuesInput) { const { subscription } = input; const plan = input.scope === "team" ? TEAM_PLAN_ID : PRO_PLAN_ID; return { @@ -529,6 +526,23 @@ function stripeSubscriptionValues(input: { }; } +function mutableStripeSubscriptionValues(input: StripeSubscriptionValuesInput) { + const values = stripeSubscriptionValues(input); + return { + customerId: values.customerId, + stackUserId: values.stackUserId, + stackTeamId: values.stackTeamId, + status: values.status, + priceId: values.priceId, + plan: values.plan, + seats: values.seats, + scope: values.scope, + currentPeriodEnd: values.currentPeriodEnd, + cancelAtPeriodEnd: values.cancelAtPeriodEnd, + raw: values.raw, + }; +} + async function userStripeSubscriptionExists( db: BillingDb, input: { subscriptionId: string; stackUserId: string }, diff --git a/web/tests/billing-purchase.test.ts b/web/tests/billing-purchase.test.ts index 024dd658d61b..b1686ea72e1e 100644 --- a/web/tests/billing-purchase.test.ts +++ b/web/tests/billing-purchase.test.ts @@ -15,6 +15,7 @@ const { applySubscriptionUpdate, recordCheckoutCompletion } = await import( const inserts: Array<{ table: unknown; values: Record }> = []; const updates: Array<{ table: unknown; values: Record }> = []; +const upsertUpdates: Array<{ table: unknown; values: Record }> = []; const insertErrorsByTable = new Map(); let selectResults: unknown[][] = []; @@ -24,7 +25,8 @@ function fakeDb() { values: (values: Record) => { inserts.push({ table, values }); return { - onConflictDoUpdate: () => { + onConflictDoUpdate: (options?: { set?: Record }) => { + upsertUpdates.push({ table, values: options?.set ?? {} }); const error = insertErrorsByTable.get(table); if (error) return Promise.reject(error); return Promise.resolve(); @@ -126,6 +128,7 @@ describe("recordCheckoutCompletion", () => { beforeEach(() => { inserts.length = 0; updates.length = 0; + upsertUpdates.length = 0; insertErrorsByTable.clear(); selectResults = []; }); @@ -492,6 +495,9 @@ describe("recordCheckoutCompletion", () => { expect(result).toEqual({ scope: "user", stackUserId: "user_123", isActive: false }); expect(removeTester).toHaveBeenCalledWith("buyer@example.com"); + expect(updates.find((entry) => entry.table === stripeSubscriptions)?.values).not.toHaveProperty( + "id", + ); expect(update).toHaveBeenCalledWith({ clientReadOnlyMetadata: {} }); }); @@ -606,6 +612,9 @@ describe("recordCheckoutCompletion", () => { insert.values.stackUserId === "user_123", ), ).toBe(true); + expect( + upsertUpdates.find((entry) => entry.table === stripeSubscriptions)?.values, + ).not.toHaveProperty("id"); expect(updates.some((update) => update.table === stripeSubscriptions)).toBe(false); }); From a5f36a8d1c38223b30210df1734871dc52e6ff21 Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Wed, 8 Jul 2026 14:55:27 -0700 Subject: [PATCH 16/89] Attempt all account deletion VM teardown --- web/app/api/account/route.ts | 11 ++++++++++- web/tests/account-route.test.ts | 29 ++++++++++++++++++++++++++++- 2 files changed, 38 insertions(+), 2 deletions(-) diff --git a/web/app/api/account/route.ts b/web/app/api/account/route.ts index 6bcf8ae6e812..70497e0f86c5 100644 --- a/web/app/api/account/route.ts +++ b/web/app/api/account/route.ts @@ -101,8 +101,17 @@ async function currentDeletableStackUser(request: Request): Promise { const vms = await runVmWorkflow(listUserVms(userId)); + const failures: unknown[] = []; for (const vm of vms) { - await runVmWorkflow(destroyVm({ userId, providerVmId: vm.providerVmId })); + try { + await runVmWorkflow(destroyVm({ userId, providerVmId: vm.providerVmId })); + } catch (error) { + failures.push(error); + logAccountDeleteError("account.delete.vm_destroy_failed", error); + } + } + if (failures.length > 0) { + throw new Error(`Failed to destroy ${failures.length} personal cloud VM${failures.length === 1 ? "" : "s"}`); } return vms.length; } diff --git a/web/tests/account-route.test.ts b/web/tests/account-route.test.ts index e6d3eaba2eae..3d83662a7e6a 100644 --- a/web/tests/account-route.test.ts +++ b/web/tests/account-route.test.ts @@ -12,7 +12,7 @@ process.env.RESEND_API_KEY ??= "test-resend-key"; process.env.CMUX_FEEDBACK_FROM_EMAIL ??= "feedback@example.com"; process.env.CMUX_FEEDBACK_RATE_LIMIT_ID ??= "test-feedback-rate-limit"; process.env.STACK_SECRET_SERVER_KEY ??= "test-stack-secret"; -process.env.NEXT_PUBLIC_STACK_PROJECT_ID ??= "test-stack-project"; +process.env.NEXT_PUBLIC_STACK_PROJECT_ID ??= "00000000-0000-4000-8000-000000000000"; process.env.NEXT_PUBLIC_STACK_PUBLISHABLE_CLIENT_KEY ??= "test-stack-publishable"; const ACCOUNT_USER_ID = "account-user-1"; @@ -66,6 +66,9 @@ const runVmWorkflow = mock(async (...args: unknown[]) => { ]; } routeEvents.push("destroy-vm"); + if (destroyVmFailureProviderIds.has(program.input.providerVmId)) { + throw new Error(`destroy failed for ${program.input.providerVmId}`); + } return undefined; }); const deleteObject = mock(async (...args: unknown[]) => { @@ -105,6 +108,7 @@ let deletedStripeCustomers: string[] = []; let stripeCancelError: unknown = null; let stripeDeleteCustomerError: unknown = null; let transactionVaultRows: TransactionVaultRows = emptyTransactionVaultRows(); +let destroyVmFailureProviderIds = new Set(); let useAccountRouteStubs = false; const originalConsoleError = console.error; const consoleError = mock(() => {}); @@ -305,6 +309,7 @@ beforeEach(() => { stripeCancelError = null; stripeDeleteCustomerError = null; transactionVaultRows = emptyTransactionVaultRows(); + destroyVmFailureProviderIds = new Set(); }); afterEach(() => { @@ -427,6 +432,28 @@ describe("account deletion route", () => { expect(deleteStackUser).not.toHaveBeenCalled(); }); + test("attempts every personal VM before failing account deletion on VM teardown errors", async () => { + destroyVmFailureProviderIds = new Set(["personal-vm-1"]); + + const response = await DELETE(accountDeletionRequest()); + + expect(response.status).toBe(500); + expect(await response.json()).toEqual({ error: "account_delete_failed" }); + expect(destroyVm).toHaveBeenCalledTimes(2); + expect(destroyVm).toHaveBeenCalledWith({ userId: "account-user-1", providerVmId: "personal-vm-1" }); + expect(destroyVm).toHaveBeenCalledWith({ userId: "account-user-1", providerVmId: "personal-vm-2" }); + expect(transaction).not.toHaveBeenCalled(); + expect(deleteStackUser).not.toHaveBeenCalled(); + expect(consoleError).toHaveBeenCalledWith( + "account.delete.vm_destroy_failed", + "Error: destroy failed for personal-vm-1", + ); + expect(consoleError).toHaveBeenCalledWith( + "account.delete.failed", + "Error: Failed to destroy 1 personal cloud VM", + ); + }); + test("does not delete rows or Stack user when active billing cleanup cannot run", async () => { selectResults = [ [{ id: "sub_user_active" }], From b9fa4a2ca507b556cd2c776936f53bf0f8c439cd Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Wed, 8 Jul 2026 14:59:49 -0700 Subject: [PATCH 17/89] Delete vault account data in bounded batches --- web/app/api/account/route.ts | 113 +++++++----------------- web/tests/account-route.test.ts | 151 +++++++++++--------------------- 2 files changed, 83 insertions(+), 181 deletions(-) diff --git a/web/app/api/account/route.ts b/web/app/api/account/route.ts index 70497e0f86c5..85acf67a9f24 100644 --- a/web/app/api/account/route.ts +++ b/web/app/api/account/route.ts @@ -56,12 +56,12 @@ export async function DELETE(request: Request): Promise { await resolveUserBillingForAccountDeletion(user.id); await markAccountDeletingAndClearBillingEntitlements(stackUser); const destroyedVms = await destroyPersonalCloudVms(user.id); - await deleteVaultObjectsForAccount(user.id); + await deleteVaultRowsAndObjectsForAccount(user.id); // Delete cmux-owned data before the Stack user so a Stack-side failure does // not strand retained app data behind an account the user can no longer use. // These deletes are idempotent, so the same signed-in user can retry the // final Stack deletion when the distinct response below is returned. - await deleteCollectedVaultObjects(await deleteCmuxOwnedAccountRows(user.id)); + await deleteCmuxOwnedAccountRows(user.id); try { await stackUser.delete(); } catch (error) { @@ -116,85 +116,83 @@ async function destroyPersonalCloudVms(userId: string): Promise { return vms.length; } -async function deleteVaultObjectsForAccount(userId: string): Promise { +async function deleteVaultRowsAndObjectsForAccount(userId: string): Promise { const db = cloudDb(); - for (let offset = 0; ; offset += VAULT_OBJECT_DELETE_BATCH_SIZE) { - const sessions = await db - .select({ latestObjectKey: vaultSessions.latestObjectKey }) - .from(vaultSessions) - .where(eq(vaultSessions.userId, userId)) - .orderBy(asc(vaultSessions.id)) - .limit(VAULT_OBJECT_DELETE_BATCH_SIZE) - .offset(offset); - if (sessions.length === 0) break; - for (const session of sessions) await deleteObject(session.latestObjectKey); - if (sessions.length < VAULT_OBJECT_DELETE_BATCH_SIZE) break; - } - - for (let offset = 0; ; offset += VAULT_OBJECT_DELETE_BATCH_SIZE) { + for (;;) { const snapshots = await db - .select({ objectKey: vaultSnapshots.objectKey }) + .select({ id: vaultSnapshots.id, objectKey: vaultSnapshots.objectKey }) .from(vaultSnapshots) .innerJoin(vaultSessions, eq(vaultSnapshots.sessionId, vaultSessions.id)) .where(eq(vaultSessions.userId, userId)) .orderBy(asc(vaultSnapshots.id)) - .limit(VAULT_OBJECT_DELETE_BATCH_SIZE) - .offset(offset); + .limit(VAULT_OBJECT_DELETE_BATCH_SIZE); if (snapshots.length === 0) break; for (const snapshot of snapshots) await deleteObject(snapshot.objectKey); + await db.delete(vaultSnapshots).where(inArray(vaultSnapshots.id, snapshots.map((snapshot) => snapshot.id))); if (snapshots.length < VAULT_OBJECT_DELETE_BATCH_SIZE) break; } - for (let offset = 0; ; offset += VAULT_OBJECT_DELETE_BATCH_SIZE) { + for (;;) { const grants = await db .select({ + id: vaultUploadGrants.id, objectKey: vaultUploadGrants.objectKey, uploadObjectKey: vaultUploadGrants.uploadObjectKey, }) .from(vaultUploadGrants) .where(eq(vaultUploadGrants.userId, userId)) .orderBy(asc(vaultUploadGrants.id)) - .limit(VAULT_OBJECT_DELETE_BATCH_SIZE) - .offset(offset); + .limit(VAULT_OBJECT_DELETE_BATCH_SIZE); if (grants.length === 0) break; for (const grant of grants) { await deleteObject(grant.objectKey); await deleteObject(grant.uploadObjectKey); } + await db.delete(vaultUploadGrants).where(inArray(vaultUploadGrants.id, grants.map((grant) => grant.id))); if (grants.length < VAULT_OBJECT_DELETE_BATCH_SIZE) break; } - for (let offset = 0; ; offset += VAULT_OBJECT_DELETE_BATCH_SIZE) { + for (;;) { const tombstones = await db .select({ + id: vaultUploadTombstones.id, objectKey: vaultUploadTombstones.objectKey, uploadObjectKey: vaultUploadTombstones.uploadObjectKey, }) .from(vaultUploadTombstones) .where(eq(vaultUploadTombstones.userId, userId)) .orderBy(asc(vaultUploadTombstones.id)) - .limit(VAULT_OBJECT_DELETE_BATCH_SIZE) - .offset(offset); + .limit(VAULT_OBJECT_DELETE_BATCH_SIZE); if (tombstones.length === 0) break; for (const tombstone of tombstones) { await deleteObject(tombstone.objectKey); await deleteObject(tombstone.uploadObjectKey); } + await db + .delete(vaultUploadTombstones) + .where(inArray(vaultUploadTombstones.id, tombstones.map((tombstone) => tombstone.id))); if (tombstones.length < VAULT_OBJECT_DELETE_BATCH_SIZE) break; } -} -async function deleteCollectedVaultObjects(rows: DeletedAccountRows): Promise { - for (const objectKey of rows.vaultObjectKeys) { - await deleteObject(objectKey); + for (;;) { + const sessions = await db + .select({ id: vaultSessions.id, latestObjectKey: vaultSessions.latestObjectKey }) + .from(vaultSessions) + .where(eq(vaultSessions.userId, userId)) + .orderBy(asc(vaultSessions.id)) + .limit(VAULT_OBJECT_DELETE_BATCH_SIZE); + if (sessions.length === 0) break; + for (const session of sessions) await deleteObject(session.latestObjectKey); + await db.delete(vaultSessions).where(inArray(vaultSessions.id, sessions.map((session) => session.id))); + if (sessions.length < VAULT_OBJECT_DELETE_BATCH_SIZE) break; } } async function finishPostStackAccountCleanup(userId: string): Promise { try { - await deleteVaultObjectsForAccount(userId); - await deleteCollectedVaultObjects(await deleteCmuxOwnedAccountRows(userId)); + await deleteVaultRowsAndObjectsForAccount(userId); + await deleteCmuxOwnedAccountRows(userId); } catch (error) { logAccountDeleteError("account.delete.post_stack_cleanup_failed", error); } @@ -283,13 +281,8 @@ function isStripeAlreadyInDeletionTargetState(error: unknown, messagePatterns: r return messagePatterns.some((pattern) => pattern.test(message)); } -type DeletedAccountRows = { - readonly vaultObjectKeys: readonly string[]; -}; - -async function deleteCmuxOwnedAccountRows(userId: string): Promise { +async function deleteCmuxOwnedAccountRows(userId: string): Promise { const db = cloudDb(); - const vaultObjectKeys = new Set(); await db.transaction(async (tx) => { await tx.delete(deviceTokens).where(eq(deviceTokens.userId, userId)); await tx.delete(notificationSendEvents).where(eq(notificationSendEvents.userId, userId)); @@ -326,52 +319,8 @@ async function deleteCmuxOwnedAccountRows(userId: string): Promise session.id); - if (sessionIds.length > 0) { - const deletedSnapshots = await tx - .delete(vaultSnapshots) - .where(inArray(vaultSnapshots.sessionId, sessionIds)) - .returning({ objectKey: vaultSnapshots.objectKey }); - for (const snapshot of deletedSnapshots) vaultObjectKeys.add(snapshot.objectKey); - } - - const deletedSessions = await tx - .delete(vaultSessions) - .where(eq(vaultSessions.userId, userId)) - .returning({ latestObjectKey: vaultSessions.latestObjectKey }); - for (const session of deletedSessions) vaultObjectKeys.add(session.latestObjectKey); }); - return { vaultObjectKeys: [...vaultObjectKeys] }; } function personalVmScope(userId: string) { diff --git a/web/tests/account-route.test.ts b/web/tests/account-route.test.ts index 3d83662a7e6a..2619a013530f 100644 --- a/web/tests/account-route.test.ts +++ b/web/tests/account-route.test.ts @@ -45,6 +45,13 @@ const transaction = mock(async (...args: unknown[]) => { routeEvents.push("transaction"); await callback(mockTransaction); }); +const deleteRows = mock((table: unknown) => { + deletedTables.push(table); + deletedTableCount += 1; + return { + where: async () => {}, + }; +}); const listUserVms = mock((...args: unknown[]) => { const [userId] = args as [string]; return { kind: "listUserVms" as const, userId }; @@ -107,7 +114,6 @@ let cancelledStripeSubscriptions: string[] = []; let deletedStripeCustomers: string[] = []; let stripeCancelError: unknown = null; let stripeDeleteCustomerError: unknown = null; -let transactionVaultRows: TransactionVaultRows = emptyTransactionVaultRows(); let destroyVmFailureProviderIds = new Set(); let useAccountRouteStubs = false; const originalConsoleError = console.error; @@ -118,14 +124,7 @@ type WorkflowProgram = | { readonly kind: "destroyVm"; readonly input: { readonly userId: string; readonly providerVmId: string } }; type MockTransaction = { - readonly delete: (table: unknown) => { readonly where: (condition: unknown) => ReturningDeleteResult }; - readonly select: (shape: unknown) => { - readonly from: (table: unknown) => { readonly where: (condition: unknown) => Promise }; - }; -}; - -type ReturningDeleteResult = Promise & { - readonly returning: (shape: unknown) => Promise; + readonly delete: (table: unknown) => { readonly where: (condition: unknown) => Promise }; }; type SelectResult = Promise & { @@ -134,29 +133,8 @@ type SelectResult = Promise & { readonly offset: (offset: number) => SelectResult; }; -type TransactionVaultRows = { - readonly sessions: unknown[]; - readonly deletedSessions: unknown[]; - readonly deletedSnapshots: unknown[]; - readonly deletedGrants: unknown[]; - readonly deletedTombstones: unknown[]; -}; - -const selectTransactionRows = mock(() => ({ - from: (table: unknown) => ({ - where: async () => selectedRowsForTransactionTable(table), - }), -})); - const mockTransaction: MockTransaction = { - delete: (table: unknown) => { - deletedTables.push(table); - deletedTableCount += 1; - return { - where: () => returningDeleteResult(table), - }; - }, - select: selectTransactionRows, + delete: deleteRows, }; function nextSelectResult(): unknown[] { @@ -173,37 +151,6 @@ function chainableSelectResult(rows: unknown[]): SelectResult { return result; } -function emptyTransactionVaultRows(): TransactionVaultRows { - return { - sessions: [], - deletedSessions: [], - deletedSnapshots: [], - deletedGrants: [], - deletedTombstones: [], - }; -} - -function returningDeleteResult(table: unknown): ReturningDeleteResult { - const result = Promise.resolve() as ReturningDeleteResult; - Object.defineProperty(result, "returning", { - value: async () => deletedRowsForTransactionTable(table), - }); - return result; -} - -function selectedRowsForTransactionTable(table: unknown): unknown[] { - if (table === vaultSessions) return transactionVaultRows.sessions; - return []; -} - -function deletedRowsForTransactionTable(table: unknown): unknown[] { - if (table === vaultSessions) return transactionVaultRows.deletedSessions; - if (table === vaultSnapshots) return transactionVaultRows.deletedSnapshots; - if (table === vaultUploadGrants) return transactionVaultRows.deletedGrants; - if (table === vaultUploadTombstones) return transactionVaultRows.deletedTombstones; - return []; -} - const mockDb = { select: mock(() => ({ from: () => ({ @@ -213,6 +160,7 @@ const mockDb = { }), }), })), + delete: deleteRows, transaction, }; @@ -286,6 +234,7 @@ beforeEach(() => { updateStackUser.mockClear(); getUser.mockClear(); transaction.mockClear(); + deleteRows.mockClear(); mockDb.select.mockClear(); listUserVms.mockClear(); destroyVm.mockClear(); @@ -293,7 +242,6 @@ beforeEach(() => { deleteObject.mockClear(); cancelSubscription.mockClear(); deleteCustomer.mockClear(); - selectTransactionRows.mockClear(); deletedTableCount = 0; deletedTables = []; routeEvents = []; @@ -308,7 +256,6 @@ beforeEach(() => { deletedStripeCustomers = []; stripeCancelError = null; stripeDeleteCustomerError = null; - transactionVaultRows = emptyTransactionVaultRows(); destroyVmFailureProviderIds = new Set(); }); @@ -329,10 +276,10 @@ describe("account deletion route", () => { selectResults = [ [{ id: "sub_user_active" }], [{ id: "cus_user" }], - [{ latestObjectKey: "vault/u/account-user-1/latest.jsonl.zst" }], [{ objectKey: "vault/u/account-user-1/snapshot.jsonl.zst" }], [{ objectKey: "vault/u/account-user-1/grant.jsonl.zst", uploadObjectKey: "vault/uploads/grant" }], [{ objectKey: "vault/u/account-user-1/tombstone.jsonl.zst", uploadObjectKey: "vault/uploads/tombstone" }], + [{ latestObjectKey: "vault/u/account-user-1/latest.jsonl.zst" }], ]; const response = await DELETE(accountDeletionRequest()); @@ -347,12 +294,12 @@ describe("account deletion route", () => { expect(deletedTableCount).toBeGreaterThan(10); expect(deletedTables).toContain(cloudVmBillingGrants); expect(deletedVaultObjects).toEqual([ - "vault/u/account-user-1/latest.jsonl.zst", "vault/u/account-user-1/snapshot.jsonl.zst", "vault/u/account-user-1/grant.jsonl.zst", "vault/uploads/grant", "vault/u/account-user-1/tombstone.jsonl.zst", "vault/uploads/tombstone", + "vault/u/account-user-1/latest.jsonl.zst", ]); expect(cancelledStripeSubscriptions).toEqual(["sub_user_active"]); expect(deletedStripeCustomers).toEqual(["cus_user"]); @@ -379,45 +326,46 @@ describe("account deletion route", () => { ]); }); - test("deletes vault objects collected from rows removed during account cleanup", async () => { - transactionVaultRows = { - sessions: [{ id: "late-session" }], - deletedSessions: [{ latestObjectKey: "vault/u/account-user-1/late-latest.jsonl.zst" }], - deletedSnapshots: [{ objectKey: "vault/u/account-user-1/late-snapshot.jsonl.zst" }], - deletedGrants: [{ - objectKey: "vault/u/account-user-1/late-grant.jsonl.zst", - uploadObjectKey: "vault/uploads/late-grant", - }], - deletedTombstones: [{ - objectKey: "vault/u/account-user-1/late-tombstone.jsonl.zst", - uploadObjectKey: "vault/uploads/late-tombstone", + test("deletes vault rows in bounded batches after their objects are removed", async () => { + selectResults = [ + [], + [], + [ + { id: "snapshot-1", objectKey: "vault/u/account-user-1/snapshot-1.jsonl.zst" }, + { id: "snapshot-2", objectKey: "vault/u/account-user-1/snapshot-2.jsonl.zst" }, + ], + [{ id: "grant-1", objectKey: "vault/u/account-user-1/grant.jsonl.zst", uploadObjectKey: "vault/uploads/grant" }], + [{ + id: "tombstone-1", + objectKey: "vault/u/account-user-1/tombstone.jsonl.zst", + uploadObjectKey: "vault/uploads/tombstone", }], - }; + [{ id: "session-1", latestObjectKey: "vault/u/account-user-1/latest.jsonl.zst" }], + ]; const response = await DELETE(accountDeletionRequest()); expect(response.status).toBe(200); expect(deletedVaultObjects).toEqual([ - "vault/u/account-user-1/late-grant.jsonl.zst", - "vault/uploads/late-grant", - "vault/u/account-user-1/late-tombstone.jsonl.zst", - "vault/uploads/late-tombstone", - "vault/u/account-user-1/late-snapshot.jsonl.zst", - "vault/u/account-user-1/late-latest.jsonl.zst", - "vault/u/account-user-1/late-grant.jsonl.zst", - "vault/uploads/late-grant", - "vault/u/account-user-1/late-tombstone.jsonl.zst", - "vault/uploads/late-tombstone", - "vault/u/account-user-1/late-snapshot.jsonl.zst", - "vault/u/account-user-1/late-latest.jsonl.zst", + "vault/u/account-user-1/snapshot-1.jsonl.zst", + "vault/u/account-user-1/snapshot-2.jsonl.zst", + "vault/u/account-user-1/grant.jsonl.zst", + "vault/uploads/grant", + "vault/u/account-user-1/tombstone.jsonl.zst", + "vault/uploads/tombstone", + "vault/u/account-user-1/latest.jsonl.zst", ]); + expect(deletedTables).toContain(vaultSnapshots); + expect(deletedTables).toContain(vaultUploadGrants); + expect(deletedTables).toContain(vaultUploadTombstones); + expect(deletedTables).toContain(vaultSessions); }); test("does not delete rows or Stack user when vault object cleanup fails", async () => { selectResults = [ [], [], - [{ latestObjectKey: "vault/u/account-user-1/latest.jsonl.zst" }], + [{ id: "snapshot-1", objectKey: "vault/u/account-user-1/snapshot.jsonl.zst" }], [], [], [], @@ -509,13 +457,18 @@ describe("account deletion route", () => { test("returns success when post-Stack cleanup fails after the account is deleted", async () => { postStackVaultDeleteError = new Error("post-delete vault unavailable"); - transactionVaultRows = { - sessions: [], - deletedSessions: [{ latestObjectKey: "vault/u/account-user-1/post-stack-latest.jsonl.zst" }], - deletedSnapshots: [], - deletedGrants: [], - deletedTombstones: [], - }; + selectResults = [ + [], + [], + [], + [], + [], + [], + [], + [], + [], + [{ id: "post-stack-session", latestObjectKey: "vault/u/account-user-1/post-stack-latest.jsonl.zst" }], + ]; const response = await DELETE(accountDeletionRequest()); From b79f6185b8a71a2e55b171305c22b7c976480240 Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Wed, 8 Jul 2026 19:49:09 -0700 Subject: [PATCH 18/89] Scrub retained user references during account deletion --- web/app/api/account/route.ts | 28 ++++++++++++++++------- web/tests/account-route.test.ts | 40 +++++++++++++++++++++++++++++++++ 2 files changed, 60 insertions(+), 8 deletions(-) diff --git a/web/app/api/account/route.ts b/web/app/api/account/route.ts index 85acf67a9f24..c6b94318bfdd 100644 --- a/web/app/api/account/route.ts +++ b/web/app/api/account/route.ts @@ -5,6 +5,7 @@ import { cloudDb } from "../../../db/client"; import { billingEmailClaims, cloudVmBaseEvents, + cloudVmBaseGenerations, cloudVmBases, cloudVmBillingGrants, cloudVmLeases, @@ -39,6 +40,7 @@ export const runtime = "nodejs"; export const dynamic = "force-dynamic"; const VAULT_OBJECT_DELETE_BATCH_SIZE = 100; +const DELETED_ACCOUNT_ACTOR_ID = "deleted-account"; type DeletableStackUser = { readonly id: string; @@ -284,6 +286,7 @@ function isStripeAlreadyInDeletionTargetState(error: unknown, messagePatterns: r async function deleteCmuxOwnedAccountRows(userId: string): Promise { const db = cloudDb(); await db.transaction(async (tx) => { + const now = new Date(); await tx.delete(deviceTokens).where(eq(deviceTokens.userId, userId)); await tx.delete(notificationSendEvents).where(eq(notificationSendEvents.userId, userId)); @@ -307,7 +310,7 @@ async function deleteCmuxOwnedAccountRows(userId: string): Promise { )); await tx.delete(cloudVmNotificationDeliveries).where(eq(cloudVmNotificationDeliveries.userId, userId)); await tx.delete(cloudVmNotificationEvents).where(eq(cloudVmNotificationEvents.userId, userId)); - await tx.delete(cloudVmUsageEvents).where(personalUsageScope(userId)); + await tx.delete(cloudVmUsageEvents).where(eq(cloudVmUsageEvents.userId, userId)); await tx.delete(cloudVmLeases).where(eq(cloudVmLeases.userId, userId)); await tx.delete(cloudVmSessions).where(eq(cloudVmSessions.userId, userId)); await tx.delete(cloudVms).where(personalVmScope(userId)); @@ -316,6 +319,22 @@ async function deleteCmuxOwnedAccountRows(userId: string): Promise { eq(cloudVmBases.scopeType, "user"), eq(cloudVmBases.scopeId, userId), )); + await tx + .update(cloudVms) + .set({ userId: DELETED_ACCOUNT_ACTOR_ID, updatedAt: now }) + .where(eq(cloudVms.userId, userId)); + await tx + .update(cloudVmBases) + .set({ createdByUserId: DELETED_ACCOUNT_ACTOR_ID, updatedAt: now }) + .where(eq(cloudVmBases.createdByUserId, userId)); + await tx + .update(cloudVmBases) + .set({ lastOpenedByUserId: null, updatedAt: now }) + .where(eq(cloudVmBases.lastOpenedByUserId, userId)); + await tx + .update(cloudVmBaseGenerations) + .set({ createdByUserId: DELETED_ACCOUNT_ACTOR_ID, updatedAt: now }) + .where(eq(cloudVmBaseGenerations.createdByUserId, userId)); await tx.delete(devices).where(eq(devices.userId, userId)); @@ -330,13 +349,6 @@ function personalVmScope(userId: string) { ); } -function personalUsageScope(userId: string) { - return and( - eq(cloudVmUsageEvents.userId, userId), - or(isNull(cloudVmUsageEvents.billingTeamId), eq(cloudVmUsageEvents.billingTeamId, userId)), - ); -} - const SENSITIVE_ERROR_TEXT = /(Bearer\s+\S+|eyJ[A-Za-z0-9_-]*\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+|srt_[A-Za-z0-9_-]+|sk-[A-Za-z0-9_-]{8,})/g; diff --git a/web/tests/account-route.test.ts b/web/tests/account-route.test.ts index 2619a013530f..44b0211fc7ff 100644 --- a/web/tests/account-route.test.ts +++ b/web/tests/account-route.test.ts @@ -1,7 +1,10 @@ import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, mock, test } from "bun:test"; import { + cloudVmBaseGenerations, + cloudVmBases, cloudVmBillingGrants, + cloudVms, vaultSessions, vaultSnapshots, vaultUploadGrants, @@ -52,6 +55,14 @@ const deleteRows = mock((table: unknown) => { where: async () => {}, }; }); +const updateRows = mock((table: unknown) => ({ + set: (values: unknown) => { + updatedRows.push({ table, values }); + return { + where: async () => {}, + }; + }, +})); const listUserVms = mock((...args: unknown[]) => { const [userId] = args as [string]; return { kind: "listUserVms" as const, userId }; @@ -102,6 +113,7 @@ const deleteCustomer = mock(async (...args: unknown[]) => { let deletedTableCount = 0; let deletedTables: unknown[] = []; +let updatedRows: Array<{ readonly table: unknown; readonly values: unknown }> = []; let routeEvents: string[] = []; let stackDeleteError: unknown = null; let stackUserIds: Array = []; @@ -125,6 +137,9 @@ type WorkflowProgram = type MockTransaction = { readonly delete: (table: unknown) => { readonly where: (condition: unknown) => Promise }; + readonly update: (table: unknown) => { + readonly set: (values: unknown) => { readonly where: (condition: unknown) => Promise }; + }; }; type SelectResult = Promise & { @@ -135,6 +150,7 @@ type SelectResult = Promise & { const mockTransaction: MockTransaction = { delete: deleteRows, + update: updateRows, }; function nextSelectResult(): unknown[] { @@ -235,6 +251,7 @@ beforeEach(() => { getUser.mockClear(); transaction.mockClear(); deleteRows.mockClear(); + updateRows.mockClear(); mockDb.select.mockClear(); listUserVms.mockClear(); destroyVm.mockClear(); @@ -244,6 +261,7 @@ beforeEach(() => { deleteCustomer.mockClear(); deletedTableCount = 0; deletedTables = []; + updatedRows = []; routeEvents = []; stackDeleteError = null; stackUserIds = []; @@ -293,6 +311,22 @@ describe("account deletion route", () => { expect(transaction).toHaveBeenCalledTimes(2); expect(deletedTableCount).toBeGreaterThan(10); expect(deletedTables).toContain(cloudVmBillingGrants); + expect(updatedRows.map(({ table, values }) => ({ + table, + values: stripUpdatedAt(values), + }))).toEqual([ + { table: cloudVms, values: { userId: "deleted-account" } }, + { table: cloudVmBases, values: { createdByUserId: "deleted-account" } }, + { table: cloudVmBases, values: { lastOpenedByUserId: null } }, + { table: cloudVmBaseGenerations, values: { createdByUserId: "deleted-account" } }, + { table: cloudVms, values: { userId: "deleted-account" } }, + { table: cloudVmBases, values: { createdByUserId: "deleted-account" } }, + { table: cloudVmBases, values: { lastOpenedByUserId: null } }, + { table: cloudVmBaseGenerations, values: { createdByUserId: "deleted-account" } }, + ]); + for (const update of updatedRows) { + expect((update.values as { readonly updatedAt?: unknown }).updatedAt).toBeInstanceOf(Date); + } expect(deletedVaultObjects).toEqual([ "vault/u/account-user-1/snapshot.jsonl.zst", "vault/u/account-user-1/grant.jsonl.zst", @@ -537,6 +571,12 @@ function stackUser(id = "account-user-1") { }; } +function stripUpdatedAt(values: unknown): Record { + const copy = { ...(values as Record) }; + delete copy.updatedAt; + return copy; +} + function isAccountDeletionVaultObject(objectKey: string): boolean { return objectKey.startsWith(`vault/u/${ACCOUNT_USER_ID}/`) || objectKey.startsWith("vault/uploads/"); From 63646bc04b90436e2178de528f0c7176db36bfd1 Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Wed, 8 Jul 2026 19:56:49 -0700 Subject: [PATCH 19/89] Parallelize vault object cleanup during account deletion --- web/app/api/account/route.ts | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/web/app/api/account/route.ts b/web/app/api/account/route.ts index c6b94318bfdd..da175afc3dcf 100644 --- a/web/app/api/account/route.ts +++ b/web/app/api/account/route.ts @@ -130,7 +130,7 @@ async function deleteVaultRowsAndObjectsForAccount(userId: string): Promise deleteObject(snapshot.objectKey))); await db.delete(vaultSnapshots).where(inArray(vaultSnapshots.id, snapshots.map((snapshot) => snapshot.id))); if (snapshots.length < VAULT_OBJECT_DELETE_BATCH_SIZE) break; } @@ -147,10 +147,10 @@ async function deleteVaultRowsAndObjectsForAccount(userId: string): Promise [ + deleteObject(grant.objectKey), + deleteObject(grant.uploadObjectKey), + ])); await db.delete(vaultUploadGrants).where(inArray(vaultUploadGrants.id, grants.map((grant) => grant.id))); if (grants.length < VAULT_OBJECT_DELETE_BATCH_SIZE) break; } @@ -167,10 +167,10 @@ async function deleteVaultRowsAndObjectsForAccount(userId: string): Promise [ + deleteObject(tombstone.objectKey), + deleteObject(tombstone.uploadObjectKey), + ])); await db .delete(vaultUploadTombstones) .where(inArray(vaultUploadTombstones.id, tombstones.map((tombstone) => tombstone.id))); @@ -185,7 +185,7 @@ async function deleteVaultRowsAndObjectsForAccount(userId: string): Promise deleteObject(session.latestObjectKey))); await db.delete(vaultSessions).where(inArray(vaultSessions.id, sessions.map((session) => session.id))); if (sessions.length < VAULT_OBJECT_DELETE_BATCH_SIZE) break; } From 8d68a590a628c06a55d93c8497cadad71c1b9a40 Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Wed, 8 Jul 2026 19:58:11 -0700 Subject: [PATCH 20/89] Scrub team billing owner references on account deletion --- web/app/api/account/route.ts | 17 ++++++++++++++++- web/tests/account-route.test.ts | 6 ++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/web/app/api/account/route.ts b/web/app/api/account/route.ts index da175afc3dcf..0fad55586569 100644 --- a/web/app/api/account/route.ts +++ b/web/app/api/account/route.ts @@ -1,4 +1,4 @@ -import { and, asc, eq, inArray, isNull, or } from "drizzle-orm"; +import { and, asc, eq, inArray, isNotNull, isNull, or } from "drizzle-orm"; import { getStackServerApp, isStackConfigured } from "../../lib/stack"; import { cloudDb } from "../../../db/client"; @@ -303,6 +303,21 @@ async function deleteCmuxOwnedAccountRows(userId: string): Promise { eq(stripeCustomers.stackUserId, userId), isNull(stripeCustomers.stackTeamId), )); + await tx + .update(stripeSubscriptions) + .set({ stackUserId: DELETED_ACCOUNT_ACTOR_ID, updatedAt: now }) + .where(and( + eq(stripeSubscriptions.stackUserId, userId), + eq(stripeSubscriptions.scope, "team"), + isNotNull(stripeSubscriptions.stackTeamId), + )); + await tx + .update(stripeCustomers) + .set({ stackUserId: DELETED_ACCOUNT_ACTOR_ID, updatedAt: now }) + .where(and( + eq(stripeCustomers.stackUserId, userId), + isNotNull(stripeCustomers.stackTeamId), + )); await tx.delete(cloudVmBillingGrants).where(and( eq(cloudVmBillingGrants.billingCustomerType, "user"), diff --git a/web/tests/account-route.test.ts b/web/tests/account-route.test.ts index 44b0211fc7ff..87607085da08 100644 --- a/web/tests/account-route.test.ts +++ b/web/tests/account-route.test.ts @@ -5,6 +5,8 @@ import { cloudVmBases, cloudVmBillingGrants, cloudVms, + stripeCustomers, + stripeSubscriptions, vaultSessions, vaultSnapshots, vaultUploadGrants, @@ -315,10 +317,14 @@ describe("account deletion route", () => { table, values: stripUpdatedAt(values), }))).toEqual([ + { table: stripeSubscriptions, values: { stackUserId: "deleted-account" } }, + { table: stripeCustomers, values: { stackUserId: "deleted-account" } }, { table: cloudVms, values: { userId: "deleted-account" } }, { table: cloudVmBases, values: { createdByUserId: "deleted-account" } }, { table: cloudVmBases, values: { lastOpenedByUserId: null } }, { table: cloudVmBaseGenerations, values: { createdByUserId: "deleted-account" } }, + { table: stripeSubscriptions, values: { stackUserId: "deleted-account" } }, + { table: stripeCustomers, values: { stackUserId: "deleted-account" } }, { table: cloudVms, values: { userId: "deleted-account" } }, { table: cloudVmBases, values: { createdByUserId: "deleted-account" } }, { table: cloudVmBases, values: { lastOpenedByUserId: null } }, From 49ed19090d6c2921bec925f81bcc841dc797bfa5 Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Wed, 8 Jul 2026 21:08:03 -0700 Subject: [PATCH 21/89] Restore deletion metadata on cleanup failure --- web/app/api/account/route.ts | 31 ++++++++++++++++++++++++++----- web/tests/account-route.test.ts | 14 ++++++++++++++ 2 files changed, 40 insertions(+), 5 deletions(-) diff --git a/web/app/api/account/route.ts b/web/app/api/account/route.ts index 0fad55586569..6f092db34d64 100644 --- a/web/app/api/account/route.ts +++ b/web/app/api/account/route.ts @@ -54,9 +54,13 @@ export async function DELETE(request: Request): Promise { const stackUser = await currentDeletableStackUser(request); if (!stackUser || stackUser.id !== user.id) return unauthorized(); + const originalStackMetadata = stackUser.clientReadOnlyMetadata; + let stackMetadataMarked = false; + let cmuxOwnedRowsDeleted = false; try { await resolveUserBillingForAccountDeletion(user.id); await markAccountDeletingAndClearBillingEntitlements(stackUser); + stackMetadataMarked = true; const destroyedVms = await destroyPersonalCloudVms(user.id); await deleteVaultRowsAndObjectsForAccount(user.id); // Delete cmux-owned data before the Stack user so a Stack-side failure does @@ -64,6 +68,7 @@ export async function DELETE(request: Request): Promise { // These deletes are idempotent, so the same signed-in user can retry the // final Stack deletion when the distinct response below is returned. await deleteCmuxOwnedAccountRows(user.id); + cmuxOwnedRowsDeleted = true; try { await stackUser.delete(); } catch (error) { @@ -77,6 +82,9 @@ export async function DELETE(request: Request): Promise { await finishPostStackAccountCleanup(user.id); return jsonResponse({ ok: true, destroyedVms }); } catch (error) { + if (stackMetadataMarked && !cmuxOwnedRowsDeleted) { + await restoreStackMetadataAfterAccountDeletionFailure(stackUser, originalStackMetadata); + } logAccountDeleteError("account.delete.failed", error); return jsonResponse({ error: "account_delete_failed" }, 500); } @@ -234,16 +242,29 @@ async function resolveUserBillingForAccountDeletion(userId: string): Promise { - const raw = user.clientReadOnlyMetadata; - const metadata: Record = - raw && typeof raw === "object" && !Array.isArray(raw) - ? { ...(raw as Record) } - : {}; + const metadata = stackMetadataRecord(user.clientReadOnlyMetadata); delete metadata.cmuxPlan; metadata.cmuxAccountDeleting = true; await user.update({ clientReadOnlyMetadata: metadata as ProMetadataJson }); } +async function restoreStackMetadataAfterAccountDeletionFailure( + user: DeletableStackUser, + metadata: unknown, +): Promise { + try { + await user.update({ clientReadOnlyMetadata: stackMetadataRecord(metadata) as ProMetadataJson }); + } catch (error) { + logAccountDeleteError("account.delete.metadata_restore_failed", error); + } +} + +function stackMetadataRecord(metadata: unknown): Record { + return metadata && typeof metadata === "object" && !Array.isArray(metadata) + ? { ...(metadata as Record) } + : {}; +} + async function cancelStripeSubscriptionForAccountDeletion( client: ReturnType, subscriptionId: string, diff --git a/web/tests/account-route.test.ts b/web/tests/account-route.test.ts index 87607085da08..1d3c821f9fdb 100644 --- a/web/tests/account-route.test.ts +++ b/web/tests/account-route.test.ts @@ -418,6 +418,12 @@ describe("account deletion route", () => { expect(await response.json()).toEqual({ error: "account_delete_failed" }); expect(transaction).not.toHaveBeenCalled(); expect(deleteStackUser).not.toHaveBeenCalled(); + expect(updateStackUser).toHaveBeenNthCalledWith(1, { + clientReadOnlyMetadata: { cmuxAccountDeleting: true }, + }); + expect(updateStackUser).toHaveBeenNthCalledWith(2, { + clientReadOnlyMetadata: { cmuxPlan: "pro" }, + }); }); test("attempts every personal VM before failing account deletion on VM teardown errors", async () => { @@ -432,6 +438,12 @@ describe("account deletion route", () => { expect(destroyVm).toHaveBeenCalledWith({ userId: "account-user-1", providerVmId: "personal-vm-2" }); expect(transaction).not.toHaveBeenCalled(); expect(deleteStackUser).not.toHaveBeenCalled(); + expect(updateStackUser).toHaveBeenNthCalledWith(1, { + clientReadOnlyMetadata: { cmuxAccountDeleting: true }, + }); + expect(updateStackUser).toHaveBeenNthCalledWith(2, { + clientReadOnlyMetadata: { cmuxPlan: "pro" }, + }); expect(consoleError).toHaveBeenCalledWith( "account.delete.vm_destroy_failed", "Error: destroy failed for personal-vm-1", @@ -460,6 +472,7 @@ describe("account deletion route", () => { expect(cancelSubscription).not.toHaveBeenCalled(); expect(transaction).not.toHaveBeenCalled(); expect(deleteStackUser).not.toHaveBeenCalled(); + expect(updateStackUser).not.toHaveBeenCalled(); }); test("returns a retryable partial-failure response when Stack deletion fails after cmux data deletion", async () => { @@ -480,6 +493,7 @@ describe("account deletion route", () => { expect(updateStackUser).toHaveBeenCalledWith({ clientReadOnlyMetadata: { cmuxAccountDeleting: true }, }); + expect(updateStackUser).toHaveBeenCalledTimes(1); expect(deleteStackUser).toHaveBeenCalledTimes(1); expect(routeEvents).toEqual([ "metadata-update", From dba2b2812e7c8f3edfb56d479a75e407ba060cb3 Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Wed, 8 Jul 2026 22:26:00 -0700 Subject: [PATCH 22/89] Close account deletion privacy gaps --- .../AuthCoordinator+AccountDeletion.swift | 25 +++++- .../AccountDeletionClientTests.swift | 28 +++++++ .../MobileSettingsAccountSection.swift | 8 ++ web/app/api/account/route.ts | 25 +++++- web/services/billing/pro.ts | 1 + web/tests/account-route.test.ts | 80 ++++++++++++++++++- web/tests/billing-pro.test.ts | 12 +++ 7 files changed, 176 insertions(+), 3 deletions(-) diff --git a/Packages/Shared/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AuthCoordinator+AccountDeletion.swift b/Packages/Shared/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AuthCoordinator+AccountDeletion.swift index 0c383b39a86e..5a6fac349cc9 100644 --- a/Packages/Shared/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AuthCoordinator+AccountDeletion.swift +++ b/Packages/Shared/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AuthCoordinator+AccountDeletion.swift @@ -8,6 +8,10 @@ public enum AccountDeletionRequestError: Error, Equatable { /// definitive response. The backend may still complete account deletion, so /// callers must treat the local session as no longer trustworthy. case timedOut + /// The DELETE request reached the network/server boundary but did not return + /// a definitive account-deletion result. The backend may still complete + /// deletion after this client gives up. + case completionUnknown case rejected(statusCode: Int) case invalidResponse } @@ -53,6 +57,8 @@ struct AccountDeletionClient: Sendable { (data, response) = try await load(request) } catch let error as URLError where error.code == .timedOut { throw AccountDeletionRequestError.timedOut + } catch is URLError { + throw AccountDeletionRequestError.completionUnknown } guard let httpResponse = response as? HTTPURLResponse else { throw AccountDeletionRequestError.invalidResponse @@ -66,6 +72,9 @@ struct AccountDeletionClient: Sendable { if Self.isRetryablePartialDeletionError(Self.errorCode(in: data)) { throw AccountDeletionRequestError.stackDeleteIncomplete } + if Self.isAmbiguousHTTPStatus(httpResponse.statusCode) { + throw AccountDeletionRequestError.completionUnknown + } throw AccountDeletionRequestError.rejected(statusCode: httpResponse.statusCode) } } @@ -78,6 +87,10 @@ struct AccountDeletionClient: Sendable { code == "account_delete_retryable" || code == "account_stack_delete_failed_after_data_delete" } + + private static func isAmbiguousHTTPStatus(_ statusCode: Int) -> Bool { + statusCode == 408 || statusCode >= 500 + } } extension AuthCoordinator { @@ -91,9 +104,19 @@ extension AuthCoordinator { let tokens = try await runTokenTouchingPhase(.accountDeletion, timeout: timeout) { try await self.currentTokens() } - try await AccountDeletionClient(apiBaseURL: apiBaseURL).deleteAccount( + try await AccountDeletionClient( + apiBaseURL: apiBaseURL, + requestTimeout: timeout.urlRequestTimeoutInterval + ).deleteAccount( accessToken: tokens.accessToken, refreshToken: tokens.refreshToken ) } } + +private extension Duration { + var urlRequestTimeoutInterval: TimeInterval { + let value = components + return TimeInterval(value.seconds) + TimeInterval(value.attoseconds) / 1_000_000_000_000_000_000 + } +} diff --git a/Packages/Shared/CmuxAuthRuntime/Tests/CmuxAuthRuntimeTests/AccountDeletionClientTests.swift b/Packages/Shared/CmuxAuthRuntime/Tests/CmuxAuthRuntimeTests/AccountDeletionClientTests.swift index 70178fd0b966..7eeb47330ab1 100644 --- a/Packages/Shared/CmuxAuthRuntime/Tests/CmuxAuthRuntimeTests/AccountDeletionClientTests.swift +++ b/Packages/Shared/CmuxAuthRuntime/Tests/CmuxAuthRuntimeTests/AccountDeletionClientTests.swift @@ -91,6 +91,34 @@ struct AccountDeletionClientTests { try await client.deleteAccount(accessToken: "access-token", refreshToken: "refresh-token") } } + + @Test func deleteAccountMapsAmbiguousTransportFailure() async { + let client = AccountDeletionClient(apiBaseURL: "https://cmux.test") { _ in + throw URLError(.networkConnectionLost) + } + + await #expect(throws: AccountDeletionRequestError.completionUnknown) { + try await client.deleteAccount(accessToken: "access-token", refreshToken: "refresh-token") + } + } + + @Test func deleteAccountMapsAmbiguousServerFailure() async { + let client = AccountDeletionClient(apiBaseURL: "https://cmux.test") { request in + ( + Data(), + HTTPURLResponse( + url: request.url!, + statusCode: 504, + httpVersion: nil, + headerFields: nil + )! + ) + } + + await #expect(throws: AccountDeletionRequestError.completionUnknown) { + try await client.deleteAccount(accessToken: "access-token", refreshToken: "refresh-token") + } + } } actor RecordedAccountDeletionRequest { diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsAccountSection.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsAccountSection.swift index b1c1de1901fc..effd7bfb01b4 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsAccountSection.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsAccountSection.swift @@ -112,6 +112,14 @@ struct MobileSettingsAccountSection: View { } dismiss() return + } else if case AccountDeletionRequestError.completionUnknown = error { + if let signOut { + signOut() + } else { + await authManager.signOut() + } + dismiss() + return } else if case AuthError.timedOut = error { deleteAccountFailureKind = .timedOut } else { diff --git a/web/app/api/account/route.ts b/web/app/api/account/route.ts index 6f092db34d64..e442e5aa6fdb 100644 --- a/web/app/api/account/route.ts +++ b/web/app/api/account/route.ts @@ -19,6 +19,7 @@ import { notificationSendEvents, stripeCustomers, stripeSubscriptions, + subrouterTenants, vaultCliAuthRequests, vaultSessions, vaultSnapshots, @@ -31,6 +32,10 @@ import { type ProMetadataCustomer, } from "../../../services/billing/pro"; import { isStripeBillingConfigured, stripe } from "../../../services/billing/stripe"; +import { + createSubrouterClientFromEnv, + SubrouterClientError, +} from "../../../services/subrouter/client"; import { deleteObject } from "../../../services/vault/storage"; import { unauthorized, verifyRequest } from "../../../services/vms/auth"; import { jsonResponse } from "../../../services/vms/routeHelpers"; @@ -63,6 +68,7 @@ export async function DELETE(request: Request): Promise { stackMetadataMarked = true; const destroyedVms = await destroyPersonalCloudVms(user.id); await deleteVaultRowsAndObjectsForAccount(user.id); + await deletePersonalSubrouterTenant(user.id); // Delete cmux-owned data before the Stack user so a Stack-side failure does // not strand retained app data behind an account the user can no longer use. // These deletes are idempotent, so the same signed-in user can retry the @@ -372,12 +378,29 @@ async function deleteCmuxOwnedAccountRows(userId: string): Promise { .set({ createdByUserId: DELETED_ACCOUNT_ACTOR_ID, updatedAt: now }) .where(eq(cloudVmBaseGenerations.createdByUserId, userId)); - await tx.delete(devices).where(eq(devices.userId, userId)); + await tx.delete(devices).where(eq(devices.teamId, userId)); await tx.delete(vaultCliAuthRequests).where(eq(vaultCliAuthRequests.userId, userId)); }); } +async function deletePersonalSubrouterTenant(userId: string): Promise { + const db = cloudDb(); + const [tenant] = await db + .select({ tenantId: subrouterTenants.tenantId }) + .from(subrouterTenants) + .where(eq(subrouterTenants.teamId, userId)) + .limit(1); + if (!tenant) return; + + try { + await createSubrouterClientFromEnv().revokeTenant(tenant.tenantId); + } catch (error) { + if (!(error instanceof SubrouterClientError && error.status === 404)) throw error; + } + await db.delete(subrouterTenants).where(eq(subrouterTenants.teamId, userId)); +} + function personalVmScope(userId: string) { return and( eq(cloudVms.userId, userId), diff --git a/web/services/billing/pro.ts b/web/services/billing/pro.ts index 21fd51c649f3..00be0c52ba7f 100644 --- a/web/services/billing/pro.ts +++ b/web/services/billing/pro.ts @@ -106,6 +106,7 @@ export async function syncProPlanMetadata( raw && typeof raw === "object" && !Array.isArray(raw) ? { ...(raw as Record) } : {}; + if (metadata.cmuxAccountDeleting === true) return; const current = metadata.cmuxPlan; if (isPro) { diff --git a/web/tests/account-route.test.ts b/web/tests/account-route.test.ts index 1d3c821f9fdb..fb94e08813ae 100644 --- a/web/tests/account-route.test.ts +++ b/web/tests/account-route.test.ts @@ -5,8 +5,10 @@ import { cloudVmBases, cloudVmBillingGrants, cloudVms, + devices, stripeCustomers, stripeSubscriptions, + subrouterTenants, vaultSessions, vaultSnapshots, vaultUploadGrants, @@ -32,6 +34,8 @@ const realIsStripeBillingConfigured = stripeModule.isStripeBillingConfigured; const realStripe = stripeModule.stripe; const storageModule = await import("../services/vault/storage"); const realDeleteObject = storageModule.deleteObject; +const subrouterClientModule = await import("../services/subrouter/client"); +const realCreateSubrouterClientFromEnv = subrouterClientModule.createSubrouterClientFromEnv; const workflowsModule = await import("../services/vms/workflows"); const realDestroyVm = workflowsModule.destroyVm; const realListUserVms = workflowsModule.listUserVms; @@ -54,7 +58,9 @@ const deleteRows = mock((table: unknown) => { deletedTables.push(table); deletedTableCount += 1; return { - where: async () => {}, + where: async (condition: unknown) => { + deletedWhere.push({ table, condition }); + }, }; }); const updateRows = mock((table: unknown) => ({ @@ -112,9 +118,15 @@ const deleteCustomer = mock(async (...args: unknown[]) => { deletedStripeCustomers.push(customerId); if (stripeDeleteCustomerError) throw stripeDeleteCustomerError; }); +const revokeTenant = mock(async (...args: unknown[]) => { + const [tenantId] = args as [string]; + routeEvents.push(`subrouter-revoke:${tenantId}`); + if (subrouterRevokeError) throw subrouterRevokeError; +}); let deletedTableCount = 0; let deletedTables: unknown[] = []; +let deletedWhere: Array<{ readonly table: unknown; readonly condition: unknown }> = []; let updatedRows: Array<{ readonly table: unknown; readonly values: unknown }> = []; let routeEvents: string[] = []; let stackDeleteError: unknown = null; @@ -129,6 +141,7 @@ let deletedStripeCustomers: string[] = []; let stripeCancelError: unknown = null; let stripeDeleteCustomerError: unknown = null; let destroyVmFailureProviderIds = new Set(); +let subrouterRevokeError: unknown = null; let useAccountRouteStubs = false; const originalConsoleError = console.error; const consoleError = mock(() => {}); @@ -216,6 +229,15 @@ mock.module("../services/billing/stripe", () => ({ : realStripe(), })); +mock.module("../services/subrouter/client", () => ({ + ...subrouterClientModule, + createSubrouterClientFromEnv: () => useAccountRouteStubs + ? { + revokeTenant, + } + : realCreateSubrouterClientFromEnv(), +})); + mock.module("../services/vms/workflows", () => ({ ...workflowsModule, destroyVm: ((...args: Parameters) => { @@ -261,8 +283,10 @@ beforeEach(() => { deleteObject.mockClear(); cancelSubscription.mockClear(); deleteCustomer.mockClear(); + revokeTenant.mockClear(); deletedTableCount = 0; deletedTables = []; + deletedWhere = []; updatedRows = []; routeEvents = []; stackDeleteError = null; @@ -277,6 +301,7 @@ beforeEach(() => { stripeCancelError = null; stripeDeleteCustomerError = null; destroyVmFailureProviderIds = new Set(); + subrouterRevokeError = null; }); afterEach(() => { @@ -313,6 +338,7 @@ describe("account deletion route", () => { expect(transaction).toHaveBeenCalledTimes(2); expect(deletedTableCount).toBeGreaterThan(10); expect(deletedTables).toContain(cloudVmBillingGrants); + expect(deletedTables).toContain(devices); expect(updatedRows.map(({ table, values }) => ({ table, values: stripUpdatedAt(values), @@ -366,6 +392,37 @@ describe("account deletion route", () => { ]); }); + test("revokes the personal Subrouter tenant before deleting local rows", async () => { + selectResults = [ + [], + [], + [], + [], + [], + [], + [{ tenantId: "tenant-personal" }], + ]; + + const response = await DELETE(accountDeletionRequest()); + + expect(response.status).toBe(200); + expect(revokeTenant).toHaveBeenCalledWith("tenant-personal"); + expect(deletedTables).toContain(subrouterTenants); + expect(routeEvents.indexOf("subrouter-revoke:tenant-personal")).toBeLessThan( + routeEvents.indexOf("transaction"), + ); + }); + + test("does not delete shared team devices registered by the deleted user", async () => { + const response = await DELETE(accountDeletionRequest()); + + expect(response.status).toBe(200); + expect(deletedTables).toContain(devices); + const deviceDelete = deletedWhere.find((entry) => entry.table === devices); + expect(conditionColumnNames(deviceDelete?.condition)).toContain("team_id"); + expect(conditionColumnNames(deviceDelete?.condition)).not.toContain("user_id"); + }); + test("deletes vault rows in bounded batches after their objects are removed", async () => { selectResults = [ [], @@ -521,6 +578,7 @@ describe("account deletion route", () => { [], [], [], + [], [{ id: "post-stack-session", latestObjectKey: "vault/u/account-user-1/post-stack-latest.jsonl.zst" }], ]; @@ -597,6 +655,26 @@ function stripUpdatedAt(values: unknown): Record { return copy; } +function conditionColumnNames(condition: unknown): string[] { + const names: string[] = []; + const visit = (value: unknown) => { + if (!value || typeof value !== "object") return; + const candidate = value as { + readonly name?: unknown; + readonly table?: unknown; + readonly queryChunks?: readonly unknown[]; + }; + if (typeof candidate.name === "string" && candidate.table) { + names.push(candidate.name); + } + if (Array.isArray(candidate.queryChunks)) { + for (const chunk of candidate.queryChunks) visit(chunk); + } + }; + visit(condition); + return names; +} + function isAccountDeletionVaultObject(objectKey: string): boolean { return objectKey.startsWith(`vault/u/${ACCOUNT_USER_ID}/`) || objectKey.startsWith("vault/uploads/"); diff --git a/web/tests/billing-pro.test.ts b/web/tests/billing-pro.test.ts index 07f1be3b5389..54ecbf7ecb29 100644 --- a/web/tests/billing-pro.test.ts +++ b/web/tests/billing-pro.test.ts @@ -182,6 +182,18 @@ describe("syncProPlanMetadata", () => { expect(user.updates).toEqual([{ theme: "dark" }]); }); + test("does not write pro metadata while account deletion is in progress", async () => { + const user = metadataUser({ cmuxAccountDeleting: true }); + await syncProPlanMetadata(user, true); + expect(user.updates).toEqual([]); + }); + + test("does not clear pro metadata while account deletion is in progress", async () => { + const user = metadataUser({ cmuxAccountDeleting: true, cmuxPlan: PRO_PLAN_ID }); + await syncProPlanMetadata(user, false); + expect(user.updates).toEqual([]); + }); + test("leaves cmuxVmPlan override untouched", async () => { const user = metadataUser({ cmuxVmPlan: "enterprise" }); await syncProPlanMetadata(user, true); From ac590ae2b61b3e98f369e5ef1b6b9e11b859120d Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Wed, 8 Jul 2026 22:33:34 -0700 Subject: [PATCH 23/89] Preserve visible account deletion failures --- .../AuthCoordinator+AccountDeletion.swift | 10 +++++- .../AccountDeletionClientTests.swift | 18 ++++++++++ web/app/api/account/route.ts | 31 +++++++++++++--- web/tests/account-route.test.ts | 36 +++++++++++++++++-- 4 files changed, 88 insertions(+), 7 deletions(-) diff --git a/Packages/Shared/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AuthCoordinator+AccountDeletion.swift b/Packages/Shared/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AuthCoordinator+AccountDeletion.swift index 5a6fac349cc9..ca466366586d 100644 --- a/Packages/Shared/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AuthCoordinator+AccountDeletion.swift +++ b/Packages/Shared/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AuthCoordinator+AccountDeletion.swift @@ -69,9 +69,13 @@ struct AccountDeletionClient: Sendable { case 401: throw AccountDeletionRequestError.unauthorized default: - if Self.isRetryablePartialDeletionError(Self.errorCode(in: data)) { + let errorCode = Self.errorCode(in: data) + if Self.isRetryablePartialDeletionError(errorCode) { throw AccountDeletionRequestError.stackDeleteIncomplete } + if Self.isDefinitiveFailureError(errorCode) { + throw AccountDeletionRequestError.rejected(statusCode: httpResponse.statusCode) + } if Self.isAmbiguousHTTPStatus(httpResponse.statusCode) { throw AccountDeletionRequestError.completionUnknown } @@ -88,6 +92,10 @@ struct AccountDeletionClient: Sendable { code == "account_stack_delete_failed_after_data_delete" } + private static func isDefinitiveFailureError(_ code: String?) -> Bool { + code == "account_delete_failed" + } + private static func isAmbiguousHTTPStatus(_ statusCode: Int) -> Bool { statusCode == 408 || statusCode >= 500 } diff --git a/Packages/Shared/CmuxAuthRuntime/Tests/CmuxAuthRuntimeTests/AccountDeletionClientTests.swift b/Packages/Shared/CmuxAuthRuntime/Tests/CmuxAuthRuntimeTests/AccountDeletionClientTests.swift index 7eeb47330ab1..bbde62700fd2 100644 --- a/Packages/Shared/CmuxAuthRuntime/Tests/CmuxAuthRuntimeTests/AccountDeletionClientTests.swift +++ b/Packages/Shared/CmuxAuthRuntime/Tests/CmuxAuthRuntimeTests/AccountDeletionClientTests.swift @@ -82,6 +82,24 @@ struct AccountDeletionClientTests { } } + @Test func deleteAccountMapsDefinitiveFailedResponse() async { + let client = AccountDeletionClient(apiBaseURL: "https://cmux.test") { request in + ( + Data(#"{"error":"account_delete_failed"}"#.utf8), + HTTPURLResponse( + url: request.url!, + statusCode: 500, + httpVersion: nil, + headerFields: nil + )! + ) + } + + await #expect(throws: AccountDeletionRequestError.rejected(statusCode: 500)) { + try await client.deleteAccount(accessToken: "access-token", refreshToken: "refresh-token") + } + } + @Test func deleteAccountMapsTransportTimeout() async { let client = AccountDeletionClient(apiBaseURL: "https://cmux.test") { _ in throw URLError(.timedOut) diff --git a/web/app/api/account/route.ts b/web/app/api/account/route.ts index e442e5aa6fdb..e9bbeb2c1be8 100644 --- a/web/app/api/account/route.ts +++ b/web/app/api/account/route.ts @@ -62,10 +62,15 @@ export async function DELETE(request: Request): Promise { const originalStackMetadata = stackUser.clientReadOnlyMetadata; let stackMetadataMarked = false; let cmuxOwnedRowsDeleted = false; + let restoreBillingEntitlementsOnFailure = true; try { - await resolveUserBillingForAccountDeletion(user.id); await markAccountDeletingAndClearBillingEntitlements(stackUser); stackMetadataMarked = true; + await resolveUserBillingForAccountDeletion(user.id, { + beforeExternalMutation: () => { + restoreBillingEntitlementsOnFailure = false; + }, + }); const destroyedVms = await destroyPersonalCloudVms(user.id); await deleteVaultRowsAndObjectsForAccount(user.id); await deletePersonalSubrouterTenant(user.id); @@ -89,7 +94,9 @@ export async function DELETE(request: Request): Promise { return jsonResponse({ ok: true, destroyedVms }); } catch (error) { if (stackMetadataMarked && !cmuxOwnedRowsDeleted) { - await restoreStackMetadataAfterAccountDeletionFailure(stackUser, originalStackMetadata); + await restoreStackMetadataAfterAccountDeletionFailure(stackUser, originalStackMetadata, { + restoreBillingEntitlements: restoreBillingEntitlementsOnFailure, + }); } logAccountDeleteError("account.delete.failed", error); return jsonResponse({ error: "account_delete_failed" }, 500); @@ -214,7 +221,10 @@ async function finishPostStackAccountCleanup(userId: string): Promise { } } -async function resolveUserBillingForAccountDeletion(userId: string): Promise { +async function resolveUserBillingForAccountDeletion( + userId: string, + options: { readonly beforeExternalMutation?: () => void } = {}, +): Promise { const db = cloudDb(); const activeSubscriptions = await db .select({ id: stripeSubscriptions.id }) @@ -239,10 +249,18 @@ async function resolveUserBillingForAccountDeletion(userId: string): Promise { + if (externalMutationMarked) return; + externalMutationMarked = true; + options.beforeExternalMutation?.(); + }; for (const subscription of activeSubscriptions) { + markExternalMutation(); await cancelStripeSubscriptionForAccountDeletion(client, subscription.id); } for (const customer of customers) { + markExternalMutation(); await deleteStripeCustomerForAccountDeletion(client, customer.id); } } @@ -257,9 +275,14 @@ async function markAccountDeletingAndClearBillingEntitlements(user: DeletableSta async function restoreStackMetadataAfterAccountDeletionFailure( user: DeletableStackUser, metadata: unknown, + options: { readonly restoreBillingEntitlements?: boolean } = {}, ): Promise { try { - await user.update({ clientReadOnlyMetadata: stackMetadataRecord(metadata) as ProMetadataJson }); + const restored = stackMetadataRecord(metadata); + if (options.restoreBillingEntitlements === false) { + delete restored.cmuxPlan; + } + await user.update({ clientReadOnlyMetadata: restored as ProMetadataJson }); } catch (error) { logAccountDeleteError("account.delete.metadata_restore_failed", error); } diff --git a/web/tests/account-route.test.ts b/web/tests/account-route.test.ts index fb94e08813ae..154607b7ac36 100644 --- a/web/tests/account-route.test.ts +++ b/web/tests/account-route.test.ts @@ -374,9 +374,9 @@ describe("account deletion route", () => { }); expect(deleteStackUser).toHaveBeenCalledTimes(1); expect(routeEvents).toEqual([ + "metadata-update", "stripe-cancel", "stripe-delete-customer", - "metadata-update", "list-vms", "destroy-vm", "destroy-vm", @@ -483,6 +483,33 @@ describe("account deletion route", () => { }); }); + test("does not restore Pro metadata when cleanup fails after Stripe cancellation", async () => { + selectResults = [ + [{ id: "sub_user_active" }], + [{ id: "cus_user" }], + [{ id: "snapshot-1", objectKey: "vault/u/account-user-1/snapshot.jsonl.zst" }], + [], + [], + [], + ]; + vaultDeleteError = new Error("vault unavailable"); + + const response = await DELETE(accountDeletionRequest()); + + expect(response.status).toBe(500); + expect(await response.json()).toEqual({ error: "account_delete_failed" }); + expect(cancelledStripeSubscriptions).toEqual(["sub_user_active"]); + expect(deletedStripeCustomers).toEqual(["cus_user"]); + expect(transaction).not.toHaveBeenCalled(); + expect(deleteStackUser).not.toHaveBeenCalled(); + expect(updateStackUser).toHaveBeenNthCalledWith(1, { + clientReadOnlyMetadata: { cmuxAccountDeleting: true }, + }); + expect(updateStackUser).toHaveBeenNthCalledWith(2, { + clientReadOnlyMetadata: {}, + }); + }); + test("attempts every personal VM before failing account deletion on VM teardown errors", async () => { destroyVmFailureProviderIds = new Set(["personal-vm-1"]); @@ -529,7 +556,12 @@ describe("account deletion route", () => { expect(cancelSubscription).not.toHaveBeenCalled(); expect(transaction).not.toHaveBeenCalled(); expect(deleteStackUser).not.toHaveBeenCalled(); - expect(updateStackUser).not.toHaveBeenCalled(); + expect(updateStackUser).toHaveBeenNthCalledWith(1, { + clientReadOnlyMetadata: { cmuxAccountDeleting: true }, + }); + expect(updateStackUser).toHaveBeenNthCalledWith(2, { + clientReadOnlyMetadata: { cmuxPlan: "pro" }, + }); }); test("returns a retryable partial-failure response when Stack deletion fails after cmux data deletion", async () => { From b12e742b241ae5ab3132f33f63e581a8d9c09ac6 Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Wed, 8 Jul 2026 22:47:12 -0700 Subject: [PATCH 24/89] Close account deletion residual gaps --- .../AccountDeletionClientTests.swift | 18 +++++++++++++++ web/app/api/account/route.ts | 22 +++++++++++++------ web/tests/account-route.test.ts | 18 +++++++++++---- 3 files changed, 47 insertions(+), 11 deletions(-) diff --git a/Packages/Shared/CmuxAuthRuntime/Tests/CmuxAuthRuntimeTests/AccountDeletionClientTests.swift b/Packages/Shared/CmuxAuthRuntime/Tests/CmuxAuthRuntimeTests/AccountDeletionClientTests.swift index bbde62700fd2..079bbd74b4b3 100644 --- a/Packages/Shared/CmuxAuthRuntime/Tests/CmuxAuthRuntimeTests/AccountDeletionClientTests.swift +++ b/Packages/Shared/CmuxAuthRuntime/Tests/CmuxAuthRuntimeTests/AccountDeletionClientTests.swift @@ -100,6 +100,24 @@ struct AccountDeletionClientTests { } } + @Test func deleteAccountMapsIncompletePostDeleteCleanupResponse() async { + let client = AccountDeletionClient(apiBaseURL: "https://cmux.test") { request in + ( + Data(#"{"error":"account_delete_incomplete"}"#.utf8), + HTTPURLResponse( + url: request.url!, + statusCode: 500, + httpVersion: nil, + headerFields: nil + )! + ) + } + + await #expect(throws: AccountDeletionRequestError.completionUnknown) { + try await client.deleteAccount(accessToken: "access-token", refreshToken: "refresh-token") + } + } + @Test func deleteAccountMapsTransportTimeout() async { let client = AccountDeletionClient(apiBaseURL: "https://cmux.test") { _ in throw URLError(.timedOut) diff --git a/web/app/api/account/route.ts b/web/app/api/account/route.ts index e9bbeb2c1be8..c94cc44838d3 100644 --- a/web/app/api/account/route.ts +++ b/web/app/api/account/route.ts @@ -90,7 +90,15 @@ export async function DELETE(request: Request): Promise { destroyedVms, }, 500); } - await finishPostStackAccountCleanup(user.id); + try { + await finishPostStackAccountCleanup(user.id); + } catch (error) { + logAccountDeleteError("account.delete.post_stack_cleanup_failed", error); + return jsonResponse({ + error: "account_delete_incomplete", + destroyedVms, + }, 500); + } return jsonResponse({ ok: true, destroyedVms }); } catch (error) { if (stackMetadataMarked && !cmuxOwnedRowsDeleted) { @@ -213,12 +221,8 @@ async function deleteVaultRowsAndObjectsForAccount(userId: string): Promise { - try { - await deleteVaultRowsAndObjectsForAccount(userId); - await deleteCmuxOwnedAccountRows(userId); - } catch (error) { - logAccountDeleteError("account.delete.post_stack_cleanup_failed", error); - } + await deleteVaultRowsAndObjectsForAccount(userId); + await deleteCmuxOwnedAccountRows(userId); } async function resolveUserBillingForAccountDeletion( @@ -402,6 +406,10 @@ async function deleteCmuxOwnedAccountRows(userId: string): Promise { .where(eq(cloudVmBaseGenerations.createdByUserId, userId)); await tx.delete(devices).where(eq(devices.teamId, userId)); + await tx + .update(devices) + .set({ userId: DELETED_ACCOUNT_ACTOR_ID, updatedAt: now }) + .where(eq(devices.userId, userId)); await tx.delete(vaultCliAuthRequests).where(eq(vaultCliAuthRequests.userId, userId)); }); diff --git a/web/tests/account-route.test.ts b/web/tests/account-route.test.ts index 154607b7ac36..e33262614324 100644 --- a/web/tests/account-route.test.ts +++ b/web/tests/account-route.test.ts @@ -349,12 +349,14 @@ describe("account deletion route", () => { { table: cloudVmBases, values: { createdByUserId: "deleted-account" } }, { table: cloudVmBases, values: { lastOpenedByUserId: null } }, { table: cloudVmBaseGenerations, values: { createdByUserId: "deleted-account" } }, + { table: devices, values: { userId: "deleted-account" } }, { table: stripeSubscriptions, values: { stackUserId: "deleted-account" } }, { table: stripeCustomers, values: { stackUserId: "deleted-account" } }, { table: cloudVms, values: { userId: "deleted-account" } }, { table: cloudVmBases, values: { createdByUserId: "deleted-account" } }, { table: cloudVmBases, values: { lastOpenedByUserId: null } }, { table: cloudVmBaseGenerations, values: { createdByUserId: "deleted-account" } }, + { table: devices, values: { userId: "deleted-account" } }, ]); for (const update of updatedRows) { expect((update.values as { readonly updatedAt?: unknown }).updatedAt).toBeInstanceOf(Date); @@ -413,7 +415,7 @@ describe("account deletion route", () => { ); }); - test("does not delete shared team devices registered by the deleted user", async () => { + test("anonymizes shared team devices registered by the deleted user", async () => { const response = await DELETE(accountDeletionRequest()); expect(response.status).toBe(200); @@ -421,6 +423,10 @@ describe("account deletion route", () => { const deviceDelete = deletedWhere.find((entry) => entry.table === devices); expect(conditionColumnNames(deviceDelete?.condition)).toContain("team_id"); expect(conditionColumnNames(deviceDelete?.condition)).not.toContain("user_id"); + expect(updatedRows.map(({ table, values }) => ({ + table, + values: stripUpdatedAt(values), + }))).toContainEqual({ table: devices, values: { userId: "deleted-account" } }); }); test("deletes vault rows in bounded batches after their objects are removed", async () => { @@ -598,7 +604,7 @@ describe("account deletion route", () => { ); }); - test("returns success when post-Stack cleanup fails after the account is deleted", async () => { + test("returns incomplete deletion when post-Stack cleanup fails after the account is deleted", async () => { postStackVaultDeleteError = new Error("post-delete vault unavailable"); selectResults = [ [], @@ -616,9 +622,13 @@ describe("account deletion route", () => { const response = await DELETE(accountDeletionRequest()); - expect(response.status).toBe(200); - expect(await response.json()).toEqual({ ok: true, destroyedVms: 2 }); + expect(response.status).toBe(500); + expect(await response.json()).toEqual({ + error: "account_delete_incomplete", + destroyedVms: 2, + }); expect(deleteStackUser).toHaveBeenCalledTimes(1); + expect(transaction).toHaveBeenCalledTimes(1); expect(consoleError).toHaveBeenCalledWith( "account.delete.post_stack_cleanup_failed", "Error: post-delete vault unavailable", From f3d21a69d04690ab37bd2dc95bd2a430f3f17764 Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Wed, 8 Jul 2026 22:54:37 -0700 Subject: [PATCH 25/89] Handle local account deletion transport failures --- .../AuthCoordinator+AccountDeletion.swift | 34 ++++++++++++++++++- .../AccountDeletionClientTests.swift | 33 ++++++++++++++++++ .../MobileSettingsAccountSection.swift | 8 +++++ ios/cmux/Resources/Localizable.xcstrings | 17 ++++++++++ 4 files changed, 91 insertions(+), 1 deletion(-) diff --git a/Packages/Shared/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AuthCoordinator+AccountDeletion.swift b/Packages/Shared/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AuthCoordinator+AccountDeletion.swift index ca466366586d..f1a54574cd34 100644 --- a/Packages/Shared/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AuthCoordinator+AccountDeletion.swift +++ b/Packages/Shared/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AuthCoordinator+AccountDeletion.swift @@ -12,6 +12,9 @@ public enum AccountDeletionRequestError: Error, Equatable { /// a definitive account-deletion result. The backend may still complete /// deletion after this client gives up. case completionUnknown + /// The request failed locally before it could plausibly reach the backend. + /// Callers should keep the current session and let the user retry. + case localTransportFailure case rejected(statusCode: Int) case invalidResponse } @@ -57,7 +60,10 @@ struct AccountDeletionClient: Sendable { (data, response) = try await load(request) } catch let error as URLError where error.code == .timedOut { throw AccountDeletionRequestError.timedOut - } catch is URLError { + } catch let error as URLError { + guard !Self.isDefiniteLocalTransportFailure(error.code) else { + throw AccountDeletionRequestError.localTransportFailure + } throw AccountDeletionRequestError.completionUnknown } guard let httpResponse = response as? HTTPURLResponse else { @@ -99,6 +105,32 @@ struct AccountDeletionClient: Sendable { private static func isAmbiguousHTTPStatus(_ statusCode: Int) -> Bool { statusCode == 408 || statusCode >= 500 } + + private static func isDefiniteLocalTransportFailure(_ code: URLError.Code) -> Bool { + switch code { + case .appTransportSecurityRequiresSecureConnection, + .badURL, + .callIsActive, + .cannotConnectToHost, + .cannotFindHost, + .cannotLoadFromNetwork, + .clientCertificateRejected, + .clientCertificateRequired, + .dataNotAllowed, + .dnsLookupFailed, + .internationalRoamingOff, + .notConnectedToInternet, + .secureConnectionFailed, + .serverCertificateHasBadDate, + .serverCertificateHasUnknownRoot, + .serverCertificateNotYetValid, + .serverCertificateUntrusted, + .unsupportedURL: + return true + default: + return false + } + } } extension AuthCoordinator { diff --git a/Packages/Shared/CmuxAuthRuntime/Tests/CmuxAuthRuntimeTests/AccountDeletionClientTests.swift b/Packages/Shared/CmuxAuthRuntime/Tests/CmuxAuthRuntimeTests/AccountDeletionClientTests.swift index 079bbd74b4b3..c6ddb3f80711 100644 --- a/Packages/Shared/CmuxAuthRuntime/Tests/CmuxAuthRuntimeTests/AccountDeletionClientTests.swift +++ b/Packages/Shared/CmuxAuthRuntime/Tests/CmuxAuthRuntimeTests/AccountDeletionClientTests.swift @@ -128,6 +128,39 @@ struct AccountDeletionClientTests { } } + @Test func deleteAccountMapsDefiniteLocalTransportFailures() async { + let localFailureCodes: [URLError.Code] = [ + .appTransportSecurityRequiresSecureConnection, + .badURL, + .callIsActive, + .cannotConnectToHost, + .cannotFindHost, + .cannotLoadFromNetwork, + .clientCertificateRejected, + .clientCertificateRequired, + .dataNotAllowed, + .dnsLookupFailed, + .internationalRoamingOff, + .notConnectedToInternet, + .secureConnectionFailed, + .serverCertificateHasBadDate, + .serverCertificateHasUnknownRoot, + .serverCertificateNotYetValid, + .serverCertificateUntrusted, + .unsupportedURL, + ] + + for code in localFailureCodes { + let client = AccountDeletionClient(apiBaseURL: "https://cmux.test") { _ in + throw URLError(code) + } + + await #expect(throws: AccountDeletionRequestError.localTransportFailure) { + try await client.deleteAccount(accessToken: "access-token", refreshToken: "refresh-token") + } + } + } + @Test func deleteAccountMapsAmbiguousTransportFailure() async { let client = AccountDeletionClient(apiBaseURL: "https://cmux.test") { _ in throw URLError(.networkConnectionLost) diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsAccountSection.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsAccountSection.swift index effd7bfb01b4..4e931413541b 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsAccountSection.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsAccountSection.swift @@ -120,6 +120,8 @@ struct MobileSettingsAccountSection: View { } dismiss() return + } else if case AccountDeletionRequestError.localTransportFailure = error { + deleteAccountFailureKind = .connection } else if case AuthError.timedOut = error { deleteAccountFailureKind = .timedOut } else { @@ -145,6 +147,7 @@ struct MobileSettingsAccountSection: View { private enum DeleteAccountFailureKind { case generic + case connection case stackDeleteIncomplete case timedOut @@ -155,6 +158,11 @@ private enum DeleteAccountFailureKind { "mobile.settings.deleteAccountFailedMessage", defaultValue: "Try again later or contact support." ) + case .connection: + return L10n.string( + "mobile.settings.deleteAccountConnectionFailedMessage", + defaultValue: "Could not reach the server. Check your internet connection and try again." + ) case .stackDeleteIncomplete: return L10n.string( "mobile.settings.deleteAccountPartialFailureMessage", diff --git a/ios/cmux/Resources/Localizable.xcstrings b/ios/cmux/Resources/Localizable.xcstrings index 5ed4381cd2f4..51b9c64981f4 100644 --- a/ios/cmux/Resources/Localizable.xcstrings +++ b/ios/cmux/Resources/Localizable.xcstrings @@ -4064,6 +4064,23 @@ } } }, + "mobile.settings.deleteAccountConnectionFailedMessage": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Could not reach the server. Check your internet connection and try again." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "サーバーに接続できませんでした。インターネット接続を確認してからもう一度お試しください。" + } + } + } + }, "mobile.settings.deleteAccountFailureOK": { "extractionState": "manual", "localizations": { From 000bb3fbcbe71af609025ae3842e732deb3fb19d Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Wed, 8 Jul 2026 23:07:02 -0700 Subject: [PATCH 26/89] Split account deletion Swift helpers --- .../Coordinator/AccountDeletionClient.swift | 117 +++++++++++++++ .../AccountDeletionRequestError.swift | 21 +++ .../AuthCoordinator+AccountDeletion.swift | 133 ------------------ .../AccountDeletionClientTests.swift | 8 -- .../RecordedAccountDeletionRequest.swift | 9 ++ .../MobileSettingsAccountSection.swift | 32 ----- ...bileSettingsDeleteAccountFailureKind.swift | 35 +++++ 7 files changed, 182 insertions(+), 173 deletions(-) create mode 100644 Packages/Shared/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AccountDeletionClient.swift create mode 100644 Packages/Shared/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AccountDeletionRequestError.swift create mode 100644 Packages/Shared/CmuxAuthRuntime/Tests/CmuxAuthRuntimeTests/RecordedAccountDeletionRequest.swift create mode 100644 Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsDeleteAccountFailureKind.swift diff --git a/Packages/Shared/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AccountDeletionClient.swift b/Packages/Shared/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AccountDeletionClient.swift new file mode 100644 index 000000000000..85fd2a95e1da --- /dev/null +++ b/Packages/Shared/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AccountDeletionClient.swift @@ -0,0 +1,117 @@ +import Foundation + +typealias AccountDeletionRequestLoader = @Sendable (URLRequest) async throws -> (Data, URLResponse) + +struct AccountDeletionClient: Sendable { + private let apiBaseURL: String + private let requestTimeout: TimeInterval + private let load: AccountDeletionRequestLoader + + init( + apiBaseURL: String, + requestTimeout: TimeInterval = 60, + load: @escaping AccountDeletionRequestLoader = { request in + try await URLSession.shared.data(for: request) + } + ) { + self.apiBaseURL = apiBaseURL + self.requestTimeout = requestTimeout + self.load = load + } + + @concurrent + func deleteAccount(accessToken: String, refreshToken: String) async throws { + let trimmedBaseURL = apiBaseURL.hasSuffix("/") ? String(apiBaseURL.dropLast()) : apiBaseURL + guard let url = URL(string: trimmedBaseURL + "/api/account") else { + throw AccountDeletionRequestError.invalidAPIBaseURL + } + + var request = URLRequest(url: url, timeoutInterval: requestTimeout) + request.httpMethod = "DELETE" + request.setValue("Bearer \(accessToken)", forHTTPHeaderField: "Authorization") + request.setValue(refreshToken, forHTTPHeaderField: "X-Stack-Refresh-Token") + + let data: Data + let response: URLResponse + do { + (data, response) = try await load(request) + } catch let error as URLError where error.code == .timedOut { + throw AccountDeletionRequestError.timedOut + } catch let error as URLError { + guard !isDefiniteLocalAccountDeletionTransportFailure(error.code) else { + throw AccountDeletionRequestError.localTransportFailure + } + throw AccountDeletionRequestError.completionUnknown + } + guard let httpResponse = response as? HTTPURLResponse else { + throw AccountDeletionRequestError.invalidResponse + } + switch httpResponse.statusCode { + case 200..<300: + return + case 401: + throw AccountDeletionRequestError.unauthorized + default: + let errorCode = accountDeletionErrorCode(in: data) + if isRetryablePartialAccountDeletionError(errorCode) { + throw AccountDeletionRequestError.stackDeleteIncomplete + } + if isDefinitiveAccountDeletionFailureError(errorCode) { + throw AccountDeletionRequestError.rejected(statusCode: httpResponse.statusCode) + } + if isAmbiguousAccountDeletionHTTPStatus(httpResponse.statusCode) { + throw AccountDeletionRequestError.completionUnknown + } + throw AccountDeletionRequestError.rejected(statusCode: httpResponse.statusCode) + } + } +} + +private func accountDeletionErrorCode(in data: Data) -> String? { + guard + let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any], + let error = object["error"] as? String + else { + return nil + } + return error +} + +private func isRetryablePartialAccountDeletionError(_ code: String?) -> Bool { + code == "account_delete_retryable" || + code == "account_stack_delete_failed_after_data_delete" +} + +private func isDefinitiveAccountDeletionFailureError(_ code: String?) -> Bool { + code == "account_delete_failed" +} + +private func isAmbiguousAccountDeletionHTTPStatus(_ statusCode: Int) -> Bool { + statusCode == 408 || statusCode >= 500 +} + +private func isDefiniteLocalAccountDeletionTransportFailure(_ code: URLError.Code) -> Bool { + switch code { + case .appTransportSecurityRequiresSecureConnection, + .badURL, + .callIsActive, + .cannotConnectToHost, + .cannotFindHost, + .cannotLoadFromNetwork, + .clientCertificateRejected, + .clientCertificateRequired, + .dataNotAllowed, + .dnsLookupFailed, + .internationalRoamingOff, + .notConnectedToInternet, + .secureConnectionFailed, + .serverCertificateHasBadDate, + .serverCertificateHasUnknownRoot, + .serverCertificateNotYetValid, + .serverCertificateUntrusted, + .unsupportedURL: + return true + default: + return false + } +} diff --git a/Packages/Shared/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AccountDeletionRequestError.swift b/Packages/Shared/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AccountDeletionRequestError.swift new file mode 100644 index 000000000000..989e3120717e --- /dev/null +++ b/Packages/Shared/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AccountDeletionRequestError.swift @@ -0,0 +1,21 @@ +import Foundation + +/// Errors returned by the native cmux account-deletion request. +public enum AccountDeletionRequestError: Error, Equatable { + /// The configured cmux API base URL could not build an account-deletion URL. + case invalidAPIBaseURL + /// The backend rejected the supplied Stack access or refresh token. + case unauthorized + /// cmux data was deleted, but Stack account deletion did not finish. + case stackDeleteIncomplete + /// The DELETE request timed out after reaching the transport layer. + case timedOut + /// The request may have reached the backend, but no definitive result returned. + case completionUnknown + /// The request failed locally before it could plausibly reach the backend. + case localTransportFailure + /// The backend returned a definitive non-success status. + case rejected(statusCode: Int) + /// URL loading returned a non-HTTP response. + case invalidResponse +} diff --git a/Packages/Shared/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AuthCoordinator+AccountDeletion.swift b/Packages/Shared/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AuthCoordinator+AccountDeletion.swift index f1a54574cd34..4d194f7659ed 100644 --- a/Packages/Shared/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AuthCoordinator+AccountDeletion.swift +++ b/Packages/Shared/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AuthCoordinator+AccountDeletion.swift @@ -1,138 +1,5 @@ import Foundation -public enum AccountDeletionRequestError: Error, Equatable { - case invalidAPIBaseURL - case unauthorized - case stackDeleteIncomplete - /// The DELETE request reached the transport layer and timed out before a - /// definitive response. The backend may still complete account deletion, so - /// callers must treat the local session as no longer trustworthy. - case timedOut - /// The DELETE request reached the network/server boundary but did not return - /// a definitive account-deletion result. The backend may still complete - /// deletion after this client gives up. - case completionUnknown - /// The request failed locally before it could plausibly reach the backend. - /// Callers should keep the current session and let the user retry. - case localTransportFailure - case rejected(statusCode: Int) - case invalidResponse -} - -typealias AccountDeletionRequestLoader = @Sendable (URLRequest) async throws -> (Data, URLResponse) - -nonisolated private struct AccountDeletionErrorResponse: Decodable { - let error: String -} - -struct AccountDeletionClient: Sendable { - private let apiBaseURL: String - private let requestTimeout: TimeInterval - private let load: AccountDeletionRequestLoader - - init( - apiBaseURL: String, - requestTimeout: TimeInterval = 60, - load: @escaping AccountDeletionRequestLoader = { request in - try await URLSession.shared.data(for: request) - } - ) { - self.apiBaseURL = apiBaseURL - self.requestTimeout = requestTimeout - self.load = load - } - - @concurrent - func deleteAccount(accessToken: String, refreshToken: String) async throws { - let trimmedBaseURL = apiBaseURL.hasSuffix("/") ? String(apiBaseURL.dropLast()) : apiBaseURL - guard let url = URL(string: trimmedBaseURL + "/api/account") else { - throw AccountDeletionRequestError.invalidAPIBaseURL - } - - var request = URLRequest(url: url, timeoutInterval: requestTimeout) - request.httpMethod = "DELETE" - request.setValue("Bearer \(accessToken)", forHTTPHeaderField: "Authorization") - request.setValue(refreshToken, forHTTPHeaderField: "X-Stack-Refresh-Token") - - let data: Data - let response: URLResponse - do { - (data, response) = try await load(request) - } catch let error as URLError where error.code == .timedOut { - throw AccountDeletionRequestError.timedOut - } catch let error as URLError { - guard !Self.isDefiniteLocalTransportFailure(error.code) else { - throw AccountDeletionRequestError.localTransportFailure - } - throw AccountDeletionRequestError.completionUnknown - } - guard let httpResponse = response as? HTTPURLResponse else { - throw AccountDeletionRequestError.invalidResponse - } - switch httpResponse.statusCode { - case 200..<300: - return - case 401: - throw AccountDeletionRequestError.unauthorized - default: - let errorCode = Self.errorCode(in: data) - if Self.isRetryablePartialDeletionError(errorCode) { - throw AccountDeletionRequestError.stackDeleteIncomplete - } - if Self.isDefinitiveFailureError(errorCode) { - throw AccountDeletionRequestError.rejected(statusCode: httpResponse.statusCode) - } - if Self.isAmbiguousHTTPStatus(httpResponse.statusCode) { - throw AccountDeletionRequestError.completionUnknown - } - throw AccountDeletionRequestError.rejected(statusCode: httpResponse.statusCode) - } - } - - private static func errorCode(in data: Data) -> String? { - try? JSONDecoder().decode(AccountDeletionErrorResponse.self, from: data).error - } - - private static func isRetryablePartialDeletionError(_ code: String?) -> Bool { - code == "account_delete_retryable" || - code == "account_stack_delete_failed_after_data_delete" - } - - private static func isDefinitiveFailureError(_ code: String?) -> Bool { - code == "account_delete_failed" - } - - private static func isAmbiguousHTTPStatus(_ statusCode: Int) -> Bool { - statusCode == 408 || statusCode >= 500 - } - - private static func isDefiniteLocalTransportFailure(_ code: URLError.Code) -> Bool { - switch code { - case .appTransportSecurityRequiresSecureConnection, - .badURL, - .callIsActive, - .cannotConnectToHost, - .cannotFindHost, - .cannotLoadFromNetwork, - .clientCertificateRejected, - .clientCertificateRequired, - .dataNotAllowed, - .dnsLookupFailed, - .internationalRoamingOff, - .notConnectedToInternet, - .secureConnectionFailed, - .serverCertificateHasBadDate, - .serverCertificateHasUnknownRoot, - .serverCertificateNotYetValid, - .serverCertificateUntrusted, - .unsupportedURL: - return true - default: - return false - } - } -} - extension AuthCoordinator { /// Permanently deletes the current Stack account through cmux's backend. /// diff --git a/Packages/Shared/CmuxAuthRuntime/Tests/CmuxAuthRuntimeTests/AccountDeletionClientTests.swift b/Packages/Shared/CmuxAuthRuntime/Tests/CmuxAuthRuntimeTests/AccountDeletionClientTests.swift index c6ddb3f80711..0a3f0b31639d 100644 --- a/Packages/Shared/CmuxAuthRuntime/Tests/CmuxAuthRuntimeTests/AccountDeletionClientTests.swift +++ b/Packages/Shared/CmuxAuthRuntime/Tests/CmuxAuthRuntimeTests/AccountDeletionClientTests.swift @@ -189,11 +189,3 @@ struct AccountDeletionClientTests { } } } - -actor RecordedAccountDeletionRequest { - private(set) var request: URLRequest? - - func record(_ request: URLRequest) { - self.request = request - } -} diff --git a/Packages/Shared/CmuxAuthRuntime/Tests/CmuxAuthRuntimeTests/RecordedAccountDeletionRequest.swift b/Packages/Shared/CmuxAuthRuntime/Tests/CmuxAuthRuntimeTests/RecordedAccountDeletionRequest.swift new file mode 100644 index 000000000000..f893d2aba910 --- /dev/null +++ b/Packages/Shared/CmuxAuthRuntime/Tests/CmuxAuthRuntimeTests/RecordedAccountDeletionRequest.swift @@ -0,0 +1,9 @@ +import Foundation + +actor RecordedAccountDeletionRequest { + private(set) var request: URLRequest? + + func record(_ request: URLRequest) { + self.request = request + } +} diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsAccountSection.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsAccountSection.swift index 4e931413541b..b3dfc97ee2d2 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsAccountSection.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsAccountSection.swift @@ -144,36 +144,4 @@ struct MobileSettingsAccountSection: View { return L10n.string("mobile.settings.account", defaultValue: "Account") } } - -private enum DeleteAccountFailureKind { - case generic - case connection - case stackDeleteIncomplete - case timedOut - - var localizedMessage: String { - switch self { - case .generic: - return L10n.string( - "mobile.settings.deleteAccountFailedMessage", - defaultValue: "Try again later or contact support." - ) - case .connection: - return L10n.string( - "mobile.settings.deleteAccountConnectionFailedMessage", - defaultValue: "Could not reach the server. Check your internet connection and try again." - ) - case .stackDeleteIncomplete: - return L10n.string( - "mobile.settings.deleteAccountPartialFailureMessage", - defaultValue: "Your cmux data was deleted, but account sign-in cleanup did not finish. Try Delete Account again to complete deletion." - ) - case .timedOut: - return L10n.string( - "mobile.settings.deleteAccountTimedOutMessage", - defaultValue: "Account deletion timed out. Check your connection and try again." - ) - } - } -} #endif diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsDeleteAccountFailureKind.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsDeleteAccountFailureKind.swift new file mode 100644 index 000000000000..9577763ff9ec --- /dev/null +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsDeleteAccountFailureKind.swift @@ -0,0 +1,35 @@ +#if os(iOS) +import CmuxMobileSupport + +enum DeleteAccountFailureKind { + case generic + case connection + case stackDeleteIncomplete + case timedOut + + var localizedMessage: String { + switch self { + case .generic: + return L10n.string( + "mobile.settings.deleteAccountFailedMessage", + defaultValue: "Try again later or contact support." + ) + case .connection: + return L10n.string( + "mobile.settings.deleteAccountConnectionFailedMessage", + defaultValue: "Could not reach the server. Check your internet connection and try again." + ) + case .stackDeleteIncomplete: + return L10n.string( + "mobile.settings.deleteAccountPartialFailureMessage", + defaultValue: "Your cmux data was deleted, but account sign-in cleanup did not finish. Try Delete Account again to complete deletion." + ) + case .timedOut: + return L10n.string( + "mobile.settings.deleteAccountTimedOutMessage", + defaultValue: "Account deletion timed out. Check your connection and try again." + ) + } + } +} +#endif From 74c71aaa3fa1bfdc06ee49e7eefe419d47969b51 Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Wed, 8 Jul 2026 23:16:12 -0700 Subject: [PATCH 27/89] Keep destructive deletion failures retryable --- .../MobileSettingsAccountSection.swift | 16 +------ ...bileSettingsDeleteAccountFailureKind.swift | 6 +++ ios/cmux/Resources/Localizable.xcstrings | 17 +++++++ web/app/api/account/route.ts | 45 +++++++++++++++++-- web/tests/account-route.test.ts | 40 ++++++++++------- 5 files changed, 89 insertions(+), 35 deletions(-) diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsAccountSection.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsAccountSection.swift index b3dfc97ee2d2..eecccc9e6e2a 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsAccountSection.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsAccountSection.swift @@ -105,21 +105,9 @@ struct MobileSettingsAccountSection: View { if case AccountDeletionRequestError.stackDeleteIncomplete = error { deleteAccountFailureKind = .stackDeleteIncomplete } else if case AccountDeletionRequestError.timedOut = error { - if let signOut { - signOut() - } else { - await authManager.signOut() - } - dismiss() - return + deleteAccountFailureKind = .unknown } else if case AccountDeletionRequestError.completionUnknown = error { - if let signOut { - signOut() - } else { - await authManager.signOut() - } - dismiss() - return + deleteAccountFailureKind = .unknown } else if case AccountDeletionRequestError.localTransportFailure = error { deleteAccountFailureKind = .connection } else if case AuthError.timedOut = error { diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsDeleteAccountFailureKind.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsDeleteAccountFailureKind.swift index 9577763ff9ec..ca90f34a526a 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsDeleteAccountFailureKind.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsDeleteAccountFailureKind.swift @@ -6,6 +6,7 @@ enum DeleteAccountFailureKind { case connection case stackDeleteIncomplete case timedOut + case unknown var localizedMessage: String { switch self { @@ -29,6 +30,11 @@ enum DeleteAccountFailureKind { "mobile.settings.deleteAccountTimedOutMessage", defaultValue: "Account deletion timed out. Check your connection and try again." ) + case .unknown: + return L10n.string( + "mobile.settings.deleteAccountUnknownMessage", + defaultValue: "We couldn't confirm whether account deletion finished. Wait a moment, then try Delete Account again." + ) } } } diff --git a/ios/cmux/Resources/Localizable.xcstrings b/ios/cmux/Resources/Localizable.xcstrings index 51b9c64981f4..7dcf4895d1a5 100644 --- a/ios/cmux/Resources/Localizable.xcstrings +++ b/ios/cmux/Resources/Localizable.xcstrings @@ -4132,6 +4132,23 @@ } } }, + "mobile.settings.deleteAccountUnknownMessage": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "We couldn't confirm whether account deletion finished. Wait a moment, then try Delete Account again." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "アカウントの削除が完了したか確認できませんでした。少し待ってから、もう一度「アカウントを削除」をお試しください。" + } + } + } + }, "mobile.settings.deleteAccountMessage": { "extractionState": "manual", "localizations": { diff --git a/web/app/api/account/route.ts b/web/app/api/account/route.ts index c94cc44838d3..32e4e2987ad1 100644 --- a/web/app/api/account/route.ts +++ b/web/app/api/account/route.ts @@ -62,6 +62,8 @@ export async function DELETE(request: Request): Promise { const originalStackMetadata = stackUser.clientReadOnlyMetadata; let stackMetadataMarked = false; let cmuxOwnedRowsDeleted = false; + let destructiveCleanupStarted = false; + let destroyedVms = 0; let restoreBillingEntitlementsOnFailure = true; try { await markAccountDeletingAndClearBillingEntitlements(stackUser); @@ -71,9 +73,21 @@ export async function DELETE(request: Request): Promise { restoreBillingEntitlementsOnFailure = false; }, }); - const destroyedVms = await destroyPersonalCloudVms(user.id); + try { + destroyedVms = await destroyPersonalCloudVms(user.id); + if (destroyedVms > 0) destructiveCleanupStarted = true; + } catch (error) { + if (error instanceof AccountDeletionDestructiveCleanupError) { + destroyedVms = error.destroyedVms; + destructiveCleanupStarted = destroyedVms > 0; + } + throw error; + } + destructiveCleanupStarted = true; await deleteVaultRowsAndObjectsForAccount(user.id); + destructiveCleanupStarted = true; await deletePersonalSubrouterTenant(user.id); + destructiveCleanupStarted = true; // Delete cmux-owned data before the Stack user so a Stack-side failure does // not strand retained app data behind an account the user can no longer use. // These deletes are idempotent, so the same signed-in user can retry the @@ -101,7 +115,15 @@ export async function DELETE(request: Request): Promise { } return jsonResponse({ ok: true, destroyedVms }); } catch (error) { - if (stackMetadataMarked && !cmuxOwnedRowsDeleted) { + if (destructiveCleanupStarted || cmuxOwnedRowsDeleted) { + logAccountDeleteError("account.delete.partial_after_destructive_cleanup", error); + return jsonResponse({ + error: "account_delete_retryable", + retryable: true, + destroyedVms, + }, 500); + } + if (stackMetadataMarked) { await restoreStackMetadataAfterAccountDeletionFailure(stackUser, originalStackMetadata, { restoreBillingEntitlements: restoreBillingEntitlementsOnFailure, }); @@ -130,21 +152,36 @@ async function currentDeletableStackUser(request: Request): Promise { const vms = await runVmWorkflow(listUserVms(userId)); const failures: unknown[] = []; + let destroyedVms = 0; for (const vm of vms) { try { await runVmWorkflow(destroyVm({ userId, providerVmId: vm.providerVmId })); + destroyedVms += 1; } catch (error) { failures.push(error); logAccountDeleteError("account.delete.vm_destroy_failed", error); } } if (failures.length > 0) { - throw new Error(`Failed to destroy ${failures.length} personal cloud VM${failures.length === 1 ? "" : "s"}`); + throw new AccountDeletionDestructiveCleanupError( + `Failed to destroy ${failures.length} personal cloud VM${failures.length === 1 ? "" : "s"}`, + destroyedVms, + ); } - return vms.length; + return destroyedVms; } async function deleteVaultRowsAndObjectsForAccount(userId: string): Promise { diff --git a/web/tests/account-route.test.ts b/web/tests/account-route.test.ts index e33262614324..f1f3a07d7413 100644 --- a/web/tests/account-route.test.ts +++ b/web/tests/account-route.test.ts @@ -464,7 +464,7 @@ describe("account deletion route", () => { expect(deletedTables).toContain(vaultSessions); }); - test("does not delete rows or Stack user when vault object cleanup fails", async () => { + test("keeps deletion retryable when vault object cleanup fails after VMs are destroyed", async () => { selectResults = [ [], [], @@ -478,18 +478,20 @@ describe("account deletion route", () => { const response = await DELETE(accountDeletionRequest()); expect(response.status).toBe(500); - expect(await response.json()).toEqual({ error: "account_delete_failed" }); + expect(await response.json()).toEqual({ + error: "account_delete_retryable", + retryable: true, + destroyedVms: 2, + }); expect(transaction).not.toHaveBeenCalled(); expect(deleteStackUser).not.toHaveBeenCalled(); expect(updateStackUser).toHaveBeenNthCalledWith(1, { clientReadOnlyMetadata: { cmuxAccountDeleting: true }, }); - expect(updateStackUser).toHaveBeenNthCalledWith(2, { - clientReadOnlyMetadata: { cmuxPlan: "pro" }, - }); + expect(updateStackUser).toHaveBeenCalledTimes(1); }); - test("does not restore Pro metadata when cleanup fails after Stripe cancellation", async () => { + test("keeps deletion retryable when cleanup fails after Stripe and VM cleanup", async () => { selectResults = [ [{ id: "sub_user_active" }], [{ id: "cus_user" }], @@ -503,7 +505,11 @@ describe("account deletion route", () => { const response = await DELETE(accountDeletionRequest()); expect(response.status).toBe(500); - expect(await response.json()).toEqual({ error: "account_delete_failed" }); + expect(await response.json()).toEqual({ + error: "account_delete_retryable", + retryable: true, + destroyedVms: 2, + }); expect(cancelledStripeSubscriptions).toEqual(["sub_user_active"]); expect(deletedStripeCustomers).toEqual(["cus_user"]); expect(transaction).not.toHaveBeenCalled(); @@ -511,18 +517,20 @@ describe("account deletion route", () => { expect(updateStackUser).toHaveBeenNthCalledWith(1, { clientReadOnlyMetadata: { cmuxAccountDeleting: true }, }); - expect(updateStackUser).toHaveBeenNthCalledWith(2, { - clientReadOnlyMetadata: {}, - }); + expect(updateStackUser).toHaveBeenCalledTimes(1); }); - test("attempts every personal VM before failing account deletion on VM teardown errors", async () => { + test("keeps deletion retryable when any VM was destroyed before a teardown error", async () => { destroyVmFailureProviderIds = new Set(["personal-vm-1"]); const response = await DELETE(accountDeletionRequest()); expect(response.status).toBe(500); - expect(await response.json()).toEqual({ error: "account_delete_failed" }); + expect(await response.json()).toEqual({ + error: "account_delete_retryable", + retryable: true, + destroyedVms: 1, + }); expect(destroyVm).toHaveBeenCalledTimes(2); expect(destroyVm).toHaveBeenCalledWith({ userId: "account-user-1", providerVmId: "personal-vm-1" }); expect(destroyVm).toHaveBeenCalledWith({ userId: "account-user-1", providerVmId: "personal-vm-2" }); @@ -531,16 +539,14 @@ describe("account deletion route", () => { expect(updateStackUser).toHaveBeenNthCalledWith(1, { clientReadOnlyMetadata: { cmuxAccountDeleting: true }, }); - expect(updateStackUser).toHaveBeenNthCalledWith(2, { - clientReadOnlyMetadata: { cmuxPlan: "pro" }, - }); + expect(updateStackUser).toHaveBeenCalledTimes(1); expect(consoleError).toHaveBeenCalledWith( "account.delete.vm_destroy_failed", "Error: destroy failed for personal-vm-1", ); expect(consoleError).toHaveBeenCalledWith( - "account.delete.failed", - "Error: Failed to destroy 1 personal cloud VM", + "account.delete.partial_after_destructive_cleanup", + "AccountDeletionDestructiveCleanupError: Failed to destroy 1 personal cloud VM", ); }); From e6e792c9bb2dbd2f938be766f68885f14c3685bf Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Wed, 8 Jul 2026 23:23:03 -0700 Subject: [PATCH 28/89] Classify irreversible deletion cleanup safely --- web/app/api/account/route.ts | 6 ++++-- web/tests/account-route.test.ts | 33 ++++++++++++++++++++++++++++++--- 2 files changed, 34 insertions(+), 5 deletions(-) diff --git a/web/app/api/account/route.ts b/web/app/api/account/route.ts index 32e4e2987ad1..6fede2e43901 100644 --- a/web/app/api/account/route.ts +++ b/web/app/api/account/route.ts @@ -71,6 +71,7 @@ export async function DELETE(request: Request): Promise { await resolveUserBillingForAccountDeletion(user.id, { beforeExternalMutation: () => { restoreBillingEntitlementsOnFailure = false; + destructiveCleanupStarted = true; }, }); try { @@ -109,9 +110,10 @@ export async function DELETE(request: Request): Promise { } catch (error) { logAccountDeleteError("account.delete.post_stack_cleanup_failed", error); return jsonResponse({ - error: "account_delete_incomplete", + ok: true, + cleanupIncomplete: true, destroyedVms, - }, 500); + }, 202); } return jsonResponse({ ok: true, destroyedVms }); } catch (error) { diff --git a/web/tests/account-route.test.ts b/web/tests/account-route.test.ts index f1f3a07d7413..4c99eaabadd3 100644 --- a/web/tests/account-route.test.ts +++ b/web/tests/account-route.test.ts @@ -520,6 +520,32 @@ describe("account deletion route", () => { expect(updateStackUser).toHaveBeenCalledTimes(1); }); + test("keeps deletion retryable when Stripe cleanup mutates billing before failing", async () => { + selectResults = [ + [{ id: "sub_user_active" }], + [{ id: "cus_user" }], + ]; + stripeDeleteCustomerError = new Error("stripe unavailable"); + + const response = await DELETE(accountDeletionRequest()); + + expect(response.status).toBe(500); + expect(await response.json()).toEqual({ + error: "account_delete_retryable", + retryable: true, + destroyedVms: 0, + }); + expect(cancelledStripeSubscriptions).toEqual(["sub_user_active"]); + expect(deletedStripeCustomers).toEqual(["cus_user"]); + expect(listUserVms).not.toHaveBeenCalled(); + expect(transaction).not.toHaveBeenCalled(); + expect(deleteStackUser).not.toHaveBeenCalled(); + expect(updateStackUser).toHaveBeenNthCalledWith(1, { + clientReadOnlyMetadata: { cmuxAccountDeleting: true }, + }); + expect(updateStackUser).toHaveBeenCalledTimes(1); + }); + test("keeps deletion retryable when any VM was destroyed before a teardown error", async () => { destroyVmFailureProviderIds = new Set(["personal-vm-1"]); @@ -610,7 +636,7 @@ describe("account deletion route", () => { ); }); - test("returns incomplete deletion when post-Stack cleanup fails after the account is deleted", async () => { + test("returns accepted deletion when post-Stack cleanup fails after the account is deleted", async () => { postStackVaultDeleteError = new Error("post-delete vault unavailable"); selectResults = [ [], @@ -628,9 +654,10 @@ describe("account deletion route", () => { const response = await DELETE(accountDeletionRequest()); - expect(response.status).toBe(500); + expect(response.status).toBe(202); expect(await response.json()).toEqual({ - error: "account_delete_incomplete", + ok: true, + cleanupIncomplete: true, destroyedVms: 2, }); expect(deleteStackUser).toHaveBeenCalledTimes(1); From 3f2d3a592bfcbb00a793418f4636a0563b8a6c1c Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Wed, 8 Jul 2026 23:34:53 -0700 Subject: [PATCH 29/89] Surface incomplete deletion cleanup on iOS --- .../Coordinator/AccountDeletionClient.swift | 14 ++++++++++-- .../Coordinator/AccountDeletionResult.swift | 9 ++++++++ .../AuthCoordinator+AccountDeletion.swift | 4 ++-- .../AccountDeletionClientTests.swift | 21 +++++++++++++++++- .../MobileSettingsAccountSection.swift | 22 ++++++++++++++----- ...bileSettingsDeleteAccountFailureKind.swift | 6 +++++ ios/cmux/Resources/Localizable.xcstrings | 17 ++++++++++++++ 7 files changed, 82 insertions(+), 11 deletions(-) create mode 100644 Packages/Shared/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AccountDeletionResult.swift diff --git a/Packages/Shared/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AccountDeletionClient.swift b/Packages/Shared/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AccountDeletionClient.swift index 85fd2a95e1da..f200ac927e70 100644 --- a/Packages/Shared/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AccountDeletionClient.swift +++ b/Packages/Shared/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AccountDeletionClient.swift @@ -20,7 +20,7 @@ struct AccountDeletionClient: Sendable { } @concurrent - func deleteAccount(accessToken: String, refreshToken: String) async throws { + func deleteAccount(accessToken: String, refreshToken: String) async throws -> AccountDeletionResult { let trimmedBaseURL = apiBaseURL.hasSuffix("/") ? String(apiBaseURL.dropLast()) : apiBaseURL guard let url = URL(string: trimmedBaseURL + "/api/account") else { throw AccountDeletionRequestError.invalidAPIBaseURL @@ -48,7 +48,7 @@ struct AccountDeletionClient: Sendable { } switch httpResponse.statusCode { case 200..<300: - return + return accountDeletionResult(in: data) case 401: throw AccountDeletionRequestError.unauthorized default: @@ -67,6 +67,16 @@ struct AccountDeletionClient: Sendable { } } +private func accountDeletionResult(in data: Data) -> AccountDeletionResult { + guard + let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any], + object["cleanupIncomplete"] as? Bool == true + else { + return .completed + } + return .completedWithIncompleteServerCleanup +} + private func accountDeletionErrorCode(in data: Data) -> String? { guard let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any], diff --git a/Packages/Shared/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AccountDeletionResult.swift b/Packages/Shared/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AccountDeletionResult.swift new file mode 100644 index 000000000000..b2b78ffc4dd8 --- /dev/null +++ b/Packages/Shared/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AccountDeletionResult.swift @@ -0,0 +1,9 @@ +import Foundation + +/// Result returned after the backend accepted account deletion. +public enum AccountDeletionResult: Equatable, Sendable { + /// Stack and cmux cleanup completed. + case completed + /// Stack account deletion completed, but the backend reported follow-up cmux cleanup needs support attention. + case completedWithIncompleteServerCleanup +} diff --git a/Packages/Shared/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AuthCoordinator+AccountDeletion.swift b/Packages/Shared/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AuthCoordinator+AccountDeletion.swift index 4d194f7659ed..6c95dbac22e0 100644 --- a/Packages/Shared/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AuthCoordinator+AccountDeletion.swift +++ b/Packages/Shared/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AuthCoordinator+AccountDeletion.swift @@ -5,13 +5,13 @@ extension AuthCoordinator { /// /// Callers clear local shell/auth state through their normal sign-out owner /// after this succeeds so app-level teardown hooks run in the right order. - public func deleteAccount() async throws { + public func deleteAccount() async throws -> AccountDeletionResult { let apiBaseURL = apiBaseURL let timeout = timeouts.network let tokens = try await runTokenTouchingPhase(.accountDeletion, timeout: timeout) { try await self.currentTokens() } - try await AccountDeletionClient( + return try await AccountDeletionClient( apiBaseURL: apiBaseURL, requestTimeout: timeout.urlRequestTimeoutInterval ).deleteAccount( diff --git a/Packages/Shared/CmuxAuthRuntime/Tests/CmuxAuthRuntimeTests/AccountDeletionClientTests.swift b/Packages/Shared/CmuxAuthRuntime/Tests/CmuxAuthRuntimeTests/AccountDeletionClientTests.swift index 0a3f0b31639d..abcfc5c42f55 100644 --- a/Packages/Shared/CmuxAuthRuntime/Tests/CmuxAuthRuntimeTests/AccountDeletionClientTests.swift +++ b/Packages/Shared/CmuxAuthRuntime/Tests/CmuxAuthRuntimeTests/AccountDeletionClientTests.swift @@ -18,9 +18,10 @@ struct AccountDeletionClientTests { ) } - try await client.deleteAccount(accessToken: "access-token", refreshToken: "refresh-token") + let result = try await client.deleteAccount(accessToken: "access-token", refreshToken: "refresh-token") let request = await recorder.request + #expect(result == .completed) #expect(request?.url?.absoluteString == "https://cmux.test/base/api/account") #expect(request?.httpMethod == "DELETE") #expect(request?.timeoutInterval == 12) @@ -28,6 +29,24 @@ struct AccountDeletionClientTests { #expect(request?.value(forHTTPHeaderField: "X-Stack-Refresh-Token") == "refresh-token") } + @Test func deleteAccountMapsCleanupIncompleteAcceptedResponse() async throws { + let client = AccountDeletionClient(apiBaseURL: "https://cmux.test") { request in + ( + Data(#"{"ok":true,"cleanupIncomplete":true}"#.utf8), + HTTPURLResponse( + url: request.url!, + statusCode: 202, + httpVersion: nil, + headerFields: nil + )! + ) + } + + let result = try await client.deleteAccount(accessToken: "access-token", refreshToken: "refresh-token") + + #expect(result == .completedWithIncompleteServerCleanup) + } + @Test func deleteAccountMapsUnauthorizedResponse() async { let client = AccountDeletionClient(apiBaseURL: "https://cmux.test") { request in ( diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsAccountSection.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsAccountSection.swift index eecccc9e6e2a..55573f13aeef 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsAccountSection.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsAccountSection.swift @@ -94,13 +94,15 @@ struct MobileSettingsAccountSection: View { deletingAccount = false } do { - try await authManager.deleteAccount() - if let signOut { - signOut() - } else { - await authManager.signOut() + let result = try await authManager.deleteAccount() + await signOutDeletedAccount() + switch result { + case .completed: + dismiss() + case .completedWithIncompleteServerCleanup: + deleteAccountFailureKind = .serverCleanupIncomplete + showingDeleteAccountFailure = true } - dismiss() } catch { if case AccountDeletionRequestError.stackDeleteIncomplete = error { deleteAccountFailureKind = .stackDeleteIncomplete @@ -120,6 +122,14 @@ struct MobileSettingsAccountSection: View { } } + private func signOutDeletedAccount() async { + if let signOut { + signOut() + } else { + await authManager.signOut() + } + } + private var accountEmail: String { let email = authManager.currentUser?.primaryEmail?.trimmingCharacters(in: .whitespacesAndNewlines) if let email, !email.isEmpty { return email } diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsDeleteAccountFailureKind.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsDeleteAccountFailureKind.swift index ca90f34a526a..9c909bfc2512 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsDeleteAccountFailureKind.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsDeleteAccountFailureKind.swift @@ -5,6 +5,7 @@ enum DeleteAccountFailureKind { case generic case connection case stackDeleteIncomplete + case serverCleanupIncomplete case timedOut case unknown @@ -25,6 +26,11 @@ enum DeleteAccountFailureKind { "mobile.settings.deleteAccountPartialFailureMessage", defaultValue: "Your cmux data was deleted, but account sign-in cleanup did not finish. Try Delete Account again to complete deletion." ) + case .serverCleanupIncomplete: + return L10n.string( + "mobile.settings.deleteAccountServerCleanupIncompleteMessage", + defaultValue: "Your account sign-in was deleted, but some cmux cleanup did not finish. You have been signed out. Contact support if cmux data is still visible." + ) case .timedOut: return L10n.string( "mobile.settings.deleteAccountTimedOutMessage", diff --git a/ios/cmux/Resources/Localizable.xcstrings b/ios/cmux/Resources/Localizable.xcstrings index 7dcf4895d1a5..718c07526d2b 100644 --- a/ios/cmux/Resources/Localizable.xcstrings +++ b/ios/cmux/Resources/Localizable.xcstrings @@ -4115,6 +4115,23 @@ } } }, + "mobile.settings.deleteAccountServerCleanupIncompleteMessage": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Your account sign-in was deleted, but some cmux cleanup did not finish. You have been signed out. Contact support if cmux data is still visible." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "アカウントのサインイン情報は削除されましたが、一部の cmux クリーンアップは完了しませんでした。サインアウトしました。cmux データがまだ表示される場合はサポートにお問い合わせください。" + } + } + } + }, "mobile.settings.deleteAccountTimedOutMessage": { "extractionState": "manual", "localizations": { From 41a10e4c5d9d103a71fac72a5773ffaa98f09029 Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Wed, 8 Jul 2026 23:48:58 -0700 Subject: [PATCH 30/89] Keep deletion retries safe after provider attempts --- web/app/api/account/route.ts | 9 +++-- web/services/billing/purchase.ts | 25 ++++++++++--- web/tests/account-route.test.ts | 26 ++++++++++++++ web/tests/billing-purchase.test.ts | 57 ++++++++++++++++++++++++++++-- 4 files changed, 109 insertions(+), 8 deletions(-) diff --git a/web/app/api/account/route.ts b/web/app/api/account/route.ts index 6fede2e43901..e16102ec7069 100644 --- a/web/app/api/account/route.ts +++ b/web/app/api/account/route.ts @@ -80,7 +80,7 @@ export async function DELETE(request: Request): Promise { } catch (error) { if (error instanceof AccountDeletionDestructiveCleanupError) { destroyedVms = error.destroyedVms; - destructiveCleanupStarted = destroyedVms > 0; + destructiveCleanupStarted = error.destructiveCleanupStarted; } throw error; } @@ -158,6 +158,7 @@ class AccountDeletionDestructiveCleanupError extends Error { constructor( message: string, readonly destroyedVms: number, + readonly destructiveCleanupStarted: boolean, ) { super(message); this.name = "AccountDeletionDestructiveCleanupError"; @@ -168,9 +169,12 @@ async function destroyPersonalCloudVms(userId: string): Promise { const vms = await runVmWorkflow(listUserVms(userId)); const failures: unknown[] = []; let destroyedVms = 0; + let destructiveCleanupStarted = false; for (const vm of vms) { try { - await runVmWorkflow(destroyVm({ userId, providerVmId: vm.providerVmId })); + const destroyProgram = destroyVm({ userId, providerVmId: vm.providerVmId }); + destructiveCleanupStarted = true; + await runVmWorkflow(destroyProgram); destroyedVms += 1; } catch (error) { failures.push(error); @@ -181,6 +185,7 @@ async function destroyPersonalCloudVms(userId: string): Promise { throw new AccountDeletionDestructiveCleanupError( `Failed to destroy ${failures.length} personal cloud VM${failures.length === 1 ? "" : "s"}`, destroyedVms, + destructiveCleanupStarted, ); } return destroyedVms; diff --git a/web/services/billing/purchase.ts b/web/services/billing/purchase.ts index 0e7c818273b1..551dab86434d 100644 --- a/web/services/billing/purchase.ts +++ b/web/services/billing/purchase.ts @@ -24,6 +24,7 @@ export const ACTIVE_STRIPE_SUBSCRIPTION_STATUSES = new Set([ "trialing", "past_due", ]); +const DELETED_ACCOUNT_ACTOR_ID = "deleted-account"; type BillingDb = ReturnType; @@ -188,19 +189,25 @@ export async function applySubscriptionUpdate( return { scope: "team", stackTeamId: teamScope.stackTeamId, isActive }; } + const metadataStackUserId = subscription.metadata?.stackUserId; const mappedStackUserId = await stackUserIdForStripeCustomer(db, customerId); - const stackUserId = subscription.metadata?.stackUserId ?? mappedStackUserId; - if (!stackUserId) return { skipped: true }; + if (mappedStackUserId === DELETED_ACCOUNT_ACTOR_ID) return { skipped: true }; + const stackUserId = metadataStackUserId ?? mappedStackUserId; + if (!stackUserId || stackUserId === DELETED_ACCOUNT_ACTOR_ID) return { skipped: true }; const isActive = isActiveStripeSubscriptionStatus(subscription.status); const hasUserSubscription = await userStripeSubscriptionExists(db, { subscriptionId: subscription.id, stackUserId, }); - if (!hasUserSubscription && mappedStackUserId !== stackUserId) return { skipped: true }; + if ( + !hasUserSubscription && + mappedStackUserId !== stackUserId && + metadataStackUserId !== stackUserId + ) return { skipped: true }; const user = await loadOptionalStackUser(stackUserId, dependencies.stackApp); - if (!user) return { skipped: true }; + if (!user || isAccountDeletionInProgress(user)) return { skipped: true }; if (hasUserSubscription) { await updateExistingUserStripeSubscription(db, { @@ -224,6 +231,16 @@ export async function applySubscriptionUpdate( return { scope: "user", stackUserId, isActive }; } +function isAccountDeletionInProgress(user: StackBillingUser): boolean { + const metadata = user.clientReadOnlyMetadata; + return Boolean( + metadata && + typeof metadata === "object" && + !Array.isArray(metadata) && + (metadata as Record).cmuxAccountDeleting === true + ); +} + export async function latestStripeSubscriptionForSession( session: Stripe.Checkout.Session, db: BillingDb = cloudDb(), diff --git a/web/tests/account-route.test.ts b/web/tests/account-route.test.ts index 4c99eaabadd3..a49bd8e2c55e 100644 --- a/web/tests/account-route.test.ts +++ b/web/tests/account-route.test.ts @@ -576,6 +576,32 @@ describe("account deletion route", () => { ); }); + test("keeps deletion retryable when VM teardown may have reached the provider", async () => { + destroyVmFailureProviderIds = new Set(["personal-vm-1", "personal-vm-2"]); + + const response = await DELETE(accountDeletionRequest()); + + expect(response.status).toBe(500); + expect(await response.json()).toEqual({ + error: "account_delete_retryable", + retryable: true, + destroyedVms: 0, + }); + expect(destroyVm).toHaveBeenCalledTimes(2); + expect(destroyVm).toHaveBeenCalledWith({ userId: "account-user-1", providerVmId: "personal-vm-1" }); + expect(destroyVm).toHaveBeenCalledWith({ userId: "account-user-1", providerVmId: "personal-vm-2" }); + expect(transaction).not.toHaveBeenCalled(); + expect(deleteStackUser).not.toHaveBeenCalled(); + expect(updateStackUser).toHaveBeenNthCalledWith(1, { + clientReadOnlyMetadata: { cmuxAccountDeleting: true }, + }); + expect(updateStackUser).toHaveBeenCalledTimes(1); + expect(consoleError).toHaveBeenCalledWith( + "account.delete.partial_after_destructive_cleanup", + "AccountDeletionDestructiveCleanupError: Failed to destroy 2 personal cloud VMs", + ); + }); + test("does not delete rows or Stack user when active billing cleanup cannot run", async () => { selectResults = [ [{ id: "sub_user_active" }], diff --git a/web/tests/billing-purchase.test.ts b/web/tests/billing-purchase.test.ts index b1686ea72e1e..c73a50492d42 100644 --- a/web/tests/billing-purchase.test.ts +++ b/web/tests/billing-purchase.test.ts @@ -562,11 +562,11 @@ describe("recordCheckoutCompletion", () => { expect(removeTester).not.toHaveBeenCalled(); }); - test("skips user subscription webhooks after local billing rows are gone", async () => { + test("skips user subscription webhooks while account deletion is in progress", async () => { const getUser = mock(async () => ({ id: "user_123", primaryEmail: "buyer@example.com", - clientReadOnlyMetadata: { cmuxPlan: "pro" }, + clientReadOnlyMetadata: { cmuxAccountDeleting: true, cmuxPlan: "pro" }, update: mock(async () => undefined), })); selectResults = [[], []]; @@ -579,12 +579,65 @@ describe("recordCheckoutCompletion", () => { }, ); + expect(result).toEqual({ skipped: true }); + expect(getUser).toHaveBeenCalledWith("user_123"); + expect(inserts.some((insert) => insert.table === stripeSubscriptions)).toBe(false); + expect(updates.some((update) => update.table === stripeSubscriptions)).toBe(false); + }); + + test("skips user subscription webhooks for anonymized local customer rows", async () => { + const getUser = mock(async () => { + throw new Error("should not load Stack user for anonymized local customer"); + }); + selectResults = [[{ stackUserId: "deleted-account" }]]; + + const result = await applySubscriptionUpdate( + userSubscriptionUpdate({ status: "active" }) as never, + { + db: fakeDb() as never, + stackApp: { getUser } as never, + }, + ); + expect(result).toEqual({ skipped: true }); expect(getUser).not.toHaveBeenCalled(); expect(inserts.some((insert) => insert.table === stripeSubscriptions)).toBe(false); expect(updates.some((update) => update.table === stripeSubscriptions)).toBe(false); }); + test("creates a missing user subscription row from Stripe metadata", async () => { + const update = mock(async () => undefined); + const user = { + id: "user_123", + primaryEmail: "buyer@example.com", + clientReadOnlyMetadata: {}, + update, + }; + selectResults = [[], []]; + + const result = await applySubscriptionUpdate( + userSubscriptionUpdate({ status: "active" }) as never, + { + db: fakeDb() as never, + stackApp: { getUser: async () => user } as never, + }, + ); + + expect(result).toEqual({ scope: "user", stackUserId: "user_123", isActive: true }); + expect( + inserts.some( + (insert) => + insert.table === stripeSubscriptions && + insert.values.id === "sub_user" && + insert.values.scope === "user" && + insert.values.stackUserId === "user_123", + ), + ).toBe(true); + expect(update).toHaveBeenCalledWith({ + clientReadOnlyMetadata: { cmuxPlan: "pro" }, + }); + }); + test("creates a missing user subscription row when the customer mapping already exists", async () => { const user = { id: "user_123", From 2db126f694ee65e110181e731b41866ec8530fde Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Thu, 9 Jul 2026 00:07:59 -0700 Subject: [PATCH 31/89] Close account deletion cleanup gaps --- .../MobileSettingsAccountSection.swift | 18 ++- ...bileSettingsDeleteAccountFailureKind.swift | 6 +- ...ettingsDeleteAccountFailureKindTests.swift | 15 +++ ios/cmux/Resources/Localizable.xcstrings | 4 +- web/app/api/account/route.ts | 32 ++++- web/services/vms/repository.ts | 31 +++++ web/services/vms/workflows.ts | 26 ++++ web/tests/account-route.test.ts | 116 ++++++++++++++++++ web/tests/vm-workflows.test.ts | 98 +++++++++++++++ 9 files changed, 339 insertions(+), 7 deletions(-) create mode 100644 Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/MobileSettingsDeleteAccountFailureKindTests.swift diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsAccountSection.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsAccountSection.swift index 55573f13aeef..753abcd83779 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsAccountSection.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsAccountSection.swift @@ -13,6 +13,7 @@ struct MobileSettingsAccountSection: View { @State private var deleteAccountFailureKind = DeleteAccountFailureKind.generic @State private var deletingAccount = false @State private var deleteAccountTask: Task? + @State private var signOutAfterDeleteAccountFailureAcknowledgement = false var body: some View { Section { @@ -79,7 +80,9 @@ struct MobileSettingsAccountSection: View { L10n.string("mobile.settings.deleteAccountFailedTitle", defaultValue: "Couldn't Delete Account"), isPresented: $showingDeleteAccountFailure ) { - Button(L10n.string("mobile.settings.deleteAccountFailureOK", defaultValue: "OK"), role: .cancel) {} + Button(L10n.string("mobile.settings.deleteAccountFailureOK", defaultValue: "OK"), role: .cancel) { + acknowledgeDeleteAccountFailure() + } } message: { Text(deleteAccountFailureKind.localizedMessage) } @@ -95,12 +98,13 @@ struct MobileSettingsAccountSection: View { } do { let result = try await authManager.deleteAccount() - await signOutDeletedAccount() switch result { case .completed: + await signOutDeletedAccount() dismiss() case .completedWithIncompleteServerCleanup: deleteAccountFailureKind = .serverCleanupIncomplete + signOutAfterDeleteAccountFailureAcknowledgement = deleteAccountFailureKind.signsOutAfterAcknowledgement showingDeleteAccountFailure = true } } catch { @@ -117,11 +121,21 @@ struct MobileSettingsAccountSection: View { } else { deleteAccountFailureKind = .generic } + signOutAfterDeleteAccountFailureAcknowledgement = deleteAccountFailureKind.signsOutAfterAcknowledgement showingDeleteAccountFailure = true } } } + private func acknowledgeDeleteAccountFailure() { + guard signOutAfterDeleteAccountFailureAcknowledgement else { return } + signOutAfterDeleteAccountFailureAcknowledgement = false + Task { + await signOutDeletedAccount() + dismiss() + } + } + private func signOutDeletedAccount() async { if let signOut { signOut() diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsDeleteAccountFailureKind.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsDeleteAccountFailureKind.swift index 9c909bfc2512..002e614c1259 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsDeleteAccountFailureKind.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsDeleteAccountFailureKind.swift @@ -9,6 +9,10 @@ enum DeleteAccountFailureKind { case timedOut case unknown + var signsOutAfterAcknowledgement: Bool { + self == .serverCleanupIncomplete + } + var localizedMessage: String { switch self { case .generic: @@ -29,7 +33,7 @@ enum DeleteAccountFailureKind { case .serverCleanupIncomplete: return L10n.string( "mobile.settings.deleteAccountServerCleanupIncompleteMessage", - defaultValue: "Your account sign-in was deleted, but some cmux cleanup did not finish. You have been signed out. Contact support if cmux data is still visible." + defaultValue: "Your account sign-in was deleted, but some cmux cleanup did not finish. You will be signed out. Contact support if cmux data is still visible." ) case .timedOut: return L10n.string( diff --git a/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/MobileSettingsDeleteAccountFailureKindTests.swift b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/MobileSettingsDeleteAccountFailureKindTests.swift new file mode 100644 index 000000000000..e709023bc298 --- /dev/null +++ b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/MobileSettingsDeleteAccountFailureKindTests.swift @@ -0,0 +1,15 @@ +#if os(iOS) +import Testing +@testable import CmuxMobileShellUI + +@Suite struct MobileSettingsDeleteAccountFailureKindTests { + @Test func cleanupIncompleteSignsOutAfterAcknowledgementOnly() { + #expect(DeleteAccountFailureKind.serverCleanupIncomplete.signsOutAfterAcknowledgement) + #expect(!DeleteAccountFailureKind.generic.signsOutAfterAcknowledgement) + #expect(!DeleteAccountFailureKind.connection.signsOutAfterAcknowledgement) + #expect(!DeleteAccountFailureKind.stackDeleteIncomplete.signsOutAfterAcknowledgement) + #expect(!DeleteAccountFailureKind.timedOut.signsOutAfterAcknowledgement) + #expect(!DeleteAccountFailureKind.unknown.signsOutAfterAcknowledgement) + } +} +#endif diff --git a/ios/cmux/Resources/Localizable.xcstrings b/ios/cmux/Resources/Localizable.xcstrings index 718c07526d2b..c5e6b34d4f53 100644 --- a/ios/cmux/Resources/Localizable.xcstrings +++ b/ios/cmux/Resources/Localizable.xcstrings @@ -4121,13 +4121,13 @@ "en": { "stringUnit": { "state": "translated", - "value": "Your account sign-in was deleted, but some cmux cleanup did not finish. You have been signed out. Contact support if cmux data is still visible." + "value": "Your account sign-in was deleted, but some cmux cleanup did not finish. You will be signed out. Contact support if cmux data is still visible." } }, "ja": { "stringUnit": { "state": "translated", - "value": "アカウントのサインイン情報は削除されましたが、一部の cmux クリーンアップは完了しませんでした。サインアウトしました。cmux データがまだ表示される場合はサポートにお問い合わせください。" + "value": "アカウントのサインイン情報は削除されましたが、一部の cmux クリーンアップは完了しませんでした。サインアウトします。cmux データがまだ表示される場合はサポートにお問い合わせください。" } } } diff --git a/web/app/api/account/route.ts b/web/app/api/account/route.ts index e16102ec7069..d3cadef6e688 100644 --- a/web/app/api/account/route.ts +++ b/web/app/api/account/route.ts @@ -39,7 +39,12 @@ import { import { deleteObject } from "../../../services/vault/storage"; import { unauthorized, verifyRequest } from "../../../services/vms/auth"; import { jsonResponse } from "../../../services/vms/routeHelpers"; -import { destroyVm, listUserVms, runVmWorkflow } from "../../../services/vms/workflows"; +import { + destroyVm, + listUserVms, + revokeUserIdentityLeasesForAccountDeletion, + runVmWorkflow, +} from "../../../services/vms/workflows"; export const runtime = "nodejs"; export const dynamic = "force-dynamic"; @@ -89,6 +94,7 @@ export async function DELETE(request: Request): Promise { destructiveCleanupStarted = true; await deletePersonalSubrouterTenant(user.id); destructiveCleanupStarted = true; + await runVmWorkflow(revokeUserIdentityLeasesForAccountDeletion(user.id)); // Delete cmux-owned data before the Stack user so a Stack-side failure does // not strand retained app data behind an account the user can no longer use. // These deletes are idempotent, so the same signed-in user can retry the @@ -385,6 +391,26 @@ async function deleteCmuxOwnedAccountRows(userId: string): Promise { const db = cloudDb(); await db.transaction(async (tx) => { const now = new Date(); + const personalVmRows = await tx + .select({ + id: cloudVms.id, + providerVmId: cloudVms.providerVmId, + status: cloudVms.status, + }) + .from(cloudVms) + .where(personalVmScope(userId)) + .for("update"); + const unsafePersonalVmRows = personalVmRows.filter((vm) => { + if (vm.status === "destroyed") return false; + if (vm.status === "failed" && !vm.providerVmId) return false; + return true; + }); + if (unsafePersonalVmRows.length > 0) { + throw new Error( + `Personal cloud VM provider teardown or creation is still pending for ${unsafePersonalVmRows.length} row${unsafePersonalVmRows.length === 1 ? "" : "s"}`, + ); + } + await tx.delete(deviceTokens).where(eq(deviceTokens.userId, userId)); await tx.delete(notificationSendEvents).where(eq(notificationSendEvents.userId, userId)); @@ -426,7 +452,9 @@ async function deleteCmuxOwnedAccountRows(userId: string): Promise { await tx.delete(cloudVmUsageEvents).where(eq(cloudVmUsageEvents.userId, userId)); await tx.delete(cloudVmLeases).where(eq(cloudVmLeases.userId, userId)); await tx.delete(cloudVmSessions).where(eq(cloudVmSessions.userId, userId)); - await tx.delete(cloudVms).where(personalVmScope(userId)); + if (personalVmRows.length > 0) { + await tx.delete(cloudVms).where(inArray(cloudVms.id, personalVmRows.map((vm) => vm.id))); + } await tx.delete(cloudVmBaseEvents).where(eq(cloudVmBaseEvents.userId, userId)); await tx.delete(cloudVmBases).where(and( eq(cloudVmBases.scopeType, "user"), diff --git a/web/services/vms/repository.ts b/web/services/vms/repository.ts index 0e69dbd72573..f47dcdfe763e 100644 --- a/web/services/vms/repository.ts +++ b/web/services/vms/repository.ts @@ -173,6 +173,7 @@ export type VmRepositoryShape = { readonly now: Date; readonly limit: number; }) => Effect.Effect; + readonly accountDeletionIdentityLeases: (userId: string) => Effect.Effect; readonly markLeaseRevocationRetry?: (input: { readonly id: string; readonly retryAfter: Date; @@ -1258,6 +1259,36 @@ export const VmRepositoryLive = Layer.succeed(VmRepository, { .limit(input.limit); }), + accountDeletionIdentityLeases: (userId) => + dbEffect("accountDeletionIdentityLeases", async () => { + const db = cloudDb(); + return await db + .select({ + id: cloudVmLeases.id, + vmId: cloudVmLeases.vmId, + userId: cloudVmLeases.userId, + kind: cloudVmLeases.kind, + tokenHash: cloudVmLeases.tokenHash, + providerIdentityHandle: cloudVmLeases.providerIdentityHandle, + sessionId: cloudVmLeases.sessionId, + transport: cloudVmLeases.transport, + metadata: cloudVmLeases.metadata, + expiresAt: cloudVmLeases.expiresAt, + consumedAt: cloudVmLeases.consumedAt, + revokedAt: cloudVmLeases.revokedAt, + createdAt: cloudVmLeases.createdAt, + provider: cloudVms.provider, + }) + .from(cloudVmLeases) + .innerJoin(cloudVms, eq(cloudVmLeases.vmId, cloudVms.id)) + .where(and( + eq(cloudVmLeases.userId, userId), + isNotNull(cloudVmLeases.providerIdentityHandle), + isNull(cloudVmLeases.revokedAt), + )) + .orderBy(asc(cloudVmLeases.createdAt), asc(cloudVmLeases.id)); + }), + markLeaseRevocationRetry: (input) => dbEffect("markLeaseRevocationRetry", async () => { const db = cloudDb(); diff --git a/web/services/vms/workflows.ts b/web/services/vms/workflows.ts index 4384e1dfee89..d4b7bba01c6d 100644 --- a/web/services/vms/workflows.ts +++ b/web/services/vms/workflows.ts @@ -1310,6 +1310,32 @@ export function revokeExpiredIdentityLeases(input: { }); } +export function revokeUserIdentityLeasesForAccountDeletion(userId: string) { + return Effect.gen(function* () { + const repo = yield* VmRepository; + const providers = yield* VmProviderGateway; + const leases = yield* repo.accountDeletionIdentityLeases(userId); + const revokedIds: string[] = []; + for (const lease of leases) { + const identityHandle = lease.providerIdentityHandle; + if (!identityHandle) continue; + const revoked = yield* revokeSSHIdentityForCleanup(providers, lease.provider, identityHandle).pipe( + Effect.as(true), + Effect.catchAll((err) => { + if (isProviderIdentityNotFoundError(err.cause)) return Effect.succeed(true); + return repo.markLeasesRevoked(revokedIds).pipe( + Effect.catchAll(() => Effect.void), + Effect.andThen(Effect.fail(err)), + ); + }), + ); + if (revoked) revokedIds.push(lease.id); + } + yield* repo.markLeasesRevoked(revokedIds); + return revokedIds.length; + }); +} + export function execVm(input: { readonly userId: string; readonly billingTeamId?: string | null; diff --git a/web/tests/account-route.test.ts b/web/tests/account-route.test.ts index a49bd8e2c55e..0357fb3ed642 100644 --- a/web/tests/account-route.test.ts +++ b/web/tests/account-route.test.ts @@ -4,6 +4,7 @@ import { cloudVmBaseGenerations, cloudVmBases, cloudVmBillingGrants, + cloudVmLeases, cloudVms, devices, stripeCustomers, @@ -39,6 +40,7 @@ const realCreateSubrouterClientFromEnv = subrouterClientModule.createSubrouterCl const workflowsModule = await import("../services/vms/workflows"); const realDestroyVm = workflowsModule.destroyVm; const realListUserVms = workflowsModule.listUserVms; +const realRevokeUserIdentityLeasesForAccountDeletion = workflowsModule.revokeUserIdentityLeasesForAccountDeletion; const realRunVmWorkflow = workflowsModule.runVmWorkflow as (...args: unknown[]) => unknown; const deleteStackUser = mock(async () => { @@ -54,6 +56,13 @@ const transaction = mock(async (...args: unknown[]) => { routeEvents.push("transaction"); await callback(mockTransaction); }); +const transactionSelect = mock(() => ({ + from: () => ({ + where: () => ({ + for: async () => nextTransactionSelectResult(), + }), + }), +})); const deleteRows = mock((table: unknown) => { deletedTables.push(table); deletedTableCount += 1; @@ -75,6 +84,13 @@ const listUserVms = mock((...args: unknown[]) => { const [userId] = args as [string]; return { kind: "listUserVms" as const, userId }; }); +const revokeUserIdentityLeasesForAccountDeletion = mock((...args: unknown[]) => { + const [userId] = args as [string]; + return { + kind: "revokeUserIdentityLeasesForAccountDeletion" as const, + userId, + }; +}); const destroyVm = mock((...args: unknown[]) => { const [input] = args as [{ readonly userId: string; readonly providerVmId: string }]; return { @@ -91,6 +107,11 @@ const runVmWorkflow = mock(async (...args: unknown[]) => { { providerVmId: "personal-vm-2" }, ]; } + if (program.kind === "revokeUserIdentityLeasesForAccountDeletion") { + routeEvents.push("revoke-identities"); + if (revokeIdentityLeasesError) throw revokeIdentityLeasesError; + return 2; + } routeEvents.push("destroy-vm"); if (destroyVmFailureProviderIds.has(program.input.providerVmId)) { throw new Error(`destroy failed for ${program.input.providerVmId}`); @@ -132,6 +153,7 @@ let routeEvents: string[] = []; let stackDeleteError: unknown = null; let stackUserIds: Array = []; let selectResults: unknown[][] = []; +let transactionSelectResults: unknown[][] = []; let deletedVaultObjects: string[] = []; let vaultDeleteError: unknown = null; let postStackVaultDeleteError: unknown = null; @@ -141,6 +163,7 @@ let deletedStripeCustomers: string[] = []; let stripeCancelError: unknown = null; let stripeDeleteCustomerError: unknown = null; let destroyVmFailureProviderIds = new Set(); +let revokeIdentityLeasesError: unknown = null; let subrouterRevokeError: unknown = null; let useAccountRouteStubs = false; const originalConsoleError = console.error; @@ -148,9 +171,17 @@ const consoleError = mock(() => {}); type WorkflowProgram = | { readonly kind: "listUserVms"; readonly userId: string } + | { readonly kind: "revokeUserIdentityLeasesForAccountDeletion"; readonly userId: string } | { readonly kind: "destroyVm"; readonly input: { readonly userId: string; readonly providerVmId: string } }; type MockTransaction = { + readonly select: (...args: unknown[]) => { + readonly from: (...args: unknown[]) => { + readonly where: (...args: unknown[]) => { + readonly for: (...args: unknown[]) => Promise; + }; + }; + }; readonly delete: (table: unknown) => { readonly where: (condition: unknown) => Promise }; readonly update: (table: unknown) => { readonly set: (values: unknown) => { readonly where: (condition: unknown) => Promise }; @@ -164,6 +195,7 @@ type SelectResult = Promise & { }; const mockTransaction: MockTransaction = { + select: transactionSelect, delete: deleteRows, update: updateRows, }; @@ -172,6 +204,10 @@ function nextSelectResult(): unknown[] { return selectResults.shift() ?? []; } +function nextTransactionSelectResult(): unknown[] { + return transactionSelectResults.shift() ?? []; +} + function chainableSelectResult(rows: unknown[]): SelectResult { const result = Promise.resolve(rows) as SelectResult; Object.defineProperties(result, { @@ -245,6 +281,11 @@ mock.module("../services/vms/workflows", () => ({ if (input.userId === ACCOUNT_USER_ID) return destroyVm(...args); return realDestroyVm(...args); }) as typeof realDestroyVm, + revokeUserIdentityLeasesForAccountDeletion: ((...args: Parameters) => { + const [userId] = args; + if (userId === ACCOUNT_USER_ID) return revokeUserIdentityLeasesForAccountDeletion(...args); + return realRevokeUserIdentityLeasesForAccountDeletion(...args); + }) as typeof realRevokeUserIdentityLeasesForAccountDeletion, listUserVms: ((...args: Parameters) => { const [userId] = args; if (userId === ACCOUNT_USER_ID) return listUserVms(...args); @@ -274,10 +315,12 @@ beforeEach(() => { updateStackUser.mockClear(); getUser.mockClear(); transaction.mockClear(); + transactionSelect.mockClear(); deleteRows.mockClear(); updateRows.mockClear(); mockDb.select.mockClear(); listUserVms.mockClear(); + revokeUserIdentityLeasesForAccountDeletion.mockClear(); destroyVm.mockClear(); runVmWorkflow.mockClear(); deleteObject.mockClear(); @@ -292,6 +335,7 @@ beforeEach(() => { stackDeleteError = null; stackUserIds = []; selectResults = [[], [], [], [], [], []]; + transactionSelectResults = []; deletedVaultObjects = []; vaultDeleteError = null; postStackVaultDeleteError = null; @@ -301,6 +345,7 @@ beforeEach(() => { stripeCancelError = null; stripeDeleteCustomerError = null; destroyVmFailureProviderIds = new Set(); + revokeIdentityLeasesError = null; subrouterRevokeError = null; }); @@ -388,6 +433,7 @@ describe("account deletion route", () => { "vault-delete", "vault-delete", "vault-delete", + "revoke-identities", "transaction", "stack-delete", "transaction", @@ -415,6 +461,72 @@ describe("account deletion route", () => { ); }); + test("revokes active account SSH identities before deleting cmux rows", async () => { + const response = await DELETE(accountDeletionRequest()); + + expect(response.status).toBe(200); + expect(revokeUserIdentityLeasesForAccountDeletion).toHaveBeenCalledWith("account-user-1"); + expect(routeEvents.indexOf("revoke-identities")).toBeGreaterThan(-1); + expect(routeEvents.indexOf("revoke-identities")).toBeLessThan(routeEvents.indexOf("transaction")); + expect(deletedTables).toContain(cloudVmLeases); + }); + + test("keeps deletion retryable when account SSH identity revocation fails", async () => { + revokeIdentityLeasesError = new Error("provider identity revoke failed"); + + const response = await DELETE(accountDeletionRequest()); + + expect(response.status).toBe(500); + expect(await response.json()).toEqual({ + error: "account_delete_retryable", + retryable: true, + destroyedVms: 2, + }); + expect(revokeUserIdentityLeasesForAccountDeletion).toHaveBeenCalledWith("account-user-1"); + expect(transaction).not.toHaveBeenCalled(); + expect(deleteStackUser).not.toHaveBeenCalled(); + expect(deletedTables).not.toContain(cloudVmLeases); + }); + + test("does not delete personal VM rows that gained a provider id before account row deletion", async () => { + transactionSelectResults = [[{ + id: "00000000-0000-4000-8000-000000000764", + providerVmId: "provider-vm-raced", + status: "running", + }]]; + + const response = await DELETE(accountDeletionRequest()); + + expect(response.status).toBe(500); + expect(await response.json()).toEqual({ + error: "account_delete_retryable", + retryable: true, + destroyedVms: 2, + }); + expect(transaction).toHaveBeenCalledTimes(1); + expect(transactionSelect).toHaveBeenCalledTimes(1); + expect(deletedTableCount).toBe(0); + expect(deleteStackUser).not.toHaveBeenCalled(); + expect(consoleError).toHaveBeenCalledWith( + "account.delete.partial_after_destructive_cleanup", + "Error: Personal cloud VM provider teardown or creation is still pending for 1 row", + ); + }); + + test("deletes destroyed personal VM rows after provider teardown completed", async () => { + transactionSelectResults = [[{ + id: "00000000-0000-4000-8000-000000000765", + providerVmId: "provider-vm-destroyed", + status: "destroyed", + }]]; + + const response = await DELETE(accountDeletionRequest()); + + expect(response.status).toBe(200); + expect(deletedTables).toContain(cloudVms); + expect(deleteStackUser).toHaveBeenCalledTimes(1); + }); + test("anonymizes shared team devices registered by the deleted user", async () => { const response = await DELETE(accountDeletionRequest()); @@ -653,6 +765,7 @@ describe("account deletion route", () => { "list-vms", "destroy-vm", "destroy-vm", + "revoke-identities", "transaction", "stack-delete", ]); @@ -789,6 +902,9 @@ function isAccountDeletionWorkflowProgram(program: unknown): boolean { readonly input?: { readonly userId?: unknown }; }; if (candidate.kind === "listUserVms") return candidate.userId === ACCOUNT_USER_ID; + if (candidate.kind === "revokeUserIdentityLeasesForAccountDeletion") { + return candidate.userId === ACCOUNT_USER_ID; + } if (candidate.kind === "destroyVm") return candidate.input?.userId === ACCOUNT_USER_ID; return false; } diff --git a/web/tests/vm-workflows.test.ts b/web/tests/vm-workflows.test.ts index a18c91c9271a..172ab89e42d5 100644 --- a/web/tests/vm-workflows.test.ts +++ b/web/tests/vm-workflows.test.ts @@ -40,6 +40,7 @@ import { openAttachEndpoint, openSshEndpoint, revokeExpiredIdentityLeases, + revokeUserIdentityLeasesForAccountDeletion, resetBaseVm, restoreVm, reconcileVmProviderStatuses, @@ -436,6 +437,81 @@ describe("VM Effect workflows", () => { expect(destroyCalls).toBe(0); }); + test("revokes account-deletion SSH identities and marks their leases revoked", async () => { + const revokedLeaseIds: string[] = []; + const repo = testWorkflowRepo({ + vm: testCloudVmRow(), + accountDeletionIdentityLeases: () => + Effect.succeed([ + testIdentityLease("lease-account-delete-1", "identity-account-delete-1"), + testIdentityLease("lease-account-delete-2", "identity-account-delete-2"), + ]), + revokedLeaseIds, + }); + const revokedIdentities: string[] = []; + const provider: VmProviderGatewayShape = { + ...unusedProviderGateway(), + revokeSSHIdentity: (_provider, identityHandle) => + Effect.sync(() => { + revokedIdentities.push(identityHandle); + }), + }; + + const revokedCount = await Effect.runPromise( + revokeUserIdentityLeasesForAccountDeletion("user-workflow-account-delete").pipe( + Effect.provide(workflowLayer(repo, provider)), + ), + ); + + expect(revokedCount).toBe(2); + expect(revokedIdentities).toEqual([ + "identity-account-delete-1", + "identity-account-delete-2", + ]); + expect(revokedLeaseIds).toEqual([ + "lease-account-delete-1", + "lease-account-delete-2", + ]); + }); + + test("keeps account-deletion SSH identity cleanup retryable when provider revocation fails", async () => { + const revokedLeaseIds: string[] = []; + const repo = testWorkflowRepo({ + vm: testCloudVmRow(), + accountDeletionIdentityLeases: () => + Effect.succeed([ + testIdentityLease("lease-account-delete-success", "identity-account-delete-success"), + testIdentityLease("lease-account-delete-failure", "identity-account-delete-failure"), + ]), + revokedLeaseIds, + }); + const revokedIdentities: string[] = []; + const provider: VmProviderGatewayShape = { + ...unusedProviderGateway(), + revokeSSHIdentity: (_provider, identityHandle) => { + revokedIdentities.push(identityHandle); + if (identityHandle === "identity-account-delete-failure") { + return Effect.fail(providerOperationError("revokeSSHIdentity", "provider delete failed")); + } + return Effect.void; + }, + }; + + await expect( + Effect.runPromise( + revokeUserIdentityLeasesForAccountDeletion("user-workflow-account-delete").pipe( + Effect.provide(workflowLayer(repo, provider)), + ), + ), + ).rejects.toThrow(); + + expect(revokedIdentities).toEqual([ + "identity-account-delete-success", + "identity-account-delete-failure", + ]); + expect(revokedLeaseIds).toEqual(["lease-account-delete-success"]); + }); + test("revokeExpiredIdentityLeases uses a small default cron batch", async () => { const vm = testCloudVmRow({ id: "00000000-0000-4000-8000-000000000131", @@ -1444,6 +1520,7 @@ describe("VM Effect workflows", () => { findUserVm: () => Effect.succeed(null), markDestroyed: () => Effect.void, recordLease: () => Effect.void, + accountDeletionIdentityLeases: () => Effect.succeed([]), listVmSessions: () => Effect.succeed([]), upsertVmSession: () => Effect.fail(new Error("unused") as never), activeIdentityLeases: () => Effect.succeed([]), @@ -4251,6 +4328,7 @@ function testWorkflowRepo(input: { readonly leases?: RecordedLease[]; readonly activeIdentityLeases?: CloudVmLeaseRow[]; readonly expiredIdentityLeases?: VmRepositoryShape["expiredIdentityLeases"]; + readonly accountDeletionIdentityLeases?: VmRepositoryShape["accountDeletionIdentityLeases"]; readonly revokedLeaseIds?: string[]; readonly leaseRevocationRetries?: LeaseRevocationRetry[]; readonly observedStatuses?: ObservedStatusUpdate[]; @@ -4297,6 +4375,7 @@ function testWorkflowRepo(input: { input.leases?.push(lease); }), expiredIdentityLeases: input.expiredIdentityLeases, + accountDeletionIdentityLeases: input.accountDeletionIdentityLeases ?? (() => Effect.succeed([])), markLeaseRevocationRetry: (retry) => Effect.sync(() => { input.leaseRevocationRetries?.push(retry); @@ -4378,6 +4457,25 @@ function providerOperationError(operation: string, message: string): VmProviderO }); } +function testIdentityLease(id: string, providerIdentityHandle: string): CloudVmIdentityLeaseRow { + return { + id, + vmId: "00000000-0000-4000-8000-000000000765", + userId: "user-workflow-account-delete", + kind: "ssh", + tokenHash: `${id}-token`, + providerIdentityHandle, + sessionId: null, + transport: "ssh", + metadata: {}, + expiresAt: new Date(Date.now() + 60_000), + consumedAt: null, + revokedAt: null, + createdAt: new Date(), + provider: "freestyle", + }; +} + function testVmHandle(overrides: Partial = {}): VMHandle { return { provider: "freestyle", From b55f23b79da0600bbe72c4fc5c1891583f4abeda Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Thu, 9 Jul 2026 00:16:26 -0700 Subject: [PATCH 32/89] Record subscription state before deletion skips --- web/services/billing/purchase.ts | 10 ++++++---- web/tests/billing-purchase.test.ts | 32 ++++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 4 deletions(-) diff --git a/web/services/billing/purchase.ts b/web/services/billing/purchase.ts index 551dab86434d..5859b0924cae 100644 --- a/web/services/billing/purchase.ts +++ b/web/services/billing/purchase.ts @@ -206,16 +206,18 @@ export async function applySubscriptionUpdate( metadataStackUserId !== stackUserId ) return { skipped: true }; - const user = await loadOptionalStackUser(stackUserId, dependencies.stackApp); - if (!user || isAccountDeletionInProgress(user)) return { skipped: true }; - if (hasUserSubscription) { await updateExistingUserStripeSubscription(db, { subscription, customerId, stackUserId, }); - } else { + } + + const user = await loadOptionalStackUser(stackUserId, dependencies.stackApp); + if (!user || isAccountDeletionInProgress(user)) return { skipped: true }; + + if (!hasUserSubscription) { await upsertStripeSubscription(db, { subscription, customerId, diff --git a/web/tests/billing-purchase.test.ts b/web/tests/billing-purchase.test.ts index c73a50492d42..3619a1a8f08b 100644 --- a/web/tests/billing-purchase.test.ts +++ b/web/tests/billing-purchase.test.ts @@ -585,6 +585,38 @@ describe("recordCheckoutCompletion", () => { expect(updates.some((update) => update.table === stripeSubscriptions)).toBe(false); }); + test("records known subscription webhooks before skipping deleting account metadata", async () => { + const update = mock(async () => undefined); + const getUser = mock(async () => ({ + id: "user_123", + primaryEmail: "buyer@example.com", + clientReadOnlyMetadata: { cmuxAccountDeleting: true, cmuxPlan: "pro" }, + update, + })); + selectResults = [[{ stackUserId: "user_123" }], [{ id: "sub_user" }]]; + + const result = await applySubscriptionUpdate( + userSubscriptionUpdate({ status: "canceled" }) as never, + { + db: fakeDb() as never, + stackApp: { getUser } as never, + }, + ); + + expect(result).toEqual({ skipped: true }); + expect(getUser).toHaveBeenCalledWith("user_123"); + expect(update).not.toHaveBeenCalled(); + expect( + updates.some( + (entry) => + entry.table === stripeSubscriptions && + entry.values.status === "canceled" && + entry.values.stackUserId === "user_123", + ), + ).toBe(true); + expect(inserts.some((insert) => insert.table === stripeSubscriptions)).toBe(false); + }); + test("skips user subscription webhooks for anonymized local customer rows", async () => { const getUser = mock(async () => { throw new Error("should not load Stack user for anonymized local customer"); From b7e8e4ae4813ca2d55b9140945cd849b25898db6 Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Thu, 9 Jul 2026 00:27:58 -0700 Subject: [PATCH 33/89] Avoid stale auth during account deletion retry --- .../MobileSettingsAccountSection.swift | 14 +-------- ...bileSettingsDeleteAccountFailureKind.swift | 31 +++++++++++++++++-- ...ettingsDeleteAccountFailureKindTests.swift | 9 +++++- ios/cmux/Resources/Localizable.xcstrings | 17 ++++++++++ web/app/api/account/route.ts | 22 ++++++------- web/tests/account-route.test.ts | 9 +++--- 6 files changed, 70 insertions(+), 32 deletions(-) diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsAccountSection.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsAccountSection.swift index 753abcd83779..dbc2d0ddd7a4 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsAccountSection.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsAccountSection.swift @@ -108,19 +108,7 @@ struct MobileSettingsAccountSection: View { showingDeleteAccountFailure = true } } catch { - if case AccountDeletionRequestError.stackDeleteIncomplete = error { - deleteAccountFailureKind = .stackDeleteIncomplete - } else if case AccountDeletionRequestError.timedOut = error { - deleteAccountFailureKind = .unknown - } else if case AccountDeletionRequestError.completionUnknown = error { - deleteAccountFailureKind = .unknown - } else if case AccountDeletionRequestError.localTransportFailure = error { - deleteAccountFailureKind = .connection - } else if case AuthError.timedOut = error { - deleteAccountFailureKind = .timedOut - } else { - deleteAccountFailureKind = .generic - } + deleteAccountFailureKind = DeleteAccountFailureKind(error: error) signOutAfterDeleteAccountFailureAcknowledgement = deleteAccountFailureKind.signsOutAfterAcknowledgement showingDeleteAccountFailure = true } diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsDeleteAccountFailureKind.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsDeleteAccountFailureKind.swift index 002e614c1259..2c4f86cf0b6c 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsDeleteAccountFailureKind.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsDeleteAccountFailureKind.swift @@ -1,16 +1,38 @@ #if os(iOS) +import CmuxAuthRuntime import CmuxMobileSupport -enum DeleteAccountFailureKind { +enum DeleteAccountFailureKind: Equatable { case generic case connection + case unauthorized case stackDeleteIncomplete case serverCleanupIncomplete case timedOut case unknown + init(error: any Error) { + if case AccountDeletionRequestError.unauthorized = error { + self = .unauthorized + } else if case AuthError.unauthorized = error { + self = .unauthorized + } else if case AccountDeletionRequestError.stackDeleteIncomplete = error { + self = .stackDeleteIncomplete + } else if case AccountDeletionRequestError.timedOut = error { + self = .unknown + } else if case AccountDeletionRequestError.completionUnknown = error { + self = .unknown + } else if case AccountDeletionRequestError.localTransportFailure = error { + self = .connection + } else if case AuthError.timedOut = error { + self = .timedOut + } else { + self = .generic + } + } + var signsOutAfterAcknowledgement: Bool { - self == .serverCleanupIncomplete + self == .serverCleanupIncomplete || self == .unauthorized } var localizedMessage: String { @@ -25,6 +47,11 @@ enum DeleteAccountFailureKind { "mobile.settings.deleteAccountConnectionFailedMessage", defaultValue: "Could not reach the server. Check your internet connection and try again." ) + case .unauthorized: + return L10n.string( + "mobile.settings.deleteAccountUnauthorizedMessage", + defaultValue: "Your session is no longer valid. You will be signed out on this device. Sign in again if the account still exists." + ) case .stackDeleteIncomplete: return L10n.string( "mobile.settings.deleteAccountPartialFailureMessage", diff --git a/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/MobileSettingsDeleteAccountFailureKindTests.swift b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/MobileSettingsDeleteAccountFailureKindTests.swift index e709023bc298..19fca28abf54 100644 --- a/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/MobileSettingsDeleteAccountFailureKindTests.swift +++ b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/MobileSettingsDeleteAccountFailureKindTests.swift @@ -1,15 +1,22 @@ #if os(iOS) +import CmuxAuthRuntime import Testing @testable import CmuxMobileShellUI @Suite struct MobileSettingsDeleteAccountFailureKindTests { - @Test func cleanupIncompleteSignsOutAfterAcknowledgementOnly() { + @Test func definitiveDeletedSessionFailuresSignOutAfterAcknowledgement() { #expect(DeleteAccountFailureKind.serverCleanupIncomplete.signsOutAfterAcknowledgement) + #expect(DeleteAccountFailureKind.unauthorized.signsOutAfterAcknowledgement) #expect(!DeleteAccountFailureKind.generic.signsOutAfterAcknowledgement) #expect(!DeleteAccountFailureKind.connection.signsOutAfterAcknowledgement) #expect(!DeleteAccountFailureKind.stackDeleteIncomplete.signsOutAfterAcknowledgement) #expect(!DeleteAccountFailureKind.timedOut.signsOutAfterAcknowledgement) #expect(!DeleteAccountFailureKind.unknown.signsOutAfterAcknowledgement) } + + @Test func accountDeletionUnauthorizedMapsToSignOutRecovery() { + #expect(DeleteAccountFailureKind(error: AccountDeletionRequestError.unauthorized) == .unauthorized) + #expect(DeleteAccountFailureKind(error: AuthError.unauthorized) == .unauthorized) + } } #endif diff --git a/ios/cmux/Resources/Localizable.xcstrings b/ios/cmux/Resources/Localizable.xcstrings index c5e6b34d4f53..df7376c94287 100644 --- a/ios/cmux/Resources/Localizable.xcstrings +++ b/ios/cmux/Resources/Localizable.xcstrings @@ -4149,6 +4149,23 @@ } } }, + "mobile.settings.deleteAccountUnauthorizedMessage": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Your session is no longer valid. You will be signed out on this device. Sign in again if the account still exists." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "セッションが無効になりました。このデバイスではサインアウトされます。アカウントがまだ存在する場合は、もう一度サインインしてください。" + } + } + } + }, "mobile.settings.deleteAccountUnknownMessage": { "extractionState": "manual", "localizations": { diff --git a/web/app/api/account/route.ts b/web/app/api/account/route.ts index d3cadef6e688..131597051fe6 100644 --- a/web/app/api/account/route.ts +++ b/web/app/api/account/route.ts @@ -37,7 +37,7 @@ import { SubrouterClientError, } from "../../../services/subrouter/client"; import { deleteObject } from "../../../services/vault/storage"; -import { unauthorized, verifyRequest } from "../../../services/vms/auth"; +import { unauthorized } from "../../../services/vms/auth"; import { jsonResponse } from "../../../services/vms/routeHelpers"; import { destroyVm, @@ -58,12 +58,10 @@ type DeletableStackUser = { } & ProMetadataCustomer; export async function DELETE(request: Request): Promise { - const user = await verifyRequest(request, { allowCookie: false, allowDeletingAccount: true }); - if (!user) return unauthorized(); - const stackUser = await currentDeletableStackUser(request); - if (!stackUser || stackUser.id !== user.id) return unauthorized(); + if (!stackUser) return unauthorized(); + const userId = stackUser.id; const originalStackMetadata = stackUser.clientReadOnlyMetadata; let stackMetadataMarked = false; let cmuxOwnedRowsDeleted = false; @@ -73,14 +71,14 @@ export async function DELETE(request: Request): Promise { try { await markAccountDeletingAndClearBillingEntitlements(stackUser); stackMetadataMarked = true; - await resolveUserBillingForAccountDeletion(user.id, { + await resolveUserBillingForAccountDeletion(userId, { beforeExternalMutation: () => { restoreBillingEntitlementsOnFailure = false; destructiveCleanupStarted = true; }, }); try { - destroyedVms = await destroyPersonalCloudVms(user.id); + destroyedVms = await destroyPersonalCloudVms(userId); if (destroyedVms > 0) destructiveCleanupStarted = true; } catch (error) { if (error instanceof AccountDeletionDestructiveCleanupError) { @@ -90,16 +88,16 @@ export async function DELETE(request: Request): Promise { throw error; } destructiveCleanupStarted = true; - await deleteVaultRowsAndObjectsForAccount(user.id); + await deleteVaultRowsAndObjectsForAccount(userId); destructiveCleanupStarted = true; - await deletePersonalSubrouterTenant(user.id); + await deletePersonalSubrouterTenant(userId); destructiveCleanupStarted = true; - await runVmWorkflow(revokeUserIdentityLeasesForAccountDeletion(user.id)); + await runVmWorkflow(revokeUserIdentityLeasesForAccountDeletion(userId)); // Delete cmux-owned data before the Stack user so a Stack-side failure does // not strand retained app data behind an account the user can no longer use. // These deletes are idempotent, so the same signed-in user can retry the // final Stack deletion when the distinct response below is returned. - await deleteCmuxOwnedAccountRows(user.id); + await deleteCmuxOwnedAccountRows(userId); cmuxOwnedRowsDeleted = true; try { await stackUser.delete(); @@ -112,7 +110,7 @@ export async function DELETE(request: Request): Promise { }, 500); } try { - await finishPostStackAccountCleanup(user.id); + await finishPostStackAccountCleanup(userId); } catch (error) { logAccountDeleteError("account.delete.post_stack_cleanup_failed", error); return jsonResponse({ diff --git a/web/tests/account-route.test.ts b/web/tests/account-route.test.ts index 0357fb3ed642..722cb0404173 100644 --- a/web/tests/account-route.test.ts +++ b/web/tests/account-route.test.ts @@ -419,6 +419,7 @@ describe("account deletion route", () => { expect(updateStackUser).toHaveBeenCalledWith({ clientReadOnlyMetadata: { cmuxAccountDeleting: true }, }); + expect(getUser).toHaveBeenCalledTimes(1); expect(deleteStackUser).toHaveBeenCalledTimes(1); expect(routeEvents).toEqual([ "metadata-update", @@ -829,14 +830,14 @@ describe("account deletion route", () => { expect(deleteStackUser).toHaveBeenCalledTimes(1); }); - test("rejects a Stack user mismatch before deleting data", async () => { + test("uses a single native Stack session lookup for deletion auth", async () => { stackUserIds = ["account-user-1", "other-user"]; const response = await DELETE(accountDeletionRequest()); - expect(response.status).toBe(401); - expect(deleteStackUser).not.toHaveBeenCalled(); - expect(transaction).not.toHaveBeenCalled(); + expect(response.status).toBe(200); + expect(getUser).toHaveBeenCalledTimes(1); + expect(deleteStackUser).toHaveBeenCalledTimes(1); }); }); From fe4df745581136e18c5c7d846db0932c231c803c Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Thu, 9 Jul 2026 00:36:20 -0700 Subject: [PATCH 34/89] Keep Stripe webhooks retryable for missing Stack users --- Packages/iOS/CmuxMobileShellUI/Package.swift | 1 + web/services/billing/purchase.ts | 3 ++- web/tests/billing-purchase.test.ts | 26 ++++++++++++++++++++ 3 files changed, 29 insertions(+), 1 deletion(-) diff --git a/Packages/iOS/CmuxMobileShellUI/Package.swift b/Packages/iOS/CmuxMobileShellUI/Package.swift index a42f67904ab9..a81320945adb 100644 --- a/Packages/iOS/CmuxMobileShellUI/Package.swift +++ b/Packages/iOS/CmuxMobileShellUI/Package.swift @@ -59,6 +59,7 @@ let package = Package( name: "CmuxMobileShellUITests", dependencies: [ "CMUXMobileCore", + "CmuxAuthRuntime", "CmuxMobilePairedMac", "CmuxMobileShellUI", "CmuxAgentChat", diff --git a/web/services/billing/purchase.ts b/web/services/billing/purchase.ts index 5859b0924cae..5897bd45b9f7 100644 --- a/web/services/billing/purchase.ts +++ b/web/services/billing/purchase.ts @@ -215,7 +215,8 @@ export async function applySubscriptionUpdate( } const user = await loadOptionalStackUser(stackUserId, dependencies.stackApp); - if (!user || isAccountDeletionInProgress(user)) return { skipped: true }; + if (!user) throw new Error(`Stack user not found for Stripe subscription update: ${stackUserId}`); + if (isAccountDeletionInProgress(user)) return { skipped: true }; if (!hasUserSubscription) { await upsertStripeSubscription(db, { diff --git a/web/tests/billing-purchase.test.ts b/web/tests/billing-purchase.test.ts index 3619a1a8f08b..1b2e4b65a826 100644 --- a/web/tests/billing-purchase.test.ts +++ b/web/tests/billing-purchase.test.ts @@ -617,6 +617,32 @@ describe("recordCheckoutCompletion", () => { expect(inserts.some((insert) => insert.table === stripeSubscriptions)).toBe(false); }); + test("fails known subscription webhooks when the Stack user is missing", async () => { + const getUser = mock(async () => null); + selectResults = [[{ stackUserId: "user_123" }], [{ id: "sub_user" }]]; + + await expect( + applySubscriptionUpdate( + userSubscriptionUpdate({ status: "canceled" }) as never, + { + db: fakeDb() as never, + stackApp: { getUser } as never, + }, + ), + ).rejects.toThrow("Stack user not found for Stripe subscription update: user_123"); + + expect(getUser).toHaveBeenCalledWith("user_123"); + expect( + updates.some( + (entry) => + entry.table === stripeSubscriptions && + entry.values.status === "canceled" && + entry.values.stackUserId === "user_123", + ), + ).toBe(true); + expect(inserts.some((insert) => insert.table === stripeSubscriptions)).toBe(false); + }); + test("skips user subscription webhooks for anonymized local customer rows", async () => { const getUser = mock(async () => { throw new Error("should not load Stack user for anonymized local customer"); From a79d03a1189c9d23b84f0bc989c40d7b57d86b32 Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Thu, 9 Jul 2026 00:46:18 -0700 Subject: [PATCH 35/89] Block delayed checkout writes during account deletion --- web/services/billing/purchase.ts | 8 ++++++-- web/tests/billing-purchase.test.ts | 33 ++++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 2 deletions(-) diff --git a/web/services/billing/purchase.ts b/web/services/billing/purchase.ts index 5897bd45b9f7..9c64e3bec8ca 100644 --- a/web/services/billing/purchase.ts +++ b/web/services/billing/purchase.ts @@ -120,8 +120,13 @@ export async function recordCheckoutCompletion( throw new Error("Stripe checkout session is missing stackUserId"); } - const email = checkoutEmail(input.session, input.customer); const db = dependencies.db ?? cloudDb(); + const user = await loadStackUser(stackUserId, dependencies.stackApp); + if (isAccountDeletionInProgress(user)) { + throw new Error("Billing writes are disabled while account deletion is in progress."); + } + + const email = checkoutEmail(input.session, input.customer); await upsertStripeCustomer(db, { customerId, stackUserId, @@ -134,7 +139,6 @@ export async function recordCheckoutCompletion( scope: "user", }); - const user = await loadStackUser(stackUserId, dependencies.stackApp); if (email) { await attachPurchaseEmailOrRecordClaim(db, { user, diff --git a/web/tests/billing-purchase.test.ts b/web/tests/billing-purchase.test.ts index 1b2e4b65a826..c97c104e4837 100644 --- a/web/tests/billing-purchase.test.ts +++ b/web/tests/billing-purchase.test.ts @@ -151,6 +151,39 @@ describe("recordCheckoutCompletion", () => { }); }); + test("blocks checkout completion while account deletion is in progress", async () => { + const update = mock(async () => undefined); + const user = { + id: "user_123", + primaryEmail: null, + clientReadOnlyMetadata: { cmuxAccountDeleting: true }, + update, + }; + + await expect( + recordCheckoutCompletion(checkoutInput() as never, { + db: fakeDb() as never, + stackApp: { getUser: async () => user } as never, + }), + ).rejects.toThrow("Billing writes are disabled while account deletion is in progress."); + + expect(inserts).toHaveLength(0); + expect(updates).toHaveLength(0); + expect(update).not.toHaveBeenCalled(); + }); + + test("does not recreate checkout billing rows after the Stack user is gone", async () => { + await expect( + recordCheckoutCompletion(checkoutInput() as never, { + db: fakeDb() as never, + stackApp: { getUser: async () => null } as never, + }), + ).rejects.toThrow("Stack user not found for Stripe purchase: user_123"); + + expect(inserts).toHaveLength(0); + expect(updates).toHaveLength(0); + }); + test("records an email claim instead of attaching an email owned by a different Stack user", async () => { const update = mock(async () => undefined); const listUsers = mock(async () => [ From c4e1de54a1d1df2a937d2d26c6cde568f06760bb Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Thu, 9 Jul 2026 00:52:46 -0700 Subject: [PATCH 36/89] Skip stale Stripe metadata after account deletion --- web/services/billing/purchase.ts | 4 ++++ web/tests/billing-purchase.test.ts | 18 ++++++++++++++++++ 2 files changed, 22 insertions(+) diff --git a/web/services/billing/purchase.ts b/web/services/billing/purchase.ts index 9c64e3bec8ca..57c5219f92fd 100644 --- a/web/services/billing/purchase.ts +++ b/web/services/billing/purchase.ts @@ -209,6 +209,9 @@ export async function applySubscriptionUpdate( mappedStackUserId !== stackUserId && metadataStackUserId !== stackUserId ) return { skipped: true }; + const isMetadataOnlyUserSubscription = !hasUserSubscription && + !mappedStackUserId && + metadataStackUserId === stackUserId; if (hasUserSubscription) { await updateExistingUserStripeSubscription(db, { @@ -219,6 +222,7 @@ export async function applySubscriptionUpdate( } const user = await loadOptionalStackUser(stackUserId, dependencies.stackApp); + if (!user && isMetadataOnlyUserSubscription) return { skipped: true }; if (!user) throw new Error(`Stack user not found for Stripe subscription update: ${stackUserId}`); if (isAccountDeletionInProgress(user)) return { skipped: true }; diff --git a/web/tests/billing-purchase.test.ts b/web/tests/billing-purchase.test.ts index c97c104e4837..0d56642b3836 100644 --- a/web/tests/billing-purchase.test.ts +++ b/web/tests/billing-purchase.test.ts @@ -676,6 +676,24 @@ describe("recordCheckoutCompletion", () => { expect(inserts.some((insert) => insert.table === stripeSubscriptions)).toBe(false); }); + test("skips metadata-only user subscription webhooks after local account rows are gone", async () => { + const getUser = mock(async () => null); + selectResults = [[], []]; + + const result = await applySubscriptionUpdate( + userSubscriptionUpdate({ status: "canceled" }) as never, + { + db: fakeDb() as never, + stackApp: { getUser } as never, + }, + ); + + expect(result).toEqual({ skipped: true }); + expect(getUser).toHaveBeenCalledWith("user_123"); + expect(inserts.some((insert) => insert.table === stripeSubscriptions)).toBe(false); + expect(updates.some((update) => update.table === stripeSubscriptions)).toBe(false); + }); + test("skips user subscription webhooks for anonymized local customer rows", async () => { const getUser = mock(async () => { throw new Error("should not load Stack user for anonymized local customer"); From fffc6500835397023277333089836808b0e92642 Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Thu, 9 Jul 2026 01:03:06 -0700 Subject: [PATCH 37/89] Restore deletion metadata before destructive cleanup --- web/app/api/account/route.ts | 63 ++++++++++++++++++++------------- web/tests/account-route.test.ts | 30 +++++++++++++--- 2 files changed, 65 insertions(+), 28 deletions(-) diff --git a/web/app/api/account/route.ts b/web/app/api/account/route.ts index 131597051fe6..828523c77059 100644 --- a/web/app/api/account/route.ts +++ b/web/app/api/account/route.ts @@ -72,7 +72,7 @@ export async function DELETE(request: Request): Promise { await markAccountDeletingAndClearBillingEntitlements(stackUser); stackMetadataMarked = true; await resolveUserBillingForAccountDeletion(userId, { - beforeExternalMutation: () => { + afterExternalMutation: () => { restoreBillingEntitlementsOnFailure = false; destructiveCleanupStarted = true; }, @@ -87,12 +87,18 @@ export async function DELETE(request: Request): Promise { } throw error; } - destructiveCleanupStarted = true; - await deleteVaultRowsAndObjectsForAccount(userId); - destructiveCleanupStarted = true; - await deletePersonalSubrouterTenant(userId); - destructiveCleanupStarted = true; - await runVmWorkflow(revokeUserIdentityLeasesForAccountDeletion(userId)); + await deleteVaultRowsAndObjectsForAccount(userId, { + beforeObjectDeletion: () => { + destructiveCleanupStarted = true; + }, + }); + await deletePersonalSubrouterTenant(userId, { + afterExternalMutation: () => { + destructiveCleanupStarted = true; + }, + }); + const revokedIdentityLeases = await runVmWorkflow(revokeUserIdentityLeasesForAccountDeletion(userId)); + if (revokedIdentityLeases > 0) destructiveCleanupStarted = true; // Delete cmux-owned data before the Stack user so a Stack-side failure does // not strand retained app data behind an account the user can no longer use. // These deletes are idempotent, so the same signed-in user can retry the @@ -195,7 +201,10 @@ async function destroyPersonalCloudVms(userId: string): Promise { return destroyedVms; } -async function deleteVaultRowsAndObjectsForAccount(userId: string): Promise { +async function deleteVaultRowsAndObjectsForAccount( + userId: string, + options: { readonly beforeObjectDeletion?: () => void } = {}, +): Promise { const db = cloudDb(); for (;;) { @@ -207,6 +216,7 @@ async function deleteVaultRowsAndObjectsForAccount(userId: string): Promise deleteObject(snapshot.objectKey))); await db.delete(vaultSnapshots).where(inArray(vaultSnapshots.id, snapshots.map((snapshot) => snapshot.id))); if (snapshots.length < VAULT_OBJECT_DELETE_BATCH_SIZE) break; @@ -224,6 +234,7 @@ async function deleteVaultRowsAndObjectsForAccount(userId: string): Promise [ deleteObject(grant.objectKey), deleteObject(grant.uploadObjectKey), @@ -244,6 +255,7 @@ async function deleteVaultRowsAndObjectsForAccount(userId: string): Promise [ deleteObject(tombstone.objectKey), deleteObject(tombstone.uploadObjectKey), @@ -262,6 +274,7 @@ async function deleteVaultRowsAndObjectsForAccount(userId: string): Promise deleteObject(session.latestObjectKey))); await db.delete(vaultSessions).where(inArray(vaultSessions.id, sessions.map((session) => session.id))); if (sessions.length < VAULT_OBJECT_DELETE_BATCH_SIZE) break; @@ -275,7 +288,7 @@ async function finishPostStackAccountCleanup(userId: string): Promise { async function resolveUserBillingForAccountDeletion( userId: string, - options: { readonly beforeExternalMutation?: () => void } = {}, + options: { readonly afterExternalMutation?: () => void } = {}, ): Promise { const db = cloudDb(); const activeSubscriptions = await db @@ -301,19 +314,15 @@ async function resolveUserBillingForAccountDeletion( } const client = stripe(); - let externalMutationMarked = false; - const markExternalMutation = () => { - if (externalMutationMarked) return; - externalMutationMarked = true; - options.beforeExternalMutation?.(); - }; for (const subscription of activeSubscriptions) { - markExternalMutation(); - await cancelStripeSubscriptionForAccountDeletion(client, subscription.id); + if (await cancelStripeSubscriptionForAccountDeletion(client, subscription.id)) { + options.afterExternalMutation?.(); + } } for (const customer of customers) { - markExternalMutation(); - await deleteStripeCustomerForAccountDeletion(client, customer.id); + if (await deleteStripeCustomerForAccountDeletion(client, customer.id)) { + options.afterExternalMutation?.(); + } } } @@ -349,11 +358,12 @@ function stackMetadataRecord(metadata: unknown): Record { async function cancelStripeSubscriptionForAccountDeletion( client: ReturnType, subscriptionId: string, -): Promise { +): Promise { try { await client.subscriptions.cancel(subscriptionId); + return true; } catch (error) { - if (isStripeAlreadyInDeletionTargetState(error, [/already been canceled/i])) return; + if (isStripeAlreadyInDeletionTargetState(error, [/already been canceled/i])) return true; throw error; } } @@ -361,11 +371,12 @@ async function cancelStripeSubscriptionForAccountDeletion( async function deleteStripeCustomerForAccountDeletion( client: ReturnType, customerId: string, -): Promise { +): Promise { try { await client.customers.del(customerId); + return true; } catch (error) { - if (isStripeAlreadyInDeletionTargetState(error, [/already deleted/i])) return; + if (isStripeAlreadyInDeletionTargetState(error, [/already deleted/i])) return true; throw error; } } @@ -485,7 +496,10 @@ async function deleteCmuxOwnedAccountRows(userId: string): Promise { }); } -async function deletePersonalSubrouterTenant(userId: string): Promise { +async function deletePersonalSubrouterTenant( + userId: string, + options: { readonly afterExternalMutation?: () => void } = {}, +): Promise { const db = cloudDb(); const [tenant] = await db .select({ tenantId: subrouterTenants.tenantId }) @@ -496,6 +510,7 @@ async function deletePersonalSubrouterTenant(userId: string): Promise { try { await createSubrouterClientFromEnv().revokeTenant(tenant.tenantId); + options.afterExternalMutation?.(); } catch (error) { if (!(error instanceof SubrouterClientError && error.status === 404)) throw error; } diff --git a/web/tests/account-route.test.ts b/web/tests/account-route.test.ts index 722cb0404173..f14a5e6e6b19 100644 --- a/web/tests/account-route.test.ts +++ b/web/tests/account-route.test.ts @@ -102,10 +102,7 @@ const runVmWorkflow = mock(async (...args: unknown[]) => { const [program] = args as [WorkflowProgram]; if (program.kind === "listUserVms") { routeEvents.push("list-vms"); - return [ - { providerVmId: "personal-vm-1" }, - { providerVmId: "personal-vm-2" }, - ]; + return listedPersonalVmIds.map((providerVmId) => ({ providerVmId })); } if (program.kind === "revokeUserIdentityLeasesForAccountDeletion") { routeEvents.push("revoke-identities"); @@ -163,6 +160,7 @@ let deletedStripeCustomers: string[] = []; let stripeCancelError: unknown = null; let stripeDeleteCustomerError: unknown = null; let destroyVmFailureProviderIds = new Set(); +let listedPersonalVmIds: string[] = []; let revokeIdentityLeasesError: unknown = null; let subrouterRevokeError: unknown = null; let useAccountRouteStubs = false; @@ -345,6 +343,7 @@ beforeEach(() => { stripeCancelError = null; stripeDeleteCustomerError = null; destroyVmFailureProviderIds = new Set(); + listedPersonalVmIds = ["personal-vm-1", "personal-vm-2"]; revokeIdentityLeasesError = null; subrouterRevokeError = null; }); @@ -472,6 +471,29 @@ describe("account deletion route", () => { expect(deletedTables).toContain(cloudVmLeases); }); + test("restores Stack metadata when pre-destructive cleanup fails", async () => { + listedPersonalVmIds = []; + revokeIdentityLeasesError = new Error("identity lookup failed"); + + const response = await DELETE(accountDeletionRequest()); + + expect(response.status).toBe(500); + expect(await response.json()).toEqual({ error: "account_delete_failed" }); + expect(deletedVaultObjects).toEqual([]); + expect(transaction).not.toHaveBeenCalled(); + expect(deleteStackUser).not.toHaveBeenCalled(); + expect(updateStackUser).toHaveBeenNthCalledWith(1, { + clientReadOnlyMetadata: { cmuxAccountDeleting: true }, + }); + expect(updateStackUser).toHaveBeenNthCalledWith(2, { + clientReadOnlyMetadata: { cmuxPlan: "pro" }, + }); + expect(consoleError).toHaveBeenCalledWith( + "account.delete.failed", + "Error: identity lookup failed", + ); + }); + test("keeps deletion retryable when account SSH identity revocation fails", async () => { revokeIdentityLeasesError = new Error("provider identity revoke failed"); From 3a9c3d92ed5d0efb2c0f7cef5195f8ec6d3a2abd Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Thu, 9 Jul 2026 01:11:33 -0700 Subject: [PATCH 38/89] Bound account deletion identity cleanup --- web/app/api/account/route.ts | 24 ++++++-------- web/services/vms/repository.ts | 12 ++++--- web/services/vms/workflows.ts | 55 +++++++++++++++++++++------------ web/tests/account-route.test.ts | 25 +++++++++++++++ web/tests/vm-workflows.test.ts | 51 ++++++++++++++++++++++++++++++ 5 files changed, 130 insertions(+), 37 deletions(-) diff --git a/web/app/api/account/route.ts b/web/app/api/account/route.ts index 828523c77059..54e54beadbcc 100644 --- a/web/app/api/account/route.ts +++ b/web/app/api/account/route.ts @@ -72,7 +72,7 @@ export async function DELETE(request: Request): Promise { await markAccountDeletingAndClearBillingEntitlements(stackUser); stackMetadataMarked = true; await resolveUserBillingForAccountDeletion(userId, { - afterExternalMutation: () => { + beforeExternalRequest: () => { restoreBillingEntitlementsOnFailure = false; destructiveCleanupStarted = true; }, @@ -288,7 +288,7 @@ async function finishPostStackAccountCleanup(userId: string): Promise { async function resolveUserBillingForAccountDeletion( userId: string, - options: { readonly afterExternalMutation?: () => void } = {}, + options: { readonly beforeExternalRequest?: () => void } = {}, ): Promise { const db = cloudDb(); const activeSubscriptions = await db @@ -315,14 +315,12 @@ async function resolveUserBillingForAccountDeletion( const client = stripe(); for (const subscription of activeSubscriptions) { - if (await cancelStripeSubscriptionForAccountDeletion(client, subscription.id)) { - options.afterExternalMutation?.(); - } + options.beforeExternalRequest?.(); + await cancelStripeSubscriptionForAccountDeletion(client, subscription.id); } for (const customer of customers) { - if (await deleteStripeCustomerForAccountDeletion(client, customer.id)) { - options.afterExternalMutation?.(); - } + options.beforeExternalRequest?.(); + await deleteStripeCustomerForAccountDeletion(client, customer.id); } } @@ -358,12 +356,11 @@ function stackMetadataRecord(metadata: unknown): Record { async function cancelStripeSubscriptionForAccountDeletion( client: ReturnType, subscriptionId: string, -): Promise { +): Promise { try { await client.subscriptions.cancel(subscriptionId); - return true; } catch (error) { - if (isStripeAlreadyInDeletionTargetState(error, [/already been canceled/i])) return true; + if (isStripeAlreadyInDeletionTargetState(error, [/already been canceled/i])) return; throw error; } } @@ -371,12 +368,11 @@ async function cancelStripeSubscriptionForAccountDeletion( async function deleteStripeCustomerForAccountDeletion( client: ReturnType, customerId: string, -): Promise { +): Promise { try { await client.customers.del(customerId); - return true; } catch (error) { - if (isStripeAlreadyInDeletionTargetState(error, [/already deleted/i])) return true; + if (isStripeAlreadyInDeletionTargetState(error, [/already deleted/i])) return; throw error; } } diff --git a/web/services/vms/repository.ts b/web/services/vms/repository.ts index f47dcdfe763e..eb73418d0301 100644 --- a/web/services/vms/repository.ts +++ b/web/services/vms/repository.ts @@ -173,7 +173,10 @@ export type VmRepositoryShape = { readonly now: Date; readonly limit: number; }) => Effect.Effect; - readonly accountDeletionIdentityLeases: (userId: string) => Effect.Effect; + readonly accountDeletionIdentityLeases: (input: { + readonly userId: string; + readonly limit: number; + }) => Effect.Effect; readonly markLeaseRevocationRetry?: (input: { readonly id: string; readonly retryAfter: Date; @@ -1259,7 +1262,7 @@ export const VmRepositoryLive = Layer.succeed(VmRepository, { .limit(input.limit); }), - accountDeletionIdentityLeases: (userId) => + accountDeletionIdentityLeases: (input) => dbEffect("accountDeletionIdentityLeases", async () => { const db = cloudDb(); return await db @@ -1282,11 +1285,12 @@ export const VmRepositoryLive = Layer.succeed(VmRepository, { .from(cloudVmLeases) .innerJoin(cloudVms, eq(cloudVmLeases.vmId, cloudVms.id)) .where(and( - eq(cloudVmLeases.userId, userId), + eq(cloudVmLeases.userId, input.userId), isNotNull(cloudVmLeases.providerIdentityHandle), isNull(cloudVmLeases.revokedAt), )) - .orderBy(asc(cloudVmLeases.createdAt), asc(cloudVmLeases.id)); + .orderBy(asc(cloudVmLeases.createdAt), asc(cloudVmLeases.id)) + .limit(input.limit); }), markLeaseRevocationRetry: (input) => diff --git a/web/services/vms/workflows.ts b/web/services/vms/workflows.ts index d4b7bba01c6d..9598bf5d53cd 100644 --- a/web/services/vms/workflows.ts +++ b/web/services/vms/workflows.ts @@ -72,6 +72,7 @@ const EXPIRED_IDENTITY_REVOKE_BATCH = 5; const EXPIRED_IDENTITY_REVOKE_RETRY_BACKOFF_MS = 10 * 60 * 1000; const IDENTITY_REVOKE_PROVIDER_TIMEOUT = "5 seconds"; const ACTIVE_IDENTITY_REVOKE_HOT_PATH_LIMIT = 8; +const ACCOUNT_DELETION_IDENTITY_REVOKE_BATCH = 8; const VM_STATUS_RECONCILE_BATCH_LIMIT = 200; type ExistingVmAccessInput = { @@ -1310,32 +1311,48 @@ export function revokeExpiredIdentityLeases(input: { }); } -export function revokeUserIdentityLeasesForAccountDeletion(userId: string) { +export function revokeUserIdentityLeasesForAccountDeletion( + userId: string, + input: { readonly limit?: number } = {}, +) { + const limit = boundedAccountDeletionIdentityRevokeLimit(input.limit); return Effect.gen(function* () { const repo = yield* VmRepository; const providers = yield* VmProviderGateway; - const leases = yield* repo.accountDeletionIdentityLeases(userId); - const revokedIds: string[] = []; - for (const lease of leases) { - const identityHandle = lease.providerIdentityHandle; - if (!identityHandle) continue; - const revoked = yield* revokeSSHIdentityForCleanup(providers, lease.provider, identityHandle).pipe( - Effect.as(true), - Effect.catchAll((err) => { - if (isProviderIdentityNotFoundError(err.cause)) return Effect.succeed(true); - return repo.markLeasesRevoked(revokedIds).pipe( - Effect.catchAll(() => Effect.void), - Effect.andThen(Effect.fail(err)), - ); - }), - ); - if (revoked) revokedIds.push(lease.id); + let revokedCount = 0; + for (;;) { + const leases = yield* repo.accountDeletionIdentityLeases({ userId, limit }); + if (leases.length === 0) return revokedCount; + + const revokedIds: string[] = []; + for (const lease of leases) { + const identityHandle = lease.providerIdentityHandle; + if (!identityHandle) continue; + const revoked = yield* revokeSSHIdentityForCleanup(providers, lease.provider, identityHandle).pipe( + Effect.as(true), + Effect.catchAll((err) => { + if (isProviderIdentityNotFoundError(err.cause)) return Effect.succeed(true); + return repo.markLeasesRevoked(revokedIds).pipe( + Effect.catchAll(() => Effect.void), + Effect.andThen(Effect.fail(err)), + ); + }), + ); + if (revoked) revokedIds.push(lease.id); + } + + yield* repo.markLeasesRevoked(revokedIds); + revokedCount += revokedIds.length; + if (leases.length < limit) return revokedCount; } - yield* repo.markLeasesRevoked(revokedIds); - return revokedIds.length; }); } +function boundedAccountDeletionIdentityRevokeLimit(limit: number | undefined): number { + if (typeof limit !== "number" || !Number.isFinite(limit)) return ACCOUNT_DELETION_IDENTITY_REVOKE_BATCH; + return Math.max(1, Math.min(Math.floor(limit), ACCOUNT_DELETION_IDENTITY_REVOKE_BATCH)); +} + export function execVm(input: { readonly userId: string; readonly billingTeamId?: string | null; diff --git a/web/tests/account-route.test.ts b/web/tests/account-route.test.ts index f14a5e6e6b19..791b227c74fd 100644 --- a/web/tests/account-route.test.ts +++ b/web/tests/account-route.test.ts @@ -681,6 +681,31 @@ describe("account deletion route", () => { expect(updateStackUser).toHaveBeenCalledTimes(1); }); + test("keeps deletion retryable when a Stripe cancellation attempt is ambiguous", async () => { + selectResults = [ + [{ id: "sub_user_active" }], + [], + ]; + stripeCancelError = new Error("request timed out after reaching Stripe"); + + const response = await DELETE(accountDeletionRequest()); + + expect(response.status).toBe(500); + expect(await response.json()).toEqual({ + error: "account_delete_retryable", + retryable: true, + destroyedVms: 0, + }); + expect(cancelledStripeSubscriptions).toEqual(["sub_user_active"]); + expect(listUserVms).not.toHaveBeenCalled(); + expect(transaction).not.toHaveBeenCalled(); + expect(deleteStackUser).not.toHaveBeenCalled(); + expect(updateStackUser).toHaveBeenNthCalledWith(1, { + clientReadOnlyMetadata: { cmuxAccountDeleting: true }, + }); + expect(updateStackUser).toHaveBeenCalledTimes(1); + }); + test("keeps deletion retryable when any VM was destroyed before a teardown error", async () => { destroyVmFailureProviderIds = new Set(["personal-vm-1"]); diff --git a/web/tests/vm-workflows.test.ts b/web/tests/vm-workflows.test.ts index 172ab89e42d5..cc912db2a055 100644 --- a/web/tests/vm-workflows.test.ts +++ b/web/tests/vm-workflows.test.ts @@ -474,6 +474,55 @@ describe("VM Effect workflows", () => { ]); }); + test("revokes account-deletion SSH identities in bounded batches", async () => { + const requestedLimits: number[] = []; + const leaseBatches = [ + [ + testIdentityLease("lease-account-delete-1", "identity-account-delete-1"), + testIdentityLease("lease-account-delete-2", "identity-account-delete-2"), + ], + [ + testIdentityLease("lease-account-delete-3", "identity-account-delete-3"), + ], + ]; + const revokedLeaseBatches: string[][] = []; + const repo = testWorkflowRepo({ + vm: testCloudVmRow(), + accountDeletionIdentityLeases: (input) => + Effect.sync(() => { + requestedLimits.push(input.limit); + return leaseBatches.shift() ?? []; + }), + revokedLeaseBatches, + }); + const revokedIdentities: string[] = []; + const provider: VmProviderGatewayShape = { + ...unusedProviderGateway(), + revokeSSHIdentity: (_provider, identityHandle) => + Effect.sync(() => { + revokedIdentities.push(identityHandle); + }), + }; + + const revokedCount = await Effect.runPromise( + revokeUserIdentityLeasesForAccountDeletion("user-workflow-account-delete", { limit: 2 }).pipe( + Effect.provide(workflowLayer(repo, provider)), + ), + ); + + expect(revokedCount).toBe(3); + expect(requestedLimits).toEqual([2, 2]); + expect(revokedIdentities).toEqual([ + "identity-account-delete-1", + "identity-account-delete-2", + "identity-account-delete-3", + ]); + expect(revokedLeaseBatches).toEqual([ + ["lease-account-delete-1", "lease-account-delete-2"], + ["lease-account-delete-3"], + ]); + }); + test("keeps account-deletion SSH identity cleanup retryable when provider revocation fails", async () => { const revokedLeaseIds: string[] = []; const repo = testWorkflowRepo({ @@ -4330,6 +4379,7 @@ function testWorkflowRepo(input: { readonly expiredIdentityLeases?: VmRepositoryShape["expiredIdentityLeases"]; readonly accountDeletionIdentityLeases?: VmRepositoryShape["accountDeletionIdentityLeases"]; readonly revokedLeaseIds?: string[]; + readonly revokedLeaseBatches?: string[][]; readonly leaseRevocationRetries?: LeaseRevocationRetry[]; readonly observedStatuses?: ObservedStatusUpdate[]; readonly markProviderObservedStatus?: ( @@ -4414,6 +4464,7 @@ function testWorkflowRepo(input: { ), markLeasesRevoked: (leaseIds) => Effect.sync(() => { + input.revokedLeaseBatches?.push([...leaseIds]); input.revokedLeaseIds?.push(...leaseIds); }), recordUsageEvent: (event) => From 402bfbd33b3aef9b07bb3c1bd4f3127c954d009d Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Thu, 9 Jul 2026 01:20:03 -0700 Subject: [PATCH 39/89] Cancel deleting-account checkout completions --- web/services/billing/purchase.ts | 39 +++++++++++++++++++++++++++++- web/tests/billing-purchase.test.ts | 11 ++++++++- 2 files changed, 48 insertions(+), 2 deletions(-) diff --git a/web/services/billing/purchase.ts b/web/services/billing/purchase.ts index 57c5219f92fd..21bc9ac7c546 100644 --- a/web/services/billing/purchase.ts +++ b/web/services/billing/purchase.ts @@ -15,6 +15,7 @@ import { syncProPlanMetadata, syncTeamPlanMetadata, } from "./pro"; +import { stripe } from "./stripe"; import { isAscConfigured } from "../asc/client"; import { removeTester } from "../asc/testflight"; import { captureAscError } from "../errors"; @@ -27,6 +28,7 @@ export const ACTIVE_STRIPE_SUBSCRIPTION_STATUSES = new Set([ const DELETED_ACCOUNT_ACTOR_ID = "deleted-account"; type BillingDb = ReturnType; +type StripeBillingClient = Pick, "subscriptions">; type StripeSubscriptionValuesInput = { subscription: Stripe.Subscription; @@ -74,6 +76,7 @@ type StackBillingApp = { type BillingPurchaseDependencies = { db?: BillingDb; stackApp?: StackBillingApp | null; + stripeClient?: () => StripeBillingClient; testflight?: { isAscConfigured?: () => boolean; removeTester?: (email: string) => Promise; @@ -96,6 +99,7 @@ export async function recordCheckoutCompletion( ): Promise< | { scope: "user"; stackUserId: string; subscriptionId: string } | { scope: "team"; stackTeamId: string; subscriptionId: string } + | { skipped: "account_deletion_in_progress"; stackUserId: string; subscriptionId: string } > { const subscription = input.subscription ?? expandedSubscription(input.session); if (!subscription) { @@ -123,7 +127,12 @@ export async function recordCheckoutCompletion( const db = dependencies.db ?? cloudDb(); const user = await loadStackUser(stackUserId, dependencies.stackApp); if (isAccountDeletionInProgress(user)) { - throw new Error("Billing writes are disabled while account deletion is in progress."); + await cancelCheckoutSubscriptionForAccountDeletion(subscription, dependencies); + return { + skipped: "account_deletion_in_progress", + stackUserId, + subscriptionId: subscription.id, + }; } const email = checkoutEmail(input.session, input.customer); @@ -153,6 +162,19 @@ export async function recordCheckoutCompletion( return { scope: "user", stackUserId, subscriptionId: subscription.id }; } +async function cancelCheckoutSubscriptionForAccountDeletion( + subscription: Stripe.Subscription, + dependencies: BillingPurchaseDependencies, +): Promise { + const client = (dependencies.stripeClient ?? stripe)(); + try { + await client.subscriptions.cancel(subscription.id); + } catch (error) { + if (isStripeSubscriptionAlreadyCanceledError(error)) return; + throw error; + } +} + export async function applySubscriptionUpdate( subscription: Stripe.Subscription, dependencies: BillingPurchaseDependencies = {}, @@ -271,6 +293,21 @@ export function isActiveStripeSubscriptionStatus(status: string): boolean { return ACTIVE_STRIPE_SUBSCRIPTION_STATUSES.has(status); } +function isStripeSubscriptionAlreadyCanceledError(error: unknown): boolean { + const statusCode = + error && typeof error === "object" + ? (error as { statusCode?: unknown; raw?: { statusCode?: unknown } }).statusCode ?? + (error as { raw?: { statusCode?: unknown } }).raw?.statusCode + : undefined; + if (statusCode === 404) return true; + + const message = + error && typeof error === "object" && typeof (error as { message?: unknown }).message === "string" + ? (error as { message: string }).message + : String(error); + return /already been canceled/i.test(message); +} + export function isCmuxCheckoutSession( session: Pick, ): boolean { diff --git a/web/tests/billing-purchase.test.ts b/web/tests/billing-purchase.test.ts index 0d56642b3836..87448be05186 100644 --- a/web/tests/billing-purchase.test.ts +++ b/web/tests/billing-purchase.test.ts @@ -153,6 +153,7 @@ describe("recordCheckoutCompletion", () => { test("blocks checkout completion while account deletion is in progress", async () => { const update = mock(async () => undefined); + const cancelSubscription = mock(async () => undefined); const user = { id: "user_123", primaryEmail: null, @@ -164,9 +165,17 @@ describe("recordCheckoutCompletion", () => { recordCheckoutCompletion(checkoutInput() as never, { db: fakeDb() as never, stackApp: { getUser: async () => user } as never, + stripeClient: () => ({ + subscriptions: { cancel: cancelSubscription }, + }) as never, }), - ).rejects.toThrow("Billing writes are disabled while account deletion is in progress."); + ).resolves.toEqual({ + skipped: "account_deletion_in_progress", + stackUserId: "user_123", + subscriptionId: "sub_123", + }); + expect(cancelSubscription).toHaveBeenCalledWith("sub_123"); expect(inserts).toHaveLength(0); expect(updates).toHaveLength(0); expect(update).not.toHaveBeenCalled(); From 46f719f4797fdae114842b25a458766777e8c2ff Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Thu, 9 Jul 2026 01:32:45 -0700 Subject: [PATCH 40/89] Close deletion cleanup retry gaps --- web/app/api/account/route.ts | 12 +++++-- web/services/billing/purchase.ts | 32 ++++++++++++++--- web/services/vms/errors.ts | 16 ++++++++- web/services/vms/workflows.ts | 3 +- web/tests/account-route.test.ts | 56 ++++++++++++++++++++++++++++++ web/tests/billing-purchase.test.ts | 18 +++++++++- 6 files changed, 126 insertions(+), 11 deletions(-) diff --git a/web/app/api/account/route.ts b/web/app/api/account/route.ts index 54e54beadbcc..45815eff6e33 100644 --- a/web/app/api/account/route.ts +++ b/web/app/api/account/route.ts @@ -38,6 +38,7 @@ import { } from "../../../services/subrouter/client"; import { deleteObject } from "../../../services/vault/storage"; import { unauthorized } from "../../../services/vms/auth"; +import { isVmAccountDeletionIdentityRevocationError } from "../../../services/vms/errors"; import { jsonResponse } from "../../../services/vms/routeHelpers"; import { destroyVm, @@ -97,8 +98,13 @@ export async function DELETE(request: Request): Promise { destructiveCleanupStarted = true; }, }); - const revokedIdentityLeases = await runVmWorkflow(revokeUserIdentityLeasesForAccountDeletion(userId)); - if (revokedIdentityLeases > 0) destructiveCleanupStarted = true; + try { + const revokedIdentityLeases = await runVmWorkflow(revokeUserIdentityLeasesForAccountDeletion(userId)); + if (revokedIdentityLeases > 0) destructiveCleanupStarted = true; + } catch (error) { + if (isVmAccountDeletionIdentityRevocationError(error)) destructiveCleanupStarted = true; + throw error; + } // Delete cmux-owned data before the Stack user so a Stack-side failure does // not strand retained app data behind an account the user can no longer use. // These deletes are idempotent, so the same signed-in user can retry the @@ -506,10 +512,10 @@ async function deletePersonalSubrouterTenant( try { await createSubrouterClientFromEnv().revokeTenant(tenant.tenantId); - options.afterExternalMutation?.(); } catch (error) { if (!(error instanceof SubrouterClientError && error.status === 404)) throw error; } + options.afterExternalMutation?.(); await db.delete(subrouterTenants).where(eq(subrouterTenants.teamId, userId)); } diff --git a/web/services/billing/purchase.ts b/web/services/billing/purchase.ts index 21bc9ac7c546..0794bbd9a512 100644 --- a/web/services/billing/purchase.ts +++ b/web/services/billing/purchase.ts @@ -28,7 +28,7 @@ export const ACTIVE_STRIPE_SUBSCRIPTION_STATUSES = new Set([ const DELETED_ACCOUNT_ACTOR_ID = "deleted-account"; type BillingDb = ReturnType; -type StripeBillingClient = Pick, "subscriptions">; +type StripeBillingClient = Pick, "customers" | "subscriptions">; type StripeSubscriptionValuesInput = { subscription: Stripe.Subscription; @@ -125,9 +125,9 @@ export async function recordCheckoutCompletion( } const db = dependencies.db ?? cloudDb(); - const user = await loadStackUser(stackUserId, dependencies.stackApp); - if (isAccountDeletionInProgress(user)) { - await cancelCheckoutSubscriptionForAccountDeletion(subscription, dependencies); + const user = await loadOptionalStackUser(stackUserId, dependencies.stackApp); + if (!user || isAccountDeletionInProgress(user)) { + await deleteCheckoutStripeResourcesForAccountDeletion(subscription, customerId, dependencies); return { skipped: "account_deletion_in_progress", stackUserId, @@ -162,8 +162,9 @@ export async function recordCheckoutCompletion( return { scope: "user", stackUserId, subscriptionId: subscription.id }; } -async function cancelCheckoutSubscriptionForAccountDeletion( +async function deleteCheckoutStripeResourcesForAccountDeletion( subscription: Stripe.Subscription, + customerId: string, dependencies: BillingPurchaseDependencies, ): Promise { const client = (dependencies.stripeClient ?? stripe)(); @@ -173,6 +174,12 @@ async function cancelCheckoutSubscriptionForAccountDeletion( if (isStripeSubscriptionAlreadyCanceledError(error)) return; throw error; } + try { + await client.customers.del(customerId); + } catch (error) { + if (isStripeCustomerAlreadyDeletedError(error)) return; + throw error; + } } export async function applySubscriptionUpdate( @@ -308,6 +315,21 @@ function isStripeSubscriptionAlreadyCanceledError(error: unknown): boolean { return /already been canceled/i.test(message); } +function isStripeCustomerAlreadyDeletedError(error: unknown): boolean { + const statusCode = + error && typeof error === "object" + ? (error as { statusCode?: unknown; raw?: { statusCode?: unknown } }).statusCode ?? + (error as { raw?: { statusCode?: unknown } }).raw?.statusCode + : undefined; + if (statusCode === 404) return true; + + const message = + error && typeof error === "object" && typeof (error as { message?: unknown }).message === "string" + ? (error as { message: string }).message + : String(error); + return /no such customer|already deleted/i.test(message); +} + export function isCmuxCheckoutSession( session: Pick, ): boolean { diff --git a/web/services/vms/errors.ts b/web/services/vms/errors.ts index 7e15ac17d904..f678ace09ed3 100644 --- a/web/services/vms/errors.ts +++ b/web/services/vms/errors.ts @@ -59,6 +59,12 @@ export class VmBillingError extends Data.TaggedError("VmBillingError")<{ readonly cause: unknown; }> {} +export class VmAccountDeletionIdentityRevocationError extends Data.TaggedError( + "VmAccountDeletionIdentityRevocationError", +)<{ + readonly cause: unknown; +}> {} + export type VmWorkflowError = | VmDatabaseError | VmProviderOperationError @@ -70,7 +76,8 @@ export type VmWorkflowError = | VmImageConfigError | VmLimitExceededError | VmCreateCreditsInsufficientError - | VmBillingError; + | VmBillingError + | VmAccountDeletionIdentityRevocationError; export function isVmNotFoundError(err: unknown): err is VmNotFoundError { return (err as { _tag?: string } | null)?._tag === "VmNotFoundError"; @@ -108,6 +115,12 @@ export function isVmBillingError(err: unknown): err is VmBillingError { return (err as { _tag?: string } | null)?._tag === "VmBillingError"; } +export function isVmAccountDeletionIdentityRevocationError( + err: unknown, +): err is VmAccountDeletionIdentityRevocationError { + return (err as { _tag?: string } | null)?._tag === "VmAccountDeletionIdentityRevocationError"; +} + export function isVmDatabaseError(err: unknown): err is VmDatabaseError { return (err as { _tag?: string } | null)?._tag === "VmDatabaseError"; } @@ -127,6 +140,7 @@ const vmWorkflowErrorTags = new Set([ "VmLimitExceededError", "VmCreateCreditsInsufficientError", "VmBillingError", + "VmAccountDeletionIdentityRevocationError", ]); export function vmWorkflowErrorCause(err: unknown): VmWorkflowError | null { diff --git a/web/services/vms/workflows.ts b/web/services/vms/workflows.ts index 9598bf5d53cd..250f3c991acb 100644 --- a/web/services/vms/workflows.ts +++ b/web/services/vms/workflows.ts @@ -19,6 +19,7 @@ import { } from "./billingGateway"; import { VmBillingError, + VmAccountDeletionIdentityRevocationError, VmCreateFailedError, VmCreateInProgressError, VmNotFoundError, @@ -1334,7 +1335,7 @@ export function revokeUserIdentityLeasesForAccountDeletion( if (isProviderIdentityNotFoundError(err.cause)) return Effect.succeed(true); return repo.markLeasesRevoked(revokedIds).pipe( Effect.catchAll(() => Effect.void), - Effect.andThen(Effect.fail(err)), + Effect.andThen(Effect.fail(new VmAccountDeletionIdentityRevocationError({ cause: err }))), ); }), ); diff --git a/web/tests/account-route.test.ts b/web/tests/account-route.test.ts index 791b227c74fd..e98c5b420901 100644 --- a/web/tests/account-route.test.ts +++ b/web/tests/account-route.test.ts @@ -37,6 +37,7 @@ const storageModule = await import("../services/vault/storage"); const realDeleteObject = storageModule.deleteObject; const subrouterClientModule = await import("../services/subrouter/client"); const realCreateSubrouterClientFromEnv = subrouterClientModule.createSubrouterClientFromEnv; +const vmErrorsModule = await import("../services/vms/errors"); const workflowsModule = await import("../services/vms/workflows"); const realDestroyVm = workflowsModule.destroyVm; const realListUserVms = workflowsModule.listUserVms; @@ -494,6 +495,29 @@ describe("account deletion route", () => { ); }); + test("keeps deletion retryable when identity revocation partially mutates provider state", async () => { + listedPersonalVmIds = []; + revokeIdentityLeasesError = new vmErrorsModule.VmAccountDeletionIdentityRevocationError({ + cause: new Error("provider identity revoke failed"), + }); + + const response = await DELETE(accountDeletionRequest()); + + expect(response.status).toBe(500); + expect(await response.json()).toEqual({ + error: "account_delete_retryable", + retryable: true, + destroyedVms: 0, + }); + expect(revokeUserIdentityLeasesForAccountDeletion).toHaveBeenCalledWith("account-user-1"); + expect(transaction).not.toHaveBeenCalled(); + expect(deleteStackUser).not.toHaveBeenCalled(); + expect(updateStackUser).toHaveBeenNthCalledWith(1, { + clientReadOnlyMetadata: { cmuxAccountDeleting: true }, + }); + expect(updateStackUser).toHaveBeenCalledTimes(1); + }); + test("keeps deletion retryable when account SSH identity revocation fails", async () => { revokeIdentityLeasesError = new Error("provider identity revoke failed"); @@ -511,6 +535,38 @@ describe("account deletion route", () => { expect(deletedTables).not.toContain(cloudVmLeases); }); + test("keeps deletion retryable after Subrouter 404 removes local tenant state", async () => { + listedPersonalVmIds = []; + selectResults = [ + [], + [], + [], + [], + [], + [], + [{ tenantId: "tenant-personal" }], + ]; + subrouterRevokeError = new subrouterClientModule.SubrouterClientError("revokeTenant", 404); + revokeIdentityLeasesError = new Error("identity lookup failed"); + + const response = await DELETE(accountDeletionRequest()); + + expect(response.status).toBe(500); + expect(await response.json()).toEqual({ + error: "account_delete_retryable", + retryable: true, + destroyedVms: 0, + }); + expect(revokeTenant).toHaveBeenCalledWith("tenant-personal"); + expect(deletedTables).toContain(subrouterTenants); + expect(transaction).not.toHaveBeenCalled(); + expect(deleteStackUser).not.toHaveBeenCalled(); + expect(updateStackUser).toHaveBeenNthCalledWith(1, { + clientReadOnlyMetadata: { cmuxAccountDeleting: true }, + }); + expect(updateStackUser).toHaveBeenCalledTimes(1); + }); + test("does not delete personal VM rows that gained a provider id before account row deletion", async () => { transactionSelectResults = [[{ id: "00000000-0000-4000-8000-000000000764", diff --git a/web/tests/billing-purchase.test.ts b/web/tests/billing-purchase.test.ts index 87448be05186..3b5a0857d739 100644 --- a/web/tests/billing-purchase.test.ts +++ b/web/tests/billing-purchase.test.ts @@ -154,6 +154,7 @@ describe("recordCheckoutCompletion", () => { test("blocks checkout completion while account deletion is in progress", async () => { const update = mock(async () => undefined); const cancelSubscription = mock(async () => undefined); + const deleteCustomer = mock(async () => undefined); const user = { id: "user_123", primaryEmail: null, @@ -167,6 +168,7 @@ describe("recordCheckoutCompletion", () => { stackApp: { getUser: async () => user } as never, stripeClient: () => ({ subscriptions: { cancel: cancelSubscription }, + customers: { del: deleteCustomer }, }) as never, }), ).resolves.toEqual({ @@ -176,19 +178,33 @@ describe("recordCheckoutCompletion", () => { }); expect(cancelSubscription).toHaveBeenCalledWith("sub_123"); + expect(deleteCustomer).toHaveBeenCalledWith("cus_123"); expect(inserts).toHaveLength(0); expect(updates).toHaveLength(0); expect(update).not.toHaveBeenCalled(); }); test("does not recreate checkout billing rows after the Stack user is gone", async () => { + const cancelSubscription = mock(async () => undefined); + const deleteCustomer = mock(async () => undefined); + await expect( recordCheckoutCompletion(checkoutInput() as never, { db: fakeDb() as never, stackApp: { getUser: async () => null } as never, + stripeClient: () => ({ + subscriptions: { cancel: cancelSubscription }, + customers: { del: deleteCustomer }, + }) as never, }), - ).rejects.toThrow("Stack user not found for Stripe purchase: user_123"); + ).resolves.toEqual({ + skipped: "account_deletion_in_progress", + stackUserId: "user_123", + subscriptionId: "sub_123", + }); + expect(cancelSubscription).toHaveBeenCalledWith("sub_123"); + expect(deleteCustomer).toHaveBeenCalledWith("cus_123"); expect(inserts).toHaveLength(0); expect(updates).toHaveLength(0); }); From e7aaf4dbbdedd3cefe0e509d470513f94cfcbb83 Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Thu, 9 Jul 2026 01:39:34 -0700 Subject: [PATCH 41/89] Continue checkout cleanup after canceled subscriptions --- web/services/billing/purchase.ts | 3 +-- web/tests/billing-purchase.test.ts | 4 +++- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/web/services/billing/purchase.ts b/web/services/billing/purchase.ts index 0794bbd9a512..d4bbc030f5ea 100644 --- a/web/services/billing/purchase.ts +++ b/web/services/billing/purchase.ts @@ -171,8 +171,7 @@ async function deleteCheckoutStripeResourcesForAccountDeletion( try { await client.subscriptions.cancel(subscription.id); } catch (error) { - if (isStripeSubscriptionAlreadyCanceledError(error)) return; - throw error; + if (!isStripeSubscriptionAlreadyCanceledError(error)) throw error; } try { await client.customers.del(customerId); diff --git a/web/tests/billing-purchase.test.ts b/web/tests/billing-purchase.test.ts index 3b5a0857d739..66f8f060f2f5 100644 --- a/web/tests/billing-purchase.test.ts +++ b/web/tests/billing-purchase.test.ts @@ -185,7 +185,9 @@ describe("recordCheckoutCompletion", () => { }); test("does not recreate checkout billing rows after the Stack user is gone", async () => { - const cancelSubscription = mock(async () => undefined); + const cancelSubscription = mock(async () => { + throw { statusCode: 404, message: "No such subscription" }; + }); const deleteCustomer = mock(async () => undefined); await expect( From 6c40a742fa8b92ff26b5058ecf196fc092a2f25b Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Thu, 9 Jul 2026 01:45:08 -0700 Subject: [PATCH 42/89] Treat Subrouter revoke attempts as destructive --- web/app/api/account/route.ts | 2 +- web/tests/account-route.test.ts | 31 +++++++++++++++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/web/app/api/account/route.ts b/web/app/api/account/route.ts index 45815eff6e33..f781456697dd 100644 --- a/web/app/api/account/route.ts +++ b/web/app/api/account/route.ts @@ -510,12 +510,12 @@ async function deletePersonalSubrouterTenant( .limit(1); if (!tenant) return; + options.afterExternalMutation?.(); try { await createSubrouterClientFromEnv().revokeTenant(tenant.tenantId); } catch (error) { if (!(error instanceof SubrouterClientError && error.status === 404)) throw error; } - options.afterExternalMutation?.(); await db.delete(subrouterTenants).where(eq(subrouterTenants.teamId, userId)); } diff --git a/web/tests/account-route.test.ts b/web/tests/account-route.test.ts index e98c5b420901..7d5bce338b04 100644 --- a/web/tests/account-route.test.ts +++ b/web/tests/account-route.test.ts @@ -567,6 +567,37 @@ describe("account deletion route", () => { expect(updateStackUser).toHaveBeenCalledTimes(1); }); + test("keeps deletion retryable when Subrouter revoke reaches the network before failing", async () => { + listedPersonalVmIds = []; + selectResults = [ + [], + [], + [], + [], + [], + [], + [{ tenantId: "tenant-personal" }], + ]; + subrouterRevokeError = new Error("subrouter request timed out"); + + const response = await DELETE(accountDeletionRequest()); + + expect(response.status).toBe(500); + expect(await response.json()).toEqual({ + error: "account_delete_retryable", + retryable: true, + destroyedVms: 0, + }); + expect(revokeTenant).toHaveBeenCalledWith("tenant-personal"); + expect(deletedTables).not.toContain(subrouterTenants); + expect(transaction).not.toHaveBeenCalled(); + expect(deleteStackUser).not.toHaveBeenCalled(); + expect(updateStackUser).toHaveBeenNthCalledWith(1, { + clientReadOnlyMetadata: { cmuxAccountDeleting: true }, + }); + expect(updateStackUser).toHaveBeenCalledTimes(1); + }); + test("does not delete personal VM rows that gained a provider id before account row deletion", async () => { transactionSelectResults = [[{ id: "00000000-0000-4000-8000-000000000764", From b2833f5e9db8c78fb5329b5e63aa12745912a516 Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Thu, 9 Jul 2026 01:53:18 -0700 Subject: [PATCH 43/89] Serialize account deletion with personal VM creation --- web/app/api/account/route.ts | 3 ++- web/tests/account-route.test.ts | 10 ++++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/web/app/api/account/route.ts b/web/app/api/account/route.ts index f781456697dd..6f1232ad6dea 100644 --- a/web/app/api/account/route.ts +++ b/web/app/api/account/route.ts @@ -1,4 +1,4 @@ -import { and, asc, eq, inArray, isNotNull, isNull, or } from "drizzle-orm"; +import { and, asc, eq, inArray, isNotNull, isNull, or, sql } from "drizzle-orm"; import { getStackServerApp, isStackConfigured } from "../../lib/stack"; import { cloudDb } from "../../../db/client"; @@ -402,6 +402,7 @@ async function deleteCmuxOwnedAccountRows(userId: string): Promise { const db = cloudDb(); await db.transaction(async (tx) => { const now = new Date(); + await tx.execute(sql`select pg_advisory_xact_lock(hashtextextended(${userId}, 0))`); const personalVmRows = await tx .select({ id: cloudVms.id, diff --git a/web/tests/account-route.test.ts b/web/tests/account-route.test.ts index 7d5bce338b04..0d27d62d9dde 100644 --- a/web/tests/account-route.test.ts +++ b/web/tests/account-route.test.ts @@ -64,6 +64,9 @@ const transactionSelect = mock(() => ({ }), }), })); +const transactionExecute = mock(async () => { + routeEvents.push("transaction-lock"); +}); const deleteRows = mock((table: unknown) => { deletedTables.push(table); deletedTableCount += 1; @@ -181,6 +184,7 @@ type MockTransaction = { }; }; }; + readonly execute: (query: unknown) => Promise; readonly delete: (table: unknown) => { readonly where: (condition: unknown) => Promise }; readonly update: (table: unknown) => { readonly set: (values: unknown) => { readonly where: (condition: unknown) => Promise }; @@ -195,6 +199,7 @@ type SelectResult = Promise & { const mockTransaction: MockTransaction = { select: transactionSelect, + execute: transactionExecute, delete: deleteRows, update: updateRows, }; @@ -315,6 +320,7 @@ beforeEach(() => { getUser.mockClear(); transaction.mockClear(); transactionSelect.mockClear(); + transactionExecute.mockClear(); deleteRows.mockClear(); updateRows.mockClear(); mockDb.select.mockClear(); @@ -436,8 +442,10 @@ describe("account deletion route", () => { "vault-delete", "revoke-identities", "transaction", + "transaction-lock", "stack-delete", "transaction", + "transaction-lock", ]); }); @@ -614,6 +622,7 @@ describe("account deletion route", () => { destroyedVms: 2, }); expect(transaction).toHaveBeenCalledTimes(1); + expect(transactionExecute).toHaveBeenCalledTimes(1); expect(transactionSelect).toHaveBeenCalledTimes(1); expect(deletedTableCount).toBe(0); expect(deleteStackUser).not.toHaveBeenCalled(); @@ -902,6 +911,7 @@ describe("account deletion route", () => { "destroy-vm", "revoke-identities", "transaction", + "transaction-lock", "stack-delete", ]); expect(consoleError).toHaveBeenCalledWith( From 424c3b8b0b5d3a1d36bd7540e1fa4276ed429519 Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Thu, 9 Jul 2026 02:02:17 -0700 Subject: [PATCH 44/89] Preserve deletion state after SSH revoke cleanup --- web/app/api/account/route.ts | 3 ++- web/services/vms/workflows.ts | 17 ++++++++++++- web/tests/account-route.test.ts | 41 ++++++++++++++++++++++++++++--- web/tests/vm-workflows.test.ts | 43 ++++++++++++++++++++++++++++++++- 4 files changed, 97 insertions(+), 7 deletions(-) diff --git a/web/app/api/account/route.ts b/web/app/api/account/route.ts index 6f1232ad6dea..d7d14194b58e 100644 --- a/web/app/api/account/route.ts +++ b/web/app/api/account/route.ts @@ -511,9 +511,10 @@ async function deletePersonalSubrouterTenant( .limit(1); if (!tenant) return; + const client = createSubrouterClientFromEnv(); options.afterExternalMutation?.(); try { - await createSubrouterClientFromEnv().revokeTenant(tenant.tenantId); + await client.revokeTenant(tenant.tenantId); } catch (error) { if (!(error instanceof SubrouterClientError && error.status === 404)) throw error; } diff --git a/web/services/vms/workflows.ts b/web/services/vms/workflows.ts index 250f3c991acb..1cf88007f065 100644 --- a/web/services/vms/workflows.ts +++ b/web/services/vms/workflows.ts @@ -1342,13 +1342,28 @@ export function revokeUserIdentityLeasesForAccountDeletion( if (revoked) revokedIds.push(lease.id); } - yield* repo.markLeasesRevoked(revokedIds); + yield* markAccountDeletionLeasesRevoked(repo, revokedIds); revokedCount += revokedIds.length; if (leases.length < limit) return revokedCount; } }); } +function markAccountDeletionLeasesRevoked( + repo: VmRepositoryShape, + revokedIds: readonly string[], +): Effect.Effect { + return repo.markLeasesRevoked(revokedIds).pipe( + Effect.catchAll((err): Effect.Effect => + Effect.fail( + revokedIds.length > 0 + ? new VmAccountDeletionIdentityRevocationError({ cause: err }) + : err, + ) + ), + ); +} + function boundedAccountDeletionIdentityRevokeLimit(limit: number | undefined): number { if (typeof limit !== "number" || !Number.isFinite(limit)) return ACCOUNT_DELETION_IDENTITY_REVOKE_BATCH; return Math.max(1, Math.min(Math.floor(limit), ACCOUNT_DELETION_IDENTITY_REVOKE_BATCH)); diff --git a/web/tests/account-route.test.ts b/web/tests/account-route.test.ts index 0d27d62d9dde..d1a02e9f017d 100644 --- a/web/tests/account-route.test.ts +++ b/web/tests/account-route.test.ts @@ -166,6 +166,7 @@ let stripeDeleteCustomerError: unknown = null; let destroyVmFailureProviderIds = new Set(); let listedPersonalVmIds: string[] = []; let revokeIdentityLeasesError: unknown = null; +let subrouterClientCreateError: unknown = null; let subrouterRevokeError: unknown = null; let useAccountRouteStubs = false; const originalConsoleError = console.error; @@ -271,11 +272,13 @@ mock.module("../services/billing/stripe", () => ({ mock.module("../services/subrouter/client", () => ({ ...subrouterClientModule, - createSubrouterClientFromEnv: () => useAccountRouteStubs - ? { + createSubrouterClientFromEnv: () => { + if (!useAccountRouteStubs) return realCreateSubrouterClientFromEnv(); + if (subrouterClientCreateError) throw subrouterClientCreateError; + return { revokeTenant, - } - : realCreateSubrouterClientFromEnv(), + }; + }, })); mock.module("../services/vms/workflows", () => ({ @@ -352,6 +355,7 @@ beforeEach(() => { destroyVmFailureProviderIds = new Set(); listedPersonalVmIds = ["personal-vm-1", "personal-vm-2"]; revokeIdentityLeasesError = null; + subrouterClientCreateError = null; subrouterRevokeError = null; }); @@ -606,6 +610,35 @@ describe("account deletion route", () => { expect(updateStackUser).toHaveBeenCalledTimes(1); }); + test("restores Stack metadata when local Subrouter configuration fails before revoke", async () => { + listedPersonalVmIds = []; + selectResults = [ + [], + [], + [], + [], + [], + [], + [{ tenantId: "tenant-personal" }], + ]; + subrouterClientCreateError = new Error("subrouter not configured"); + + const response = await DELETE(accountDeletionRequest()); + + expect(response.status).toBe(500); + expect(await response.json()).toEqual({ error: "account_delete_failed" }); + expect(revokeTenant).not.toHaveBeenCalled(); + expect(deletedTables).not.toContain(subrouterTenants); + expect(transaction).not.toHaveBeenCalled(); + expect(deleteStackUser).not.toHaveBeenCalled(); + expect(updateStackUser).toHaveBeenNthCalledWith(1, { + clientReadOnlyMetadata: { cmuxAccountDeleting: true }, + }); + expect(updateStackUser).toHaveBeenNthCalledWith(2, { + clientReadOnlyMetadata: { cmuxPlan: "pro" }, + }); + }); + test("does not delete personal VM rows that gained a provider id before account row deletion", async () => { transactionSelectResults = [[{ id: "00000000-0000-4000-8000-000000000764", diff --git a/web/tests/vm-workflows.test.ts b/web/tests/vm-workflows.test.ts index cc912db2a055..e935800e723a 100644 --- a/web/tests/vm-workflows.test.ts +++ b/web/tests/vm-workflows.test.ts @@ -23,6 +23,7 @@ import { } from "../services/vms/repository"; import { VmCreateCreditsInsufficientError, + VmAccountDeletionIdentityRevocationError, VmCreateFailedError, VmCreateInProgressError, VmDatabaseError, @@ -561,6 +562,43 @@ describe("VM Effect workflows", () => { expect(revokedLeaseIds).toEqual(["lease-account-delete-success"]); }); + test("marks account-deletion SSH identity cleanup destructive when lease marking fails after revoke", async () => { + const repo = testWorkflowRepo({ + vm: testCloudVmRow(), + accountDeletionIdentityLeases: () => + Effect.succeed([ + testIdentityLease("lease-account-delete-success", "identity-account-delete-success"), + ]), + markLeasesRevoked: () => + Effect.fail(new VmDatabaseError({ + operation: "markLeasesRevoked", + cause: new Error("db unavailable"), + })), + }); + const revokedIdentities: string[] = []; + const provider: VmProviderGatewayShape = { + ...unusedProviderGateway(), + revokeSSHIdentity: (_provider, identityHandle) => + Effect.sync(() => { + revokedIdentities.push(identityHandle); + }), + }; + + let thrown: unknown; + try { + await Effect.runPromise( + revokeUserIdentityLeasesForAccountDeletion("user-workflow-account-delete").pipe( + Effect.provide(workflowLayer(repo, provider)), + ), + ); + } catch (error) { + thrown = error; + } + + expect(revokedIdentities).toEqual(["identity-account-delete-success"]); + expect(String(thrown)).toContain(VmAccountDeletionIdentityRevocationError.name); + }); + test("revokeExpiredIdentityLeases uses a small default cron batch", async () => { const vm = testCloudVmRow({ id: "00000000-0000-4000-8000-000000000131", @@ -4378,6 +4416,7 @@ function testWorkflowRepo(input: { readonly activeIdentityLeases?: CloudVmLeaseRow[]; readonly expiredIdentityLeases?: VmRepositoryShape["expiredIdentityLeases"]; readonly accountDeletionIdentityLeases?: VmRepositoryShape["accountDeletionIdentityLeases"]; + readonly markLeasesRevoked?: VmRepositoryShape["markLeasesRevoked"]; readonly revokedLeaseIds?: string[]; readonly revokedLeaseBatches?: string[][]; readonly leaseRevocationRetries?: LeaseRevocationRetry[]; @@ -4463,7 +4502,9 @@ function testWorkflowRepo(input: { : input.activeIdentityLeases ?? [], ), markLeasesRevoked: (leaseIds) => - Effect.sync(() => { + input.markLeasesRevoked + ? input.markLeasesRevoked(leaseIds) + : Effect.sync(() => { input.revokedLeaseBatches?.push([...leaseIds]); input.revokedLeaseIds?.push(...leaseIds); }), From 871f8057580fcf3285293335cf7eacc076d01f37 Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Thu, 9 Jul 2026 02:23:14 -0700 Subject: [PATCH 45/89] Harden account deletion cleanup coverage --- .../MobileSettingsAccountSection.swift | 2 +- ...bileSettingsDeleteAccountFailureKind.swift | 17 +- ...ettingsDeleteAccountFailureKindTests.swift | 4 + ios/cmux/Resources/Localizable.xcstrings | 17 ++ web/app/api/account/route.ts | 157 ++++++++++++++---- web/app/api/billing/complete/route.ts | 5 +- web/app/api/stripe/webhook/route.ts | 3 +- web/services/billing/purchase.ts | 13 +- web/tests/account-route.test.ts | 153 +++++++++++++++-- web/tests/billing-complete-route.test.ts | 22 ++- web/tests/billing-purchase.test.ts | 20 +++ web/tests/stripe-webhook-route.test.ts | 27 +++ 12 files changed, 377 insertions(+), 63 deletions(-) diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsAccountSection.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsAccountSection.swift index dbc2d0ddd7a4..2b54a900c9e0 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsAccountSection.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsAccountSection.swift @@ -77,7 +77,7 @@ struct MobileSettingsAccountSection: View { )) } .alert( - L10n.string("mobile.settings.deleteAccountFailedTitle", defaultValue: "Couldn't Delete Account"), + deleteAccountFailureKind.localizedTitle, isPresented: $showingDeleteAccountFailure ) { Button(L10n.string("mobile.settings.deleteAccountFailureOK", defaultValue: "OK"), role: .cancel) { diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsDeleteAccountFailureKind.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsDeleteAccountFailureKind.swift index 2c4f86cf0b6c..b3959ec0595f 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsDeleteAccountFailureKind.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsDeleteAccountFailureKind.swift @@ -19,7 +19,7 @@ enum DeleteAccountFailureKind: Equatable { } else if case AccountDeletionRequestError.stackDeleteIncomplete = error { self = .stackDeleteIncomplete } else if case AccountDeletionRequestError.timedOut = error { - self = .unknown + self = .timedOut } else if case AccountDeletionRequestError.completionUnknown = error { self = .unknown } else if case AccountDeletionRequestError.localTransportFailure = error { @@ -35,6 +35,21 @@ enum DeleteAccountFailureKind: Equatable { self == .serverCleanupIncomplete || self == .unauthorized } + var localizedTitle: String { + switch self { + case .serverCleanupIncomplete: + return L10n.string( + "mobile.settings.deleteAccountCleanupIncompleteTitle", + defaultValue: "Account Deleted" + ) + default: + return L10n.string( + "mobile.settings.deleteAccountFailedTitle", + defaultValue: "Couldn't Delete Account" + ) + } + } + var localizedMessage: String { switch self { case .generic: diff --git a/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/MobileSettingsDeleteAccountFailureKindTests.swift b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/MobileSettingsDeleteAccountFailureKindTests.swift index 19fca28abf54..a2e287f2f690 100644 --- a/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/MobileSettingsDeleteAccountFailureKindTests.swift +++ b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/MobileSettingsDeleteAccountFailureKindTests.swift @@ -18,5 +18,9 @@ import Testing #expect(DeleteAccountFailureKind(error: AccountDeletionRequestError.unauthorized) == .unauthorized) #expect(DeleteAccountFailureKind(error: AuthError.unauthorized) == .unauthorized) } + + @Test func accountDeletionTransportTimeoutMapsToTimeoutCopy() { + #expect(DeleteAccountFailureKind(error: AccountDeletionRequestError.timedOut) == .timedOut) + } } #endif diff --git a/ios/cmux/Resources/Localizable.xcstrings b/ios/cmux/Resources/Localizable.xcstrings index df7376c94287..0596f5eeaaaf 100644 --- a/ios/cmux/Resources/Localizable.xcstrings +++ b/ios/cmux/Resources/Localizable.xcstrings @@ -4081,6 +4081,23 @@ } } }, + "mobile.settings.deleteAccountCleanupIncompleteTitle": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Account Deleted" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "アカウントを削除しました" + } + } + } + }, "mobile.settings.deleteAccountFailureOK": { "extractionState": "manual", "localizations": { diff --git a/web/app/api/account/route.ts b/web/app/api/account/route.ts index d7d14194b58e..79e41995a4be 100644 --- a/web/app/api/account/route.ts +++ b/web/app/api/account/route.ts @@ -31,6 +31,9 @@ import { type ProMetadataJson, type ProMetadataCustomer, } from "../../../services/billing/pro"; +import { isAscConfigured } from "../../../services/asc/client"; +import { removeTester } from "../../../services/asc/testflight"; +import { captureAscError } from "../../../services/errors"; import { isStripeBillingConfigured, stripe } from "../../../services/billing/stripe"; import { createSubrouterClientFromEnv, @@ -55,6 +58,9 @@ const DELETED_ACCOUNT_ACTOR_ID = "deleted-account"; type DeletableStackUser = { readonly id: string; + readonly primaryEmail?: string | null; + readonly selectedTeam?: unknown; + readonly listTeams?: () => Promise; readonly delete: () => Promise; } & ProMetadataCustomer; @@ -70,6 +76,7 @@ export async function DELETE(request: Request): Promise { let destroyedVms = 0; let restoreBillingEntitlementsOnFailure = true; try { + const accountScope = await accountDeletionScopeForUser(stackUser); await markAccountDeletingAndClearBillingEntitlements(stackUser); stackMetadataMarked = true; await resolveUserBillingForAccountDeletion(userId, { @@ -78,8 +85,14 @@ export async function DELETE(request: Request): Promise { destructiveCleanupStarted = true; }, }); + await removeTestFlightAccessForAccountDeletion(stackUser, { + afterExternalMutation: () => { + restoreBillingEntitlementsOnFailure = false; + destructiveCleanupStarted = true; + }, + }); try { - destroyedVms = await destroyPersonalCloudVms(userId); + destroyedVms = await destroyPersonalCloudVms(userId, accountScope.teamIds); if (destroyedVms > 0) destructiveCleanupStarted = true; } catch (error) { if (error instanceof AccountDeletionDestructiveCleanupError) { @@ -97,7 +110,7 @@ export async function DELETE(request: Request): Promise { afterExternalMutation: () => { destructiveCleanupStarted = true; }, - }); + }, accountScope.teamIds); try { const revokedIdentityLeases = await runVmWorkflow(revokeUserIdentityLeasesForAccountDeletion(userId)); if (revokedIdentityLeases > 0) destructiveCleanupStarted = true; @@ -109,7 +122,7 @@ export async function DELETE(request: Request): Promise { // not strand retained app data behind an account the user can no longer use. // These deletes are idempotent, so the same signed-in user can retry the // final Stack deletion when the distinct response below is returned. - await deleteCmuxOwnedAccountRows(userId); + await deleteCmuxOwnedAccountRows(userId, accountScope.teamIds); cmuxOwnedRowsDeleted = true; try { await stackUser.delete(); @@ -122,7 +135,7 @@ export async function DELETE(request: Request): Promise { }, 500); } try { - await finishPostStackAccountCleanup(userId); + await finishPostStackAccountCleanup(userId, accountScope.teamIds); } catch (error) { logAccountDeleteError("account.delete.post_stack_cleanup_failed", error); return jsonResponse({ @@ -181,14 +194,25 @@ class AccountDeletionDestructiveCleanupError extends Error { } } -async function destroyPersonalCloudVms(userId: string): Promise { - const vms = await runVmWorkflow(listUserVms(userId)); +async function destroyPersonalCloudVms(userId: string, accountTeamIds: readonly string[]): Promise { + const vms = await listAccountDeletionCloudVms(userId, accountTeamIds); const failures: unknown[] = []; let destroyedVms = 0; let destructiveCleanupStarted = false; for (const vm of vms) { try { - const destroyProgram = destroyVm({ userId, providerVmId: vm.providerVmId }); + const destroyInput: { + userId: string; + billingTeamId?: string | null; + teamIds: readonly string[]; + providerVmId: string; + } = { + userId, + teamIds: accountTeamIds, + providerVmId: vm.providerVmId, + }; + if (vm.billingTeamId) destroyInput.billingTeamId = vm.billingTeamId; + const destroyProgram = destroyVm(destroyInput); destructiveCleanupStarted = true; await runVmWorkflow(destroyProgram); destroyedVms += 1; @@ -207,6 +231,25 @@ async function destroyPersonalCloudVms(userId: string): Promise { return destroyedVms; } +async function listAccountDeletionCloudVms( + userId: string, + accountTeamIds: readonly string[], +): Promise> { + const vms = new Map(); + const legacyScopedVms = await runVmWorkflow(listUserVms(userId)); + for (const vm of legacyScopedVms) { + vms.set(vm.providerVmId, { providerVmId: vm.providerVmId }); + } + for (const teamId of accountTeamIds) { + if (teamId === userId) continue; + const teamScopedVms = await runVmWorkflow(listUserVms(userId, teamId)); + for (const vm of teamScopedVms) { + vms.set(vm.providerVmId, { providerVmId: vm.providerVmId, billingTeamId: teamId }); + } + } + return [...vms.values()]; +} + async function deleteVaultRowsAndObjectsForAccount( userId: string, options: { readonly beforeObjectDeletion?: () => void } = {}, @@ -287,9 +330,9 @@ async function deleteVaultRowsAndObjectsForAccount( } } -async function finishPostStackAccountCleanup(userId: string): Promise { +async function finishPostStackAccountCleanup(userId: string, accountTeamIds: readonly string[]): Promise { await deleteVaultRowsAndObjectsForAccount(userId); - await deleteCmuxOwnedAccountRows(userId); + await deleteCmuxOwnedAccountRows(userId, accountTeamIds); } async function resolveUserBillingForAccountDeletion( @@ -330,6 +373,25 @@ async function resolveUserBillingForAccountDeletion( } } +async function removeTestFlightAccessForAccountDeletion( + user: DeletableStackUser, + options: { readonly afterExternalMutation?: () => void } = {}, +): Promise { + if (!isAscConfigured()) return; + const email = user.primaryEmail?.trim(); + if (!email) return; + try { + await removeTester(email); + options.afterExternalMutation?.(); + } catch (error) { + captureAscError(error, { + route: "/api/account", + stackUserId: user.id, + email, + }); + } +} + async function markAccountDeletingAndClearBillingEntitlements(user: DeletableStackUser): Promise { const metadata = stackMetadataRecord(user.clientReadOnlyMetadata); delete metadata.cmuxPlan; @@ -398,21 +460,24 @@ function isStripeAlreadyInDeletionTargetState(error: unknown, messagePatterns: r return messagePatterns.some((pattern) => pattern.test(message)); } -async function deleteCmuxOwnedAccountRows(userId: string): Promise { +async function deleteCmuxOwnedAccountRows(userId: string, accountTeamIds: readonly string[]): Promise { const db = cloudDb(); await db.transaction(async (tx) => { const now = new Date(); - await tx.execute(sql`select pg_advisory_xact_lock(hashtextextended(${userId}, 0))`); - const personalVmRows = await tx + const deletionTeamIds = uniqueNonEmptyStrings([userId, ...accountTeamIds]); + for (const teamId of deletionTeamIds) { + await tx.execute(sql`select pg_advisory_xact_lock(hashtextextended(${teamId}, 0))`); + } + const userVmRows = await tx .select({ id: cloudVms.id, providerVmId: cloudVms.providerVmId, status: cloudVms.status, }) .from(cloudVms) - .where(personalVmScope(userId)) + .where(eq(cloudVms.userId, userId)) .for("update"); - const unsafePersonalVmRows = personalVmRows.filter((vm) => { + const unsafePersonalVmRows = userVmRows.filter((vm) => { if (vm.status === "destroyed") return false; if (vm.status === "failed" && !vm.providerVmId) return false; return true; @@ -464,18 +529,14 @@ async function deleteCmuxOwnedAccountRows(userId: string): Promise { await tx.delete(cloudVmUsageEvents).where(eq(cloudVmUsageEvents.userId, userId)); await tx.delete(cloudVmLeases).where(eq(cloudVmLeases.userId, userId)); await tx.delete(cloudVmSessions).where(eq(cloudVmSessions.userId, userId)); - if (personalVmRows.length > 0) { - await tx.delete(cloudVms).where(inArray(cloudVms.id, personalVmRows.map((vm) => vm.id))); + if (userVmRows.length > 0) { + await tx.delete(cloudVms).where(inArray(cloudVms.id, userVmRows.map((vm) => vm.id))); } await tx.delete(cloudVmBaseEvents).where(eq(cloudVmBaseEvents.userId, userId)); await tx.delete(cloudVmBases).where(and( eq(cloudVmBases.scopeType, "user"), eq(cloudVmBases.scopeId, userId), )); - await tx - .update(cloudVms) - .set({ userId: DELETED_ACCOUNT_ACTOR_ID, updatedAt: now }) - .where(eq(cloudVms.userId, userId)); await tx .update(cloudVmBases) .set({ createdByUserId: DELETED_ACCOUNT_ACTOR_ID, updatedAt: now }) @@ -489,7 +550,10 @@ async function deleteCmuxOwnedAccountRows(userId: string): Promise { .set({ createdByUserId: DELETED_ACCOUNT_ACTOR_ID, updatedAt: now }) .where(eq(cloudVmBaseGenerations.createdByUserId, userId)); - await tx.delete(devices).where(eq(devices.teamId, userId)); + await tx.delete(devices).where(and( + inArray(devices.teamId, deletionTeamIds), + eq(devices.userId, userId), + )); await tx .update(devices) .set({ userId: DELETED_ACCOUNT_ACTOR_ID, updatedAt: now }) @@ -502,30 +566,51 @@ async function deleteCmuxOwnedAccountRows(userId: string): Promise { async function deletePersonalSubrouterTenant( userId: string, options: { readonly afterExternalMutation?: () => void } = {}, + accountTeamIds: readonly string[] = [userId], ): Promise { const db = cloudDb(); - const [tenant] = await db + const teamIds = uniqueNonEmptyStrings([userId, ...accountTeamIds]); + const tenants = await db .select({ tenantId: subrouterTenants.tenantId }) .from(subrouterTenants) - .where(eq(subrouterTenants.teamId, userId)) - .limit(1); - if (!tenant) return; + .where(inArray(subrouterTenants.teamId, teamIds)); + if (tenants.length === 0) return; const client = createSubrouterClientFromEnv(); - options.afterExternalMutation?.(); - try { - await client.revokeTenant(tenant.tenantId); - } catch (error) { - if (!(error instanceof SubrouterClientError && error.status === 404)) throw error; + for (const tenant of tenants) { + options.afterExternalMutation?.(); + try { + await client.revokeTenant(tenant.tenantId); + } catch (error) { + if (!(error instanceof SubrouterClientError && error.status === 404)) throw error; + } } - await db.delete(subrouterTenants).where(eq(subrouterTenants.teamId, userId)); + await db.delete(subrouterTenants).where(inArray(subrouterTenants.teamId, teamIds)); +} + +async function accountDeletionScopeForUser(user: DeletableStackUser): Promise<{ readonly teamIds: readonly string[] }> { + const selectedTeamId = stackTeamIdFromUnknown(user.selectedTeam); + if (selectedTeamId) return { teamIds: uniqueNonEmptyStrings([user.id, selectedTeamId]) }; + if (typeof user.listTeams !== "function") return { teamIds: [user.id] }; + + const listedTeamIds = (await user.listTeams()) + .map(stackTeamIdFromUnknown) + .filter((teamId): teamId is string => !!teamId); + return listedTeamIds.length === 1 + ? { teamIds: uniqueNonEmptyStrings([user.id, listedTeamIds[0]]) } + : { teamIds: [user.id] }; +} + +function stackTeamIdFromUnknown(value: unknown): string | null { + if (!value || typeof value !== "object") return null; + const id = (value as { readonly id?: unknown }).id; + if (typeof id !== "string") return null; + const trimmed = id.trim(); + return trimmed || null; } -function personalVmScope(userId: string) { - return and( - eq(cloudVms.userId, userId), - or(isNull(cloudVms.billingTeamId), eq(cloudVms.billingTeamId, userId)), - ); +function uniqueNonEmptyStrings(values: readonly (string | null | undefined)[]): readonly string[] { + return [...new Set(values.map((value) => value?.trim()).filter((value): value is string => !!value))]; } const SENSITIVE_ERROR_TEXT = diff --git a/web/app/api/billing/complete/route.ts b/web/app/api/billing/complete/route.ts index ca373f247118..429e07e6d6a9 100644 --- a/web/app/api/billing/complete/route.ts +++ b/web/app/api/billing/complete/route.ts @@ -62,11 +62,14 @@ export function makeBillingCompleteHandler( session.payment_status === "paid" || session.payment_status === "no_payment_required" ) { - await dependencies.recordCheckoutCompletion({ + const completion = await dependencies.recordCheckoutCompletion({ session, subscription: expandedSubscription(session), customer: expandedCustomer(session), }); + if ("skipped" in completion) { + return NextResponse.redirect(new URL("/pricing?billing=account_deletion", request.url)); + } if (session.metadata?.plan === "team") { return NextResponse.redirect( new URL("/dashboard/billing?welcome=team", request.nextUrl.origin), diff --git a/web/app/api/stripe/webhook/route.ts b/web/app/api/stripe/webhook/route.ts index 75357781edec..28b55cf2042e 100644 --- a/web/app/api/stripe/webhook/route.ts +++ b/web/app/api/stripe/webhook/route.ts @@ -132,11 +132,12 @@ async function processStripeEvent( const expanded = await dependencies.stripe().checkout.sessions.retrieve(session.id, { expand: ["subscription", "customer"], }); - await dependencies.recordCheckoutCompletion({ + const result = await dependencies.recordCheckoutCompletion({ session: expanded, subscription: expandedSubscription(expanded), customer: expandedCustomer(expanded), }); + if (result && "skipped" in result) return { skipped: result.skipped }; return { processed: "checkout.session.completed" }; } case "customer.subscription.created": diff --git a/web/services/billing/purchase.ts b/web/services/billing/purchase.ts index d4bbc030f5ea..bbd8bdcb3f52 100644 --- a/web/services/billing/purchase.ts +++ b/web/services/billing/purchase.ts @@ -224,7 +224,13 @@ export async function applySubscriptionUpdate( const metadataStackUserId = subscription.metadata?.stackUserId; const mappedStackUserId = await stackUserIdForStripeCustomer(db, customerId); if (mappedStackUserId === DELETED_ACCOUNT_ACTOR_ID) return { skipped: true }; - const stackUserId = metadataStackUserId ?? mappedStackUserId; + if ( + metadataStackUserId && + mappedStackUserId && + metadataStackUserId !== mappedStackUserId + ) return { skipped: true }; + + const stackUserId = mappedStackUserId ?? metadataStackUserId; if (!stackUserId || stackUserId === DELETED_ACCOUNT_ACTOR_ID) return { skipped: true }; const isActive = isActiveStripeSubscriptionStatus(subscription.status); @@ -232,11 +238,6 @@ export async function applySubscriptionUpdate( subscriptionId: subscription.id, stackUserId, }); - if ( - !hasUserSubscription && - mappedStackUserId !== stackUserId && - metadataStackUserId !== stackUserId - ) return { skipped: true }; const isMetadataOnlyUserSubscription = !hasUserSubscription && !mappedStackUserId && metadataStackUserId === stackUserId; diff --git a/web/tests/account-route.test.ts b/web/tests/account-route.test.ts index d1a02e9f017d..29f28711d9c1 100644 --- a/web/tests/account-route.test.ts +++ b/web/tests/account-route.test.ts @@ -33,6 +33,12 @@ const realCloseCloudDbForTests = dbClientModule.closeCloudDbForTests; const stripeModule = await import("../services/billing/stripe"); const realIsStripeBillingConfigured = stripeModule.isStripeBillingConfigured; const realStripe = stripeModule.stripe; +const ascClientModule = await import("../services/asc/client"); +const realIsAscConfigured = ascClientModule.isAscConfigured; +const ascTestflightModule = await import("../services/asc/testflight"); +const realRemoveTester = ascTestflightModule.removeTester; +const errorsModule = await import("../services/errors"); +const realCaptureAscError = errorsModule.captureAscError; const storageModule = await import("../services/vault/storage"); const realDeleteObject = storageModule.deleteObject; const subrouterClientModule = await import("../services/subrouter/client"); @@ -85,8 +91,8 @@ const updateRows = mock((table: unknown) => ({ }, })); const listUserVms = mock((...args: unknown[]) => { - const [userId] = args as [string]; - return { kind: "listUserVms" as const, userId }; + const [userId, billingTeamId] = args as [string, string | null | undefined]; + return { kind: "listUserVms" as const, userId, billingTeamId }; }); const revokeUserIdentityLeasesForAccountDeletion = mock((...args: unknown[]) => { const [userId] = args as [string]; @@ -106,7 +112,10 @@ const runVmWorkflow = mock(async (...args: unknown[]) => { const [program] = args as [WorkflowProgram]; if (program.kind === "listUserVms") { routeEvents.push("list-vms"); - return listedPersonalVmIds.map((providerVmId) => ({ providerVmId })); + const providerVmIds = program.billingTeamId + ? listedPersonalVmIdsByBillingTeam[program.billingTeamId] ?? [] + : listedPersonalVmIds; + return providerVmIds.map((providerVmId) => ({ providerVmId })); } if (program.kind === "revokeUserIdentityLeasesForAccountDeletion") { routeEvents.push("revoke-identities"); @@ -140,6 +149,14 @@ const deleteCustomer = mock(async (...args: unknown[]) => { deletedStripeCustomers.push(customerId); if (stripeDeleteCustomerError) throw stripeDeleteCustomerError; }); +const removeTester = mock(async (...args: unknown[]) => { + const [email] = args as [string]; + routeEvents.push(`testflight-remove:${email}`); + if (removeTesterError) throw removeTesterError; +}); +const captureAscError = mock((..._args: unknown[]) => { + routeEvents.push("testflight-error"); +}); const revokeTenant = mock(async (...args: unknown[]) => { const [tenantId] = args as [string]; routeEvents.push(`subrouter-revoke:${tenantId}`); @@ -159,23 +176,35 @@ let deletedVaultObjects: string[] = []; let vaultDeleteError: unknown = null; let postStackVaultDeleteError: unknown = null; let stripeConfigured = true; +let ascConfigured = false; let cancelledStripeSubscriptions: string[] = []; let deletedStripeCustomers: string[] = []; let stripeCancelError: unknown = null; let stripeDeleteCustomerError: unknown = null; +let removeTesterError: unknown = null; let destroyVmFailureProviderIds = new Set(); let listedPersonalVmIds: string[] = []; +let listedPersonalVmIdsByBillingTeam: Record = {}; let revokeIdentityLeasesError: unknown = null; let subrouterClientCreateError: unknown = null; let subrouterRevokeError: unknown = null; +let stackUserSelectedTeam: unknown = null; +let stackUserTeams: readonly unknown[] = []; let useAccountRouteStubs = false; const originalConsoleError = console.error; const consoleError = mock(() => {}); type WorkflowProgram = - | { readonly kind: "listUserVms"; readonly userId: string } + | { readonly kind: "listUserVms"; readonly userId: string; readonly billingTeamId?: string | null } | { readonly kind: "revokeUserIdentityLeasesForAccountDeletion"; readonly userId: string } - | { readonly kind: "destroyVm"; readonly input: { readonly userId: string; readonly providerVmId: string } }; + | { + readonly kind: "destroyVm"; + readonly input: { + readonly userId: string; + readonly billingTeamId?: string | null; + readonly providerVmId: string; + }; + }; type MockTransaction = { readonly select: (...args: unknown[]) => { @@ -270,6 +299,28 @@ mock.module("../services/billing/stripe", () => ({ : realStripe(), })); +mock.module("../services/asc/client", () => ({ + ...ascClientModule, + isAscConfigured: () => useAccountRouteStubs ? ascConfigured : realIsAscConfigured(), +})); + +mock.module("../services/asc/testflight", () => ({ + ...ascTestflightModule, + removeTester: ((...args: Parameters) => { + const [email] = args; + if (useAccountRouteStubs) return removeTester(email); + return realRemoveTester(...args); + }) as typeof realRemoveTester, +})); + +mock.module("../services/errors", () => ({ + ...errorsModule, + captureAscError: ((...args: Parameters) => { + if (useAccountRouteStubs) return captureAscError(...args); + return realCaptureAscError(...args); + }) as typeof realCaptureAscError, +})); + mock.module("../services/subrouter/client", () => ({ ...subrouterClientModule, createSubrouterClientFromEnv: () => { @@ -334,6 +385,8 @@ beforeEach(() => { deleteObject.mockClear(); cancelSubscription.mockClear(); deleteCustomer.mockClear(); + removeTester.mockClear(); + captureAscError.mockClear(); revokeTenant.mockClear(); deletedTableCount = 0; deletedTables = []; @@ -348,15 +401,20 @@ beforeEach(() => { vaultDeleteError = null; postStackVaultDeleteError = null; stripeConfigured = true; + ascConfigured = false; cancelledStripeSubscriptions = []; deletedStripeCustomers = []; stripeCancelError = null; stripeDeleteCustomerError = null; + removeTesterError = null; destroyVmFailureProviderIds = new Set(); listedPersonalVmIds = ["personal-vm-1", "personal-vm-2"]; + listedPersonalVmIdsByBillingTeam = {}; revokeIdentityLeasesError = null; subrouterClientCreateError = null; subrouterRevokeError = null; + stackUserSelectedTeam = null; + stackUserTeams = []; }); afterEach(() => { @@ -388,8 +446,16 @@ describe("account deletion route", () => { expect(await response.json()).toEqual({ ok: true, destroyedVms: 2 }); expect(listUserVms).toHaveBeenCalledWith("account-user-1"); expect(destroyVm).toHaveBeenCalledTimes(2); - expect(destroyVm).toHaveBeenCalledWith({ userId: "account-user-1", providerVmId: "personal-vm-1" }); - expect(destroyVm).toHaveBeenCalledWith({ userId: "account-user-1", providerVmId: "personal-vm-2" }); + expect(destroyVm).toHaveBeenCalledWith({ + userId: "account-user-1", + teamIds: ["account-user-1"], + providerVmId: "personal-vm-1", + }); + expect(destroyVm).toHaveBeenCalledWith({ + userId: "account-user-1", + teamIds: ["account-user-1"], + providerVmId: "personal-vm-2", + }); expect(transaction).toHaveBeenCalledTimes(2); expect(deletedTableCount).toBeGreaterThan(10); expect(deletedTables).toContain(cloudVmBillingGrants); @@ -400,14 +466,12 @@ describe("account deletion route", () => { }))).toEqual([ { table: stripeSubscriptions, values: { stackUserId: "deleted-account" } }, { table: stripeCustomers, values: { stackUserId: "deleted-account" } }, - { table: cloudVms, values: { userId: "deleted-account" } }, { table: cloudVmBases, values: { createdByUserId: "deleted-account" } }, { table: cloudVmBases, values: { lastOpenedByUserId: null } }, { table: cloudVmBaseGenerations, values: { createdByUserId: "deleted-account" } }, { table: devices, values: { userId: "deleted-account" } }, { table: stripeSubscriptions, values: { stackUserId: "deleted-account" } }, { table: stripeCustomers, values: { stackUserId: "deleted-account" } }, - { table: cloudVms, values: { userId: "deleted-account" } }, { table: cloudVmBases, values: { createdByUserId: "deleted-account" } }, { table: cloudVmBases, values: { lastOpenedByUserId: null } }, { table: cloudVmBaseGenerations, values: { createdByUserId: "deleted-account" } }, @@ -453,6 +517,36 @@ describe("account deletion route", () => { ]); }); + test("destroys personal-team scoped VMs before deleting account rows", async () => { + listedPersonalVmIds = []; + listedPersonalVmIdsByBillingTeam = { "team-personal": ["personal-team-vm"] }; + stackUserTeams = [{ id: "team-personal" }]; + selectResults = [ + [], + [], + [], + [], + [], + [], + [{ tenantId: "tenant-team-personal" }], + ]; + + const response = await DELETE(accountDeletionRequest()); + + expect(response.status).toBe(200); + expect(await response.json()).toEqual({ ok: true, destroyedVms: 1 }); + expect(listUserVms).toHaveBeenCalledWith("account-user-1"); + expect(listUserVms).toHaveBeenCalledWith("account-user-1", "team-personal"); + expect(destroyVm).toHaveBeenCalledWith({ + userId: "account-user-1", + billingTeamId: "team-personal", + teamIds: ["account-user-1", "team-personal"], + providerVmId: "personal-team-vm", + }); + expect(revokeTenant).toHaveBeenCalledWith("tenant-team-personal"); + expect(transactionExecute).toHaveBeenCalledTimes(4); + }); + test("revokes the personal Subrouter tenant before deleting local rows", async () => { selectResults = [ [], @@ -474,6 +568,17 @@ describe("account deletion route", () => { ); }); + test("removes TestFlight access during account deletion when ASC is configured", async () => { + ascConfigured = true; + listedPersonalVmIds = []; + + const response = await DELETE(accountDeletionRequest()); + + expect(response.status).toBe(200); + expect(removeTester).toHaveBeenCalledWith("account@example.com"); + expect(routeEvents).toContain("testflight-remove:account@example.com"); + }); + test("revokes active account SSH identities before deleting cmux rows", async () => { const response = await DELETE(accountDeletionRequest()); @@ -686,7 +791,7 @@ describe("account deletion route", () => { expect(deletedTables).toContain(devices); const deviceDelete = deletedWhere.find((entry) => entry.table === devices); expect(conditionColumnNames(deviceDelete?.condition)).toContain("team_id"); - expect(conditionColumnNames(deviceDelete?.condition)).not.toContain("user_id"); + expect(conditionColumnNames(deviceDelete?.condition)).toContain("user_id"); expect(updatedRows.map(({ table, values }) => ({ table, values: stripUpdatedAt(values), @@ -847,8 +952,16 @@ describe("account deletion route", () => { destroyedVms: 1, }); expect(destroyVm).toHaveBeenCalledTimes(2); - expect(destroyVm).toHaveBeenCalledWith({ userId: "account-user-1", providerVmId: "personal-vm-1" }); - expect(destroyVm).toHaveBeenCalledWith({ userId: "account-user-1", providerVmId: "personal-vm-2" }); + expect(destroyVm).toHaveBeenCalledWith({ + userId: "account-user-1", + teamIds: ["account-user-1"], + providerVmId: "personal-vm-1", + }); + expect(destroyVm).toHaveBeenCalledWith({ + userId: "account-user-1", + teamIds: ["account-user-1"], + providerVmId: "personal-vm-2", + }); expect(transaction).not.toHaveBeenCalled(); expect(deleteStackUser).not.toHaveBeenCalled(); expect(updateStackUser).toHaveBeenNthCalledWith(1, { @@ -877,8 +990,16 @@ describe("account deletion route", () => { destroyedVms: 0, }); expect(destroyVm).toHaveBeenCalledTimes(2); - expect(destroyVm).toHaveBeenCalledWith({ userId: "account-user-1", providerVmId: "personal-vm-1" }); - expect(destroyVm).toHaveBeenCalledWith({ userId: "account-user-1", providerVmId: "personal-vm-2" }); + expect(destroyVm).toHaveBeenCalledWith({ + userId: "account-user-1", + teamIds: ["account-user-1"], + providerVmId: "personal-vm-1", + }); + expect(destroyVm).toHaveBeenCalledWith({ + userId: "account-user-1", + teamIds: ["account-user-1"], + providerVmId: "personal-vm-2", + }); expect(transaction).not.toHaveBeenCalled(); expect(deleteStackUser).not.toHaveBeenCalled(); expect(updateStackUser).toHaveBeenNthCalledWith(1, { @@ -1034,8 +1155,8 @@ function stackUser(id = "account-user-1") { displayName: null, primaryEmail: "account@example.com", clientReadOnlyMetadata: { cmuxPlan: "pro" }, - selectedTeam: null, - listTeams: async () => [], + selectedTeam: stackUserSelectedTeam, + listTeams: async () => stackUserTeams, update: updateStackUser, delete: deleteStackUser, }; diff --git a/web/tests/billing-complete-route.test.ts b/web/tests/billing-complete-route.test.ts index 7ddf83863801..0355de6b5086 100644 --- a/web/tests/billing-complete-route.test.ts +++ b/web/tests/billing-complete-route.test.ts @@ -6,7 +6,8 @@ import { makeBillingCompleteHandler } from "../app/api/billing/complete/route"; let stripeConfigured = true; let retrievedSession: Record; const retrieveSession = mock(async () => retrievedSession); -const recordCheckoutCompletion = mock(async () => ({ stackUserId: "user-1", subscriptionId: "sub_1" })); +let recordCheckoutCompletionResult: unknown = { stackUserId: "user-1", subscriptionId: "sub_1" }; +const recordCheckoutCompletion = mock(async () => recordCheckoutCompletionResult); const GET = makeBillingCompleteHandler({ isConfigured: () => stripeConfigured, @@ -34,6 +35,7 @@ describe("billing complete route", () => { }; retrieveSession.mockClear(); recordCheckoutCompletion.mockClear(); + recordCheckoutCompletionResult = { stackUserId: "user-1", subscriptionId: "sub_1" }; }); test("records paid sessions and redirects to success with the validated scheme", async () => { @@ -95,6 +97,24 @@ describe("billing complete route", () => { ); }); + test("does not redirect to success when checkout is cancelled for account deletion", async () => { + recordCheckoutCompletionResult = { + skipped: "account_deletion_in_progress", + stackUserId: "user-1", + subscriptionId: "sub_1", + }; + + const response = await GET( + new NextRequest("https://cmux.test/api/billing/complete?session_id=cs_123"), + ); + + expect(recordCheckoutCompletion).toHaveBeenCalled(); + expect(response.status).toBe(307); + expect(response.headers.get("location")).toBe( + "https://cmux.test/pricing?billing=account_deletion", + ); + }); + test("rejects foreign paid sessions without recording them", async () => { retrievedSession = { id: "cs_foreign", diff --git a/web/tests/billing-purchase.test.ts b/web/tests/billing-purchase.test.ts index 66f8f060f2f5..c9304beecd29 100644 --- a/web/tests/billing-purchase.test.ts +++ b/web/tests/billing-purchase.test.ts @@ -741,6 +741,26 @@ describe("recordCheckoutCompletion", () => { expect(updates.some((update) => update.table === stripeSubscriptions)).toBe(false); }); + test("skips user subscription webhooks when Stripe metadata conflicts with the local customer mapping", async () => { + const getUser = mock(async () => { + throw new Error("should not load Stack user for conflicting Stripe identity"); + }); + selectResults = [[{ stackUserId: "user_local" }]]; + + const result = await applySubscriptionUpdate( + userSubscriptionUpdate({ status: "active" }) as never, + { + db: fakeDb() as never, + stackApp: { getUser } as never, + }, + ); + + expect(result).toEqual({ skipped: true }); + expect(getUser).not.toHaveBeenCalled(); + expect(inserts.some((insert) => insert.table === stripeSubscriptions)).toBe(false); + expect(updates.some((update) => update.table === stripeSubscriptions)).toBe(false); + }); + test("creates a missing user subscription row from Stripe metadata", async () => { const update = mock(async () => undefined); const user = { diff --git a/web/tests/stripe-webhook-route.test.ts b/web/tests/stripe-webhook-route.test.ts index d1066136bcbc..7b70b28f22ab 100644 --- a/web/tests/stripe-webhook-route.test.ts +++ b/web/tests/stripe-webhook-route.test.ts @@ -8,8 +8,14 @@ let insertedEventRows: unknown[] = [{ id: "evt_1" }]; let selectedEventRows: unknown[] = []; const updates: Record[] = []; let recordCheckoutShouldFail = false; +let recordCheckoutCompletionResult: unknown = { + scope: "user", + stackUserId: "user_1", + subscriptionId: "sub_1", +}; const recordCheckoutCompletion = mock(async () => { if (recordCheckoutShouldFail) throw new Error("db down"); + return recordCheckoutCompletionResult; }); const applySubscriptionUpdate = mock(async () => ({ stackUserId: "user_1", isActive: true })); const retrieveSession = mock(async () => ({ @@ -96,6 +102,11 @@ describe("Stripe billing webhook route", () => { selectedEventRows = []; updates.length = 0; recordCheckoutShouldFail = false; + recordCheckoutCompletionResult = { + scope: "user", + stackUserId: "user_1", + subscriptionId: "sub_1", + }; recordCheckoutCompletion.mockClear(); applySubscriptionUpdate.mockClear(); retrieveSession.mockClear(); @@ -147,6 +158,22 @@ describe("Stripe billing webhook route", () => { expect(updates.at(-1)).toMatchObject({ error: null }); }); + test("reports checkout completions skipped during account deletion", async () => { + recordCheckoutCompletionResult = { + skipped: "account_deletion_in_progress", + stackUserId: "user_1", + subscriptionId: "sub_1", + }; + + const response = await POST(webhookRequest()); + + expect(response.status).toBe(200); + await expect(response.json()).resolves.toMatchObject({ + skipped: "account_deletion_in_progress", + }); + expect(updates.at(-1)).toMatchObject({ error: null }); + }); + test("applies deleted subscription updates", async () => { currentEvent = { id: "evt_1", From 100439411005a91516a573e9bf18b4d9ae533b04 Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Thu, 9 Jul 2026 02:31:07 -0700 Subject: [PATCH 46/89] Restrict account deletion to owned Stack teams --- web/app/api/account/route.ts | 60 +++++++++++++++++++++++++-------- web/tests/account-route.test.ts | 29 +++++++++++++++- 2 files changed, 74 insertions(+), 15 deletions(-) diff --git a/web/app/api/account/route.ts b/web/app/api/account/route.ts index 79e41995a4be..992fd70038e0 100644 --- a/web/app/api/account/route.ts +++ b/web/app/api/account/route.ts @@ -64,6 +64,11 @@ type DeletableStackUser = { readonly delete: () => Promise; } & ProMetadataCustomer; +type AccountDeletionStackTeam = { + readonly id: string; + readonly listUsers?: () => Promise; +}; + export async function DELETE(request: Request): Promise { const stackUser = await currentDeletableStackUser(request); if (!stackUser) return unauthorized(); @@ -589,24 +594,51 @@ async function deletePersonalSubrouterTenant( } async function accountDeletionScopeForUser(user: DeletableStackUser): Promise<{ readonly teamIds: readonly string[] }> { - const selectedTeamId = stackTeamIdFromUnknown(user.selectedTeam); - if (selectedTeamId) return { teamIds: uniqueNonEmptyStrings([user.id, selectedTeamId]) }; - if (typeof user.listTeams !== "function") return { teamIds: [user.id] }; - - const listedTeamIds = (await user.listTeams()) - .map(stackTeamIdFromUnknown) - .filter((teamId): teamId is string => !!teamId); - return listedTeamIds.length === 1 - ? { teamIds: uniqueNonEmptyStrings([user.id, listedTeamIds[0]]) } - : { teamIds: [user.id] }; + const listedTeams = typeof user.listTeams === "function" ? await user.listTeams() : []; + const teams = uniqueStackTeams([ + stackTeamFromUnknown(user.selectedTeam), + ...listedTeams.map(stackTeamFromUnknown), + ]); + const personalTeamIds: string[] = []; + for (const team of teams) { + const memberIds = await stackTeamMemberIds(team); + if (memberIds.length === 1 && memberIds[0] === user.id) personalTeamIds.push(team.id); + } + return { teamIds: uniqueNonEmptyStrings([user.id, ...personalTeamIds]) }; } -function stackTeamIdFromUnknown(value: unknown): string | null { +function stackTeamFromUnknown(value: unknown): AccountDeletionStackTeam | null { if (!value || typeof value !== "object") return null; const id = (value as { readonly id?: unknown }).id; - if (typeof id !== "string") return null; - const trimmed = id.trim(); - return trimmed || null; + if (typeof id !== "string" || !id.trim()) return null; + const listUsers = (value as { readonly listUsers?: unknown }).listUsers; + return { + id: id.trim(), + listUsers: typeof listUsers === "function" + ? async () => await listUsers.call(value) + : undefined, + }; +} + +async function stackTeamMemberIds(team: AccountDeletionStackTeam): Promise { + if (typeof team.listUsers !== "function") return []; + const members = await team.listUsers(); + return uniqueNonEmptyStrings(members.flatMap((member) => { + if (!member || typeof member !== "object") return []; + const id = (member as { readonly id?: unknown }).id; + return typeof id === "string" ? [id] : []; + })); +} + +function uniqueStackTeams(values: readonly (AccountDeletionStackTeam | null)[]): readonly AccountDeletionStackTeam[] { + const teams: AccountDeletionStackTeam[] = []; + const seen = new Set(); + for (const team of values) { + if (!team || seen.has(team.id)) continue; + seen.add(team.id); + teams.push(team); + } + return teams; } function uniqueNonEmptyStrings(values: readonly (string | null | undefined)[]): readonly string[] { diff --git a/web/tests/account-route.test.ts b/web/tests/account-route.test.ts index 29f28711d9c1..8a6a7e7acdb6 100644 --- a/web/tests/account-route.test.ts +++ b/web/tests/account-route.test.ts @@ -520,7 +520,7 @@ describe("account deletion route", () => { test("destroys personal-team scoped VMs before deleting account rows", async () => { listedPersonalVmIds = []; listedPersonalVmIdsByBillingTeam = { "team-personal": ["personal-team-vm"] }; - stackUserTeams = [{ id: "team-personal" }]; + stackUserTeams = [stackTeam("team-personal", ["account-user-1"])]; selectResults = [ [], [], @@ -547,6 +547,26 @@ describe("account deletion route", () => { expect(transactionExecute).toHaveBeenCalledTimes(4); }); + test("does not treat a selected shared Stack team as account-owned data", async () => { + listedPersonalVmIds = []; + listedPersonalVmIdsByBillingTeam = { "team-shared": ["shared-team-vm"] }; + stackUserSelectedTeam = stackTeam("team-shared", ["account-user-1", "other-user"]); + + const response = await DELETE(accountDeletionRequest()); + + expect(response.status).toBe(200); + expect(await response.json()).toEqual({ ok: true, destroyedVms: 0 }); + expect(listUserVms).toHaveBeenCalledWith("account-user-1"); + expect(listUserVms).not.toHaveBeenCalledWith("account-user-1", "team-shared"); + expect(destroyVm).not.toHaveBeenCalledWith({ + userId: "account-user-1", + billingTeamId: "team-shared", + teamIds: ["account-user-1", "team-shared"], + providerVmId: "shared-team-vm", + }); + expect(transactionExecute).toHaveBeenCalledTimes(2); + }); + test("revokes the personal Subrouter tenant before deleting local rows", async () => { selectResults = [ [], @@ -1162,6 +1182,13 @@ function stackUser(id = "account-user-1") { }; } +function stackTeam(id: string, userIds: readonly string[]) { + return { + id, + listUsers: async () => userIds.map((userId) => ({ id: userId })), + }; +} + function stripUpdatedAt(values: unknown): Record { const copy = { ...(values as Record) }; delete copy.updatedAt; From 463f9042742fef67a21e33b8cd99cfa5f32aff6b Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Thu, 9 Jul 2026 02:49:19 -0700 Subject: [PATCH 47/89] Add deletion tombstone guards --- web/app/api/account/route.ts | 56 +++++++++++++++ .../migration.sql | 16 +++++ web/db/schema.ts | 19 +++++ web/services/account/deletionLock.ts | 18 +++++ web/services/billing/purchase.ts | 20 +++++- web/services/vms/repository.ts | 41 ++++++++++- web/tests/account-route.test.ts | 70 ++++++++++++------- web/tests/billing-purchase.test.ts | 46 ++++++++++-- 8 files changed, 256 insertions(+), 30 deletions(-) create mode 100644 web/db/migrations/20260708140000_account_deletion_locks/migration.sql create mode 100644 web/services/account/deletionLock.ts diff --git a/web/app/api/account/route.ts b/web/app/api/account/route.ts index 992fd70038e0..c207eef2b6e9 100644 --- a/web/app/api/account/route.ts +++ b/web/app/api/account/route.ts @@ -3,6 +3,7 @@ import { and, asc, eq, inArray, isNotNull, isNull, or, sql } from "drizzle-orm"; import { getStackServerApp, isStackConfigured } from "../../lib/stack"; import { cloudDb } from "../../../db/client"; import { + accountDeletionTombstones, billingEmailClaims, cloudVmBaseEvents, cloudVmBaseGenerations, @@ -40,6 +41,10 @@ import { SubrouterClientError, } from "../../../services/subrouter/client"; import { deleteObject } from "../../../services/vault/storage"; +import { + accountDeletionAdvisoryLockKey, + accountDeletionUserHash, +} from "../../../services/account/deletionLock"; import { unauthorized } from "../../../services/vms/auth"; import { isVmAccountDeletionIdentityRevocationError } from "../../../services/vms/errors"; import { jsonResponse } from "../../../services/vms/routeHelpers"; @@ -76,12 +81,15 @@ export async function DELETE(request: Request): Promise { const userId = stackUser.id; const originalStackMetadata = stackUser.clientReadOnlyMetadata; let stackMetadataMarked = false; + let accountDeletionTombstoneStarted = false; let cmuxOwnedRowsDeleted = false; let destructiveCleanupStarted = false; let destroyedVms = 0; let restoreBillingEntitlementsOnFailure = true; try { const accountScope = await accountDeletionScopeForUser(stackUser); + await markAccountDeletionTombstonePending(userId); + accountDeletionTombstoneStarted = true; await markAccountDeletingAndClearBillingEntitlements(stackUser); stackMetadataMarked = true; await resolveUserBillingForAccountDeletion(userId, { @@ -149,6 +157,7 @@ export async function DELETE(request: Request): Promise { destroyedVms, }, 202); } + await markAccountDeletionTombstoneCompleted(userId); return jsonResponse({ ok: true, destroyedVms }); } catch (error) { if (destructiveCleanupStarted || cmuxOwnedRowsDeleted) { @@ -164,6 +173,7 @@ export async function DELETE(request: Request): Promise { restoreBillingEntitlements: restoreBillingEntitlementsOnFailure, }); } + if (accountDeletionTombstoneStarted) await markAccountDeletionTombstoneFailed(userId, error); logAccountDeleteError("account.delete.failed", error); return jsonResponse({ error: "account_delete_failed" }, 500); } @@ -188,6 +198,52 @@ async function currentDeletableStackUser(request: Request): Promise { + const db = cloudDb(); + const now = new Date(); + const userIdHash = accountDeletionUserHash(userId); + await db.transaction(async (tx) => { + await tx.execute(sql`select pg_advisory_xact_lock(hashtextextended(${accountDeletionAdvisoryLockKey(userId)}, 0))`); + await tx + .insert(accountDeletionTombstones) + .values({ + userId, + userIdHash, + status: "pending", + updatedAt: now, + errorMessage: null, + }) + .onConflictDoUpdate({ + target: accountDeletionTombstones.userIdHash, + set: { + userId, + status: "pending", + updatedAt: now, + errorMessage: null, + }, + }); + }); +} + +async function markAccountDeletionTombstoneCompleted(userId: string): Promise { + const now = new Date(); + await cloudDb() + .update(accountDeletionTombstones) + .set({ status: "completed", updatedAt: now, completedAt: now, errorMessage: null }) + .where(eq(accountDeletionTombstones.userIdHash, accountDeletionUserHash(userId))); +} + +async function markAccountDeletionTombstoneFailed(userId: string, error: unknown): Promise { + await cloudDb() + .update(accountDeletionTombstones) + .set({ + status: "failed", + updatedAt: new Date(), + errorMessage: sanitizedErrorSummary(error), + }) + .where(eq(accountDeletionTombstones.userIdHash, accountDeletionUserHash(userId))); +} + class AccountDeletionDestructiveCleanupError extends Error { constructor( message: string, diff --git a/web/db/migrations/20260708140000_account_deletion_locks/migration.sql b/web/db/migrations/20260708140000_account_deletion_locks/migration.sql new file mode 100644 index 000000000000..99c517dfbf4b --- /dev/null +++ b/web/db/migrations/20260708140000_account_deletion_locks/migration.sql @@ -0,0 +1,16 @@ +CREATE TABLE "account_deletion_tombstones" ( + "user_id_hash" text PRIMARY KEY NOT NULL, + "user_id" text, + "status" text DEFAULT 'pending' NOT NULL, + "attempt_count" integer DEFAULT 0 NOT NULL, + "created_at" timestamp with time zone DEFAULT now() NOT NULL, + "updated_at" timestamp with time zone DEFAULT now() NOT NULL, + "started_at" timestamp with time zone, + "completed_at" timestamp with time zone, + "error_message" text +); + +CREATE INDEX "account_deletion_tombstones_status_updated_idx" + ON "account_deletion_tombstones" ("status", "updated_at"); +CREATE INDEX "account_deletion_tombstones_user_idx" + ON "account_deletion_tombstones" ("user_id"); diff --git a/web/db/schema.ts b/web/db/schema.ts index 39559fdf3e27..7bb0624382da 100644 --- a/web/db/schema.ts +++ b/web/db/schema.ts @@ -79,6 +79,25 @@ export const cloudVms = pgTable( ], ); +export const accountDeletionTombstones = pgTable( + "account_deletion_tombstones", + { + userIdHash: text("user_id_hash").primaryKey(), + userId: text("user_id"), + status: text("status").$type<"pending" | "in_progress" | "stack_delete_pending" | "stack_delete_in_progress" | "completed" | "failed">().notNull().default("pending"), + attemptCount: integer("attempt_count").notNull().default(0), + createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), + updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), + startedAt: timestamp("started_at", { withTimezone: true }), + completedAt: timestamp("completed_at", { withTimezone: true }), + errorMessage: text("error_message"), + }, + (table) => [ + index("account_deletion_tombstones_status_updated_idx").on(table.status, table.updatedAt), + index("account_deletion_tombstones_user_idx").on(table.userId), + ], +); + export const cloudVmLeases = pgTable( "cloud_vm_leases", { diff --git a/web/services/account/deletionLock.ts b/web/services/account/deletionLock.ts new file mode 100644 index 000000000000..f59ee00ce173 --- /dev/null +++ b/web/services/account/deletionLock.ts @@ -0,0 +1,18 @@ +import { createHash } from "node:crypto"; + +export function accountDeletionUserHash(userId: string): string { + return createHash("sha256").update(userId).digest("hex"); +} + +export function accountDeletionAdvisoryLockKey(userId: string): string { + return `account-deletion:${accountDeletionUserHash(userId)}`; +} + +export function isBlockingAccountDeletionStatus(status: string): boolean { + return ( + status === "pending" || + status === "in_progress" || + status === "stack_delete_pending" || + status === "stack_delete_in_progress" + ); +} diff --git a/web/services/billing/purchase.ts b/web/services/billing/purchase.ts index bbd8bdcb3f52..57d302fd05a4 100644 --- a/web/services/billing/purchase.ts +++ b/web/services/billing/purchase.ts @@ -4,10 +4,15 @@ import type Stripe from "stripe"; import { stackServerApp } from "../../app/lib/stack"; import { cloudDb } from "../../db/client"; import { + accountDeletionTombstones, billingEmailClaims, stripeCustomers, stripeSubscriptions, } from "../../db/schema"; +import { + accountDeletionUserHash, + isBlockingAccountDeletionStatus, +} from "../account/deletionLock"; import { PRO_PLAN_ID, type ProMetadataJson, @@ -126,7 +131,7 @@ export async function recordCheckoutCompletion( const db = dependencies.db ?? cloudDb(); const user = await loadOptionalStackUser(stackUserId, dependencies.stackApp); - if (!user || isAccountDeletionInProgress(user)) { + if (await hasCheckoutBlockingAccountDeletionTombstone(stackUserId, db) || (user && isAccountDeletionInProgress(user))) { await deleteCheckoutStripeResourcesForAccountDeletion(subscription, customerId, dependencies); return { skipped: "account_deletion_in_progress", @@ -134,6 +139,7 @@ export async function recordCheckoutCompletion( subscriptionId: subscription.id, }; } + if (!user) throw new Error(`Stack user not found for checkout completion: ${stackUserId}`); const email = checkoutEmail(input.session, input.customer); await upsertStripeCustomer(db, { @@ -281,6 +287,18 @@ function isAccountDeletionInProgress(user: StackBillingUser): boolean { ); } +async function hasCheckoutBlockingAccountDeletionTombstone( + stackUserId: string, + db: BillingDb, +): Promise { + const [row] = await db + .select({ status: accountDeletionTombstones.status }) + .from(accountDeletionTombstones) + .where(eq(accountDeletionTombstones.userIdHash, accountDeletionUserHash(stackUserId))) + .limit(1); + return row ? row.status === "completed" || isBlockingAccountDeletionStatus(row.status) : false; +} + export async function latestStripeSubscriptionForSession( session: Stripe.Checkout.Session, db: BillingDb = cloudDb(), diff --git a/web/services/vms/repository.ts b/web/services/vms/repository.ts index eb73418d0301..26c9ee705f6b 100644 --- a/web/services/vms/repository.ts +++ b/web/services/vms/repository.ts @@ -4,6 +4,7 @@ import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import { cloudDb } from "../../db/client"; import { + accountDeletionTombstones, cloudVmBaseEvents, cloudVmBaseGenerations, cloudVmBases, @@ -13,8 +14,19 @@ import { cloudVms, cloudVmUsageEvents, } from "../../db/schema"; +import { + accountDeletionAdvisoryLockKey, + accountDeletionUserHash, + isBlockingAccountDeletionStatus, +} from "../account/deletionLock"; import type { ProviderId } from "./drivers"; -import { VmCreateInProgressError, VmDatabaseError, VmLimitExceededError, isVmLimitExceededError } from "./errors"; +import { + VmCreateDisabledError, + VmCreateInProgressError, + VmDatabaseError, + VmLimitExceededError, + isVmLimitExceededError, +} from "./errors"; export type CloudVmRow = typeof cloudVms.$inferSelect; export type CloudVmBaseRow = typeof cloudVmBases.$inferSelect; @@ -239,6 +251,29 @@ function dbEffect( }); } +type CloudDbTransaction = Parameters["transaction"]>[0]>[0]; + +async function assertAccountVmCreateAllowed( + tx: CloudDbTransaction, + input: { readonly userId: string; readonly provider: ProviderId }, +): Promise { + await tx.execute(sql`select pg_advisory_xact_lock(hashtextextended(${accountDeletionAdvisoryLockKey(input.userId)}, 0))`); + const userIdHash = accountDeletionUserHash(input.userId); + const [deletion] = await tx + .select({ + userIdHash: accountDeletionTombstones.userIdHash, + status: accountDeletionTombstones.status, + }) + .from(accountDeletionTombstones) + .where(eq(accountDeletionTombstones.userIdHash, userIdHash)) + .limit(1); + if (deletion?.userIdHash !== userIdHash || !isBlockingAccountDeletionStatus(deletion.status)) return; + throw new VmCreateDisabledError({ + provider: input.provider, + reason: "Account deletion is in progress.", + }); +} + function pgErrorCode(cause: unknown): string | null { if (!cause || typeof cause !== "object") return null; const code = (cause as { code?: unknown }).code; @@ -405,6 +440,10 @@ export const VmRepositoryLive = Layer.succeed(VmRepository, { const db = cloudDb(); try { return await db.transaction(async (tx) => { + await assertAccountVmCreateAllowed(tx, { + userId: input.userId, + provider: input.provider, + }); if (idempotencyKey) { const [existing] = await tx .select() diff --git a/web/tests/account-route.test.ts b/web/tests/account-route.test.ts index 8a6a7e7acdb6..8ba5768dd9e0 100644 --- a/web/tests/account-route.test.ts +++ b/web/tests/account-route.test.ts @@ -1,6 +1,7 @@ import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, mock, test } from "bun:test"; import { + accountDeletionTombstones, cloudVmBaseGenerations, cloudVmBases, cloudVmBillingGrants, @@ -84,12 +85,21 @@ const deleteRows = mock((table: unknown) => { }); const updateRows = mock((table: unknown) => ({ set: (values: unknown) => { - updatedRows.push({ table, values }); + if (table !== accountDeletionTombstones) { + updatedRows.push({ table, values }); + } return { where: async () => {}, }; }, })); +const insertRows = mock((table: unknown) => ({ + values: (values: unknown) => ({ + onConflictDoUpdate: async () => { + routeEvents.push("tombstone-upsert"); + }, + }), +})); const listUserVms = mock((...args: unknown[]) => { const [userId, billingTeamId] = args as [string, string | null | undefined]; return { kind: "listUserVms" as const, userId, billingTeamId }; @@ -216,6 +226,9 @@ type MockTransaction = { }; readonly execute: (query: unknown) => Promise; readonly delete: (table: unknown) => { readonly where: (condition: unknown) => Promise }; + readonly insert: (table: unknown) => { + readonly values: (values: unknown) => { readonly onConflictDoUpdate: () => Promise }; + }; readonly update: (table: unknown) => { readonly set: (values: unknown) => { readonly where: (condition: unknown) => Promise }; }; @@ -231,6 +244,7 @@ const mockTransaction: MockTransaction = { select: transactionSelect, execute: transactionExecute, delete: deleteRows, + insert: insertRows, update: updateRows, }; @@ -262,6 +276,7 @@ const mockDb = { }), })), delete: deleteRows, + update: updateRows, transaction, }; @@ -376,6 +391,7 @@ beforeEach(() => { transactionSelect.mockClear(); transactionExecute.mockClear(); deleteRows.mockClear(); + insertRows.mockClear(); updateRows.mockClear(); mockDb.select.mockClear(); listUserVms.mockClear(); @@ -456,7 +472,7 @@ describe("account deletion route", () => { teamIds: ["account-user-1"], providerVmId: "personal-vm-2", }); - expect(transaction).toHaveBeenCalledTimes(2); + expect(transaction).toHaveBeenCalledTimes(3); expect(deletedTableCount).toBeGreaterThan(10); expect(deletedTables).toContain(cloudVmBillingGrants); expect(deletedTables).toContain(devices); @@ -496,6 +512,9 @@ describe("account deletion route", () => { expect(getUser).toHaveBeenCalledTimes(1); expect(deleteStackUser).toHaveBeenCalledTimes(1); expect(routeEvents).toEqual([ + "transaction", + "transaction-lock", + "tombstone-upsert", "metadata-update", "stripe-cancel", "stripe-delete-customer", @@ -544,7 +563,7 @@ describe("account deletion route", () => { providerVmId: "personal-team-vm", }); expect(revokeTenant).toHaveBeenCalledWith("tenant-team-personal"); - expect(transactionExecute).toHaveBeenCalledTimes(4); + expect(transactionExecute).toHaveBeenCalledTimes(5); }); test("does not treat a selected shared Stack team as account-owned data", async () => { @@ -564,7 +583,7 @@ describe("account deletion route", () => { teamIds: ["account-user-1", "team-shared"], providerVmId: "shared-team-vm", }); - expect(transactionExecute).toHaveBeenCalledTimes(2); + expect(transactionExecute).toHaveBeenCalledTimes(3); }); test("revokes the personal Subrouter tenant before deleting local rows", async () => { @@ -584,7 +603,7 @@ describe("account deletion route", () => { expect(revokeTenant).toHaveBeenCalledWith("tenant-personal"); expect(deletedTables).toContain(subrouterTenants); expect(routeEvents.indexOf("subrouter-revoke:tenant-personal")).toBeLessThan( - routeEvents.indexOf("transaction"), + routeEvents.lastIndexOf("transaction"), ); }); @@ -605,7 +624,7 @@ describe("account deletion route", () => { expect(response.status).toBe(200); expect(revokeUserIdentityLeasesForAccountDeletion).toHaveBeenCalledWith("account-user-1"); expect(routeEvents.indexOf("revoke-identities")).toBeGreaterThan(-1); - expect(routeEvents.indexOf("revoke-identities")).toBeLessThan(routeEvents.indexOf("transaction")); + expect(routeEvents.indexOf("revoke-identities")).toBeLessThan(routeEvents.lastIndexOf("transaction")); expect(deletedTables).toContain(cloudVmLeases); }); @@ -618,7 +637,7 @@ describe("account deletion route", () => { expect(response.status).toBe(500); expect(await response.json()).toEqual({ error: "account_delete_failed" }); expect(deletedVaultObjects).toEqual([]); - expect(transaction).not.toHaveBeenCalled(); + expect(transaction).toHaveBeenCalledTimes(1); expect(deleteStackUser).not.toHaveBeenCalled(); expect(updateStackUser).toHaveBeenNthCalledWith(1, { clientReadOnlyMetadata: { cmuxAccountDeleting: true }, @@ -647,7 +666,7 @@ describe("account deletion route", () => { destroyedVms: 0, }); expect(revokeUserIdentityLeasesForAccountDeletion).toHaveBeenCalledWith("account-user-1"); - expect(transaction).not.toHaveBeenCalled(); + expect(transaction).toHaveBeenCalledTimes(1); expect(deleteStackUser).not.toHaveBeenCalled(); expect(updateStackUser).toHaveBeenNthCalledWith(1, { clientReadOnlyMetadata: { cmuxAccountDeleting: true }, @@ -667,7 +686,7 @@ describe("account deletion route", () => { destroyedVms: 2, }); expect(revokeUserIdentityLeasesForAccountDeletion).toHaveBeenCalledWith("account-user-1"); - expect(transaction).not.toHaveBeenCalled(); + expect(transaction).toHaveBeenCalledTimes(1); expect(deleteStackUser).not.toHaveBeenCalled(); expect(deletedTables).not.toContain(cloudVmLeases); }); @@ -696,7 +715,7 @@ describe("account deletion route", () => { }); expect(revokeTenant).toHaveBeenCalledWith("tenant-personal"); expect(deletedTables).toContain(subrouterTenants); - expect(transaction).not.toHaveBeenCalled(); + expect(transaction).toHaveBeenCalledTimes(1); expect(deleteStackUser).not.toHaveBeenCalled(); expect(updateStackUser).toHaveBeenNthCalledWith(1, { clientReadOnlyMetadata: { cmuxAccountDeleting: true }, @@ -727,7 +746,7 @@ describe("account deletion route", () => { }); expect(revokeTenant).toHaveBeenCalledWith("tenant-personal"); expect(deletedTables).not.toContain(subrouterTenants); - expect(transaction).not.toHaveBeenCalled(); + expect(transaction).toHaveBeenCalledTimes(1); expect(deleteStackUser).not.toHaveBeenCalled(); expect(updateStackUser).toHaveBeenNthCalledWith(1, { clientReadOnlyMetadata: { cmuxAccountDeleting: true }, @@ -754,7 +773,7 @@ describe("account deletion route", () => { expect(await response.json()).toEqual({ error: "account_delete_failed" }); expect(revokeTenant).not.toHaveBeenCalled(); expect(deletedTables).not.toContain(subrouterTenants); - expect(transaction).not.toHaveBeenCalled(); + expect(transaction).toHaveBeenCalledTimes(1); expect(deleteStackUser).not.toHaveBeenCalled(); expect(updateStackUser).toHaveBeenNthCalledWith(1, { clientReadOnlyMetadata: { cmuxAccountDeleting: true }, @@ -779,8 +798,8 @@ describe("account deletion route", () => { retryable: true, destroyedVms: 2, }); - expect(transaction).toHaveBeenCalledTimes(1); - expect(transactionExecute).toHaveBeenCalledTimes(1); + expect(transaction).toHaveBeenCalledTimes(2); + expect(transactionExecute).toHaveBeenCalledTimes(2); expect(transactionSelect).toHaveBeenCalledTimes(1); expect(deletedTableCount).toBe(0); expect(deleteStackUser).not.toHaveBeenCalled(); @@ -872,7 +891,7 @@ describe("account deletion route", () => { retryable: true, destroyedVms: 2, }); - expect(transaction).not.toHaveBeenCalled(); + expect(transaction).toHaveBeenCalledTimes(1); expect(deleteStackUser).not.toHaveBeenCalled(); expect(updateStackUser).toHaveBeenNthCalledWith(1, { clientReadOnlyMetadata: { cmuxAccountDeleting: true }, @@ -901,7 +920,7 @@ describe("account deletion route", () => { }); expect(cancelledStripeSubscriptions).toEqual(["sub_user_active"]); expect(deletedStripeCustomers).toEqual(["cus_user"]); - expect(transaction).not.toHaveBeenCalled(); + expect(transaction).toHaveBeenCalledTimes(1); expect(deleteStackUser).not.toHaveBeenCalled(); expect(updateStackUser).toHaveBeenNthCalledWith(1, { clientReadOnlyMetadata: { cmuxAccountDeleting: true }, @@ -927,7 +946,7 @@ describe("account deletion route", () => { expect(cancelledStripeSubscriptions).toEqual(["sub_user_active"]); expect(deletedStripeCustomers).toEqual(["cus_user"]); expect(listUserVms).not.toHaveBeenCalled(); - expect(transaction).not.toHaveBeenCalled(); + expect(transaction).toHaveBeenCalledTimes(1); expect(deleteStackUser).not.toHaveBeenCalled(); expect(updateStackUser).toHaveBeenNthCalledWith(1, { clientReadOnlyMetadata: { cmuxAccountDeleting: true }, @@ -952,7 +971,7 @@ describe("account deletion route", () => { }); expect(cancelledStripeSubscriptions).toEqual(["sub_user_active"]); expect(listUserVms).not.toHaveBeenCalled(); - expect(transaction).not.toHaveBeenCalled(); + expect(transaction).toHaveBeenCalledTimes(1); expect(deleteStackUser).not.toHaveBeenCalled(); expect(updateStackUser).toHaveBeenNthCalledWith(1, { clientReadOnlyMetadata: { cmuxAccountDeleting: true }, @@ -982,7 +1001,7 @@ describe("account deletion route", () => { teamIds: ["account-user-1"], providerVmId: "personal-vm-2", }); - expect(transaction).not.toHaveBeenCalled(); + expect(transaction).toHaveBeenCalledTimes(1); expect(deleteStackUser).not.toHaveBeenCalled(); expect(updateStackUser).toHaveBeenNthCalledWith(1, { clientReadOnlyMetadata: { cmuxAccountDeleting: true }, @@ -1020,7 +1039,7 @@ describe("account deletion route", () => { teamIds: ["account-user-1"], providerVmId: "personal-vm-2", }); - expect(transaction).not.toHaveBeenCalled(); + expect(transaction).toHaveBeenCalledTimes(1); expect(deleteStackUser).not.toHaveBeenCalled(); expect(updateStackUser).toHaveBeenNthCalledWith(1, { clientReadOnlyMetadata: { cmuxAccountDeleting: true }, @@ -1048,7 +1067,7 @@ describe("account deletion route", () => { expect(response.status).toBe(500); expect(await response.json()).toEqual({ error: "account_delete_failed" }); expect(cancelSubscription).not.toHaveBeenCalled(); - expect(transaction).not.toHaveBeenCalled(); + expect(transaction).toHaveBeenCalledTimes(1); expect(deleteStackUser).not.toHaveBeenCalled(); expect(updateStackUser).toHaveBeenNthCalledWith(1, { clientReadOnlyMetadata: { cmuxAccountDeleting: true }, @@ -1071,7 +1090,7 @@ describe("account deletion route", () => { retryable: true, destroyedVms: 2, }); - expect(transaction).toHaveBeenCalledTimes(1); + expect(transaction).toHaveBeenCalledTimes(2); expect(deletedTableCount).toBeGreaterThan(10); expect(updateStackUser).toHaveBeenCalledWith({ clientReadOnlyMetadata: { cmuxAccountDeleting: true }, @@ -1079,6 +1098,9 @@ describe("account deletion route", () => { expect(updateStackUser).toHaveBeenCalledTimes(1); expect(deleteStackUser).toHaveBeenCalledTimes(1); expect(routeEvents).toEqual([ + "transaction", + "transaction-lock", + "tombstone-upsert", "metadata-update", "list-vms", "destroy-vm", @@ -1119,7 +1141,7 @@ describe("account deletion route", () => { destroyedVms: 2, }); expect(deleteStackUser).toHaveBeenCalledTimes(1); - expect(transaction).toHaveBeenCalledTimes(1); + expect(transaction).toHaveBeenCalledTimes(2); expect(consoleError).toHaveBeenCalledWith( "account.delete.post_stack_cleanup_failed", "Error: post-delete vault unavailable", @@ -1144,7 +1166,7 @@ describe("account deletion route", () => { expect(await response.json()).toEqual({ ok: true, destroyedVms: 2 }); expect(cancelledStripeSubscriptions).toEqual(["sub_user_active"]); expect(deletedStripeCustomers).toEqual(["cus_user"]); - expect(transaction).toHaveBeenCalledTimes(2); + expect(transaction).toHaveBeenCalledTimes(3); expect(deleteStackUser).toHaveBeenCalledTimes(1); }); diff --git a/web/tests/billing-purchase.test.ts b/web/tests/billing-purchase.test.ts index c9304beecd29..18cc24f881c4 100644 --- a/web/tests/billing-purchase.test.ts +++ b/web/tests/billing-purchase.test.ts @@ -1,6 +1,11 @@ import { beforeEach, describe, expect, mock, test } from "bun:test"; -import { billingEmailClaims, stripeCustomers, stripeSubscriptions } from "../db/schema"; +import { + accountDeletionTombstones, + billingEmailClaims, + stripeCustomers, + stripeSubscriptions, +} from "../db/schema"; process.env.RESEND_API_KEY ??= "test-resend-key"; process.env.CMUX_FEEDBACK_FROM_EMAIL ??= "feedback@example.com"; @@ -18,6 +23,7 @@ const updates: Array<{ table: unknown; values: Record }> = []; const upsertUpdates: Array<{ table: unknown; values: Record }> = []; const insertErrorsByTable = new Map(); let selectResults: unknown[][] = []; +let tombstoneSelectResults: unknown[][] = []; function fakeDb() { return { @@ -36,8 +42,10 @@ function fakeDb() { }, }), select: () => ({ - from: () => ({ - where: () => selectableResult(), + from: (table: unknown) => ({ + where: () => table === accountDeletionTombstones + ? tombstoneSelectableResult() + : selectableResult(), }), }), update: (table: unknown) => ({ @@ -58,6 +66,13 @@ function selectableResult() { }; } +function tombstoneSelectableResult() { + return { + orderBy: () => tombstoneSelectableResult(), + limit: () => Promise.resolve(tombstoneSelectResults.shift() ?? []), + }; +} + function checkoutInput(customerId = "cus_123") { return { session: { @@ -131,6 +146,7 @@ describe("recordCheckoutCompletion", () => { upsertUpdates.length = 0; insertErrorsByTable.clear(); selectResults = []; + tombstoneSelectResults = []; }); test("attaches Stripe email to a purchaser without a primary email", async () => { @@ -184,11 +200,12 @@ describe("recordCheckoutCompletion", () => { expect(update).not.toHaveBeenCalled(); }); - test("does not recreate checkout billing rows after the Stack user is gone", async () => { + test("does not recreate checkout billing rows after tombstoned Stack user is gone", async () => { const cancelSubscription = mock(async () => { throw { statusCode: 404, message: "No such subscription" }; }); const deleteCustomer = mock(async () => undefined); + tombstoneSelectResults = [[{ status: "completed" }]]; await expect( recordCheckoutCompletion(checkoutInput() as never, { @@ -211,6 +228,27 @@ describe("recordCheckoutCompletion", () => { expect(updates).toHaveLength(0); }); + test("fails closed when checkout metadata points at a missing Stack user without a deletion tombstone", async () => { + const cancelSubscription = mock(async () => undefined); + const deleteCustomer = mock(async () => undefined); + + await expect( + recordCheckoutCompletion(checkoutInput() as never, { + db: fakeDb() as never, + stackApp: { getUser: async () => null } as never, + stripeClient: () => ({ + subscriptions: { cancel: cancelSubscription }, + customers: { del: deleteCustomer }, + }) as never, + }), + ).rejects.toThrow("Stack user not found for checkout completion: user_123"); + + expect(cancelSubscription).not.toHaveBeenCalled(); + expect(deleteCustomer).not.toHaveBeenCalled(); + expect(inserts).toHaveLength(0); + expect(updates).toHaveLength(0); + }); + test("records an email claim instead of attaching an email owned by a different Stack user", async () => { const update = mock(async () => undefined); const listUsers = mock(async () => [ From f71a8db2d7a40be76645798c49f54969790752cf Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Thu, 9 Jul 2026 02:58:03 -0700 Subject: [PATCH 48/89] Serialize checkout completion with account deletion --- web/app/api/account/route.ts | 8 +- web/services/billing/purchase.ts | 137 +++++++++++++++++++---------- web/tests/account-route.test.ts | 17 +++- web/tests/billing-purchase.test.ts | 52 ++++++++++- 4 files changed, 164 insertions(+), 50 deletions(-) diff --git a/web/app/api/account/route.ts b/web/app/api/account/route.ts index c207eef2b6e9..056853b83bc2 100644 --- a/web/app/api/account/route.ts +++ b/web/app/api/account/route.ts @@ -229,7 +229,13 @@ async function markAccountDeletionTombstoneCompleted(userId: string): Promise; +type BillingDbClient = Pick; +type BillingDbTransaction = BillingDbClient & { + execute(query: unknown): Promise; +}; type StripeBillingClient = Pick, "customers" | "subscriptions">; type StripeSubscriptionValuesInput = { @@ -98,14 +103,15 @@ export type CheckoutCompletionInput = { customer?: Stripe.Customer | Stripe.DeletedCustomer | null; }; +type CheckoutCompletionResult = + | { scope: "user"; stackUserId: string; subscriptionId: string } + | { scope: "team"; stackTeamId: string; subscriptionId: string } + | { skipped: "account_deletion_in_progress"; stackUserId: string; subscriptionId: string }; + export async function recordCheckoutCompletion( input: CheckoutCompletionInput, dependencies: BillingPurchaseDependencies = {}, -): Promise< - | { scope: "user"; stackUserId: string; subscriptionId: string } - | { scope: "team"; stackTeamId: string; subscriptionId: string } - | { skipped: "account_deletion_in_progress"; stackUserId: string; subscriptionId: string } -> { +): Promise { const subscription = input.subscription ?? expandedSubscription(input.session); if (!subscription) { throw new Error("Stripe checkout session is missing an expanded subscription"); @@ -130,42 +136,65 @@ export async function recordCheckoutCompletion( } const db = dependencies.db ?? cloudDb(); - const user = await loadOptionalStackUser(stackUserId, dependencies.stackApp); - if (await hasCheckoutBlockingAccountDeletionTombstone(stackUserId, db) || (user && isAccountDeletionInProgress(user))) { - await deleteCheckoutStripeResourcesForAccountDeletion(subscription, customerId, dependencies); - return { - skipped: "account_deletion_in_progress", - stackUserId, - subscriptionId: subscription.id, - }; - } - if (!user) throw new Error(`Stack user not found for checkout completion: ${stackUserId}`); - - const email = checkoutEmail(input.session, input.customer); - await upsertStripeCustomer(db, { - customerId, - stackUserId, - email, - }); - await upsertStripeSubscription(db, { - subscription, - customerId, + const lockedResult = await withAccountDeletionUserLock( + db, stackUserId, - scope: "user", - }); + async (tx): Promise<{ + result: CheckoutCompletionResult; + deleteCheckoutStripeResources: boolean; + }> => { + const user = await loadOptionalStackUser(stackUserId, dependencies.stackApp); + if ( + await hasCheckoutBlockingAccountDeletionTombstone(stackUserId, tx) || + (user && isAccountDeletionInProgress(user)) + ) { + return { + deleteCheckoutStripeResources: true, + result: { + skipped: "account_deletion_in_progress", + stackUserId, + subscriptionId: subscription.id, + }, + }; + } + if (!user) throw new Error(`Stack user not found for checkout completion: ${stackUserId}`); + + const email = checkoutEmail(input.session, input.customer); + await upsertStripeCustomer(tx, { + customerId, + stackUserId, + email, + }); + await upsertStripeSubscription(tx, { + subscription, + customerId, + stackUserId, + scope: "user", + }); - if (email) { - await attachPurchaseEmailOrRecordClaim(db, { - user, - email, - stripeCustomerId: customerId, - stackUserId, - stackApp: dependencies.stackApp ?? stackServerApp, - }); + if (email) { + await attachPurchaseEmailOrRecordClaim(tx, { + user, + email, + stripeCustomerId: customerId, + stackUserId, + stackApp: dependencies.stackApp ?? stackServerApp, + }); + } + await syncProPlanMetadata(user, true); + + return { + deleteCheckoutStripeResources: false, + result: { scope: "user", stackUserId, subscriptionId: subscription.id }, + }; + }, + ); + + if (lockedResult.deleteCheckoutStripeResources) { + await deleteCheckoutStripeResourcesForAccountDeletion(subscription, customerId, dependencies); } - await syncProPlanMetadata(user, true); - return { scope: "user", stackUserId, subscriptionId: subscription.id }; + return lockedResult.result; } async function deleteCheckoutStripeResourcesForAccountDeletion( @@ -289,7 +318,7 @@ function isAccountDeletionInProgress(user: StackBillingUser): boolean { async function hasCheckoutBlockingAccountDeletionTombstone( stackUserId: string, - db: BillingDb, + db: BillingDbClient, ): Promise { const [row] = await db .select({ status: accountDeletionTombstones.status }) @@ -299,6 +328,20 @@ async function hasCheckoutBlockingAccountDeletionTombstone( return row ? row.status === "completed" || isBlockingAccountDeletionStatus(row.status) : false; } +async function withAccountDeletionUserLock( + db: BillingDb, + stackUserId: string, + callback: (tx: BillingDbClient) => Promise, +): Promise { + return db.transaction(async (tx) => { + const accountTx = tx as BillingDbTransaction; + await accountTx.execute( + sql`select pg_advisory_xact_lock(hashtextextended(${accountDeletionAdvisoryLockKey(stackUserId)}, 0))`, + ); + return callback(accountTx); + }); +} + export async function latestStripeSubscriptionForSession( session: Stripe.Checkout.Session, db: BillingDb = cloudDb(), @@ -446,7 +489,7 @@ async function recordTeamCheckoutCompletion(input: { } async function upsertStripeCustomer( - db: BillingDb, + db: BillingDbClient, input: { customerId: string; stackUserId: string; email: string | null }, ): Promise { const [existingForStackUser] = await db @@ -515,7 +558,7 @@ async function upsertStripeCustomer( } async function upsertTeamStripeCustomer( - db: BillingDb, + db: BillingDbClient, input: { customerId: string; stackUserId: string; stackTeamId: string }, ): Promise { const [existingForStackTeam] = await db @@ -567,7 +610,7 @@ async function upsertTeamStripeCustomer( } async function upsertStripeSubscription( - db: BillingDb, + db: BillingDbClient, input: StripeSubscriptionValuesInput, ): Promise { const values = stripeSubscriptionValues(input); @@ -585,7 +628,7 @@ async function upsertStripeSubscription( } async function updateExistingUserStripeSubscription( - db: BillingDb, + db: BillingDbClient, input: { subscription: Stripe.Subscription; customerId: string; @@ -649,7 +692,7 @@ function mutableStripeSubscriptionValues(input: StripeSubscriptionValuesInput) { } async function userStripeSubscriptionExists( - db: BillingDb, + db: BillingDbClient, input: { subscriptionId: string; stackUserId: string }, ): Promise { const [row] = await db @@ -668,7 +711,7 @@ async function userStripeSubscriptionExists( } async function attachPurchaseEmailOrRecordClaim( - db: BillingDb, + db: BillingDbClient, input: { user: StackBillingUser; email: string; @@ -720,7 +763,7 @@ async function findUserIdByEmail( } async function recordBillingEmailClaim( - db: BillingDb, + db: BillingDbClient, input: { email: string; stripeCustomerId: string; @@ -749,7 +792,7 @@ async function recordBillingEmailClaim( } async function stackUserIdForStripeCustomer( - db: BillingDb, + db: BillingDbClient, customerId: string, ): Promise { const rows = await db @@ -762,7 +805,7 @@ async function stackUserIdForStripeCustomer( } async function stackUserIdForTeamStripeCustomer( - db: BillingDb, + db: BillingDbClient, input: { stackTeamId: string; customerId: string }, ): Promise { const byTeam = await db diff --git a/web/tests/account-route.test.ts b/web/tests/account-route.test.ts index 8ba5768dd9e0..cc45529f3168 100644 --- a/web/tests/account-route.test.ts +++ b/web/tests/account-route.test.ts @@ -85,7 +85,9 @@ const deleteRows = mock((table: unknown) => { }); const updateRows = mock((table: unknown) => ({ set: (values: unknown) => { - if (table !== accountDeletionTombstones) { + if (table === accountDeletionTombstones) { + tombstoneUpdates.push(values); + } else { updatedRows.push({ table, values }); } return { @@ -177,6 +179,7 @@ let deletedTableCount = 0; let deletedTables: unknown[] = []; let deletedWhere: Array<{ readonly table: unknown; readonly condition: unknown }> = []; let updatedRows: Array<{ readonly table: unknown; readonly values: unknown }> = []; +let tombstoneUpdates: unknown[] = []; let routeEvents: string[] = []; let stackDeleteError: unknown = null; let stackUserIds: Array = []; @@ -408,6 +411,7 @@ beforeEach(() => { deletedTables = []; deletedWhere = []; updatedRows = []; + tombstoneUpdates = []; routeEvents = []; stackDeleteError = null; stackUserIds = []; @@ -511,6 +515,17 @@ describe("account deletion route", () => { }); expect(getUser).toHaveBeenCalledTimes(1); expect(deleteStackUser).toHaveBeenCalledTimes(1); + const completedTombstone = tombstoneUpdates.find((update) => + Boolean( + update && + typeof update === "object" && + (update as { readonly userId?: unknown }).userId === null && + (update as { readonly status?: unknown }).status === "completed" && + (update as { readonly errorMessage?: unknown }).errorMessage === null, + ) + ); + expect(completedTombstone).toBeTruthy(); + expect((completedTombstone as { readonly completedAt?: unknown }).completedAt).toBeInstanceOf(Date); expect(routeEvents).toEqual([ "transaction", "transaction-lock", diff --git a/web/tests/billing-purchase.test.ts b/web/tests/billing-purchase.test.ts index 18cc24f881c4..55e8ff090c13 100644 --- a/web/tests/billing-purchase.test.ts +++ b/web/tests/billing-purchase.test.ts @@ -26,7 +26,7 @@ let selectResults: unknown[][] = []; let tombstoneSelectResults: unknown[][] = []; function fakeDb() { - return { + const client = { insert: (table: unknown) => ({ values: (values: Record) => { inserts.push({ table, values }); @@ -57,6 +57,13 @@ function fakeDb() { }), }), }; + return { + ...client, + execute: async (_query?: unknown) => undefined, + transaction: async ( + callback: (tx: typeof client & { execute: (_query?: unknown) => Promise }) => Promise, + ) => await callback({ ...client, execute: async (_query?: unknown) => undefined }), + }; } function selectableResult() { @@ -249,6 +256,49 @@ describe("recordCheckoutCompletion", () => { expect(updates).toHaveLength(0); }); + test("syncs checkout metadata while holding the account deletion lock", async () => { + let transactionOpen = false; + let lockAcquired = false; + const baseDb = fakeDb(); + const db = { + ...baseDb, + transaction: async ( + callback: (tx: typeof baseDb & { execute: (_query?: unknown) => Promise }) => Promise, + ) => { + transactionOpen = true; + try { + return await callback({ + ...baseDb, + execute: async (_query?: unknown) => { + lockAcquired = true; + }, + }); + } finally { + transactionOpen = false; + } + }, + }; + const update = mock(async () => { + expect(transactionOpen).toBe(true); + expect(lockAcquired).toBe(true); + }); + const user = { + id: "user_123", + primaryEmail: "buyer@example.com", + clientReadOnlyMetadata: {}, + update, + }; + + await recordCheckoutCompletion(checkoutInput() as never, { + db: db as never, + stackApp: { getUser: async () => user } as never, + }); + + expect(update).toHaveBeenCalledWith({ + clientReadOnlyMetadata: { cmuxPlan: "pro" }, + }); + }); + test("records an email claim instead of attaching an email owned by a different Stack user", async () => { const update = mock(async () => undefined); const listUsers = mock(async () => [ From 9e6fa414a32e2b8f8c346517b31449226a77271a Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Thu, 9 Jul 2026 03:10:17 -0700 Subject: [PATCH 49/89] Cancel personal team billing during deletion --- web/app/api/account/route.ts | 21 +++++++++++++++++---- web/tests/account-route.test.ts | 6 ++++-- 2 files changed, 21 insertions(+), 6 deletions(-) diff --git a/web/app/api/account/route.ts b/web/app/api/account/route.ts index 056853b83bc2..9cbc9cd88954 100644 --- a/web/app/api/account/route.ts +++ b/web/app/api/account/route.ts @@ -92,7 +92,7 @@ export async function DELETE(request: Request): Promise { accountDeletionTombstoneStarted = true; await markAccountDeletingAndClearBillingEntitlements(stackUser); stackMetadataMarked = true; - await resolveUserBillingForAccountDeletion(userId, { + await resolveUserBillingForAccountDeletion(userId, accountScope.teamIds, { beforeExternalRequest: () => { restoreBillingEntitlementsOnFailure = false; destructiveCleanupStarted = true; @@ -404,16 +404,26 @@ async function finishPostStackAccountCleanup(userId: string, accountTeamIds: rea async function resolveUserBillingForAccountDeletion( userId: string, + accountTeamIds: readonly string[], options: { readonly beforeExternalRequest?: () => void } = {}, ): Promise { const db = cloudDb(); + const deletionTeamIds = uniqueNonEmptyStrings([userId, ...accountTeamIds]); const activeSubscriptions = await db .select({ id: stripeSubscriptions.id }) .from(stripeSubscriptions) .where(and( eq(stripeSubscriptions.stackUserId, userId), - eq(stripeSubscriptions.scope, "user"), - isNull(stripeSubscriptions.stackTeamId), + or( + and( + eq(stripeSubscriptions.scope, "user"), + isNull(stripeSubscriptions.stackTeamId), + ), + and( + eq(stripeSubscriptions.scope, "team"), + inArray(stripeSubscriptions.stackTeamId, deletionTeamIds), + ), + ), inArray(stripeSubscriptions.status, ACTIVE_STRIPE_PRO_STATUSES), )); const customers = await db @@ -421,7 +431,10 @@ async function resolveUserBillingForAccountDeletion( .from(stripeCustomers) .where(and( eq(stripeCustomers.stackUserId, userId), - isNull(stripeCustomers.stackTeamId), + or( + isNull(stripeCustomers.stackTeamId), + inArray(stripeCustomers.stackTeamId, deletionTeamIds), + ), )); if (activeSubscriptions.length === 0 && customers.length === 0) return; diff --git a/web/tests/account-route.test.ts b/web/tests/account-route.test.ts index cc45529f3168..8d37d33e25b5 100644 --- a/web/tests/account-route.test.ts +++ b/web/tests/account-route.test.ts @@ -556,8 +556,8 @@ describe("account deletion route", () => { listedPersonalVmIdsByBillingTeam = { "team-personal": ["personal-team-vm"] }; stackUserTeams = [stackTeam("team-personal", ["account-user-1"])]; selectResults = [ - [], - [], + [{ id: "sub_user_active" }, { id: "sub_team_active" }], + [{ id: "cus_user" }, { id: "cus_team" }], [], [], [], @@ -577,6 +577,8 @@ describe("account deletion route", () => { teamIds: ["account-user-1", "team-personal"], providerVmId: "personal-team-vm", }); + expect(cancelledStripeSubscriptions).toEqual(["sub_user_active", "sub_team_active"]); + expect(deletedStripeCustomers).toEqual(["cus_user", "cus_team"]); expect(revokeTenant).toHaveBeenCalledWith("tenant-team-personal"); expect(transactionExecute).toHaveBeenCalledTimes(5); }); From c3a49fc5c9090821ef877c03a7f47a4c429078c6 Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Thu, 9 Jul 2026 03:17:43 -0700 Subject: [PATCH 50/89] Anonymize retained shared team VMs --- web/app/api/account/route.ts | 19 ++++++++++++++++--- web/tests/account-route.test.ts | 21 +++++++++++++++++++++ 2 files changed, 37 insertions(+), 3 deletions(-) diff --git a/web/app/api/account/route.ts b/web/app/api/account/route.ts index 9cbc9cd88954..a2935c3adb23 100644 --- a/web/app/api/account/route.ts +++ b/web/app/api/account/route.ts @@ -551,13 +551,20 @@ async function deleteCmuxOwnedAccountRows(userId: string, accountTeamIds: readon const userVmRows = await tx .select({ id: cloudVms.id, + billingTeamId: cloudVms.billingTeamId, providerVmId: cloudVms.providerVmId, status: cloudVms.status, }) .from(cloudVms) .where(eq(cloudVms.userId, userId)) .for("update"); - const unsafePersonalVmRows = userVmRows.filter((vm) => { + const personalVmRows = userVmRows.filter((vm) => + !vm.billingTeamId || deletionTeamIds.includes(vm.billingTeamId) + ); + const sharedTeamVmRows = userVmRows.filter((vm) => + vm.billingTeamId && !deletionTeamIds.includes(vm.billingTeamId) + ); + const unsafePersonalVmRows = personalVmRows.filter((vm) => { if (vm.status === "destroyed") return false; if (vm.status === "failed" && !vm.providerVmId) return false; return true; @@ -609,8 +616,14 @@ async function deleteCmuxOwnedAccountRows(userId: string, accountTeamIds: readon await tx.delete(cloudVmUsageEvents).where(eq(cloudVmUsageEvents.userId, userId)); await tx.delete(cloudVmLeases).where(eq(cloudVmLeases.userId, userId)); await tx.delete(cloudVmSessions).where(eq(cloudVmSessions.userId, userId)); - if (userVmRows.length > 0) { - await tx.delete(cloudVms).where(inArray(cloudVms.id, userVmRows.map((vm) => vm.id))); + if (personalVmRows.length > 0) { + await tx.delete(cloudVms).where(inArray(cloudVms.id, personalVmRows.map((vm) => vm.id))); + } + if (sharedTeamVmRows.length > 0) { + await tx + .update(cloudVms) + .set({ userId: DELETED_ACCOUNT_ACTOR_ID, updatedAt: now }) + .where(inArray(cloudVms.id, sharedTeamVmRows.map((vm) => vm.id))); } await tx.delete(cloudVmBaseEvents).where(eq(cloudVmBaseEvents.userId, userId)); await tx.delete(cloudVmBases).where(and( diff --git a/web/tests/account-route.test.ts b/web/tests/account-route.test.ts index 8d37d33e25b5..db3e2a90d851 100644 --- a/web/tests/account-route.test.ts +++ b/web/tests/account-route.test.ts @@ -840,6 +840,27 @@ describe("account deletion route", () => { expect(deleteStackUser).toHaveBeenCalledTimes(1); }); + test("anonymizes retained shared-team VM rows without blocking deletion", async () => { + transactionSelectResults = [[{ + id: "00000000-0000-4000-8000-000000000766", + billingTeamId: "team-shared", + providerVmId: "provider-vm-shared", + status: "running", + }]]; + stackUserSelectedTeam = stackTeam("team-shared", ["account-user-1", "other-user"]); + + const response = await DELETE(accountDeletionRequest()); + + expect(response.status).toBe(200); + expect(listUserVms).not.toHaveBeenCalledWith("account-user-1", "team-shared"); + expect(deletedTables).not.toContain(cloudVms); + expect(updatedRows.map(({ table, values }) => ({ + table, + values: stripUpdatedAt(values), + }))).toContainEqual({ table: cloudVms, values: { userId: "deleted-account" } }); + expect(deleteStackUser).toHaveBeenCalledTimes(1); + }); + test("anonymizes shared team devices registered by the deleted user", async () => { const response = await DELETE(accountDeletionRequest()); From 51825c99b6801497744a3742246e83e64d708bf4 Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Thu, 9 Jul 2026 03:27:59 -0700 Subject: [PATCH 51/89] Guard team checkout during account deletion --- web/services/billing/purchase.ts | 107 ++++++++++++++++++++++------- web/tests/billing-purchase.test.ts | 47 ++++++++++++- 2 files changed, 128 insertions(+), 26 deletions(-) diff --git a/web/services/billing/purchase.ts b/web/services/billing/purchase.ts index 441c12101def..2f27a68052b0 100644 --- a/web/services/billing/purchase.ts +++ b/web/services/billing/purchase.ts @@ -126,6 +126,7 @@ export async function recordCheckoutCompletion( subscription, customerId, stackTeamId: teamScope.stackTeamId, + stackUserId: teamScope.stackUserId, dependencies, }); } @@ -458,34 +459,83 @@ async function recordTeamCheckoutCompletion(input: { subscription: Stripe.Subscription; customerId: string; stackTeamId: string; + stackUserId?: string | null; dependencies: BillingPurchaseDependencies; -}): Promise<{ scope: "team"; stackTeamId: string; subscriptionId: string }> { +}): Promise { const db = input.dependencies.db ?? cloudDb(); - const stackUserId = + const checkoutOwnerStackUserId = + input.stackUserId ?? (await stackUserIdForTeamStripeCustomer(db, { stackTeamId: input.stackTeamId, customerId: input.customerId, - })) ?? input.stackTeamId; - await upsertTeamStripeCustomer(db, { - customerId: input.customerId, - stackUserId, - stackTeamId: input.stackTeamId, - }); - await upsertStripeSubscription(db, { - subscription: input.subscription, - customerId: input.customerId, - stackUserId, - stackTeamId: input.stackTeamId, - scope: "team", + })); + const lockStackUserId = checkoutOwnerStackUserId ?? input.stackTeamId; + const lockedResult = await withAccountDeletionUserLock(db, lockStackUserId, async (tx) => { + const stackUserId = + input.stackUserId ?? + (await stackUserIdForTeamStripeCustomer(tx, { + stackTeamId: input.stackTeamId, + customerId: input.customerId, + })) ?? + checkoutOwnerStackUserId ?? + input.stackTeamId; + const ownerStackUserId = + stackUserId !== input.stackTeamId && stackUserId !== DELETED_ACCOUNT_ACTOR_ID + ? stackUserId + : null; + const owner = ownerStackUserId + ? await loadOptionalStackUser(ownerStackUserId, input.dependencies.stackApp) + : null; + if ( + stackUserId === DELETED_ACCOUNT_ACTOR_ID || + (await hasCheckoutBlockingAccountDeletionTombstone(stackUserId, tx)) || + (ownerStackUserId && !owner) || + (owner && isAccountDeletionInProgress(owner)) + ) { + return { + deleteCheckoutStripeResources: true, + result: { + skipped: "account_deletion_in_progress" as const, + stackUserId, + subscriptionId: input.subscription.id, + }, + }; + } + + await upsertTeamStripeCustomer(tx, { + customerId: input.customerId, + stackUserId, + stackTeamId: input.stackTeamId, + }); + await upsertStripeSubscription(tx, { + subscription: input.subscription, + customerId: input.customerId, + stackUserId, + stackTeamId: input.stackTeamId, + scope: "team", + }); + + const team = await loadStackTeam(input.stackTeamId, input.dependencies.stackApp); + await syncTeamPlanMetadata(team, true); + return { + deleteCheckoutStripeResources: false, + result: { + scope: "team" as const, + stackTeamId: input.stackTeamId, + subscriptionId: input.subscription.id, + }, + }; }); - const team = await loadStackTeam(input.stackTeamId, input.dependencies.stackApp); - await syncTeamPlanMetadata(team, true); - return { - scope: "team", - stackTeamId: input.stackTeamId, - subscriptionId: input.subscription.id, - }; + if (lockedResult.deleteCheckoutStripeResources) { + await deleteCheckoutStripeResourcesForAccountDeletion( + input.subscription, + input.customerId, + input.dependencies, + ); + } + + return lockedResult.result; } async function upsertStripeCustomer( @@ -836,13 +886,20 @@ function expandedSubscription( function teamScopeFromSession( session: Stripe.Checkout.Session, subscription: Stripe.Subscription, -): { stackTeamId: string } | null { +): { stackTeamId: string; stackUserId: string | null } | null { const metadata = session.metadata?.plan === TEAM_PLAN_ID ? session.metadata : subscription.metadata; const stackTeamId = metadata?.stackTeamId; + const metadataStackUserId = + nonEmptyString(session.metadata?.stackUserId) ?? + nonEmptyString(subscription.metadata?.stackUserId); + const clientReferenceStackUserId = + nonEmptyString(session.client_reference_id) !== stackTeamId + ? nonEmptyString(session.client_reference_id) + : null; return metadata?.plan === TEAM_PLAN_ID && typeof stackTeamId === "string" && stackTeamId - ? { stackTeamId } + ? { stackTeamId, stackUserId: metadataStackUserId ?? clientReferenceStackUserId } : null; } @@ -864,6 +921,10 @@ function stackUserIdFromSession( return session.client_reference_id ?? subscription.metadata?.stackUserId ?? null; } +function nonEmptyString(value: unknown): string | null { + return typeof value === "string" && value ? value : null; +} + function customerIdFromSession( session: Stripe.Checkout.Session, customer: Stripe.Customer | Stripe.DeletedCustomer | null | undefined, diff --git a/web/tests/billing-purchase.test.ts b/web/tests/billing-purchase.test.ts index 55e8ff090c13..708441ee8ba9 100644 --- a/web/tests/billing-purchase.test.ts +++ b/web/tests/billing-purchase.test.ts @@ -531,9 +531,12 @@ describe("recordCheckoutCompletion", () => { const result = await recordCheckoutCompletion(teamCheckoutInput() as never, { db: fakeDb() as never, stackApp: { - getUser: async () => { - throw new Error("should not load Stack user for Team checkout"); - }, + getUser: async () => ({ + id: "owner_123", + primaryEmail: "owner@example.com", + clientReadOnlyMetadata: {}, + update: mock(async () => undefined), + }), getTeam: async () => team, } as never, }); @@ -567,6 +570,44 @@ describe("recordCheckoutCompletion", () => { }); }); + test("blocks Team checkout completion while the billing owner is deleting their account", async () => { + const cancelSubscription = mock(async () => undefined); + const deleteCustomer = mock(async () => undefined); + const owner = { + id: "owner_123", + primaryEmail: "owner@example.com", + clientReadOnlyMetadata: { cmuxAccountDeleting: true }, + update: mock(async () => undefined), + }; + selectResults = [[{ stackUserId: "owner_123" }], []]; + + await expect( + recordCheckoutCompletion(teamCheckoutInput() as never, { + db: fakeDb() as never, + stackApp: { + getUser: async () => owner, + getTeam: async () => { + throw new Error("should not load Stack team for blocked Team checkout"); + }, + } as never, + stripeClient: () => ({ + subscriptions: { cancel: cancelSubscription }, + customers: { del: deleteCustomer }, + }) as never, + }), + ).resolves.toEqual({ + skipped: "account_deletion_in_progress", + stackUserId: "owner_123", + subscriptionId: "sub_team", + }); + + expect(cancelSubscription).toHaveBeenCalledWith("sub_team"); + expect(deleteCustomer).toHaveBeenCalledWith("cus_team"); + expect(inserts).toHaveLength(0); + expect(updates).toHaveLength(0); + expect(owner.update).not.toHaveBeenCalled(); + }); + test("clears Team metadata when a Team subscription lapses", async () => { const updateTeam = mock(async () => undefined); const team = { From 728c54511dd703658e10c1ae7b9968cba2be53d2 Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Thu, 9 Jul 2026 03:39:25 -0700 Subject: [PATCH 52/89] Transfer retained team billing during deletion --- web/app/api/account/route.ts | 201 ++++++++++++++++++++++++++------ web/tests/account-route.test.ts | 82 ++++++++++++- 2 files changed, 244 insertions(+), 39 deletions(-) diff --git a/web/app/api/account/route.ts b/web/app/api/account/route.ts index a2935c3adb23..5bf221821039 100644 --- a/web/app/api/account/route.ts +++ b/web/app/api/account/route.ts @@ -74,6 +74,11 @@ type AccountDeletionStackTeam = { readonly listUsers?: () => Promise; }; +type RetainedTeamBillingOwner = { + readonly stackTeamId: string; + readonly stackUserId: string; +}; + export async function DELETE(request: Request): Promise { const stackUser = await currentDeletableStackUser(request); if (!stackUser) return unauthorized(); @@ -92,12 +97,17 @@ export async function DELETE(request: Request): Promise { accountDeletionTombstoneStarted = true; await markAccountDeletingAndClearBillingEntitlements(stackUser); stackMetadataMarked = true; - await resolveUserBillingForAccountDeletion(userId, accountScope.teamIds, { - beforeExternalRequest: () => { - restoreBillingEntitlementsOnFailure = false; - destructiveCleanupStarted = true; + await resolveUserBillingForAccountDeletion( + userId, + accountScope.teamIds, + accountScope.retainedTeamBillingOwners, + { + beforeExternalRequest: () => { + restoreBillingEntitlementsOnFailure = false; + destructiveCleanupStarted = true; + }, }, - }); + ); await removeTestFlightAccessForAccountDeletion(stackUser, { afterExternalMutation: () => { restoreBillingEntitlementsOnFailure = false; @@ -147,6 +157,7 @@ export async function DELETE(request: Request): Promise { destroyedVms, }, 500); } + await markAccountDeletionTombstoneCompleted(userId); try { await finishPostStackAccountCleanup(userId, accountScope.teamIds); } catch (error) { @@ -157,7 +168,6 @@ export async function DELETE(request: Request): Promise { destroyedVms, }, 202); } - await markAccountDeletionTombstoneCompleted(userId); return jsonResponse({ ok: true, destroyedVms }); } catch (error) { if (destructiveCleanupStarted || cmuxOwnedRowsDeleted) { @@ -405,44 +415,98 @@ async function finishPostStackAccountCleanup(userId: string, accountTeamIds: rea async function resolveUserBillingForAccountDeletion( userId: string, accountTeamIds: readonly string[], + retainedTeamBillingOwners: readonly RetainedTeamBillingOwner[], options: { readonly beforeExternalRequest?: () => void } = {}, ): Promise { const db = cloudDb(); const deletionTeamIds = uniqueNonEmptyStrings([userId, ...accountTeamIds]); - const activeSubscriptions = await db - .select({ id: stripeSubscriptions.id }) + const retainedOwnerByTeam = new Map( + retainedTeamBillingOwners.map((owner) => [owner.stackTeamId, owner.stackUserId] as const), + ); + const subscriptionRows = await db + .select({ + id: stripeSubscriptions.id, + stackTeamId: stripeSubscriptions.stackTeamId, + scope: stripeSubscriptions.scope, + status: stripeSubscriptions.status, + }) .from(stripeSubscriptions) - .where(and( - eq(stripeSubscriptions.stackUserId, userId), - or( - and( - eq(stripeSubscriptions.scope, "user"), - isNull(stripeSubscriptions.stackTeamId), - ), - and( - eq(stripeSubscriptions.scope, "team"), - inArray(stripeSubscriptions.stackTeamId, deletionTeamIds), - ), - ), - inArray(stripeSubscriptions.status, ACTIVE_STRIPE_PRO_STATUSES), - )); - const customers = await db - .select({ id: stripeCustomers.id }) + .where(eq(stripeSubscriptions.stackUserId, userId)); + const activeSubscriptions = subscriptionRows.filter((subscription) => + stripeSubscriptionBelongsToDeletingAccount(subscription, deletionTeamIds) && + stripeSubscriptionIsActive(subscription) + ); + const retainedTeamSubscriptions = subscriptionRows.filter((subscription) => + stripeSubscriptionBelongsToRetainedTeam(subscription, deletionTeamIds) + ); + const customerRows = await db + .select({ + id: stripeCustomers.id, + stackTeamId: stripeCustomers.stackTeamId, + }) .from(stripeCustomers) - .where(and( - eq(stripeCustomers.stackUserId, userId), - or( - isNull(stripeCustomers.stackTeamId), - inArray(stripeCustomers.stackTeamId, deletionTeamIds), - ), - )); + .where(eq(stripeCustomers.stackUserId, userId)); + const customers = customerRows.filter((customer) => + !customer.stackTeamId || deletionTeamIds.includes(customer.stackTeamId) + ); + const retainedTeamCustomers = customerRows.filter((customer) => + customer.stackTeamId && !deletionTeamIds.includes(customer.stackTeamId) + ); + assertRetainedTeamBillingOwners({ + retainedOwnerByTeam, + rows: [...retainedTeamCustomers, ...retainedTeamSubscriptions], + }); - if (activeSubscriptions.length === 0 && customers.length === 0) return; + if ( + activeSubscriptions.length === 0 && + customers.length === 0 && + retainedTeamCustomers.length === 0 && + retainedTeamSubscriptions.length === 0 + ) return; if (!isStripeBillingConfigured()) { throw new Error("Stripe billing cleanup is not configured"); } const client = stripe(); + for (const customer of retainedTeamCustomers) { + const retainedOwnerId = retainedOwnerByTeam.get(customer.stackTeamId ?? ""); + if (!retainedOwnerId) throw new Error(`retained team billing owner missing for ${customer.stackTeamId}`); + options.beforeExternalRequest?.(); + await client.customers.update(customer.id, { + email: "", + metadata: { + stackUserId: retainedOwnerId, + deletedAccountId: deletedStripeAccountId(userId), + }, + }); + await db + .update(stripeCustomers) + .set({ + stackUserId: retainedOwnerId, + email: null, + updatedAt: sql`now()`, + }) + .where(eq(stripeCustomers.id, customer.id)); + } + for (const subscription of retainedTeamSubscriptions) { + const retainedOwnerId = retainedOwnerByTeam.get(subscription.stackTeamId ?? ""); + if (!retainedOwnerId) throw new Error(`retained team billing owner missing for ${subscription.stackTeamId}`); + options.beforeExternalRequest?.(); + await client.subscriptions.update(subscription.id, { + metadata: { + stackUserId: retainedOwnerId, + deletedAccountId: deletedStripeAccountId(userId), + }, + }); + await db + .update(stripeSubscriptions) + .set({ + stackUserId: retainedOwnerId, + raw: null, + updatedAt: sql`now()`, + }) + .where(eq(stripeSubscriptions.id, subscription.id)); + } for (const subscription of activeSubscriptions) { options.beforeExternalRequest?.(); await cancelStripeSubscriptionForAccountDeletion(client, subscription.id); @@ -453,6 +517,48 @@ async function resolveUserBillingForAccountDeletion( } } +function stripeSubscriptionBelongsToDeletingAccount( + subscription: { readonly scope?: string | null; readonly stackTeamId?: string | null }, + deletionTeamIds: readonly string[], +): boolean { + const scope = subscription.scope ?? "user"; + if (scope === "user" && !subscription.stackTeamId) return true; + return scope === "team" && + typeof subscription.stackTeamId === "string" && + deletionTeamIds.includes(subscription.stackTeamId); +} + +function stripeSubscriptionBelongsToRetainedTeam( + subscription: { readonly scope?: string | null; readonly stackTeamId?: string | null }, + deletionTeamIds: readonly string[], +): boolean { + return (subscription.scope ?? "user") === "team" && + typeof subscription.stackTeamId === "string" && + !deletionTeamIds.includes(subscription.stackTeamId); +} + +function stripeSubscriptionIsActive(subscription: { readonly status?: string | null }): boolean { + return !subscription.status || + (ACTIVE_STRIPE_PRO_STATUSES as readonly string[]).includes(subscription.status); +} + +function assertRetainedTeamBillingOwners(input: { + readonly retainedOwnerByTeam: ReadonlyMap; + readonly rows: readonly { readonly stackTeamId: string | null }[]; +}): void { + const missingTeamIds = uniqueNonEmptyStrings(input.rows.flatMap((row) => { + const stackTeamId = row.stackTeamId; + return stackTeamId && !input.retainedOwnerByTeam.has(stackTeamId) ? [stackTeamId] : []; + })); + if (missingTeamIds.length > 0) { + throw new Error(`retained team billing owner missing for ${missingTeamIds.join(", ")}`); + } +} + +function deletedStripeAccountId(userId: string): string { + return `deleted_${accountDeletionUserHash(userId).slice(0, 24)}`; +} + async function removeTestFlightAccessForAccountDeletion( user: DeletableStackUser, options: { readonly afterExternalMutation?: () => void } = {}, @@ -681,18 +787,39 @@ async function deletePersonalSubrouterTenant( await db.delete(subrouterTenants).where(inArray(subrouterTenants.teamId, teamIds)); } -async function accountDeletionScopeForUser(user: DeletableStackUser): Promise<{ readonly teamIds: readonly string[] }> { +async function accountDeletionScopeForUser(user: DeletableStackUser): Promise<{ + readonly teamIds: readonly string[]; + readonly retainedTeamBillingOwners: readonly RetainedTeamBillingOwner[]; +}> { const listedTeams = typeof user.listTeams === "function" ? await user.listTeams() : []; const teams = uniqueStackTeams([ stackTeamFromUnknown(user.selectedTeam), ...listedTeams.map(stackTeamFromUnknown), ]); const personalTeamIds: string[] = []; + const retainedTeamBillingOwners: RetainedTeamBillingOwner[] = []; for (const team of teams) { const memberIds = await stackTeamMemberIds(team); - if (memberIds.length === 1 && memberIds[0] === user.id) personalTeamIds.push(team.id); + if (!memberIds) { + throw new Error(`Stack team membership is required for account deletion: ${team.id}`); + } + if (memberIds.length === 1 && memberIds[0] === user.id) { + personalTeamIds.push(team.id); + continue; + } + if (!memberIds.includes(user.id)) continue; + const retainedOwnerId = memberIds.find((memberId) => memberId !== user.id); + if (retainedOwnerId) { + retainedTeamBillingOwners.push({ + stackTeamId: team.id, + stackUserId: retainedOwnerId, + }); + } } - return { teamIds: uniqueNonEmptyStrings([user.id, ...personalTeamIds]) }; + return { + teamIds: uniqueNonEmptyStrings([user.id, ...personalTeamIds]), + retainedTeamBillingOwners, + }; } function stackTeamFromUnknown(value: unknown): AccountDeletionStackTeam | null { @@ -708,8 +835,8 @@ function stackTeamFromUnknown(value: unknown): AccountDeletionStackTeam | null { }; } -async function stackTeamMemberIds(team: AccountDeletionStackTeam): Promise { - if (typeof team.listUsers !== "function") return []; +async function stackTeamMemberIds(team: AccountDeletionStackTeam): Promise { + if (typeof team.listUsers !== "function") return null; const members = await team.listUsers(); return uniqueNonEmptyStrings(members.flatMap((member) => { if (!member || typeof member !== "object") return []; diff --git a/web/tests/account-route.test.ts b/web/tests/account-route.test.ts index db3e2a90d851..79735c6746dc 100644 --- a/web/tests/account-route.test.ts +++ b/web/tests/account-route.test.ts @@ -161,6 +161,16 @@ const deleteCustomer = mock(async (...args: unknown[]) => { deletedStripeCustomers.push(customerId); if (stripeDeleteCustomerError) throw stripeDeleteCustomerError; }); +const updateCustomer = mock(async (...args: unknown[]) => { + const [customerId, params] = args as [string, Record]; + routeEvents.push("stripe-update-customer"); + updatedStripeCustomers.push({ id: customerId, params }); +}); +const updateSubscription = mock(async (...args: unknown[]) => { + const [subscriptionId, params] = args as [string, Record]; + routeEvents.push("stripe-update-subscription"); + updatedStripeSubscriptions.push({ id: subscriptionId, params }); +}); const removeTester = mock(async (...args: unknown[]) => { const [email] = args as [string]; routeEvents.push(`testflight-remove:${email}`); @@ -192,6 +202,8 @@ let stripeConfigured = true; let ascConfigured = false; let cancelledStripeSubscriptions: string[] = []; let deletedStripeCustomers: string[] = []; +let updatedStripeCustomers: Array<{ readonly id: string; readonly params: Record }> = []; +let updatedStripeSubscriptions: Array<{ readonly id: string; readonly params: Record }> = []; let stripeCancelError: unknown = null; let stripeDeleteCustomerError: unknown = null; let removeTesterError: unknown = null; @@ -311,8 +323,8 @@ mock.module("../services/billing/stripe", () => ({ : realIsStripeBillingConfigured(), stripe: () => useAccountRouteStubs ? { - subscriptions: { cancel: cancelSubscription }, - customers: { del: deleteCustomer }, + subscriptions: { cancel: cancelSubscription, update: updateSubscription }, + customers: { del: deleteCustomer, update: updateCustomer }, } : realStripe(), })); @@ -404,6 +416,8 @@ beforeEach(() => { deleteObject.mockClear(); cancelSubscription.mockClear(); deleteCustomer.mockClear(); + updateCustomer.mockClear(); + updateSubscription.mockClear(); removeTester.mockClear(); captureAscError.mockClear(); revokeTenant.mockClear(); @@ -424,6 +438,8 @@ beforeEach(() => { ascConfigured = false; cancelledStripeSubscriptions = []; deletedStripeCustomers = []; + updatedStripeCustomers = []; + updatedStripeSubscriptions = []; stripeCancelError = null; stripeDeleteCustomerError = null; removeTesterError = null; @@ -603,6 +619,64 @@ describe("account deletion route", () => { expect(transactionExecute).toHaveBeenCalledTimes(3); }); + test("reassigns retained shared-team Stripe billing to another team member", async () => { + listedPersonalVmIds = []; + stackUserSelectedTeam = stackTeam("team-shared", ["account-user-1", "other-user"]); + selectResults = [ + [{ id: "sub_shared", stackTeamId: "team-shared", scope: "team", status: "active" }], + [{ id: "cus_shared", stackTeamId: "team-shared" }], + [], + [], + [], + [], + ]; + + const response = await DELETE(accountDeletionRequest()); + + expect(response.status).toBe(200); + expect(cancelledStripeSubscriptions).toEqual([]); + expect(deletedStripeCustomers).toEqual([]); + expect(updatedStripeCustomers).toEqual([{ + id: "cus_shared", + params: { + email: "", + metadata: expect.objectContaining({ stackUserId: "other-user" }), + }, + }]); + expect(updatedStripeSubscriptions).toEqual([{ + id: "sub_shared", + params: { + metadata: expect.objectContaining({ stackUserId: "other-user" }), + }, + }]); + expect(updatedRows.map(({ table, values }) => ({ + table, + values: stripUpdatedAt(values), + }))).toContainEqual({ + table: stripeCustomers, + values: { stackUserId: "other-user", email: null }, + }); + expect(updatedRows.map(({ table, values }) => ({ + table, + values: stripUpdatedAt(values), + }))).toContainEqual({ + table: stripeSubscriptions, + values: { stackUserId: "other-user", raw: null }, + }); + }); + + test("fails closed when Stack cannot list selected team members", async () => { + stackUserSelectedTeam = { id: "team-shared" }; + + const response = await DELETE(accountDeletionRequest()); + + expect(response.status).toBe(500); + expect(await response.json()).toEqual({ error: "account_delete_failed" }); + expect(updateStackUser).not.toHaveBeenCalled(); + expect(cancelSubscription).not.toHaveBeenCalled(); + expect(deleteStackUser).not.toHaveBeenCalled(); + }); + test("revokes the personal Subrouter tenant before deleting local rows", async () => { selectResults = [ [], @@ -1180,6 +1254,10 @@ describe("account deletion route", () => { }); expect(deleteStackUser).toHaveBeenCalledTimes(1); expect(transaction).toHaveBeenCalledTimes(2); + expect(tombstoneUpdates.some((values) => + (values as { readonly status?: unknown; readonly userId?: unknown }).status === "completed" && + (values as { readonly userId?: unknown }).userId === null + )).toBe(true); expect(consoleError).toHaveBeenCalledWith( "account.delete.post_stack_cleanup_failed", "Error: post-delete vault unavailable", From aa2110c0af657a2146f39756dc511a3d8ec8b2af Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Thu, 9 Jul 2026 03:43:36 -0700 Subject: [PATCH 53/89] Treat post-stack deletion failures as accepted --- web/app/api/account/route.ts | 2 +- web/tests/account-route.test.ts | 30 +++++++++++++++++++++++++++++- 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/web/app/api/account/route.ts b/web/app/api/account/route.ts index 5bf221821039..76ceebdbe0df 100644 --- a/web/app/api/account/route.ts +++ b/web/app/api/account/route.ts @@ -157,8 +157,8 @@ export async function DELETE(request: Request): Promise { destroyedVms, }, 500); } - await markAccountDeletionTombstoneCompleted(userId); try { + await markAccountDeletionTombstoneCompleted(userId); await finishPostStackAccountCleanup(userId, accountScope.teamIds); } catch (error) { logAccountDeleteError("account.delete.post_stack_cleanup_failed", error); diff --git a/web/tests/account-route.test.ts b/web/tests/account-route.test.ts index 79735c6746dc..a3ee284380c9 100644 --- a/web/tests/account-route.test.ts +++ b/web/tests/account-route.test.ts @@ -91,7 +91,15 @@ const updateRows = mock((table: unknown) => ({ updatedRows.push({ table, values }); } return { - where: async () => {}, + where: async () => { + if ( + table === accountDeletionTombstones && + (values as { readonly status?: unknown }).status === "completed" && + tombstoneCompleteError + ) { + throw tombstoneCompleteError; + } + }, }; }, })); @@ -190,6 +198,7 @@ let deletedTables: unknown[] = []; let deletedWhere: Array<{ readonly table: unknown; readonly condition: unknown }> = []; let updatedRows: Array<{ readonly table: unknown; readonly values: unknown }> = []; let tombstoneUpdates: unknown[] = []; +let tombstoneCompleteError: unknown = null; let routeEvents: string[] = []; let stackDeleteError: unknown = null; let stackUserIds: Array = []; @@ -426,6 +435,7 @@ beforeEach(() => { deletedWhere = []; updatedRows = []; tombstoneUpdates = []; + tombstoneCompleteError = null; routeEvents = []; stackDeleteError = null; stackUserIds = []; @@ -1264,6 +1274,24 @@ describe("account deletion route", () => { ); }); + test("returns accepted deletion when tombstone completion fails after the account is deleted", async () => { + tombstoneCompleteError = new Error("tombstone unavailable"); + + const response = await DELETE(accountDeletionRequest()); + + expect(response.status).toBe(202); + expect(await response.json()).toEqual({ + ok: true, + cleanupIncomplete: true, + destroyedVms: 2, + }); + expect(deleteStackUser).toHaveBeenCalledTimes(1); + expect(consoleError).toHaveBeenCalledWith( + "account.delete.post_stack_cleanup_failed", + "Error: tombstone unavailable", + ); + }); + test("continues when Stripe resources are already in the deletion target state", async () => { selectResults = [ [{ id: "sub_user_active" }], From a92453539066394acc298718e52088d74f8ca945 Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Thu, 9 Jul 2026 03:56:49 -0700 Subject: [PATCH 54/89] Serialize account deletion cleanup --- web/app/api/account/route.ts | 54 ++++++++++++++++++++++++++------- web/tests/account-route.test.ts | 39 ++++++++++++++++++++++-- 2 files changed, 79 insertions(+), 14 deletions(-) diff --git a/web/app/api/account/route.ts b/web/app/api/account/route.ts index 76ceebdbe0df..376093d923eb 100644 --- a/web/app/api/account/route.ts +++ b/web/app/api/account/route.ts @@ -44,6 +44,7 @@ import { deleteObject } from "../../../services/vault/storage"; import { accountDeletionAdvisoryLockKey, accountDeletionUserHash, + isBlockingAccountDeletionStatus, } from "../../../services/account/deletionLock"; import { unauthorized } from "../../../services/vms/auth"; import { isVmAccountDeletionIdentityRevocationError } from "../../../services/vms/errors"; @@ -93,8 +94,10 @@ export async function DELETE(request: Request): Promise { let restoreBillingEntitlementsOnFailure = true; try { const accountScope = await accountDeletionScopeForUser(stackUser); - await markAccountDeletionTombstonePending(userId); - accountDeletionTombstoneStarted = true; + accountDeletionTombstoneStarted = await markAccountDeletionTombstonePending(userId); + if (!accountDeletionTombstoneStarted) { + return jsonResponse({ ok: true, deletionPending: true, destroyedVms: 0 }, 202); + } await markAccountDeletingAndClearBillingEntitlements(stackUser); stackMetadataMarked = true; await resolveUserBillingForAccountDeletion( @@ -171,6 +174,7 @@ export async function DELETE(request: Request): Promise { return jsonResponse({ ok: true, destroyedVms }); } catch (error) { if (destructiveCleanupStarted || cmuxOwnedRowsDeleted) { + if (accountDeletionTombstoneStarted) await markAccountDeletionTombstoneFailed(userId, error); logAccountDeleteError("account.delete.partial_after_destructive_cleanup", error); return jsonResponse({ error: "account_delete_retryable", @@ -208,12 +212,24 @@ async function currentDeletableStackUser(request: Request): Promise { +async function markAccountDeletionTombstonePending(userId: string): Promise { const db = cloudDb(); const now = new Date(); const userIdHash = accountDeletionUserHash(userId); - await db.transaction(async (tx) => { + return await db.transaction(async (tx) => { await tx.execute(sql`select pg_advisory_xact_lock(hashtextextended(${accountDeletionAdvisoryLockKey(userId)}, 0))`); + const [existing] = await tx + .select({ + userIdHash: accountDeletionTombstones.userIdHash, + status: accountDeletionTombstones.status, + }) + .from(accountDeletionTombstones) + .where(eq(accountDeletionTombstones.userIdHash, userIdHash)) + .limit(1); + if (existing && (existing.status === "completed" || isBlockingAccountDeletionStatus(existing.status))) { + return false; + } + await tx .insert(accountDeletionTombstones) .values({ @@ -232,6 +248,7 @@ async function markAccountDeletionTombstonePending(userId: string): Promise vm.id))); } await tx.delete(cloudVmBaseEvents).where(eq(cloudVmBaseEvents.userId, userId)); - await tx.delete(cloudVmBases).where(and( - eq(cloudVmBases.scopeType, "user"), - eq(cloudVmBases.scopeId, userId), + await tx.delete(cloudVmBases).where(or( + and( + eq(cloudVmBases.scopeType, "user"), + eq(cloudVmBases.scopeId, userId), + ), + and( + eq(cloudVmBases.scopeType, "team"), + inArray(cloudVmBases.scopeId, deletionTeamIds), + ), )); await tx .update(cloudVmBases) @@ -791,7 +820,10 @@ async function accountDeletionScopeForUser(user: DeletableStackUser): Promise<{ readonly teamIds: readonly string[]; readonly retainedTeamBillingOwners: readonly RetainedTeamBillingOwner[]; }> { - const listedTeams = typeof user.listTeams === "function" ? await user.listTeams() : []; + if (typeof user.listTeams !== "function") { + throw new Error("Stack team listing is required for account deletion"); + } + const listedTeams = await user.listTeams(); const teams = uniqueStackTeams([ stackTeamFromUnknown(user.selectedTeam), ...listedTeams.map(stackTeamFromUnknown), diff --git a/web/tests/account-route.test.ts b/web/tests/account-route.test.ts index a3ee284380c9..e699ade2a4e0 100644 --- a/web/tests/account-route.test.ts +++ b/web/tests/account-route.test.ts @@ -62,12 +62,15 @@ const getUser = mock(async () => stackUser(stackUserIds.shift())); const transaction = mock(async (...args: unknown[]) => { const [callback] = args as [(tx: MockTransaction) => Promise]; routeEvents.push("transaction"); - await callback(mockTransaction); + return await callback(mockTransaction); }); const transactionSelect = mock(() => ({ - from: () => ({ + from: (table: unknown) => ({ where: () => ({ for: async () => nextTransactionSelectResult(), + limit: async () => table === accountDeletionTombstones + ? nextTransactionTombstoneSelectResult() + : nextTransactionSelectResult(), }), }), })); @@ -204,6 +207,7 @@ let stackDeleteError: unknown = null; let stackUserIds: Array = []; let selectResults: unknown[][] = []; let transactionSelectResults: unknown[][] = []; +let transactionTombstoneSelectResults: unknown[][] = []; let deletedVaultObjects: string[] = []; let vaultDeleteError: unknown = null; let postStackVaultDeleteError: unknown = null; @@ -280,6 +284,10 @@ function nextTransactionSelectResult(): unknown[] { return transactionSelectResults.shift() ?? []; } +function nextTransactionTombstoneSelectResult(): unknown[] { + return transactionTombstoneSelectResults.shift() ?? []; +} + function chainableSelectResult(rows: unknown[]): SelectResult { const result = Promise.resolve(rows) as SelectResult; Object.defineProperties(result, { @@ -441,6 +449,7 @@ beforeEach(() => { stackUserIds = []; selectResults = [[], [], [], [], [], []]; transactionSelectResults = []; + transactionTombstoneSelectResults = []; deletedVaultObjects = []; vaultDeleteError = null; postStackVaultDeleteError = null; @@ -607,6 +616,30 @@ describe("account deletion route", () => { expect(deletedStripeCustomers).toEqual(["cus_user", "cus_team"]); expect(revokeTenant).toHaveBeenCalledWith("tenant-team-personal"); expect(transactionExecute).toHaveBeenCalledTimes(5); + const grantDelete = deletedWhere.find((entry) => entry.table === cloudVmBillingGrants); + expect(conditionColumnNames(grantDelete?.condition)).toContain("billing_customer_id"); + const baseDelete = deletedWhere.find((entry) => entry.table === cloudVmBases); + expect(conditionColumnNames(baseDelete?.condition)).toContain("scope_id"); + }); + + test("joins an in-progress account deletion instead of rerunning destructive cleanup", async () => { + transactionTombstoneSelectResults = [[{ + userIdHash: "existing-hash", + status: "pending", + }]]; + + const response = await DELETE(accountDeletionRequest()); + + expect(response.status).toBe(202); + expect(await response.json()).toEqual({ + ok: true, + deletionPending: true, + destroyedVms: 0, + }); + expect(updateStackUser).not.toHaveBeenCalled(); + expect(cancelSubscription).not.toHaveBeenCalled(); + expect(listUserVms).not.toHaveBeenCalled(); + expect(deleteStackUser).not.toHaveBeenCalled(); }); test("does not treat a selected shared Stack team as account-owned data", async () => { @@ -901,7 +934,7 @@ describe("account deletion route", () => { }); expect(transaction).toHaveBeenCalledTimes(2); expect(transactionExecute).toHaveBeenCalledTimes(2); - expect(transactionSelect).toHaveBeenCalledTimes(1); + expect(transactionSelect).toHaveBeenCalledTimes(2); expect(deletedTableCount).toBe(0); expect(deleteStackUser).not.toHaveBeenCalled(); expect(consoleError).toHaveBeenCalledWith( From ed30ccdd47ffb813f1bf59b3d744359df7269206 Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Thu, 9 Jul 2026 04:04:12 -0700 Subject: [PATCH 55/89] Fix deletion retry blockers --- web/app/api/account/route.ts | 1 + web/services/vms/repository.ts | 5 +++-- web/tests/account-route.test.ts | 4 ++++ 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/web/app/api/account/route.ts b/web/app/api/account/route.ts index 376093d923eb..9633d3866c72 100644 --- a/web/app/api/account/route.ts +++ b/web/app/api/account/route.ts @@ -154,6 +154,7 @@ export async function DELETE(request: Request): Promise { await stackUser.delete(); } catch (error) { logAccountDeleteError("account.delete.stack_user_failed_after_data_delete", error); + if (accountDeletionTombstoneStarted) await markAccountDeletionTombstoneFailed(userId, error); return jsonResponse({ error: "account_delete_retryable", retryable: true, diff --git a/web/services/vms/repository.ts b/web/services/vms/repository.ts index 26c9ee705f6b..f06cb7b8f486 100644 --- a/web/services/vms/repository.ts +++ b/web/services/vms/repository.ts @@ -25,6 +25,7 @@ import { VmCreateInProgressError, VmDatabaseError, VmLimitExceededError, + isVmCreateDisabledError, isVmLimitExceededError, } from "./errors"; @@ -85,7 +86,7 @@ export type VmRepositoryShape = { readonly imageVersion?: string | null; readonly maxActiveVms: number; readonly idempotencyKey?: string; - }) => Effect.Effect; + }) => Effect.Effect; readonly beginBaseOpen: (input: { readonly userId: string; readonly billingTeamId: string; @@ -517,7 +518,7 @@ export const VmRepositoryLive = Layer.succeed(VmRepository, { throw err; } }, - catch: (cause) => isVmLimitExceededError(cause) + catch: (cause) => isVmCreateDisabledError(cause) || isVmLimitExceededError(cause) ? cause : new VmDatabaseError({ operation: "beginCreate", cause }), }), diff --git a/web/tests/account-route.test.ts b/web/tests/account-route.test.ts index e699ade2a4e0..c3caa5c959a8 100644 --- a/web/tests/account-route.test.ts +++ b/web/tests/account-route.test.ts @@ -1252,6 +1252,10 @@ describe("account deletion route", () => { }); expect(updateStackUser).toHaveBeenCalledTimes(1); expect(deleteStackUser).toHaveBeenCalledTimes(1); + expect(tombstoneUpdates.some((values) => + (values as { readonly status?: unknown; readonly errorMessage?: unknown }).status === "failed" && + (values as { readonly errorMessage?: unknown }).errorMessage === "Error: raw [redacted] leaked by upstream" + )).toBe(true); expect(routeEvents).toEqual([ "transaction", "transaction-lock", From f7415c86d7f0d949d9b42a2a8856672f07e48625 Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Thu, 9 Jul 2026 04:10:03 -0700 Subject: [PATCH 56/89] Handle pending account deletion safely --- .../Coordinator/AccountDeletionClient.swift | 13 +++++++++---- .../AccountDeletionClientTests.swift | 18 ++++++++++++++++++ web/app/api/account/route.ts | 12 +++++++++++- web/tests/account-route.test.ts | 19 +++++++++++++++++++ 4 files changed, 57 insertions(+), 5 deletions(-) diff --git a/Packages/Shared/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AccountDeletionClient.swift b/Packages/Shared/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AccountDeletionClient.swift index f200ac927e70..6d468bcc8e1e 100644 --- a/Packages/Shared/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AccountDeletionClient.swift +++ b/Packages/Shared/CmuxAuthRuntime/Sources/CmuxAuthRuntime/Coordinator/AccountDeletionClient.swift @@ -48,7 +48,7 @@ struct AccountDeletionClient: Sendable { } switch httpResponse.statusCode { case 200..<300: - return accountDeletionResult(in: data) + return try accountDeletionResult(in: data) case 401: throw AccountDeletionRequestError.unauthorized default: @@ -67,13 +67,18 @@ struct AccountDeletionClient: Sendable { } } -private func accountDeletionResult(in data: Data) -> AccountDeletionResult { +private func accountDeletionResult(in data: Data) throws -> AccountDeletionResult { guard - let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any], - object["cleanupIncomplete"] as? Bool == true + let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { return .completed } + if object["deletionPending"] as? Bool == true { + throw AccountDeletionRequestError.completionUnknown + } + guard object["cleanupIncomplete"] as? Bool == true else { + return .completed + } return .completedWithIncompleteServerCleanup } diff --git a/Packages/Shared/CmuxAuthRuntime/Tests/CmuxAuthRuntimeTests/AccountDeletionClientTests.swift b/Packages/Shared/CmuxAuthRuntime/Tests/CmuxAuthRuntimeTests/AccountDeletionClientTests.swift index abcfc5c42f55..8adf3a76d958 100644 --- a/Packages/Shared/CmuxAuthRuntime/Tests/CmuxAuthRuntimeTests/AccountDeletionClientTests.swift +++ b/Packages/Shared/CmuxAuthRuntime/Tests/CmuxAuthRuntimeTests/AccountDeletionClientTests.swift @@ -47,6 +47,24 @@ struct AccountDeletionClientTests { #expect(result == .completedWithIncompleteServerCleanup) } + @Test func deleteAccountDoesNotTreatPendingAcceptedResponseAsCompleted() async { + let client = AccountDeletionClient(apiBaseURL: "https://cmux.test") { request in + ( + Data(#"{"ok":true,"deletionPending":true,"destroyedVms":0}"#.utf8), + HTTPURLResponse( + url: request.url!, + statusCode: 202, + httpVersion: nil, + headerFields: nil + )! + ) + } + + await #expect(throws: AccountDeletionRequestError.completionUnknown) { + try await client.deleteAccount(accessToken: "access-token", refreshToken: "refresh-token") + } + } + @Test func deleteAccountMapsUnauthorizedResponse() async { let client = AccountDeletionClient(apiBaseURL: "https://cmux.test") { request in ( diff --git a/web/app/api/account/route.ts b/web/app/api/account/route.ts index 9633d3866c72..8384888e00e8 100644 --- a/web/app/api/account/route.ts +++ b/web/app/api/account/route.ts @@ -80,6 +80,8 @@ type RetainedTeamBillingOwner = { readonly stackUserId: string; }; +const ACCOUNT_DELETION_TOMBSTONE_LEASE_MS = 15 * 60 * 1000; + export async function DELETE(request: Request): Promise { const stackUser = await currentDeletableStackUser(request); if (!stackUser) return unauthorized(); @@ -223,11 +225,13 @@ async function markAccountDeletionTombstonePending(userId: string): Promise= ACCOUNT_DELETION_TOMBSTONE_LEASE_MS; +} + async function markAccountDeletionTombstoneCompleted(userId: string): Promise { const now = new Date(); await cloudDb() diff --git a/web/tests/account-route.test.ts b/web/tests/account-route.test.ts index c3caa5c959a8..d5a63be000cb 100644 --- a/web/tests/account-route.test.ts +++ b/web/tests/account-route.test.ts @@ -626,6 +626,7 @@ describe("account deletion route", () => { transactionTombstoneSelectResults = [[{ userIdHash: "existing-hash", status: "pending", + updatedAt: new Date(), }]]; const response = await DELETE(accountDeletionRequest()); @@ -642,6 +643,24 @@ describe("account deletion route", () => { expect(deleteStackUser).not.toHaveBeenCalled(); }); + test("adopts a stale in-progress account deletion instead of blocking forever", async () => { + transactionTombstoneSelectResults = [[{ + userIdHash: "existing-hash", + status: "pending", + updatedAt: new Date(Date.now() - 20 * 60 * 1000), + }]]; + + const response = await DELETE(accountDeletionRequest()); + + expect(response.status).toBe(200); + expect(await response.json()).toEqual({ ok: true, destroyedVms: 2 }); + expect(routeEvents).toContain("tombstone-upsert"); + expect(updateStackUser).toHaveBeenCalledWith({ + clientReadOnlyMetadata: { cmuxAccountDeleting: true }, + }); + expect(deleteStackUser).toHaveBeenCalledTimes(1); + }); + test("does not treat a selected shared Stack team as account-owned data", async () => { listedPersonalVmIds = []; listedPersonalVmIdsByBillingTeam = { "team-shared": ["shared-team-vm"] }; From 80046dc3168943af06d0a99a2fe1acb205138665 Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Thu, 9 Jul 2026 04:23:20 -0700 Subject: [PATCH 57/89] Move checkout entitlement sync after commit --- web/services/billing/purchase.ts | 89 ++++++++++++++++++++++-------- web/tests/billing-purchase.test.ts | 4 +- 2 files changed, 69 insertions(+), 24 deletions(-) diff --git a/web/services/billing/purchase.ts b/web/services/billing/purchase.ts index 2f27a68052b0..13eb51c9cc01 100644 --- a/web/services/billing/purchase.ts +++ b/web/services/billing/purchase.ts @@ -108,6 +108,24 @@ type CheckoutCompletionResult = | { scope: "team"; stackTeamId: string; subscriptionId: string } | { skipped: "account_deletion_in_progress"; stackUserId: string; subscriptionId: string }; +type UserCheckoutPostCommitSync = { + user: StackBillingUser; + email: string | null; + stripeCustomerId: string; + stackUserId: string; + stackApp: StackBillingApp | null | undefined; +}; + +type CheckoutCompletionLockedResult = { + result: CheckoutCompletionResult; + deleteCheckoutStripeResources: boolean; + postCommitUserSync?: UserCheckoutPostCommitSync; + postCommitTeamSync?: { + stackTeamId: string; + stackApp: StackBillingApp | null | undefined; + }; +}; + export async function recordCheckoutCompletion( input: CheckoutCompletionInput, dependencies: BillingPurchaseDependencies = {}, @@ -137,14 +155,11 @@ export async function recordCheckoutCompletion( } const db = dependencies.db ?? cloudDb(); + const user = await loadOptionalStackUser(stackUserId, dependencies.stackApp); const lockedResult = await withAccountDeletionUserLock( db, stackUserId, - async (tx): Promise<{ - result: CheckoutCompletionResult; - deleteCheckoutStripeResources: boolean; - }> => { - const user = await loadOptionalStackUser(stackUserId, dependencies.stackApp); + async (tx): Promise => { if ( await hasCheckoutBlockingAccountDeletionTombstone(stackUserId, tx) || (user && isAccountDeletionInProgress(user)) @@ -173,19 +188,15 @@ export async function recordCheckoutCompletion( scope: "user", }); - if (email) { - await attachPurchaseEmailOrRecordClaim(tx, { + return { + deleteCheckoutStripeResources: false, + postCommitUserSync: { user, email, stripeCustomerId: customerId, stackUserId, stackApp: dependencies.stackApp ?? stackServerApp, - }); - } - await syncProPlanMetadata(user, true); - - return { - deleteCheckoutStripeResources: false, + }, result: { scope: "user", stackUserId, subscriptionId: subscription.id }, }; }, @@ -194,10 +205,29 @@ export async function recordCheckoutCompletion( if (lockedResult.deleteCheckoutStripeResources) { await deleteCheckoutStripeResourcesForAccountDeletion(subscription, customerId, dependencies); } + if (lockedResult.postCommitUserSync) { + await syncUserCheckoutAfterCommit(db, lockedResult.postCommitUserSync); + } return lockedResult.result; } +async function syncUserCheckoutAfterCommit( + db: BillingDb, + input: UserCheckoutPostCommitSync, +): Promise { + if (input.email) { + await attachPurchaseEmailOrRecordClaim(db, { + user: input.user, + email: input.email, + stripeCustomerId: input.stripeCustomerId, + stackUserId: input.stackUserId, + stackApp: input.stackApp, + }); + } + await syncProPlanMetadata(input.user, true); +} + async function deleteCheckoutStripeResourcesForAccountDeletion( subscription: Stripe.Subscription, customerId: string, @@ -469,8 +499,15 @@ async function recordTeamCheckoutCompletion(input: { stackTeamId: input.stackTeamId, customerId: input.customerId, })); - const lockStackUserId = checkoutOwnerStackUserId ?? input.stackTeamId; - const lockedResult = await withAccountDeletionUserLock(db, lockStackUserId, async (tx) => { + const resolvedStackUserId = checkoutOwnerStackUserId ?? input.stackTeamId; + const ownerStackUserId = + resolvedStackUserId !== input.stackTeamId && resolvedStackUserId !== DELETED_ACCOUNT_ACTOR_ID + ? resolvedStackUserId + : null; + const owner = ownerStackUserId + ? await loadOptionalStackUser(ownerStackUserId, input.dependencies.stackApp) + : null; + const lockedResult = await withAccountDeletionUserLock(db, resolvedStackUserId, async (tx) => { const stackUserId = input.stackUserId ?? (await stackUserIdForTeamStripeCustomer(tx, { @@ -479,17 +516,16 @@ async function recordTeamCheckoutCompletion(input: { })) ?? checkoutOwnerStackUserId ?? input.stackTeamId; - const ownerStackUserId = + const transactionOwnerStackUserId = stackUserId !== input.stackTeamId && stackUserId !== DELETED_ACCOUNT_ACTOR_ID ? stackUserId : null; - const owner = ownerStackUserId - ? await loadOptionalStackUser(ownerStackUserId, input.dependencies.stackApp) - : null; + const ownerChangedDuringCheckout = transactionOwnerStackUserId !== ownerStackUserId; if ( stackUserId === DELETED_ACCOUNT_ACTOR_ID || (await hasCheckoutBlockingAccountDeletionTombstone(stackUserId, tx)) || - (ownerStackUserId && !owner) || + ownerChangedDuringCheckout || + (transactionOwnerStackUserId && !owner) || (owner && isAccountDeletionInProgress(owner)) ) { return { @@ -515,10 +551,12 @@ async function recordTeamCheckoutCompletion(input: { scope: "team", }); - const team = await loadStackTeam(input.stackTeamId, input.dependencies.stackApp); - await syncTeamPlanMetadata(team, true); return { deleteCheckoutStripeResources: false, + postCommitTeamSync: { + stackTeamId: input.stackTeamId, + stackApp: input.dependencies.stackApp, + }, result: { scope: "team" as const, stackTeamId: input.stackTeamId, @@ -534,6 +572,13 @@ async function recordTeamCheckoutCompletion(input: { input.dependencies, ); } + if (lockedResult.postCommitTeamSync) { + const team = await loadStackTeam( + lockedResult.postCommitTeamSync.stackTeamId, + lockedResult.postCommitTeamSync.stackApp, + ); + await syncTeamPlanMetadata(team, true); + } return lockedResult.result; } diff --git a/web/tests/billing-purchase.test.ts b/web/tests/billing-purchase.test.ts index 708441ee8ba9..f236f02d1c67 100644 --- a/web/tests/billing-purchase.test.ts +++ b/web/tests/billing-purchase.test.ts @@ -256,7 +256,7 @@ describe("recordCheckoutCompletion", () => { expect(updates).toHaveLength(0); }); - test("syncs checkout metadata while holding the account deletion lock", async () => { + test("syncs checkout metadata after the account deletion lock commits", async () => { let transactionOpen = false; let lockAcquired = false; const baseDb = fakeDb(); @@ -279,7 +279,7 @@ describe("recordCheckoutCompletion", () => { }, }; const update = mock(async () => { - expect(transactionOpen).toBe(true); + expect(transactionOpen).toBe(false); expect(lockAcquired).toBe(true); }); const user = { From e221420da030bcb535b52383a9412d804295341b Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Thu, 9 Jul 2026 04:35:31 -0700 Subject: [PATCH 58/89] Close account deletion edge cases --- web/app/api/account/route.ts | 25 ++++++++++++--- web/services/billing/purchase.ts | 18 ++++++++--- web/services/vms/repository.ts | 15 ++++----- web/services/vms/workflows.ts | 3 ++ web/tests/account-route.test.ts | 49 ++++++++++++++++++++++++++++-- web/tests/billing-purchase.test.ts | 37 ++++++++++++++++++++++ 6 files changed, 128 insertions(+), 19 deletions(-) diff --git a/web/app/api/account/route.ts b/web/app/api/account/route.ts index 8384888e00e8..70025d4fa620 100644 --- a/web/app/api/account/route.ts +++ b/web/app/api/account/route.ts @@ -48,6 +48,7 @@ import { } from "../../../services/account/deletionLock"; import { unauthorized } from "../../../services/vms/auth"; import { isVmAccountDeletionIdentityRevocationError } from "../../../services/vms/errors"; +import type { ProviderId } from "../../../services/vms/drivers"; import { jsonResponse } from "../../../services/vms/routeHelpers"; import { destroyVm, @@ -311,10 +312,12 @@ async function destroyPersonalCloudVms(userId: string, accountTeamIds: readonly billingTeamId?: string | null; teamIds: readonly string[]; providerVmId: string; + provider: ProviderId; } = { userId, teamIds: accountTeamIds, providerVmId: vm.providerVmId, + provider: vm.provider, }; if (vm.billingTeamId) destroyInput.billingTeamId = vm.billingTeamId; const destroyProgram = destroyVm(destroyInput); @@ -339,22 +342,36 @@ async function destroyPersonalCloudVms(userId: string, accountTeamIds: readonly async function listAccountDeletionCloudVms( userId: string, accountTeamIds: readonly string[], -): Promise> { - const vms = new Map(); +): Promise> { + const vms = new Map< + string, + { readonly providerVmId: string; readonly provider: ProviderId; readonly billingTeamId?: string | null } + >(); const legacyScopedVms = await runVmWorkflow(listUserVms(userId)); for (const vm of legacyScopedVms) { - vms.set(vm.providerVmId, { providerVmId: vm.providerVmId }); + vms.set(accountDeletionVmKey(vm), { + providerVmId: vm.providerVmId, + provider: vm.provider, + }); } for (const teamId of accountTeamIds) { if (teamId === userId) continue; const teamScopedVms = await runVmWorkflow(listUserVms(userId, teamId)); for (const vm of teamScopedVms) { - vms.set(vm.providerVmId, { providerVmId: vm.providerVmId, billingTeamId: teamId }); + vms.set(accountDeletionVmKey(vm), { + providerVmId: vm.providerVmId, + provider: vm.provider, + billingTeamId: teamId, + }); } } return [...vms.values()]; } +function accountDeletionVmKey(vm: { readonly provider: ProviderId; readonly providerVmId: string }): string { + return `${vm.provider}:${vm.providerVmId}`; +} + async function deleteVaultRowsAndObjectsForAccount( userId: string, options: { readonly beforeObjectDeletion?: () => void } = {}, diff --git a/web/services/billing/purchase.ts b/web/services/billing/purchase.ts index 13eb51c9cc01..37eea1918f19 100644 --- a/web/services/billing/purchase.ts +++ b/web/services/billing/purchase.ts @@ -263,11 +263,19 @@ export async function applySubscriptionUpdate( const teamScope = teamScopeFromSubscription(subscription); if (teamScope) { - const stackUserId = - (await stackUserIdForTeamStripeCustomer(db, { - stackTeamId: teamScope.stackTeamId, - customerId, - })) ?? teamScope.stackTeamId; + const metadataStackUserId = nonEmptyString(subscription.metadata?.stackUserId); + const mappedStackUserId = await stackUserIdForTeamStripeCustomer(db, { + stackTeamId: teamScope.stackTeamId, + customerId, + }); + if (mappedStackUserId === DELETED_ACCOUNT_ACTOR_ID) return { skipped: true }; + if ( + metadataStackUserId && + mappedStackUserId && + metadataStackUserId !== mappedStackUserId + ) return { skipped: true }; + const stackUserId = mappedStackUserId ?? metadataStackUserId ?? teamScope.stackTeamId; + if (stackUserId === DELETED_ACCOUNT_ACTOR_ID) return { skipped: true }; await upsertTeamStripeCustomer(db, { customerId, stackUserId, diff --git a/web/services/vms/repository.ts b/web/services/vms/repository.ts index f06cb7b8f486..997bb5b2fa55 100644 --- a/web/services/vms/repository.ts +++ b/web/services/vms/repository.ts @@ -169,6 +169,7 @@ export type VmRepositoryShape = { readonly userId: string; readonly billingTeamId?: string | null; readonly providerVmId: string; + readonly provider?: ProviderId; }) => Effect.Effect; readonly markDestroyed: (id: string) => Effect.Effect; readonly recordLease: (input: { @@ -1193,16 +1194,16 @@ export const VmRepositoryLive = Layer.succeed(VmRepository, { findUserVm: (input) => dbEffect("findUserVm", async () => { const db = cloudDb(); + const conditions = [ + accountScopeWhere({ userId: input.userId, billingTeamId: input.billingTeamId }), + eq(cloudVms.providerVmId, input.providerVmId), + ne(cloudVms.status, "destroyed"), + ]; + if (input.provider) conditions.push(eq(cloudVms.provider, input.provider)); const [vm] = await db .select() .from(cloudVms) - .where( - and( - accountScopeWhere({ userId: input.userId, billingTeamId: input.billingTeamId }), - eq(cloudVms.providerVmId, input.providerVmId), - ne(cloudVms.status, "destroyed"), - ), - ) + .where(and(...conditions)) .limit(1); return vm ?? null; }), diff --git a/web/services/vms/workflows.ts b/web/services/vms/workflows.ts index 1cf88007f065..e4e0943c8dbc 100644 --- a/web/services/vms/workflows.ts +++ b/web/services/vms/workflows.ts @@ -81,6 +81,7 @@ type ExistingVmAccessInput = { readonly billingTeamId?: string | null; readonly teamIds?: readonly string[]; readonly providerVmId: string; + readonly provider?: ProviderId; }; export type VmProviderStatusReconcileResult = { @@ -1248,6 +1249,7 @@ export function destroyVm(input: { readonly billingTeamId?: string | null; readonly teamIds?: readonly string[]; readonly providerVmId: string; + readonly provider?: ProviderId; }) { return Effect.gen(function* () { const repo = yield* VmRepository; @@ -1569,6 +1571,7 @@ function requireUserVm(input: ExistingVmAccessInput) { userId: input.userId, billingTeamId: input.billingTeamId, providerVmId: input.providerVmId, + provider: input.provider, }); if (!vm || !vm.providerVmId) { return yield* Effect.fail(new VmNotFoundError({ vmId: input.providerVmId })); diff --git a/web/tests/account-route.test.ts b/web/tests/account-route.test.ts index d5a63be000cb..83f06ac6812d 100644 --- a/web/tests/account-route.test.ts +++ b/web/tests/account-route.test.ts @@ -16,6 +16,7 @@ import { vaultUploadGrants, vaultUploadTombstones, } from "../db/schema"; +import type { ProviderId } from "../services/vms/drivers"; process.env.RESEND_API_KEY ??= "test-resend-key"; process.env.CMUX_FEEDBACK_FROM_EMAIL ??= "feedback@example.com"; @@ -50,6 +51,10 @@ const realDestroyVm = workflowsModule.destroyVm; const realListUserVms = workflowsModule.listUserVms; const realRevokeUserIdentityLeasesForAccountDeletion = workflowsModule.revokeUserIdentityLeasesForAccountDeletion; const realRunVmWorkflow = workflowsModule.runVmWorkflow as (...args: unknown[]) => unknown; +type ListedAccountVm = string | { + readonly providerVmId: string; + readonly provider?: ProviderId; +}; const deleteStackUser = mock(async () => { routeEvents.push("stack-delete"); @@ -138,7 +143,11 @@ const runVmWorkflow = mock(async (...args: unknown[]) => { const providerVmIds = program.billingTeamId ? listedPersonalVmIdsByBillingTeam[program.billingTeamId] ?? [] : listedPersonalVmIds; - return providerVmIds.map((providerVmId) => ({ providerVmId })); + return providerVmIds.map((vm) => + typeof vm === "string" + ? { providerVmId: vm, provider: "freestyle" as ProviderId } + : { provider: "freestyle" as ProviderId, ...vm } + ); } if (program.kind === "revokeUserIdentityLeasesForAccountDeletion") { routeEvents.push("revoke-identities"); @@ -221,8 +230,8 @@ let stripeCancelError: unknown = null; let stripeDeleteCustomerError: unknown = null; let removeTesterError: unknown = null; let destroyVmFailureProviderIds = new Set(); -let listedPersonalVmIds: string[] = []; -let listedPersonalVmIdsByBillingTeam: Record = {}; +let listedPersonalVmIds: ListedAccountVm[] = []; +let listedPersonalVmIdsByBillingTeam: Record = {}; let revokeIdentityLeasesError: unknown = null; let subrouterClientCreateError: unknown = null; let subrouterRevokeError: unknown = null; @@ -241,6 +250,7 @@ type WorkflowProgram = readonly userId: string; readonly billingTeamId?: string | null; readonly providerVmId: string; + readonly provider?: ProviderId; }; }; @@ -505,11 +515,13 @@ describe("account deletion route", () => { userId: "account-user-1", teamIds: ["account-user-1"], providerVmId: "personal-vm-1", + provider: "freestyle", }); expect(destroyVm).toHaveBeenCalledWith({ userId: "account-user-1", teamIds: ["account-user-1"], providerVmId: "personal-vm-2", + provider: "freestyle", }); expect(transaction).toHaveBeenCalledTimes(3); expect(deletedTableCount).toBeGreaterThan(10); @@ -586,6 +598,31 @@ describe("account deletion route", () => { ]); }); + test("destroys personal VMs with the same provider id on different providers", async () => { + listedPersonalVmIds = [ + { providerVmId: "shared-provider-id", provider: "freestyle" }, + { providerVmId: "shared-provider-id", provider: "e2b" }, + ]; + + const response = await DELETE(accountDeletionRequest()); + + expect(response.status).toBe(200); + expect(await response.json()).toEqual({ ok: true, destroyedVms: 2 }); + expect(destroyVm).toHaveBeenCalledTimes(2); + expect(destroyVm).toHaveBeenCalledWith({ + userId: "account-user-1", + teamIds: ["account-user-1"], + providerVmId: "shared-provider-id", + provider: "freestyle", + }); + expect(destroyVm).toHaveBeenCalledWith({ + userId: "account-user-1", + teamIds: ["account-user-1"], + providerVmId: "shared-provider-id", + provider: "e2b", + }); + }); + test("destroys personal-team scoped VMs before deleting account rows", async () => { listedPersonalVmIds = []; listedPersonalVmIdsByBillingTeam = { "team-personal": ["personal-team-vm"] }; @@ -611,6 +648,7 @@ describe("account deletion route", () => { billingTeamId: "team-personal", teamIds: ["account-user-1", "team-personal"], providerVmId: "personal-team-vm", + provider: "freestyle", }); expect(cancelledStripeSubscriptions).toEqual(["sub_user_active", "sub_team_active"]); expect(deletedStripeCustomers).toEqual(["cus_user", "cus_team"]); @@ -677,6 +715,7 @@ describe("account deletion route", () => { billingTeamId: "team-shared", teamIds: ["account-user-1", "team-shared"], providerVmId: "shared-team-vm", + provider: "freestyle", }); expect(transactionExecute).toHaveBeenCalledTimes(3); }); @@ -1169,11 +1208,13 @@ describe("account deletion route", () => { userId: "account-user-1", teamIds: ["account-user-1"], providerVmId: "personal-vm-1", + provider: "freestyle", }); expect(destroyVm).toHaveBeenCalledWith({ userId: "account-user-1", teamIds: ["account-user-1"], providerVmId: "personal-vm-2", + provider: "freestyle", }); expect(transaction).toHaveBeenCalledTimes(1); expect(deleteStackUser).not.toHaveBeenCalled(); @@ -1207,11 +1248,13 @@ describe("account deletion route", () => { userId: "account-user-1", teamIds: ["account-user-1"], providerVmId: "personal-vm-1", + provider: "freestyle", }); expect(destroyVm).toHaveBeenCalledWith({ userId: "account-user-1", teamIds: ["account-user-1"], providerVmId: "personal-vm-2", + provider: "freestyle", }); expect(transaction).toHaveBeenCalledTimes(1); expect(deleteStackUser).not.toHaveBeenCalled(); diff --git a/web/tests/billing-purchase.test.ts b/web/tests/billing-purchase.test.ts index f236f02d1c67..b5234c8d592a 100644 --- a/web/tests/billing-purchase.test.ts +++ b/web/tests/billing-purchase.test.ts @@ -659,6 +659,43 @@ describe("recordCheckoutCompletion", () => { }); }); + test("skips Team subscription webhooks for deleted-account owner rows", async () => { + const getTeam = mock(async () => { + throw new Error("should not load Stack team for deleted account owner"); + }); + selectResults = [[{ stackUserId: "deleted-account" }]]; + + const result = await applySubscriptionUpdate( + { + id: "sub_team", + customer: "cus_team", + status: "canceled", + metadata: { stackTeamId: "team_123", plan: "team", app: "cmux" }, + cancel_at_period_end: false, + items: { + data: [ + { + quantity: 7, + current_period_end: 1_800_000_000, + price: { id: "price_team" }, + }, + ], + }, + } as never, + { + db: fakeDb() as never, + stackApp: { + getTeam, + } as never, + }, + ); + + expect(result).toEqual({ skipped: true }); + expect(getTeam).not.toHaveBeenCalled(); + expect(inserts.some((insert) => insert.table === stripeSubscriptions)).toBe(false); + expect(updates.some((update) => update.table === stripeSubscriptions)).toBe(false); + }); + test("removes a user from TestFlight when a user Pro subscription lapses", async () => { const update = mock(async () => undefined); const removeTester = mock(async () => undefined); From efec72fb2fbfc0db0c8cdeaa4a2c3dd129ffbf18 Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Thu, 9 Jul 2026 04:52:25 -0700 Subject: [PATCH 59/89] Keep team checkout customers during deletion --- web/services/billing/purchase.ts | 28 +++++++++++++++++++++------- web/tests/billing-purchase.test.ts | 4 ++-- 2 files changed, 23 insertions(+), 9 deletions(-) diff --git a/web/services/billing/purchase.ts b/web/services/billing/purchase.ts index 37eea1918f19..532aeee651f0 100644 --- a/web/services/billing/purchase.ts +++ b/web/services/billing/purchase.ts @@ -234,11 +234,7 @@ async function deleteCheckoutStripeResourcesForAccountDeletion( dependencies: BillingPurchaseDependencies, ): Promise { const client = (dependencies.stripeClient ?? stripe)(); - try { - await client.subscriptions.cancel(subscription.id); - } catch (error) { - if (!isStripeSubscriptionAlreadyCanceledError(error)) throw error; - } + await cancelCheckoutSubscription(client, subscription.id); try { await client.customers.del(customerId); } catch (error) { @@ -247,6 +243,25 @@ async function deleteCheckoutStripeResourcesForAccountDeletion( } } +async function cancelCheckoutSubscriptionForAccountDeletion( + subscription: Stripe.Subscription, + dependencies: BillingPurchaseDependencies, +): Promise { + const client = (dependencies.stripeClient ?? stripe)(); + await cancelCheckoutSubscription(client, subscription.id); +} + +async function cancelCheckoutSubscription( + client: Pick, "subscriptions">, + subscriptionId: string, +): Promise { + try { + await client.subscriptions.cancel(subscriptionId); + } catch (error) { + if (!isStripeSubscriptionAlreadyCanceledError(error)) throw error; + } +} + export async function applySubscriptionUpdate( subscription: Stripe.Subscription, dependencies: BillingPurchaseDependencies = {}, @@ -574,9 +589,8 @@ async function recordTeamCheckoutCompletion(input: { }); if (lockedResult.deleteCheckoutStripeResources) { - await deleteCheckoutStripeResourcesForAccountDeletion( + await cancelCheckoutSubscriptionForAccountDeletion( input.subscription, - input.customerId, input.dependencies, ); } diff --git a/web/tests/billing-purchase.test.ts b/web/tests/billing-purchase.test.ts index b5234c8d592a..695c180d4ed0 100644 --- a/web/tests/billing-purchase.test.ts +++ b/web/tests/billing-purchase.test.ts @@ -570,7 +570,7 @@ describe("recordCheckoutCompletion", () => { }); }); - test("blocks Team checkout completion while the billing owner is deleting their account", async () => { + test("blocks Team checkout completion while the billing owner is deleting without deleting the team customer", async () => { const cancelSubscription = mock(async () => undefined); const deleteCustomer = mock(async () => undefined); const owner = { @@ -602,7 +602,7 @@ describe("recordCheckoutCompletion", () => { }); expect(cancelSubscription).toHaveBeenCalledWith("sub_team"); - expect(deleteCustomer).toHaveBeenCalledWith("cus_team"); + expect(deleteCustomer).not.toHaveBeenCalled(); expect(inserts).toHaveLength(0); expect(updates).toHaveLength(0); expect(owner.update).not.toHaveBeenCalled(); From 2d196e43785b93d1f491ecfcb19261b16611d170 Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Thu, 9 Jul 2026 05:02:43 -0700 Subject: [PATCH 60/89] Keep account deletion leases fresh --- web/app/api/account/route.ts | 55 +++++++++++++++++++++++++++--- web/services/billing/purchase.ts | 15 ++++---- web/tests/account-route.test.ts | 9 +++++ web/tests/billing-purchase.test.ts | 20 ++--------- 4 files changed, 70 insertions(+), 29 deletions(-) diff --git a/web/app/api/account/route.ts b/web/app/api/account/route.ts index 70025d4fa620..16a325fbe036 100644 --- a/web/app/api/account/route.ts +++ b/web/app/api/account/route.ts @@ -112,6 +112,9 @@ export async function DELETE(request: Request): Promise { restoreBillingEntitlementsOnFailure = false; destructiveCleanupStarted = true; }, + afterExternalMutation: async () => { + await refreshAccountDeletionTombstoneLease(userId); + }, }, ); await removeTestFlightAccessForAccountDeletion(stackUser, { @@ -120,8 +123,13 @@ export async function DELETE(request: Request): Promise { destructiveCleanupStarted = true; }, }); + await refreshAccountDeletionTombstoneLease(userId); try { - destroyedVms = await destroyPersonalCloudVms(userId, accountScope.teamIds); + destroyedVms = await destroyPersonalCloudVms(userId, accountScope.teamIds, { + afterVmDestroy: async () => { + await refreshAccountDeletionTombstoneLease(userId); + }, + }); if (destroyedVms > 0) destructiveCleanupStarted = true; } catch (error) { if (error instanceof AccountDeletionDestructiveCleanupError) { @@ -134,12 +142,16 @@ export async function DELETE(request: Request): Promise { beforeObjectDeletion: () => { destructiveCleanupStarted = true; }, + afterObjectDeletion: async () => { + await refreshAccountDeletionTombstoneLease(userId); + }, }); await deletePersonalSubrouterTenant(userId, { afterExternalMutation: () => { destructiveCleanupStarted = true; }, }, accountScope.teamIds); + await refreshAccountDeletionTombstoneLease(userId); try { const revokedIdentityLeases = await runVmWorkflow(revokeUserIdentityLeasesForAccountDeletion(userId)); if (revokedIdentityLeases > 0) destructiveCleanupStarted = true; @@ -147,6 +159,7 @@ export async function DELETE(request: Request): Promise { if (isVmAccountDeletionIdentityRevocationError(error)) destructiveCleanupStarted = true; throw error; } + await refreshAccountDeletionTombstoneLease(userId); // Delete cmux-owned data before the Stack user so a Stack-side failure does // not strand retained app data behind an account the user can no longer use. // These deletes are idempotent, so the same signed-in user can retry the @@ -289,6 +302,21 @@ async function markAccountDeletionTombstoneFailed(userId: string, error: unknown .where(eq(accountDeletionTombstones.userIdHash, accountDeletionUserHash(userId))); } +async function refreshAccountDeletionTombstoneLease(userId: string): Promise { + await cloudDb() + .update(accountDeletionTombstones) + .set({ updatedAt: new Date() }) + .where(and( + eq(accountDeletionTombstones.userIdHash, accountDeletionUserHash(userId)), + inArray(accountDeletionTombstones.status, [ + "pending", + "in_progress", + "stack_delete_pending", + "stack_delete_in_progress", + ]), + )); +} + class AccountDeletionDestructiveCleanupError extends Error { constructor( message: string, @@ -300,7 +328,11 @@ class AccountDeletionDestructiveCleanupError extends Error { } } -async function destroyPersonalCloudVms(userId: string, accountTeamIds: readonly string[]): Promise { +async function destroyPersonalCloudVms( + userId: string, + accountTeamIds: readonly string[], + options: { readonly afterVmDestroy?: () => Promise } = {}, +): Promise { const vms = await listAccountDeletionCloudVms(userId, accountTeamIds); const failures: unknown[] = []; let destroyedVms = 0; @@ -324,6 +356,7 @@ async function destroyPersonalCloudVms(userId: string, accountTeamIds: readonly destructiveCleanupStarted = true; await runVmWorkflow(destroyProgram); destroyedVms += 1; + await options.afterVmDestroy?.(); } catch (error) { failures.push(error); logAccountDeleteError("account.delete.vm_destroy_failed", error); @@ -374,7 +407,10 @@ function accountDeletionVmKey(vm: { readonly provider: ProviderId; readonly prov async function deleteVaultRowsAndObjectsForAccount( userId: string, - options: { readonly beforeObjectDeletion?: () => void } = {}, + options: { + readonly beforeObjectDeletion?: () => void; + readonly afterObjectDeletion?: () => Promise; + } = {}, ): Promise { const db = cloudDb(); @@ -390,6 +426,7 @@ async function deleteVaultRowsAndObjectsForAccount( options.beforeObjectDeletion?.(); await Promise.all(snapshots.map((snapshot) => deleteObject(snapshot.objectKey))); await db.delete(vaultSnapshots).where(inArray(vaultSnapshots.id, snapshots.map((snapshot) => snapshot.id))); + await options.afterObjectDeletion?.(); if (snapshots.length < VAULT_OBJECT_DELETE_BATCH_SIZE) break; } @@ -411,6 +448,7 @@ async function deleteVaultRowsAndObjectsForAccount( deleteObject(grant.uploadObjectKey), ])); await db.delete(vaultUploadGrants).where(inArray(vaultUploadGrants.id, grants.map((grant) => grant.id))); + await options.afterObjectDeletion?.(); if (grants.length < VAULT_OBJECT_DELETE_BATCH_SIZE) break; } @@ -434,6 +472,7 @@ async function deleteVaultRowsAndObjectsForAccount( await db .delete(vaultUploadTombstones) .where(inArray(vaultUploadTombstones.id, tombstones.map((tombstone) => tombstone.id))); + await options.afterObjectDeletion?.(); if (tombstones.length < VAULT_OBJECT_DELETE_BATCH_SIZE) break; } @@ -448,6 +487,7 @@ async function deleteVaultRowsAndObjectsForAccount( options.beforeObjectDeletion?.(); await Promise.all(sessions.map((session) => deleteObject(session.latestObjectKey))); await db.delete(vaultSessions).where(inArray(vaultSessions.id, sessions.map((session) => session.id))); + await options.afterObjectDeletion?.(); if (sessions.length < VAULT_OBJECT_DELETE_BATCH_SIZE) break; } } @@ -461,7 +501,10 @@ async function resolveUserBillingForAccountDeletion( userId: string, accountTeamIds: readonly string[], retainedTeamBillingOwners: readonly RetainedTeamBillingOwner[], - options: { readonly beforeExternalRequest?: () => void } = {}, + options: { + readonly beforeExternalRequest?: () => void; + readonly afterExternalMutation?: () => Promise; + } = {}, ): Promise { const db = cloudDb(); const deletionTeamIds = uniqueNonEmptyStrings([userId, ...accountTeamIds]); @@ -524,6 +567,7 @@ async function resolveUserBillingForAccountDeletion( deletedAccountId: deletedStripeAccountId(userId), }, }); + await options.afterExternalMutation?.(); await db .update(stripeCustomers) .set({ @@ -543,6 +587,7 @@ async function resolveUserBillingForAccountDeletion( deletedAccountId: deletedStripeAccountId(userId), }, }); + await options.afterExternalMutation?.(); await db .update(stripeSubscriptions) .set({ @@ -555,10 +600,12 @@ async function resolveUserBillingForAccountDeletion( for (const subscription of activeSubscriptions) { options.beforeExternalRequest?.(); await cancelStripeSubscriptionForAccountDeletion(client, subscription.id); + await options.afterExternalMutation?.(); } for (const customer of customers) { options.beforeExternalRequest?.(); await deleteStripeCustomerForAccountDeletion(client, customer.id); + await options.afterExternalMutation?.(); } } diff --git a/web/services/billing/purchase.ts b/web/services/billing/purchase.ts index 532aeee651f0..0cf5c7c11dd5 100644 --- a/web/services/billing/purchase.ts +++ b/web/services/billing/purchase.ts @@ -331,20 +331,19 @@ export async function applySubscriptionUpdate( !mappedStackUserId && metadataStackUserId === stackUserId; + if (await hasCheckoutBlockingAccountDeletionTombstone(stackUserId, db)) return { skipped: true }; + const user = await loadOptionalStackUser(stackUserId, dependencies.stackApp); + if (!user && isMetadataOnlyUserSubscription) return { skipped: true }; + if (!user) throw new Error(`Stack user not found for Stripe subscription update: ${stackUserId}`); + if (isAccountDeletionInProgress(user)) return { skipped: true }; + if (hasUserSubscription) { await updateExistingUserStripeSubscription(db, { subscription, customerId, stackUserId, }); - } - - const user = await loadOptionalStackUser(stackUserId, dependencies.stackApp); - if (!user && isMetadataOnlyUserSubscription) return { skipped: true }; - if (!user) throw new Error(`Stack user not found for Stripe subscription update: ${stackUserId}`); - if (isAccountDeletionInProgress(user)) return { skipped: true }; - - if (!hasUserSubscription) { + } else { await upsertStripeSubscription(db, { subscription, customerId, diff --git a/web/tests/account-route.test.ts b/web/tests/account-route.test.ts index 83f06ac6812d..fcb898e835de 100644 --- a/web/tests/account-route.test.ts +++ b/web/tests/account-route.test.ts @@ -573,6 +573,15 @@ describe("account deletion route", () => { ); expect(completedTombstone).toBeTruthy(); expect((completedTombstone as { readonly completedAt?: unknown }).completedAt).toBeInstanceOf(Date); + const leaseRefreshes = tombstoneUpdates.filter((update) => + Boolean( + update && + typeof update === "object" && + (update as { readonly updatedAt?: unknown }).updatedAt instanceof Date && + !("status" in update), + ) + ); + expect(leaseRefreshes.length).toBeGreaterThanOrEqual(3); expect(routeEvents).toEqual([ "transaction", "transaction-lock", diff --git a/web/tests/billing-purchase.test.ts b/web/tests/billing-purchase.test.ts index 695c180d4ed0..844e9efcb9f2 100644 --- a/web/tests/billing-purchase.test.ts +++ b/web/tests/billing-purchase.test.ts @@ -811,7 +811,7 @@ describe("recordCheckoutCompletion", () => { expect(updates.some((update) => update.table === stripeSubscriptions)).toBe(false); }); - test("records known subscription webhooks before skipping deleting account metadata", async () => { + test("skips known subscription webhooks before writing rows while account deletion is in progress", async () => { const update = mock(async () => undefined); const getUser = mock(async () => ({ id: "user_123", @@ -832,14 +832,7 @@ describe("recordCheckoutCompletion", () => { expect(result).toEqual({ skipped: true }); expect(getUser).toHaveBeenCalledWith("user_123"); expect(update).not.toHaveBeenCalled(); - expect( - updates.some( - (entry) => - entry.table === stripeSubscriptions && - entry.values.status === "canceled" && - entry.values.stackUserId === "user_123", - ), - ).toBe(true); + expect(updates.some((entry) => entry.table === stripeSubscriptions)).toBe(false); expect(inserts.some((insert) => insert.table === stripeSubscriptions)).toBe(false); }); @@ -858,14 +851,7 @@ describe("recordCheckoutCompletion", () => { ).rejects.toThrow("Stack user not found for Stripe subscription update: user_123"); expect(getUser).toHaveBeenCalledWith("user_123"); - expect( - updates.some( - (entry) => - entry.table === stripeSubscriptions && - entry.values.status === "canceled" && - entry.values.stackUserId === "user_123", - ), - ).toBe(true); + expect(updates.some((entry) => entry.table === stripeSubscriptions)).toBe(false); expect(inserts.some((insert) => insert.table === stripeSubscriptions)).toBe(false); }); From 69f326f5b15b99136b82c4ac354277da94ec0b6f Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Thu, 9 Jul 2026 05:17:15 -0700 Subject: [PATCH 61/89] Close account deletion VM cleanup gaps --- web/app/api/account/route.ts | 16 ++++++++++++++-- web/services/vms/routeHelpers.ts | 13 +++++++++++++ web/services/vms/workflows.ts | 6 +++++- web/tests/account-route.test.ts | 26 +++++++++++++++++++++----- web/tests/vm-route-auth.test.ts | 30 ++++++++++++++++++++++++++++++ web/tests/vm-workflows.test.ts | 10 +++++++++- 6 files changed, 92 insertions(+), 9 deletions(-) diff --git a/web/app/api/account/route.ts b/web/app/api/account/route.ts index 16a325fbe036..f0db8ef56741 100644 --- a/web/app/api/account/route.ts +++ b/web/app/api/account/route.ts @@ -1,4 +1,5 @@ import { and, asc, eq, inArray, isNotNull, isNull, or, sql } from "drizzle-orm"; +import * as Effect from "effect/Effect"; import { getStackServerApp, isStackConfigured } from "../../lib/stack"; import { cloudDb } from "../../../db/client"; @@ -47,7 +48,10 @@ import { isBlockingAccountDeletionStatus, } from "../../../services/account/deletionLock"; import { unauthorized } from "../../../services/vms/auth"; -import { isVmAccountDeletionIdentityRevocationError } from "../../../services/vms/errors"; +import { + VmAccountDeletionIdentityRevocationError, + isVmAccountDeletionIdentityRevocationError, +} from "../../../services/vms/errors"; import type { ProviderId } from "../../../services/vms/drivers"; import { jsonResponse } from "../../../services/vms/routeHelpers"; import { @@ -153,7 +157,15 @@ export async function DELETE(request: Request): Promise { }, accountScope.teamIds); await refreshAccountDeletionTombstoneLease(userId); try { - const revokedIdentityLeases = await runVmWorkflow(revokeUserIdentityLeasesForAccountDeletion(userId)); + const revokedIdentityLeases = await runVmWorkflow( + revokeUserIdentityLeasesForAccountDeletion(userId, { + afterBatch: () => + Effect.tryPromise({ + try: () => refreshAccountDeletionTombstoneLease(userId), + catch: (cause) => new VmAccountDeletionIdentityRevocationError({ cause }), + }), + }), + ); if (revokedIdentityLeases > 0) destructiveCleanupStarted = true; } catch (error) { if (isVmAccountDeletionIdentityRevocationError(error)) destructiveCleanupStarted = true; diff --git a/web/services/vms/routeHelpers.ts b/web/services/vms/routeHelpers.ts index 2b02fe200bb3..c72d26420134 100644 --- a/web/services/vms/routeHelpers.ts +++ b/web/services/vms/routeHelpers.ts @@ -8,6 +8,7 @@ import { } from "./entitlements"; import { isVmBillingError, + isVmCreateDisabledError, isVmDatabaseError, isVmProviderOperationError, vmWorkflowErrorCause, @@ -256,6 +257,18 @@ export function vmRequiresProResponse(): Response { export function vmWorkflowErrorResponse(err: unknown): Response | null { const workflowError = vmWorkflowErrorCause(err) ?? err; + if (isVmCreateDisabledError(workflowError)) { + return vmErrorResponse({ + error: "vm_create_disabled", + status: 503, + message: "Cloud VM creation is disabled for this environment.", + action: "Ask an admin to enable Cloud VM creation, then retry.", + reason: workflowError.reason, + phase: "create", + retryable: true, + }); + } + if (isVmProviderOperationError(workflowError)) { const providerCause = providerCauseSummary(workflowError.cause); const phase = vmPhaseForOperation(workflowError.operation); diff --git a/web/services/vms/workflows.ts b/web/services/vms/workflows.ts index e4e0943c8dbc..a684ed88b118 100644 --- a/web/services/vms/workflows.ts +++ b/web/services/vms/workflows.ts @@ -1316,7 +1316,10 @@ export function revokeExpiredIdentityLeases(input: { export function revokeUserIdentityLeasesForAccountDeletion( userId: string, - input: { readonly limit?: number } = {}, + input: { + readonly limit?: number; + readonly afterBatch?: () => Effect.Effect; + } = {}, ) { const limit = boundedAccountDeletionIdentityRevokeLimit(input.limit); return Effect.gen(function* () { @@ -1346,6 +1349,7 @@ export function revokeUserIdentityLeasesForAccountDeletion( yield* markAccountDeletionLeasesRevoked(repo, revokedIds); revokedCount += revokedIds.length; + if (input.afterBatch) yield* input.afterBatch(); if (leases.length < limit) return revokedCount; } }); diff --git a/web/tests/account-route.test.ts b/web/tests/account-route.test.ts index fcb898e835de..6492a7d9679a 100644 --- a/web/tests/account-route.test.ts +++ b/web/tests/account-route.test.ts @@ -123,10 +123,15 @@ const listUserVms = mock((...args: unknown[]) => { return { kind: "listUserVms" as const, userId, billingTeamId }; }); const revokeUserIdentityLeasesForAccountDeletion = mock((...args: unknown[]) => { - const [userId] = args as [string]; + const [userId, input] = args as [ + string, + { readonly afterBatch?: () => unknown } | undefined, + ]; + lastRevokeIdentityCall = { userId, afterBatch: input?.afterBatch }; return { kind: "revokeUserIdentityLeasesForAccountDeletion" as const, userId, + afterBatch: input?.afterBatch, }; }); const destroyVm = mock((...args: unknown[]) => { @@ -238,12 +243,17 @@ let subrouterRevokeError: unknown = null; let stackUserSelectedTeam: unknown = null; let stackUserTeams: readonly unknown[] = []; let useAccountRouteStubs = false; +let lastRevokeIdentityCall: { readonly userId: string; readonly afterBatch?: unknown } | null = null; const originalConsoleError = console.error; const consoleError = mock(() => {}); type WorkflowProgram = | { readonly kind: "listUserVms"; readonly userId: string; readonly billingTeamId?: string | null } - | { readonly kind: "revokeUserIdentityLeasesForAccountDeletion"; readonly userId: string } + | { + readonly kind: "revokeUserIdentityLeasesForAccountDeletion"; + readonly userId: string; + readonly afterBatch?: () => unknown; + } | { readonly kind: "destroyVm"; readonly input: { @@ -476,6 +486,7 @@ beforeEach(() => { listedPersonalVmIds = ["personal-vm-1", "personal-vm-2"]; listedPersonalVmIdsByBillingTeam = {}; revokeIdentityLeasesError = null; + lastRevokeIdentityCall = null; subrouterClientCreateError = null; subrouterRevokeError = null; stackUserSelectedTeam = null; @@ -823,7 +834,7 @@ describe("account deletion route", () => { const response = await DELETE(accountDeletionRequest()); expect(response.status).toBe(200); - expect(revokeUserIdentityLeasesForAccountDeletion).toHaveBeenCalledWith("account-user-1"); + expectIdentityRevocationHeartbeatConfigured(); expect(routeEvents.indexOf("revoke-identities")).toBeGreaterThan(-1); expect(routeEvents.indexOf("revoke-identities")).toBeLessThan(routeEvents.lastIndexOf("transaction")); expect(deletedTables).toContain(cloudVmLeases); @@ -866,7 +877,7 @@ describe("account deletion route", () => { retryable: true, destroyedVms: 0, }); - expect(revokeUserIdentityLeasesForAccountDeletion).toHaveBeenCalledWith("account-user-1"); + expectIdentityRevocationHeartbeatConfigured(); expect(transaction).toHaveBeenCalledTimes(1); expect(deleteStackUser).not.toHaveBeenCalled(); expect(updateStackUser).toHaveBeenNthCalledWith(1, { @@ -886,7 +897,7 @@ describe("account deletion route", () => { retryable: true, destroyedVms: 2, }); - expect(revokeUserIdentityLeasesForAccountDeletion).toHaveBeenCalledWith("account-user-1"); + expectIdentityRevocationHeartbeatConfigured(); expect(transaction).toHaveBeenCalledTimes(1); expect(deleteStackUser).not.toHaveBeenCalled(); expect(deletedTables).not.toContain(cloudVmLeases); @@ -1508,3 +1519,8 @@ function isAccountDeletionWorkflowProgram(program: unknown): boolean { if (candidate.kind === "destroyVm") return candidate.input?.userId === ACCOUNT_USER_ID; return false; } + +function expectIdentityRevocationHeartbeatConfigured(): void { + expect(lastRevokeIdentityCall?.userId).toBe(ACCOUNT_USER_ID); + expect(typeof lastRevokeIdentityCall?.afterBatch).toBe("function"); +} diff --git a/web/tests/vm-route-auth.test.ts b/web/tests/vm-route-auth.test.ts index 81d26de58b43..1495de65c601 100644 --- a/web/tests/vm-route-auth.test.ts +++ b/web/tests/vm-route-auth.test.ts @@ -138,6 +138,7 @@ const sshRoute = await import("../app/api/vm/[id]/ssh-endpoint/route"); const restoreRoute = await import("../app/api/vm/restore/route"); const { VmCreateCreditsInsufficientError, + VmCreateDisabledError, VmCreateFailedError, VmProviderOperationError, } = await import("../services/vms/errors"); @@ -1253,6 +1254,35 @@ describe("VM REST auth", () => { expect(runVmWorkflow).not.toHaveBeenCalled(); }); + test("maps workflow VM create kill switch without an internal error", async () => { + getUser.mockResolvedValue(authedStackUser()); + rejectRunVmWorkflowWith( + new VmCreateDisabledError({ + provider: "freestyle", + reason: "Account deletion is in progress.", + }), + ); + + const response = await POST( + new Request("https://cmux.test/api/vm", { + method: "POST", + headers: { origin: "https://cmux.test" }, + body: JSON.stringify({ provider: "freestyle", image: "snapshot-test" }), + }), + ); + + expect(response.status).toBe(503); + const payload = await response.json(); + expect(payload).toMatchObject({ + error: "vm_create_disabled", + reason: "Account deletion is in progress.", + phase: "create", + }); + expectNoCloudVmImplementationLeaks(payload); + expect(payload.action).toContain("enable Cloud VM creation"); + expect(runVmWorkflow).toHaveBeenCalled(); + }); + test("blocks provider kill switch before workflow", async () => { process.env.CMUX_VM_E2B_ENABLED = "false"; getUser.mockResolvedValue(authedStackUser()); diff --git a/web/tests/vm-workflows.test.ts b/web/tests/vm-workflows.test.ts index e935800e723a..5d339cca8a0b 100644 --- a/web/tests/vm-workflows.test.ts +++ b/web/tests/vm-workflows.test.ts @@ -477,6 +477,7 @@ describe("VM Effect workflows", () => { test("revokes account-deletion SSH identities in bounded batches", async () => { const requestedLimits: number[] = []; + const refreshedAfterBatch: number[] = []; const leaseBatches = [ [ testIdentityLease("lease-account-delete-1", "identity-account-delete-1"), @@ -506,7 +507,13 @@ describe("VM Effect workflows", () => { }; const revokedCount = await Effect.runPromise( - revokeUserIdentityLeasesForAccountDeletion("user-workflow-account-delete", { limit: 2 }).pipe( + revokeUserIdentityLeasesForAccountDeletion("user-workflow-account-delete", { + limit: 2, + afterBatch: () => + Effect.sync(() => { + refreshedAfterBatch.push(revokedLeaseBatches.length); + }), + }).pipe( Effect.provide(workflowLayer(repo, provider)), ), ); @@ -522,6 +529,7 @@ describe("VM Effect workflows", () => { ["lease-account-delete-1", "lease-account-delete-2"], ["lease-account-delete-3"], ]); + expect(refreshedAfterBatch).toEqual([1, 2]); }); test("keeps account-deletion SSH identity cleanup retryable when provider revocation fails", async () => { From 0bf7fb379068e1f1ea15766677343a27f0cc14b2 Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Thu, 9 Jul 2026 05:22:23 -0700 Subject: [PATCH 62/89] Keep incomplete account deletion retryable --- web/app/api/account/route.ts | 9 ++++++++- web/tests/account-route.test.ts | 9 +++++++-- 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/web/app/api/account/route.ts b/web/app/api/account/route.ts index f0db8ef56741..da81e68d05b8 100644 --- a/web/app/api/account/route.ts +++ b/web/app/api/account/route.ts @@ -190,10 +190,17 @@ export async function DELETE(request: Request): Promise { }, 500); } try { - await markAccountDeletionTombstoneCompleted(userId); await finishPostStackAccountCleanup(userId, accountScope.teamIds); + await markAccountDeletionTombstoneCompleted(userId); } catch (error) { logAccountDeleteError("account.delete.post_stack_cleanup_failed", error); + if (accountDeletionTombstoneStarted) { + try { + await markAccountDeletionTombstoneFailed(userId, error); + } catch (markFailedError) { + logAccountDeleteError("account.delete.post_stack_cleanup_mark_failed", markFailedError); + } + } return jsonResponse({ ok: true, cleanupIncomplete: true, diff --git a/web/tests/account-route.test.ts b/web/tests/account-route.test.ts index 6492a7d9679a..14a906dd7ed8 100644 --- a/web/tests/account-route.test.ts +++ b/web/tests/account-route.test.ts @@ -1384,8 +1384,10 @@ describe("account deletion route", () => { expect(deleteStackUser).toHaveBeenCalledTimes(1); expect(transaction).toHaveBeenCalledTimes(2); expect(tombstoneUpdates.some((values) => - (values as { readonly status?: unknown; readonly userId?: unknown }).status === "completed" && - (values as { readonly userId?: unknown }).userId === null + (values as { readonly status?: unknown }).status === "completed" + )).toBe(false); + expect(tombstoneUpdates.some((values) => + (values as { readonly status?: unknown }).status === "failed" )).toBe(true); expect(consoleError).toHaveBeenCalledWith( "account.delete.post_stack_cleanup_failed", @@ -1405,6 +1407,9 @@ describe("account deletion route", () => { destroyedVms: 2, }); expect(deleteStackUser).toHaveBeenCalledTimes(1); + expect(tombstoneUpdates.some((values) => + (values as { readonly status?: unknown }).status === "failed" + )).toBe(true); expect(consoleError).toHaveBeenCalledWith( "account.delete.post_stack_cleanup_failed", "Error: tombstone unavailable", From dbbef353118b8eadf013b859657a928c1b76b5fa Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Thu, 9 Jul 2026 05:33:38 -0700 Subject: [PATCH 63/89] Guard billing sync during account deletion --- web/services/billing/purchase.ts | 51 +++++++++++++++---- web/tests/billing-purchase.test.ts | 80 ++++++++++++++++++++++++++++-- 2 files changed, 115 insertions(+), 16 deletions(-) diff --git a/web/services/billing/purchase.ts b/web/services/billing/purchase.ts index 0cf5c7c11dd5..e78921bd4dee 100644 --- a/web/services/billing/purchase.ts +++ b/web/services/billing/purchase.ts @@ -216,16 +216,23 @@ async function syncUserCheckoutAfterCommit( db: BillingDb, input: UserCheckoutPostCommitSync, ): Promise { - if (input.email) { - await attachPurchaseEmailOrRecordClaim(db, { - user: input.user, - email: input.email, - stripeCustomerId: input.stripeCustomerId, - stackUserId: input.stackUserId, - stackApp: input.stackApp, - }); - } - await syncProPlanMetadata(input.user, true); + await syncStackUserMetadataWithAccountDeletionGuard({ + db, + stackUserId: input.stackUserId, + stackApp: input.stackApp, + sync: async (user, tx) => { + if (input.email) { + await attachPurchaseEmailOrRecordClaim(tx, { + user, + email: input.email, + stripeCustomerId: input.stripeCustomerId, + stackUserId: input.stackUserId, + stackApp: input.stackApp, + }); + } + await syncProPlanMetadata(user, true); + }, + }); } async function deleteCheckoutStripeResourcesForAccountDeletion( @@ -352,7 +359,14 @@ export async function applySubscriptionUpdate( }); } - await syncProPlanMetadata(user, isActive); + await syncStackUserMetadataWithAccountDeletionGuard({ + db, + stackUserId, + stackApp: dependencies.stackApp ?? stackServerApp, + sync: async (freshUser) => { + await syncProPlanMetadata(freshUser, isActive); + }, + }); if (!isActive) { await removeUserFromTestflightOnLapse(user, stackUserId, dependencies); } @@ -395,6 +409,21 @@ async function withAccountDeletionUserLock( }); } +async function syncStackUserMetadataWithAccountDeletionGuard(input: { + readonly db: BillingDb; + readonly stackUserId: string; + readonly stackApp: StackBillingApp | null | undefined; + readonly sync: (user: StackBillingUser, tx: BillingDbClient) => Promise; +}): Promise { + return await withAccountDeletionUserLock(input.db, input.stackUserId, async (tx) => { + if (await hasCheckoutBlockingAccountDeletionTombstone(input.stackUserId, tx)) return false; + const freshUser = await loadOptionalStackUser(input.stackUserId, input.stackApp); + if (!freshUser || isAccountDeletionInProgress(freshUser)) return false; + await input.sync(freshUser, tx); + return true; + }); +} + export async function latestStripeSubscriptionForSession( session: Stripe.Checkout.Session, db: BillingDb = cloudDb(), diff --git a/web/tests/billing-purchase.test.ts b/web/tests/billing-purchase.test.ts index 844e9efcb9f2..a67f77918965 100644 --- a/web/tests/billing-purchase.test.ts +++ b/web/tests/billing-purchase.test.ts @@ -256,9 +256,9 @@ describe("recordCheckoutCompletion", () => { expect(updates).toHaveLength(0); }); - test("syncs checkout metadata after the account deletion lock commits", async () => { + test("syncs checkout metadata under a fresh account deletion lock", async () => { let transactionOpen = false; - let lockAcquired = false; + let lockCount = 0; const baseDb = fakeDb(); const db = { ...baseDb, @@ -270,7 +270,7 @@ describe("recordCheckoutCompletion", () => { return await callback({ ...baseDb, execute: async (_query?: unknown) => { - lockAcquired = true; + lockCount += 1; }, }); } finally { @@ -279,8 +279,8 @@ describe("recordCheckoutCompletion", () => { }, }; const update = mock(async () => { - expect(transactionOpen).toBe(false); - expect(lockAcquired).toBe(true); + expect(transactionOpen).toBe(true); + expect(lockCount).toBe(2); }); const user = { id: "user_123", @@ -297,6 +297,39 @@ describe("recordCheckoutCompletion", () => { expect(update).toHaveBeenCalledWith({ clientReadOnlyMetadata: { cmuxPlan: "pro" }, }); + expect(lockCount).toBe(2); + }); + + test("skips checkout metadata sync when deletion starts after checkout rows commit", async () => { + const staleUpdate = mock(async () => undefined); + const deletingUpdate = mock(async () => undefined); + const staleUser = { + id: "user_123", + primaryEmail: "buyer@example.com", + clientReadOnlyMetadata: {}, + update: staleUpdate, + }; + const deletingUser = { + id: "user_123", + primaryEmail: "buyer@example.com", + clientReadOnlyMetadata: { cmuxAccountDeleting: true }, + update: deletingUpdate, + }; + let getUserCalls = 0; + const getUser = mock(async () => { + getUserCalls += 1; + return getUserCalls === 1 ? staleUser : deletingUser; + }); + + await recordCheckoutCompletion(checkoutInput() as never, { + db: fakeDb() as never, + stackApp: { getUser } as never, + }); + + expect(getUser).toHaveBeenCalledTimes(2); + expect(inserts.some((insert) => insert.table === stripeSubscriptions)).toBe(true); + expect(staleUpdate).not.toHaveBeenCalled(); + expect(deletingUpdate).not.toHaveBeenCalled(); }); test("records an email claim instead of attaching an email owned by a different Stack user", async () => { @@ -836,6 +869,43 @@ describe("recordCheckoutCompletion", () => { expect(inserts.some((insert) => insert.table === stripeSubscriptions)).toBe(false); }); + test("skips subscription metadata sync when deletion starts after webhook rows update", async () => { + const staleUpdate = mock(async () => undefined); + const deletingUpdate = mock(async () => undefined); + const staleUser = { + id: "user_123", + primaryEmail: "buyer@example.com", + clientReadOnlyMetadata: { cmuxPlan: "pro" }, + update: staleUpdate, + }; + const deletingUser = { + id: "user_123", + primaryEmail: "buyer@example.com", + clientReadOnlyMetadata: { cmuxAccountDeleting: true, cmuxPlan: "pro" }, + update: deletingUpdate, + }; + let getUserCalls = 0; + const getUser = mock(async () => { + getUserCalls += 1; + return getUserCalls === 1 ? staleUser : deletingUser; + }); + selectResults = [[], []]; + + const result = await applySubscriptionUpdate( + userSubscriptionUpdate({ status: "canceled" }) as never, + { + db: fakeDb() as never, + stackApp: { getUser } as never, + }, + ); + + expect(result).toEqual({ scope: "user", stackUserId: "user_123", isActive: false }); + expect(getUser).toHaveBeenCalledTimes(2); + expect(inserts.some((insert) => insert.table === stripeSubscriptions)).toBe(true); + expect(staleUpdate).not.toHaveBeenCalled(); + expect(deletingUpdate).not.toHaveBeenCalled(); + }); + test("fails known subscription webhooks when the Stack user is missing", async () => { const getUser = mock(async () => null); selectResults = [[{ stackUserId: "user_123" }], [{ id: "sub_user" }]]; From fdb94658af0c8648abbfd6e6770ded586052e885 Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Thu, 9 Jul 2026 05:46:41 -0700 Subject: [PATCH 64/89] Skip tombstoned team billing webhooks --- web/services/billing/purchase.ts | 73 ++++++++++++++++++++++++------ web/tests/billing-purchase.test.ts | 72 +++++++++++++++++++++++++---- 2 files changed, 123 insertions(+), 22 deletions(-) diff --git a/web/services/billing/purchase.ts b/web/services/billing/purchase.ts index e78921bd4dee..72cfecc292ef 100644 --- a/web/services/billing/purchase.ts +++ b/web/services/billing/purchase.ts @@ -298,23 +298,59 @@ export async function applySubscriptionUpdate( ) return { skipped: true }; const stackUserId = mappedStackUserId ?? metadataStackUserId ?? teamScope.stackTeamId; if (stackUserId === DELETED_ACCOUNT_ACTOR_ID) return { skipped: true }; - await upsertTeamStripeCustomer(db, { - customerId, - stackUserId, - stackTeamId: teamScope.stackTeamId, - }); - await upsertStripeSubscription(db, { - subscription, - customerId, - stackUserId, - stackTeamId: teamScope.stackTeamId, - scope: "team", - }); - const isActive = isActiveStripeSubscriptionStatus(subscription.status); + const ownerStackUserId = teamSubscriptionOwnerStackUserId(stackUserId, teamScope.stackTeamId); + const lockedResult = await withAccountDeletionUserLock( + db, + ownerStackUserId ?? stackUserId, + async (tx): Promise< + | { skipped: true } + | { scope: "team"; stackTeamId: string; isActive: boolean } + > => { + const transactionMappedStackUserId = await stackUserIdForTeamStripeCustomer(tx, { + stackTeamId: teamScope.stackTeamId, + customerId, + }); + if (transactionMappedStackUserId === DELETED_ACCOUNT_ACTOR_ID) return { skipped: true }; + if ( + metadataStackUserId && + transactionMappedStackUserId && + metadataStackUserId !== transactionMappedStackUserId + ) return { skipped: true }; + + const transactionStackUserId = transactionMappedStackUserId ?? metadataStackUserId ?? teamScope.stackTeamId; + if (transactionStackUserId === DELETED_ACCOUNT_ACTOR_ID) return { skipped: true }; + const transactionOwnerStackUserId = teamSubscriptionOwnerStackUserId( + transactionStackUserId, + teamScope.stackTeamId, + ); + if (transactionOwnerStackUserId !== ownerStackUserId) return { skipped: true }; + if (transactionOwnerStackUserId) { + if (await hasCheckoutBlockingAccountDeletionTombstone(transactionOwnerStackUserId, tx)) return { skipped: true }; + const owner = await loadOptionalStackUser(transactionOwnerStackUserId, dependencies.stackApp); + if (!owner || isAccountDeletionInProgress(owner)) return { skipped: true }; + } + + await upsertTeamStripeCustomer(tx, { + customerId, + stackUserId: transactionStackUserId, + stackTeamId: teamScope.stackTeamId, + }); + await upsertStripeSubscription(tx, { + subscription, + customerId, + stackUserId: transactionStackUserId, + stackTeamId: teamScope.stackTeamId, + scope: "team", + }); + + return { scope: "team", stackTeamId: teamScope.stackTeamId, isActive }; + }, + ); + if ("skipped" in lockedResult) return { skipped: true }; const team = await loadStackTeam(teamScope.stackTeamId, dependencies.stackApp); await syncTeamPlanMetadata(team, isActive); - return { scope: "team", stackTeamId: teamScope.stackTeamId, isActive }; + return lockedResult; } const metadataStackUserId = subscription.metadata?.stackUserId; @@ -424,6 +460,15 @@ async function syncStackUserMetadataWithAccountDeletionGuard(input: { }); } +function teamSubscriptionOwnerStackUserId( + stackUserId: string, + stackTeamId: string, +): string | null { + return stackUserId !== stackTeamId && stackUserId !== DELETED_ACCOUNT_ACTOR_ID + ? stackUserId + : null; +} + export async function latestStripeSubscriptionForSession( session: Stripe.Checkout.Session, db: BillingDb = cloudDb(), diff --git a/web/tests/billing-purchase.test.ts b/web/tests/billing-purchase.test.ts index a67f77918965..d612c37f590a 100644 --- a/web/tests/billing-purchase.test.ts +++ b/web/tests/billing-purchase.test.ts @@ -648,7 +648,7 @@ describe("recordCheckoutCompletion", () => { clientReadOnlyMetadata: { cmuxPlan: "team", cmuxVmPlan: "pro" }, update: updateTeam, }; - selectResults = [[{ stackUserId: "owner_123" }], []]; + selectResults = [[{ stackUserId: "owner_123" }], [{ stackUserId: "owner_123" }], []]; const result = await applySubscriptionUpdate( { @@ -670,9 +670,12 @@ describe("recordCheckoutCompletion", () => { { db: fakeDb() as never, stackApp: { - getUser: async () => { - throw new Error("should not load Stack user for Team subscription"); - }, + getUser: async () => ({ + id: "owner_123", + primaryEmail: "owner@example.com", + clientReadOnlyMetadata: {}, + update: mock(async () => undefined), + }), getTeam: async () => team, } as never, }, @@ -729,6 +732,56 @@ describe("recordCheckoutCompletion", () => { expect(updates.some((update) => update.table === stripeSubscriptions)).toBe(false); }); + test("skips Team subscription webhooks for tombstoned metadata owners before writing rows", async () => { + const getUser = mock(async () => { + throw new Error("should not load Stack user after tombstone blocks Team subscription"); + }); + const getTeam = mock(async () => { + throw new Error("should not load Stack team after tombstone blocks Team subscription"); + }); + selectResults = [[], [], [], []]; + tombstoneSelectResults = [[{ status: "pending" }]]; + + const result = await applySubscriptionUpdate( + { + id: "sub_team", + customer: "cus_team", + status: "active", + metadata: { + stackTeamId: "team_123", + stackUserId: "owner_123", + plan: "team", + app: "cmux", + }, + cancel_at_period_end: false, + items: { + data: [ + { + quantity: 7, + current_period_end: 1_800_000_000, + price: { id: "price_team" }, + }, + ], + }, + } as never, + { + db: fakeDb() as never, + stackApp: { + getUser, + getTeam, + } as never, + }, + ); + + expect(result).toEqual({ skipped: true }); + expect(getUser).not.toHaveBeenCalled(); + expect(getTeam).not.toHaveBeenCalled(); + expect(inserts.some((insert) => insert.table === stripeCustomers)).toBe(false); + expect(inserts.some((insert) => insert.table === stripeSubscriptions)).toBe(false); + expect(updates.some((update) => update.table === stripeCustomers)).toBe(false); + expect(updates.some((update) => update.table === stripeSubscriptions)).toBe(false); + }); + test("removes a user from TestFlight when a user Pro subscription lapses", async () => { const update = mock(async () => undefined); const removeTester = mock(async () => undefined); @@ -1056,7 +1109,7 @@ describe("recordCheckoutCompletion", () => { clientReadOnlyMetadata: { cmuxPlan: "team" }, update: mock(async () => undefined), }; - selectResults = [[{ stackUserId: "owner_123" }], []]; + selectResults = [[{ stackUserId: "owner_123" }], [{ stackUserId: "owner_123" }], []]; const result = await applySubscriptionUpdate( { @@ -1078,9 +1131,12 @@ describe("recordCheckoutCompletion", () => { { db: fakeDb() as never, stackApp: { - getUser: async () => { - throw new Error("should not load Stack user for Team subscription"); - }, + getUser: async () => ({ + id: "owner_123", + primaryEmail: "owner@example.com", + clientReadOnlyMetadata: {}, + update: mock(async () => undefined), + }), getTeam: async () => team, } as never, testflight: { From 0bf1784cdb1af1e7b53fd5de49ef4a8904078817 Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Thu, 9 Jul 2026 05:57:05 -0700 Subject: [PATCH 65/89] Close account deletion billing races --- web/app/api/account/route.ts | 10 ++++- web/services/billing/purchase.ts | 70 +++++++++++++++++------------- web/tests/account-route.test.ts | 34 +++++++++++---- web/tests/billing-purchase.test.ts | 21 +++++++++ 4 files changed, 96 insertions(+), 39 deletions(-) diff --git a/web/app/api/account/route.ts b/web/app/api/account/route.ts index da81e68d05b8..17d6204e0c57 100644 --- a/web/app/api/account/route.ts +++ b/web/app/api/account/route.ts @@ -538,7 +538,10 @@ async function resolveUserBillingForAccountDeletion( status: stripeSubscriptions.status, }) .from(stripeSubscriptions) - .where(eq(stripeSubscriptions.stackUserId, userId)); + .where(or( + eq(stripeSubscriptions.stackUserId, userId), + inArray(stripeSubscriptions.stackTeamId, deletionTeamIds), + )); const activeSubscriptions = subscriptionRows.filter((subscription) => stripeSubscriptionBelongsToDeletingAccount(subscription, deletionTeamIds) && stripeSubscriptionIsActive(subscription) @@ -552,7 +555,10 @@ async function resolveUserBillingForAccountDeletion( stackTeamId: stripeCustomers.stackTeamId, }) .from(stripeCustomers) - .where(eq(stripeCustomers.stackUserId, userId)); + .where(or( + eq(stripeCustomers.stackUserId, userId), + inArray(stripeCustomers.stackTeamId, deletionTeamIds), + )); const customers = customerRows.filter((customer) => !customer.stackTeamId || deletionTeamIds.includes(customer.stackTeamId) ); diff --git a/web/services/billing/purchase.ts b/web/services/billing/purchase.ts index 72cfecc292ef..debbad4cd3b8 100644 --- a/web/services/billing/purchase.ts +++ b/web/services/billing/purchase.ts @@ -366,47 +366,59 @@ export async function applySubscriptionUpdate( if (!stackUserId || stackUserId === DELETED_ACCOUNT_ACTOR_ID) return { skipped: true }; const isActive = isActiveStripeSubscriptionStatus(subscription.status); - const hasUserSubscription = await userStripeSubscriptionExists(db, { - subscriptionId: subscription.id, + const lockedResult = await withAccountDeletionUserLock( + db, stackUserId, - }); - const isMetadataOnlyUserSubscription = !hasUserSubscription && - !mappedStackUserId && - metadataStackUserId === stackUserId; - - if (await hasCheckoutBlockingAccountDeletionTombstone(stackUserId, db)) return { skipped: true }; - const user = await loadOptionalStackUser(stackUserId, dependencies.stackApp); - if (!user && isMetadataOnlyUserSubscription) return { skipped: true }; - if (!user) throw new Error(`Stack user not found for Stripe subscription update: ${stackUserId}`); - if (isAccountDeletionInProgress(user)) return { skipped: true }; + async (tx): Promise< + | { skipped: true } + | { user: StackBillingUser; stackUserId: string; isActive: boolean } + > => { + const hasUserSubscription = await userStripeSubscriptionExists(tx, { + subscriptionId: subscription.id, + stackUserId, + }); + const isMetadataOnlyUserSubscription = !hasUserSubscription && + !mappedStackUserId && + metadataStackUserId === stackUserId; + + if (await hasCheckoutBlockingAccountDeletionTombstone(stackUserId, tx)) return { skipped: true }; + const user = await loadOptionalStackUser(stackUserId, dependencies.stackApp); + if (!user && isMetadataOnlyUserSubscription) return { skipped: true }; + if (!user) throw new Error(`Stack user not found for Stripe subscription update: ${stackUserId}`); + if (isAccountDeletionInProgress(user)) return { skipped: true }; + + if (hasUserSubscription) { + await updateExistingUserStripeSubscription(tx, { + subscription, + customerId, + stackUserId, + }); + } else { + await upsertStripeSubscription(tx, { + subscription, + customerId, + stackUserId, + scope: "user", + }); + } - if (hasUserSubscription) { - await updateExistingUserStripeSubscription(db, { - subscription, - customerId, - stackUserId, - }); - } else { - await upsertStripeSubscription(db, { - subscription, - customerId, - stackUserId, - scope: "user", - }); - } + return { user, stackUserId, isActive }; + }, + ); + if ("skipped" in lockedResult) return { skipped: true }; await syncStackUserMetadataWithAccountDeletionGuard({ db, - stackUserId, + stackUserId: lockedResult.stackUserId, stackApp: dependencies.stackApp ?? stackServerApp, sync: async (freshUser) => { await syncProPlanMetadata(freshUser, isActive); }, }); if (!isActive) { - await removeUserFromTestflightOnLapse(user, stackUserId, dependencies); + await removeUserFromTestflightOnLapse(lockedResult.user, lockedResult.stackUserId, dependencies); } - return { scope: "user", stackUserId, isActive }; + return { scope: "user", stackUserId: lockedResult.stackUserId, isActive }; } function isAccountDeletionInProgress(user: StackBillingUser): boolean { diff --git a/web/tests/account-route.test.ts b/web/tests/account-route.test.ts index 14a906dd7ed8..b56c4ada5763 100644 --- a/web/tests/account-route.test.ts +++ b/web/tests/account-route.test.ts @@ -213,6 +213,7 @@ const revokeTenant = mock(async (...args: unknown[]) => { let deletedTableCount = 0; let deletedTables: unknown[] = []; let deletedWhere: Array<{ readonly table: unknown; readonly condition: unknown }> = []; +let selectedWhere: Array<{ readonly table: unknown; readonly condition: unknown }> = []; let updatedRows: Array<{ readonly table: unknown; readonly values: unknown }> = []; let tombstoneUpdates: unknown[] = []; let tombstoneCompleteError: unknown = null; @@ -319,14 +320,26 @@ function chainableSelectResult(rows: unknown[]): SelectResult { } const mockDb = { - select: mock(() => ({ - from: () => ({ - where: () => chainableSelectResult(nextSelectResult()), - innerJoin: () => ({ - where: () => chainableSelectResult(nextSelectResult()), - }), - }), - })), + select: mock(() => { + let selectedTable: unknown = null; + return { + from: (table: unknown) => { + selectedTable = table; + return { + where: (condition: unknown) => { + selectedWhere.push({ table: selectedTable, condition }); + return chainableSelectResult(nextSelectResult()); + }, + innerJoin: () => ({ + where: (condition: unknown) => { + selectedWhere.push({ table: selectedTable, condition }); + return chainableSelectResult(nextSelectResult()); + }, + }), + }; + }, + }; + }), delete: deleteRows, update: updateRows, transaction, @@ -461,6 +474,7 @@ beforeEach(() => { deletedTableCount = 0; deletedTables = []; deletedWhere = []; + selectedWhere = []; updatedRows = []; tombstoneUpdates = []; tombstoneCompleteError = null; @@ -672,6 +686,10 @@ describe("account deletion route", () => { }); expect(cancelledStripeSubscriptions).toEqual(["sub_user_active", "sub_team_active"]); expect(deletedStripeCustomers).toEqual(["cus_user", "cus_team"]); + const subscriptionSelect = selectedWhere.find((entry) => entry.table === stripeSubscriptions); + expect(conditionColumnNames(subscriptionSelect?.condition)).toContain("stack_team_id"); + const customerSelect = selectedWhere.find((entry) => entry.table === stripeCustomers); + expect(conditionColumnNames(customerSelect?.condition)).toContain("stack_team_id"); expect(revokeTenant).toHaveBeenCalledWith("tenant-team-personal"); expect(transactionExecute).toHaveBeenCalledTimes(5); const grantDelete = deletedWhere.find((entry) => entry.table === cloudVmBillingGrants); diff --git a/web/tests/billing-purchase.test.ts b/web/tests/billing-purchase.test.ts index d612c37f590a..9f9298943be5 100644 --- a/web/tests/billing-purchase.test.ts +++ b/web/tests/billing-purchase.test.ts @@ -922,6 +922,27 @@ describe("recordCheckoutCompletion", () => { expect(inserts.some((insert) => insert.table === stripeSubscriptions)).toBe(false); }); + test("skips user subscription webhooks when deletion starts before the locked write", async () => { + const getUser = mock(async () => { + throw new Error("should not load Stack user after tombstone blocks subscription write"); + }); + selectResults = [[{ stackUserId: "user_123" }], [{ id: "sub_user" }]]; + tombstoneSelectResults = [[{ status: "pending" }]]; + + const result = await applySubscriptionUpdate( + userSubscriptionUpdate({ status: "canceled" }) as never, + { + db: fakeDb() as never, + stackApp: { getUser } as never, + }, + ); + + expect(result).toEqual({ skipped: true }); + expect(getUser).not.toHaveBeenCalled(); + expect(updates.some((entry) => entry.table === stripeSubscriptions)).toBe(false); + expect(inserts.some((insert) => insert.table === stripeSubscriptions)).toBe(false); + }); + test("skips subscription metadata sync when deletion starts after webhook rows update", async () => { const staleUpdate = mock(async () => undefined); const deletingUpdate = mock(async () => undefined); From 10bfed7b5bd8bdb695f83331c2fd9043c37fb941 Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Thu, 9 Jul 2026 06:05:23 -0700 Subject: [PATCH 66/89] Close account deletion cleanup gaps --- web/app/api/account/route.ts | 31 +++++++++++++++++----------- web/db/schema.ts | 2 +- web/services/account/deletionLock.ts | 3 ++- web/tests/account-route.test.ts | 16 +++++++------- 4 files changed, 30 insertions(+), 22 deletions(-) diff --git a/web/app/api/account/route.ts b/web/app/api/account/route.ts index 17d6204e0c57..5e7fb2703e53 100644 --- a/web/app/api/account/route.ts +++ b/web/app/api/account/route.ts @@ -196,9 +196,9 @@ export async function DELETE(request: Request): Promise { logAccountDeleteError("account.delete.post_stack_cleanup_failed", error); if (accountDeletionTombstoneStarted) { try { - await markAccountDeletionTombstoneFailed(userId, error); - } catch (markFailedError) { - logAccountDeleteError("account.delete.post_stack_cleanup_mark_failed", markFailedError); + await markAccountDeletionTombstoneCleanupIncomplete(userId, error); + } catch (markIncompleteError) { + logAccountDeleteError("account.delete.post_stack_cleanup_mark_incomplete", markIncompleteError); } } return jsonResponse({ @@ -263,7 +263,7 @@ async function markAccountDeletionTombstonePending(userId: string): Promise { + const now = new Date(); + await cloudDb() + .update(accountDeletionTombstones) + .set({ + userId: null, + status: "cleanup_incomplete", + updatedAt: now, + completedAt: now, + errorMessage: sanitizedErrorSummary(error), + }) + .where(eq(accountDeletionTombstones.userIdHash, accountDeletionUserHash(userId))); +} + async function refreshAccountDeletionTombstoneLease(userId: string): Promise { await cloudDb() .update(accountDeletionTombstones) @@ -878,14 +892,7 @@ async function deleteCmuxOwnedAccountRows(userId: string, accountTeamIds: readon .set({ createdByUserId: DELETED_ACCOUNT_ACTOR_ID, updatedAt: now }) .where(eq(cloudVmBaseGenerations.createdByUserId, userId)); - await tx.delete(devices).where(and( - inArray(devices.teamId, deletionTeamIds), - eq(devices.userId, userId), - )); - await tx - .update(devices) - .set({ userId: DELETED_ACCOUNT_ACTOR_ID, updatedAt: now }) - .where(eq(devices.userId, userId)); + await tx.delete(devices).where(eq(devices.userId, userId)); await tx.delete(vaultCliAuthRequests).where(eq(vaultCliAuthRequests.userId, userId)); }); diff --git a/web/db/schema.ts b/web/db/schema.ts index 7bb0624382da..3f21598ddc16 100644 --- a/web/db/schema.ts +++ b/web/db/schema.ts @@ -84,7 +84,7 @@ export const accountDeletionTombstones = pgTable( { userIdHash: text("user_id_hash").primaryKey(), userId: text("user_id"), - status: text("status").$type<"pending" | "in_progress" | "stack_delete_pending" | "stack_delete_in_progress" | "completed" | "failed">().notNull().default("pending"), + status: text("status").$type<"pending" | "in_progress" | "stack_delete_pending" | "stack_delete_in_progress" | "completed" | "cleanup_incomplete" | "failed">().notNull().default("pending"), attemptCount: integer("attempt_count").notNull().default(0), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), diff --git a/web/services/account/deletionLock.ts b/web/services/account/deletionLock.ts index f59ee00ce173..1a5e3a580f76 100644 --- a/web/services/account/deletionLock.ts +++ b/web/services/account/deletionLock.ts @@ -13,6 +13,7 @@ export function isBlockingAccountDeletionStatus(status: string): boolean { status === "pending" || status === "in_progress" || status === "stack_delete_pending" || - status === "stack_delete_in_progress" + status === "stack_delete_in_progress" || + status === "cleanup_incomplete" ); } diff --git a/web/tests/account-route.test.ts b/web/tests/account-route.test.ts index b56c4ada5763..d80baf4e10c8 100644 --- a/web/tests/account-route.test.ts +++ b/web/tests/account-route.test.ts @@ -561,13 +561,11 @@ describe("account deletion route", () => { { table: cloudVmBases, values: { createdByUserId: "deleted-account" } }, { table: cloudVmBases, values: { lastOpenedByUserId: null } }, { table: cloudVmBaseGenerations, values: { createdByUserId: "deleted-account" } }, - { table: devices, values: { userId: "deleted-account" } }, { table: stripeSubscriptions, values: { stackUserId: "deleted-account" } }, { table: stripeCustomers, values: { stackUserId: "deleted-account" } }, { table: cloudVmBases, values: { createdByUserId: "deleted-account" } }, { table: cloudVmBases, values: { lastOpenedByUserId: null } }, { table: cloudVmBaseGenerations, values: { createdByUserId: "deleted-account" } }, - { table: devices, values: { userId: "deleted-account" } }, ]); for (const update of updatedRows) { expect((update.values as { readonly updatedAt?: unknown }).updatedAt).toBeInstanceOf(Date); @@ -1074,18 +1072,14 @@ describe("account deletion route", () => { expect(deleteStackUser).toHaveBeenCalledTimes(1); }); - test("anonymizes shared team devices registered by the deleted user", async () => { + test("deletes shared team devices registered by the deleted user", async () => { const response = await DELETE(accountDeletionRequest()); expect(response.status).toBe(200); expect(deletedTables).toContain(devices); const deviceDelete = deletedWhere.find((entry) => entry.table === devices); - expect(conditionColumnNames(deviceDelete?.condition)).toContain("team_id"); expect(conditionColumnNames(deviceDelete?.condition)).toContain("user_id"); - expect(updatedRows.map(({ table, values }) => ({ - table, - values: stripUpdatedAt(values), - }))).toContainEqual({ table: devices, values: { userId: "deleted-account" } }); + expect(updatedRows.map(({ table }) => table)).not.toContain(devices); }); test("deletes vault rows in bounded batches after their objects are removed", async () => { @@ -1406,6 +1400,9 @@ describe("account deletion route", () => { )).toBe(false); expect(tombstoneUpdates.some((values) => (values as { readonly status?: unknown }).status === "failed" + )).toBe(false); + expect(tombstoneUpdates.some((values) => + (values as { readonly status?: unknown }).status === "cleanup_incomplete" )).toBe(true); expect(consoleError).toHaveBeenCalledWith( "account.delete.post_stack_cleanup_failed", @@ -1427,6 +1424,9 @@ describe("account deletion route", () => { expect(deleteStackUser).toHaveBeenCalledTimes(1); expect(tombstoneUpdates.some((values) => (values as { readonly status?: unknown }).status === "failed" + )).toBe(false); + expect(tombstoneUpdates.some((values) => + (values as { readonly status?: unknown }).status === "cleanup_incomplete" )).toBe(true); expect(consoleError).toHaveBeenCalledWith( "account.delete.post_stack_cleanup_failed", From db70bbd05aae08df104731ccbde1ea91e17930d5 Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Thu, 9 Jul 2026 06:18:16 -0700 Subject: [PATCH 67/89] Synchronize account vault cleanup --- web/app/api/account/route.ts | 32 ++++++++++++---- web/tests/account-route.test.ts | 66 ++++++++++++++++++++++++++------- 2 files changed, 78 insertions(+), 20 deletions(-) diff --git a/web/app/api/account/route.ts b/web/app/api/account/route.ts index 5e7fb2703e53..90a21219e490 100644 --- a/web/app/api/account/route.ts +++ b/web/app/api/account/route.ts @@ -42,6 +42,7 @@ import { SubrouterClientError, } from "../../../services/subrouter/client"; import { deleteObject } from "../../../services/vault/storage"; +import { withVaultUserQuotaLock } from "../../../services/vault/usage"; import { accountDeletionAdvisoryLockKey, accountDeletionUserHash, @@ -446,7 +447,19 @@ async function deleteVaultRowsAndObjectsForAccount( } = {}, ): Promise { const db = cloudDb(); + await withVaultUserQuotaLock(db, userId, async (lockedDb) => { + await deleteVaultRowsAndObjectsForAccountLocked(lockedDb, userId, options); + }); +} +async function deleteVaultRowsAndObjectsForAccountLocked( + db: ReturnType, + userId: string, + options: { + readonly beforeObjectDeletion?: () => void; + readonly afterObjectDeletion?: () => Promise; + }, +): Promise { for (;;) { const snapshots = await db .select({ id: vaultSnapshots.id, objectKey: vaultSnapshots.objectKey }) @@ -463,6 +476,7 @@ async function deleteVaultRowsAndObjectsForAccount( if (snapshots.length < VAULT_OBJECT_DELETE_BATCH_SIZE) break; } + let grantOffset = 0; for (;;) { const grants = await db .select({ @@ -473,18 +487,20 @@ async function deleteVaultRowsAndObjectsForAccount( .from(vaultUploadGrants) .where(eq(vaultUploadGrants.userId, userId)) .orderBy(asc(vaultUploadGrants.id)) - .limit(VAULT_OBJECT_DELETE_BATCH_SIZE); + .limit(VAULT_OBJECT_DELETE_BATCH_SIZE) + .offset(grantOffset); if (grants.length === 0) break; options.beforeObjectDeletion?.(); await Promise.all(grants.flatMap((grant) => [ deleteObject(grant.objectKey), deleteObject(grant.uploadObjectKey), ])); - await db.delete(vaultUploadGrants).where(inArray(vaultUploadGrants.id, grants.map((grant) => grant.id))); await options.afterObjectDeletion?.(); if (grants.length < VAULT_OBJECT_DELETE_BATCH_SIZE) break; + grantOffset += grants.length; } + let tombstoneOffset = 0; for (;;) { const tombstones = await db .select({ @@ -495,18 +511,17 @@ async function deleteVaultRowsAndObjectsForAccount( .from(vaultUploadTombstones) .where(eq(vaultUploadTombstones.userId, userId)) .orderBy(asc(vaultUploadTombstones.id)) - .limit(VAULT_OBJECT_DELETE_BATCH_SIZE); + .limit(VAULT_OBJECT_DELETE_BATCH_SIZE) + .offset(tombstoneOffset); if (tombstones.length === 0) break; options.beforeObjectDeletion?.(); await Promise.all(tombstones.flatMap((tombstone) => [ deleteObject(tombstone.objectKey), deleteObject(tombstone.uploadObjectKey), ])); - await db - .delete(vaultUploadTombstones) - .where(inArray(vaultUploadTombstones.id, tombstones.map((tombstone) => tombstone.id))); await options.afterObjectDeletion?.(); if (tombstones.length < VAULT_OBJECT_DELETE_BATCH_SIZE) break; + tombstoneOffset += tombstones.length; } for (;;) { @@ -892,7 +907,10 @@ async function deleteCmuxOwnedAccountRows(userId: string, accountTeamIds: readon .set({ createdByUserId: DELETED_ACCOUNT_ACTOR_ID, updatedAt: now }) .where(eq(cloudVmBaseGenerations.createdByUserId, userId)); - await tx.delete(devices).where(eq(devices.userId, userId)); + await tx.delete(devices).where(or( + eq(devices.userId, userId), + inArray(devices.teamId, deletionTeamIds), + )); await tx.delete(vaultCliAuthRequests).where(eq(vaultCliAuthRequests.userId, userId)); }); diff --git a/web/tests/account-route.test.ts b/web/tests/account-route.test.ts index d80baf4e10c8..5700c69b8201 100644 --- a/web/tests/account-route.test.ts +++ b/web/tests/account-route.test.ts @@ -43,6 +43,8 @@ const errorsModule = await import("../services/errors"); const realCaptureAscError = errorsModule.captureAscError; const storageModule = await import("../services/vault/storage"); const realDeleteObject = storageModule.deleteObject; +const vaultUsageModule = await import("../services/vault/usage"); +const realWithVaultUserQuotaLock = vaultUsageModule.withVaultUserQuotaLock; const subrouterClientModule = await import("../services/subrouter/client"); const realCreateSubrouterClientFromEnv = subrouterClientModule.createSubrouterClientFromEnv; const vmErrorsModule = await import("../services/vms/errors"); @@ -69,16 +71,38 @@ const transaction = mock(async (...args: unknown[]) => { routeEvents.push("transaction"); return await callback(mockTransaction); }); -const transactionSelect = mock(() => ({ - from: (table: unknown) => ({ - where: () => ({ - for: async () => nextTransactionSelectResult(), - limit: async () => table === accountDeletionTombstones - ? nextTransactionTombstoneSelectResult() - : nextTransactionSelectResult(), - }), - }), -})); +const transactionSelect = mock(() => { + let selectedTable: unknown = null; + const rows = () => { + if (selectedTable === accountDeletionTombstones) return nextTransactionTombstoneSelectResult(); + if ( + selectedTable === vaultSnapshots || + selectedTable === vaultUploadGrants || + selectedTable === vaultUploadTombstones || + selectedTable === vaultSessions + ) { + return nextSelectResult(); + } + return nextTransactionSelectResult(); + }; + const builder = { + from: (table: unknown) => { + selectedTable = table; + return builder; + }, + innerJoin: () => builder, + where: () => builder, + orderBy: () => builder, + limit: () => builder, + offset: () => builder, + for: async () => rows(), + then: ( + resolve: (value: unknown[]) => unknown, + reject: (reason: unknown) => unknown, + ) => Promise.resolve(rows()).then(resolve, reject), + }; + return builder; +}); const transactionExecute = mock(async () => { routeEvents.push("transaction-lock"); }); @@ -245,6 +269,7 @@ let stackUserSelectedTeam: unknown = null; let stackUserTeams: readonly unknown[] = []; let useAccountRouteStubs = false; let lastRevokeIdentityCall: { readonly userId: string; readonly afterBatch?: unknown } | null = null; +let vaultLockUsers: string[] = []; const originalConsoleError = console.error; const consoleError = mock(() => {}); @@ -366,6 +391,18 @@ mock.module("../services/vault/storage", () => ({ }) as typeof realDeleteObject, })); +mock.module("../services/vault/usage", () => ({ + ...vaultUsageModule, + withVaultUserQuotaLock: (async (...args: Parameters) => { + const [db, userId, run] = args; + if (useAccountRouteStubs) { + vaultLockUsers.push(userId); + return await run(db); + } + return await realWithVaultUserQuotaLock(...args); + }) as typeof realWithVaultUserQuotaLock, +})); + mock.module("../services/billing/stripe", () => ({ ...stripeModule, isStripeBillingConfigured: () => useAccountRouteStubs @@ -505,6 +542,7 @@ beforeEach(() => { subrouterRevokeError = null; stackUserSelectedTeam = null; stackUserTeams = []; + vaultLockUsers = []; }); afterEach(() => { @@ -1072,13 +1110,14 @@ describe("account deletion route", () => { expect(deleteStackUser).toHaveBeenCalledTimes(1); }); - test("deletes shared team devices registered by the deleted user", async () => { + test("deletes owned team and shared team devices registered by the deleted user", async () => { const response = await DELETE(accountDeletionRequest()); expect(response.status).toBe(200); expect(deletedTables).toContain(devices); const deviceDelete = deletedWhere.find((entry) => entry.table === devices); expect(conditionColumnNames(deviceDelete?.condition)).toContain("user_id"); + expect(conditionColumnNames(deviceDelete?.condition)).toContain("team_id"); expect(updatedRows.map(({ table }) => table)).not.toContain(devices); }); @@ -1112,9 +1151,10 @@ describe("account deletion route", () => { "vault/u/account-user-1/latest.jsonl.zst", ]); expect(deletedTables).toContain(vaultSnapshots); - expect(deletedTables).toContain(vaultUploadGrants); - expect(deletedTables).toContain(vaultUploadTombstones); + expect(deletedTables).not.toContain(vaultUploadGrants); + expect(deletedTables).not.toContain(vaultUploadTombstones); expect(deletedTables).toContain(vaultSessions); + expect(vaultLockUsers).toContain("account-user-1"); }); test("keeps deletion retryable when vault object cleanup fails after VMs are destroyed", async () => { From d09609993e7e7cf2eb3748649463ad7b8b224f11 Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Thu, 9 Jul 2026 06:28:20 -0700 Subject: [PATCH 68/89] Delete account vault upload tracking rows --- web/app/api/account/route.ts | 14 ++++++-------- web/tests/account-route.test.ts | 4 ++-- 2 files changed, 8 insertions(+), 10 deletions(-) diff --git a/web/app/api/account/route.ts b/web/app/api/account/route.ts index 90a21219e490..8c305dc3f991 100644 --- a/web/app/api/account/route.ts +++ b/web/app/api/account/route.ts @@ -476,7 +476,6 @@ async function deleteVaultRowsAndObjectsForAccountLocked( if (snapshots.length < VAULT_OBJECT_DELETE_BATCH_SIZE) break; } - let grantOffset = 0; for (;;) { const grants = await db .select({ @@ -487,20 +486,18 @@ async function deleteVaultRowsAndObjectsForAccountLocked( .from(vaultUploadGrants) .where(eq(vaultUploadGrants.userId, userId)) .orderBy(asc(vaultUploadGrants.id)) - .limit(VAULT_OBJECT_DELETE_BATCH_SIZE) - .offset(grantOffset); + .limit(VAULT_OBJECT_DELETE_BATCH_SIZE); if (grants.length === 0) break; options.beforeObjectDeletion?.(); await Promise.all(grants.flatMap((grant) => [ deleteObject(grant.objectKey), deleteObject(grant.uploadObjectKey), ])); + await db.delete(vaultUploadGrants).where(inArray(vaultUploadGrants.id, grants.map((grant) => grant.id))); await options.afterObjectDeletion?.(); if (grants.length < VAULT_OBJECT_DELETE_BATCH_SIZE) break; - grantOffset += grants.length; } - let tombstoneOffset = 0; for (;;) { const tombstones = await db .select({ @@ -511,17 +508,18 @@ async function deleteVaultRowsAndObjectsForAccountLocked( .from(vaultUploadTombstones) .where(eq(vaultUploadTombstones.userId, userId)) .orderBy(asc(vaultUploadTombstones.id)) - .limit(VAULT_OBJECT_DELETE_BATCH_SIZE) - .offset(tombstoneOffset); + .limit(VAULT_OBJECT_DELETE_BATCH_SIZE); if (tombstones.length === 0) break; options.beforeObjectDeletion?.(); await Promise.all(tombstones.flatMap((tombstone) => [ deleteObject(tombstone.objectKey), deleteObject(tombstone.uploadObjectKey), ])); + await db + .delete(vaultUploadTombstones) + .where(inArray(vaultUploadTombstones.id, tombstones.map((tombstone) => tombstone.id))); await options.afterObjectDeletion?.(); if (tombstones.length < VAULT_OBJECT_DELETE_BATCH_SIZE) break; - tombstoneOffset += tombstones.length; } for (;;) { diff --git a/web/tests/account-route.test.ts b/web/tests/account-route.test.ts index 5700c69b8201..e1db8cd90118 100644 --- a/web/tests/account-route.test.ts +++ b/web/tests/account-route.test.ts @@ -1151,8 +1151,8 @@ describe("account deletion route", () => { "vault/u/account-user-1/latest.jsonl.zst", ]); expect(deletedTables).toContain(vaultSnapshots); - expect(deletedTables).not.toContain(vaultUploadGrants); - expect(deletedTables).not.toContain(vaultUploadTombstones); + expect(deletedTables).toContain(vaultUploadGrants); + expect(deletedTables).toContain(vaultUploadTombstones); expect(deletedTables).toContain(vaultSessions); expect(vaultLockUsers).toContain("account-user-1"); }); From 24f1db7a0cac23e878ad11f85935d5d0ee149958 Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Thu, 9 Jul 2026 06:43:02 -0700 Subject: [PATCH 69/89] Block Base VM creation during account deletion --- web/services/account/deletionLock.ts | 8 +--- web/services/vms/repository.ts | 16 +++++-- web/tests/vm-workflows.test.ts | 68 ++++++++++++++++++++++++++++ 3 files changed, 81 insertions(+), 11 deletions(-) diff --git a/web/services/account/deletionLock.ts b/web/services/account/deletionLock.ts index 1a5e3a580f76..fb0c6382c06c 100644 --- a/web/services/account/deletionLock.ts +++ b/web/services/account/deletionLock.ts @@ -9,11 +9,5 @@ export function accountDeletionAdvisoryLockKey(userId: string): string { } export function isBlockingAccountDeletionStatus(status: string): boolean { - return ( - status === "pending" || - status === "in_progress" || - status === "stack_delete_pending" || - status === "stack_delete_in_progress" || - status === "cleanup_incomplete" - ); + return status !== "failed"; } diff --git a/web/services/vms/repository.ts b/web/services/vms/repository.ts index 997bb5b2fa55..cebbafdf47db 100644 --- a/web/services/vms/repository.ts +++ b/web/services/vms/repository.ts @@ -97,7 +97,7 @@ export type VmRepositoryShape = { readonly imageVersion?: string | null; readonly maxActiveVms: number; readonly baseName?: string; - }) => Effect.Effect; + }) => Effect.Effect; readonly beginBaseReset: (input: { readonly userId: string; readonly billingTeamId: string; @@ -109,7 +109,7 @@ export type VmRepositoryShape = { readonly maxActiveVms: number; readonly baseName?: string; readonly reason?: string | null; - }) => Effect.Effect, VmCreateInProgressError | VmDatabaseError | VmLimitExceededError>; + }) => Effect.Effect, VmCreateDisabledError | VmCreateInProgressError | VmDatabaseError | VmLimitExceededError>; readonly markBaseCreateRunning: (input: { readonly baseId: string; readonly generation: number; @@ -533,6 +533,10 @@ export const VmRepositoryLive = Layer.succeed(VmRepository, { try { return await db.transaction(async (tx) => { await tx.execute(sql`select pg_advisory_xact_lock(hashtextextended(${`${scope.scopeType}:${scope.scopeId}:${name}`}, 0))`); + await assertAccountVmCreateAllowed(tx, { + userId: input.userId, + provider: input.provider, + }); const [existing] = await tx .select({ @@ -720,7 +724,7 @@ export const VmRepositoryLive = Layer.succeed(VmRepository, { throw err; } }, - catch: (cause) => isVmLimitExceededError(cause) + catch: (cause) => isVmCreateDisabledError(cause) || isVmLimitExceededError(cause) ? cause : new VmDatabaseError({ operation: "beginBaseOpen", cause }), }), @@ -733,6 +737,10 @@ export const VmRepositoryLive = Layer.succeed(VmRepository, { const name = baseName(input.baseName); return await db.transaction(async (tx) => { await tx.execute(sql`select pg_advisory_xact_lock(hashtextextended(${`${scope.scopeType}:${scope.scopeId}:${name}`}, 0))`); + await assertAccountVmCreateAllowed(tx, { + userId: input.userId, + provider: input.provider, + }); const [existing] = await tx .select({ base: cloudVmBases, @@ -881,7 +889,7 @@ export const VmRepositoryLive = Layer.succeed(VmRepository, { }; }); }, - catch: (cause) => isVmLimitExceededError(cause) + catch: (cause) => isVmCreateDisabledError(cause) || isVmLimitExceededError(cause) ? cause : new VmDatabaseError({ operation: "beginBaseReset", cause }), }), diff --git a/web/tests/vm-workflows.test.ts b/web/tests/vm-workflows.test.ts index 5d339cca8a0b..b40c6a7a0907 100644 --- a/web/tests/vm-workflows.test.ts +++ b/web/tests/vm-workflows.test.ts @@ -31,7 +31,9 @@ import { VmNotFoundError, VmProviderOperationError, VmSnapshotNotFoundError, + isVmCreateDisabledError, } from "../services/vms/errors"; +import { accountDeletionUserHash } from "../services/account/deletionLock"; import { createVm, destroyVm, @@ -1757,6 +1759,72 @@ describe("VM Effect workflows", () => { expect(imageVersion).toBe("test-version"); }); + dbTest("does not open or reset Base while account deletion blocks VM creation", async () => { + if (!sql) throw new Error("test database not initialized"); + await sql` + truncate account_deletion_tombstones, cloud_vm_base_events, cloud_vm_base_generations, + cloud_vm_bases, cloud_vm_billing_grants, cloud_vm_usage_events, cloud_vm_leases, + cloud_vms restart identity cascade + `; + await sql` + insert into account_deletion_tombstones (user_id_hash, user_id, status) + values (${accountDeletionUserHash("user-base-deleting")}, 'user-base-deleting', 'completed') + `; + + let createCalls = 0; + const provider: VmProviderGatewayShape = { + create: () => + Effect.sync(() => { + createCalls += 1; + return { + provider: "e2b" as const, + providerVmId: "provider-vm-base-deleting", + status: "running" as const, + image: "cmuxd-ws:test", + createdAt: Date.now(), + }; + }), + destroy: () => Effect.void, + exec: () => Effect.succeed({ exitCode: 0, stdout: "", stderr: "" }), + openAttach: () => Effect.fail(new Error("unused") as never), + openSSH: () => Effect.fail(new Error("unused") as never), + revokeSSHIdentity: () => Effect.void, + }; + const layer = providerLayer(provider); + const input = { + userId: "user-base-deleting", + billingCustomerType: "user" as const, + billingTeamId: "user-base-deleting", + billingPlanId: "free", + maxActiveVms: 1, + provider: "e2b" as const, + image: "cmuxd-ws:test", + baseName: "default", + }; + + for (const workflow of [ + openBaseVm(input), + resetBaseVm({ ...input, reason: "try during deletion" }), + ]) { + try { + await Effect.runPromise(workflow.pipe(Effect.provide(layer))); + throw new Error("expected Base VM creation to be blocked"); + } catch (error) { + expect(isVmCreateDisabledError(error)).toBe(true); + if (isVmCreateDisabledError(error)) { + expect(error.reason).toBe("Account deletion is in progress."); + } + } + } + + expect(createCalls).toBe(0); + const [{ vmCount }] = await sql<{ vmCount: string }[]>` + select count(*)::text as "vmCount" from cloud_vms + where user_id = 'user-base-deleting' + `; + expect(vmCount).toBe("0"); + }); + dbTest("opens Base as one stable VM per account scope", async () => { if (!sql) throw new Error("test database not initialized"); await sql`truncate cloud_vm_billing_grants, cloud_vm_usage_events, cloud_vm_leases, cloud_vms restart identity cascade`; From b19bc1e7edcf321272b6003d5feeb3f3b1a6a376 Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Thu, 9 Jul 2026 07:08:24 -0700 Subject: [PATCH 70/89] Unwrap Base deletion block in DB test --- web/tests/vm-workflows.test.ts | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/web/tests/vm-workflows.test.ts b/web/tests/vm-workflows.test.ts index b40c6a7a0907..32190dca54dc 100644 --- a/web/tests/vm-workflows.test.ts +++ b/web/tests/vm-workflows.test.ts @@ -32,6 +32,7 @@ import { VmProviderOperationError, VmSnapshotNotFoundError, isVmCreateDisabledError, + vmWorkflowErrorCause, } from "../services/vms/errors"; import { accountDeletionUserHash } from "../services/account/deletionLock"; import { @@ -1810,9 +1811,10 @@ describe("VM Effect workflows", () => { await Effect.runPromise(workflow.pipe(Effect.provide(layer))); throw new Error("expected Base VM creation to be blocked"); } catch (error) { - expect(isVmCreateDisabledError(error)).toBe(true); - if (isVmCreateDisabledError(error)) { - expect(error.reason).toBe("Account deletion is in progress."); + const workflowError = vmWorkflowErrorCause(error) ?? error; + expect(isVmCreateDisabledError(workflowError)).toBe(true); + if (isVmCreateDisabledError(workflowError)) { + expect(workflowError.reason).toBe("Account deletion is in progress."); } } } From c328efd1852346e3185800aec0f4c4568c57a6d0 Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Thu, 9 Jul 2026 07:16:35 -0700 Subject: [PATCH 71/89] Handle terminal account deletion retries --- web/app/api/account/route.ts | 39 ++++++++++++++------- web/tests/account-route.test.ts | 62 +++++++++++++++++++++++++++++++++ 2 files changed, 89 insertions(+), 12 deletions(-) diff --git a/web/app/api/account/route.ts b/web/app/api/account/route.ts index 8c305dc3f991..8dc54c842c1c 100644 --- a/web/app/api/account/route.ts +++ b/web/app/api/account/route.ts @@ -86,6 +86,12 @@ type RetainedTeamBillingOwner = { readonly stackUserId: string; }; +type AccountDeletionTombstoneStart = + | { readonly kind: "started" } + | { readonly kind: "pending" } + | { readonly kind: "completed" } + | { readonly kind: "cleanupIncomplete" }; + const ACCOUNT_DELETION_TOMBSTONE_LEASE_MS = 15 * 60 * 1000; export async function DELETE(request: Request): Promise { @@ -102,10 +108,17 @@ export async function DELETE(request: Request): Promise { let restoreBillingEntitlementsOnFailure = true; try { const accountScope = await accountDeletionScopeForUser(stackUser); - accountDeletionTombstoneStarted = await markAccountDeletionTombstonePending(userId); - if (!accountDeletionTombstoneStarted) { + const tombstoneStart = await markAccountDeletionTombstonePending(userId); + accountDeletionTombstoneStarted = tombstoneStart.kind === "started"; + if (tombstoneStart.kind === "pending") { return jsonResponse({ ok: true, deletionPending: true, destroyedVms: 0 }, 202); } + if (tombstoneStart.kind === "completed") { + return jsonResponse({ ok: true, destroyedVms: 0 }, 200); + } + if (tombstoneStart.kind === "cleanupIncomplete") { + return jsonResponse({ ok: true, cleanupIncomplete: true, destroyedVms: 0 }, 202); + } await markAccountDeletingAndClearBillingEntitlements(stackUser); stackMetadataMarked = true; await resolveUserBillingForAccountDeletion( @@ -249,7 +262,7 @@ async function currentDeletableStackUser(request: Request): Promise { +async function markAccountDeletionTombstonePending(userId: string): Promise { const db = cloudDb(); const now = new Date(); const userIdHash = accountDeletionUserHash(userId); @@ -264,9 +277,10 @@ async function markAccountDeletionTombstonePending(userId: string): Promise(); + const teams = new Map(); for (const team of values) { - if (!team || seen.has(team.id)) continue; - seen.add(team.id); - teams.push(team); + if (!team) continue; + const existing = teams.get(team.id); + if (!existing || (typeof existing.listUsers !== "function" && typeof team.listUsers === "function")) { + teams.set(team.id, team); + } } - return teams; + return [...teams.values()]; } function uniqueNonEmptyStrings(values: readonly (string | null | undefined)[]): readonly string[] { diff --git a/web/tests/account-route.test.ts b/web/tests/account-route.test.ts index e1db8cd90118..542c21fdf387 100644 --- a/web/tests/account-route.test.ts +++ b/web/tests/account-route.test.ts @@ -755,6 +755,47 @@ describe("account deletion route", () => { expect(deleteStackUser).not.toHaveBeenCalled(); }); + test("returns completed when a retry sees a completed account deletion tombstone", async () => { + transactionTombstoneSelectResults = [[{ + userIdHash: "existing-hash", + status: "completed", + updatedAt: new Date(), + }]]; + + const response = await DELETE(accountDeletionRequest()); + + expect(response.status).toBe(200); + expect(await response.json()).toEqual({ + ok: true, + destroyedVms: 0, + }); + expect(updateStackUser).not.toHaveBeenCalled(); + expect(cancelSubscription).not.toHaveBeenCalled(); + expect(listUserVms).not.toHaveBeenCalled(); + expect(deleteStackUser).not.toHaveBeenCalled(); + }); + + test("returns cleanup incomplete when a retry sees a cleanup-incomplete tombstone", async () => { + transactionTombstoneSelectResults = [[{ + userIdHash: "existing-hash", + status: "cleanup_incomplete", + updatedAt: new Date(), + }]]; + + const response = await DELETE(accountDeletionRequest()); + + expect(response.status).toBe(202); + expect(await response.json()).toEqual({ + ok: true, + cleanupIncomplete: true, + destroyedVms: 0, + }); + expect(updateStackUser).not.toHaveBeenCalled(); + expect(cancelSubscription).not.toHaveBeenCalled(); + expect(listUserVms).not.toHaveBeenCalled(); + expect(deleteStackUser).not.toHaveBeenCalled(); + }); + test("adopts a stale in-progress account deletion instead of blocking forever", async () => { transactionTombstoneSelectResults = [[{ userIdHash: "existing-hash", @@ -794,6 +835,27 @@ describe("account deletion route", () => { expect(transactionExecute).toHaveBeenCalledTimes(3); }); + test("uses the listed Stack team when selectedTeam has no member listing", async () => { + listedPersonalVmIds = []; + listedPersonalVmIdsByBillingTeam = { "team-personal": ["personal-team-vm"] }; + stackUserSelectedTeam = { id: "team-personal" }; + stackUserTeams = [stackTeam("team-personal", ["account-user-1"])]; + + const response = await DELETE(accountDeletionRequest()); + + expect(response.status).toBe(200); + expect(await response.json()).toEqual({ ok: true, destroyedVms: 1 }); + expect(listUserVms).toHaveBeenCalledWith("account-user-1"); + expect(listUserVms).toHaveBeenCalledWith("account-user-1", "team-personal"); + expect(destroyVm).toHaveBeenCalledWith({ + userId: "account-user-1", + billingTeamId: "team-personal", + teamIds: ["account-user-1", "team-personal"], + providerVmId: "personal-team-vm", + provider: "freestyle", + }); + }); + test("reassigns retained shared-team Stripe billing to another team member", async () => { listedPersonalVmIds = []; stackUserSelectedTeam = stackTeam("team-shared", ["account-user-1", "other-user"]); From 11bd876a26b91ca992eb872ee32a305d9e32001e Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Thu, 9 Jul 2026 07:37:28 -0700 Subject: [PATCH 72/89] Close account deletion retry blockers --- web/app/api/account/route.ts | 57 +++++++++---- web/services/billing/purchase.ts | 95 ++++++++++++--------- web/tests/account-route.test.ts | 118 ++++++++++++++++++++++++--- web/tests/billing-purchase.test.ts | 127 ++++++++++++++++++++++++++++- 4 files changed, 326 insertions(+), 71 deletions(-) diff --git a/web/app/api/account/route.ts b/web/app/api/account/route.ts index 8dc54c842c1c..69d86f35f924 100644 --- a/web/app/api/account/route.ts +++ b/web/app/api/account/route.ts @@ -52,6 +52,8 @@ import { unauthorized } from "../../../services/vms/auth"; import { VmAccountDeletionIdentityRevocationError, isVmAccountDeletionIdentityRevocationError, + isVmProviderOperationError, + vmWorkflowErrorCause, } from "../../../services/vms/errors"; import type { ProviderId } from "../../../services/vms/drivers"; import { jsonResponse } from "../../../services/vms/routeHelpers"; @@ -142,6 +144,18 @@ export async function DELETE(request: Request): Promise { }, }); await refreshAccountDeletionTombstoneLease(userId); + try { + const revokedIdentityLeases = await revokeAccountDeletionIdentityLeases(userId, { + afterBatch: async () => { + await refreshAccountDeletionTombstoneLease(userId); + }, + }); + if (revokedIdentityLeases > 0) destructiveCleanupStarted = true; + } catch (error) { + if (isVmAccountDeletionIdentityRevocationError(error)) destructiveCleanupStarted = true; + throw error; + } + await refreshAccountDeletionTombstoneLease(userId); try { destroyedVms = await destroyPersonalCloudVms(userId, accountScope.teamIds, { afterVmDestroy: async () => { @@ -152,7 +166,7 @@ export async function DELETE(request: Request): Promise { } catch (error) { if (error instanceof AccountDeletionDestructiveCleanupError) { destroyedVms = error.destroyedVms; - destructiveCleanupStarted = error.destructiveCleanupStarted; + destructiveCleanupStarted = destructiveCleanupStarted || error.destructiveCleanupStarted; } throw error; } @@ -170,22 +184,6 @@ export async function DELETE(request: Request): Promise { }, }, accountScope.teamIds); await refreshAccountDeletionTombstoneLease(userId); - try { - const revokedIdentityLeases = await runVmWorkflow( - revokeUserIdentityLeasesForAccountDeletion(userId, { - afterBatch: () => - Effect.tryPromise({ - try: () => refreshAccountDeletionTombstoneLease(userId), - catch: (cause) => new VmAccountDeletionIdentityRevocationError({ cause }), - }), - }), - ); - if (revokedIdentityLeases > 0) destructiveCleanupStarted = true; - } catch (error) { - if (isVmAccountDeletionIdentityRevocationError(error)) destructiveCleanupStarted = true; - throw error; - } - await refreshAccountDeletionTombstoneLease(userId); // Delete cmux-owned data before the Stack user so a Stack-side failure does // not strand retained app data behind an account the user can no longer use. // These deletes are idempotent, so the same signed-in user can retry the @@ -376,6 +374,23 @@ class AccountDeletionDestructiveCleanupError extends Error { } } +async function revokeAccountDeletionIdentityLeases( + userId: string, + options: { readonly afterBatch?: () => Promise } = {}, +): Promise { + return await runVmWorkflow( + revokeUserIdentityLeasesForAccountDeletion(userId, { + afterBatch: () => + Effect.tryPromise({ + try: async () => { + await options.afterBatch?.(); + }, + catch: (cause) => new VmAccountDeletionIdentityRevocationError({ cause }), + }), + }), + ); +} + async function destroyPersonalCloudVms( userId: string, accountTeamIds: readonly string[], @@ -401,11 +416,12 @@ async function destroyPersonalCloudVms( }; if (vm.billingTeamId) destroyInput.billingTeamId = vm.billingTeamId; const destroyProgram = destroyVm(destroyInput); - destructiveCleanupStarted = true; await runVmWorkflow(destroyProgram); + destructiveCleanupStarted = true; destroyedVms += 1; await options.afterVmDestroy?.(); } catch (error) { + if (didVmDestroyReachProvider(error)) destructiveCleanupStarted = true; failures.push(error); logAccountDeleteError("account.delete.vm_destroy_failed", error); } @@ -420,6 +436,11 @@ async function destroyPersonalCloudVms( return destroyedVms; } +function didVmDestroyReachProvider(error: unknown): boolean { + const workflowError = vmWorkflowErrorCause(error) ?? error; + return isVmProviderOperationError(workflowError) && workflowError.operation === "destroy"; +} + async function listAccountDeletionCloudVms( userId: string, accountTeamIds: readonly string[], diff --git a/web/services/billing/purchase.ts b/web/services/billing/purchase.ts index debbad4cd3b8..f1d206477d4a 100644 --- a/web/services/billing/purchase.ts +++ b/web/services/billing/purchase.ts @@ -118,7 +118,9 @@ type UserCheckoutPostCommitSync = { type CheckoutCompletionLockedResult = { result: CheckoutCompletionResult; - deleteCheckoutStripeResources: boolean; + checkoutCleanup?: { + deleteCustomer: boolean; + }; postCommitUserSync?: UserCheckoutPostCommitSync; postCommitTeamSync?: { stackTeamId: string; @@ -165,7 +167,7 @@ export async function recordCheckoutCompletion( (user && isAccountDeletionInProgress(user)) ) { return { - deleteCheckoutStripeResources: true, + checkoutCleanup: { deleteCustomer: true }, result: { skipped: "account_deletion_in_progress", stackUserId, @@ -189,7 +191,6 @@ export async function recordCheckoutCompletion( }); return { - deleteCheckoutStripeResources: false, postCommitUserSync: { user, email, @@ -202,8 +203,13 @@ export async function recordCheckoutCompletion( }, ); - if (lockedResult.deleteCheckoutStripeResources) { - await deleteCheckoutStripeResourcesForAccountDeletion(subscription, customerId, dependencies); + if (lockedResult.checkoutCleanup) { + await cleanupCheckoutStripeResourcesForAccountDeletion({ + subscription, + customerId, + dependencies, + deleteCustomer: lockedResult.checkoutCleanup.deleteCustomer, + }); } if (lockedResult.postCommitUserSync) { await syncUserCheckoutAfterCommit(db, lockedResult.postCommitUserSync); @@ -235,13 +241,16 @@ async function syncUserCheckoutAfterCommit( }); } -async function deleteCheckoutStripeResourcesForAccountDeletion( - subscription: Stripe.Subscription, - customerId: string, - dependencies: BillingPurchaseDependencies, -): Promise { +async function cleanupCheckoutStripeResourcesForAccountDeletion(input: { + subscription: Stripe.Subscription; + customerId: string; + dependencies: BillingPurchaseDependencies; + deleteCustomer: boolean; +}): Promise { + const { subscription, customerId, dependencies } = input; const client = (dependencies.stripeClient ?? stripe)(); await cancelCheckoutSubscription(client, subscription.id); + if (!input.deleteCustomer) return; try { await client.customers.del(customerId); } catch (error) { @@ -250,14 +259,6 @@ async function deleteCheckoutStripeResourcesForAccountDeletion( } } -async function cancelCheckoutSubscriptionForAccountDeletion( - subscription: Stripe.Subscription, - dependencies: BillingPurchaseDependencies, -): Promise { - const client = (dependencies.stripeClient ?? stripe)(); - await cancelCheckoutSubscription(client, subscription.id); -} - async function cancelCheckoutSubscription( client: Pick, "subscriptions">, subscriptionId: string, @@ -601,12 +602,12 @@ async function recordTeamCheckoutCompletion(input: { dependencies: BillingPurchaseDependencies; }): Promise { const db = input.dependencies.db ?? cloudDb(); + const checkoutCustomerOwnership = await teamStripeCustomerOwnership(db, { + stackTeamId: input.stackTeamId, + customerId: input.customerId, + }); const checkoutOwnerStackUserId = - input.stackUserId ?? - (await stackUserIdForTeamStripeCustomer(db, { - stackTeamId: input.stackTeamId, - customerId: input.customerId, - })); + input.stackUserId ?? checkoutCustomerOwnership.stackUserId; const resolvedStackUserId = checkoutOwnerStackUserId ?? input.stackTeamId; const ownerStackUserId = resolvedStackUserId !== input.stackTeamId && resolvedStackUserId !== DELETED_ACCOUNT_ACTOR_ID @@ -616,12 +617,13 @@ async function recordTeamCheckoutCompletion(input: { ? await loadOptionalStackUser(ownerStackUserId, input.dependencies.stackApp) : null; const lockedResult = await withAccountDeletionUserLock(db, resolvedStackUserId, async (tx) => { + const transactionCustomerOwnership = await teamStripeCustomerOwnership(tx, { + stackTeamId: input.stackTeamId, + customerId: input.customerId, + }); const stackUserId = input.stackUserId ?? - (await stackUserIdForTeamStripeCustomer(tx, { - stackTeamId: input.stackTeamId, - customerId: input.customerId, - })) ?? + transactionCustomerOwnership.stackUserId ?? checkoutOwnerStackUserId ?? input.stackTeamId; const transactionOwnerStackUserId = @@ -629,6 +631,9 @@ async function recordTeamCheckoutCompletion(input: { ? stackUserId : null; const ownerChangedDuringCheckout = transactionOwnerStackUserId !== ownerStackUserId; + const observedExistingCheckoutCustomer = + checkoutCustomerOwnership.customerRowExists || + transactionCustomerOwnership.customerRowExists; if ( stackUserId === DELETED_ACCOUNT_ACTOR_ID || (await hasCheckoutBlockingAccountDeletionTombstone(stackUserId, tx)) || @@ -637,7 +642,7 @@ async function recordTeamCheckoutCompletion(input: { (owner && isAccountDeletionInProgress(owner)) ) { return { - deleteCheckoutStripeResources: true, + checkoutCleanup: { deleteCustomer: !observedExistingCheckoutCustomer }, result: { skipped: "account_deletion_in_progress" as const, stackUserId, @@ -660,7 +665,6 @@ async function recordTeamCheckoutCompletion(input: { }); return { - deleteCheckoutStripeResources: false, postCommitTeamSync: { stackTeamId: input.stackTeamId, stackApp: input.dependencies.stackApp, @@ -673,11 +677,13 @@ async function recordTeamCheckoutCompletion(input: { }; }); - if (lockedResult.deleteCheckoutStripeResources) { - await cancelCheckoutSubscriptionForAccountDeletion( - input.subscription, - input.dependencies, - ); + if (lockedResult.checkoutCleanup) { + await cleanupCheckoutStripeResourcesForAccountDeletion({ + subscription: input.subscription, + customerId: input.customerId, + dependencies: input.dependencies, + deleteCustomer: lockedResult.checkoutCleanup.deleteCustomer, + }); } if (lockedResult.postCommitTeamSync) { const team = await loadStackTeam( @@ -1010,13 +1016,25 @@ async function stackUserIdForTeamStripeCustomer( db: BillingDbClient, input: { stackTeamId: string; customerId: string }, ): Promise { + return (await teamStripeCustomerOwnership(db, input)).stackUserId; +} + +async function teamStripeCustomerOwnership( + db: BillingDbClient, + input: { stackTeamId: string; customerId: string }, +): Promise<{ stackUserId: string | null; customerRowExists: boolean }> { const byTeam = await db - .select({ stackUserId: stripeCustomers.stackUserId }) + .select({ id: stripeCustomers.id, stackUserId: stripeCustomers.stackUserId }) .from(stripeCustomers) .where(eq(stripeCustomers.stackTeamId, input.stackTeamId)) .orderBy(desc(stripeCustomers.updatedAt)) .limit(1); - if (byTeam[0]?.stackUserId) return byTeam[0].stackUserId; + if (byTeam[0]) { + return { + stackUserId: byTeam[0].stackUserId ?? null, + customerRowExists: byTeam[0].id === input.customerId, + }; + } const byCustomer = await db .select({ stackUserId: stripeCustomers.stackUserId }) @@ -1024,7 +1042,10 @@ async function stackUserIdForTeamStripeCustomer( .where(eq(stripeCustomers.id, input.customerId)) .orderBy(desc(stripeCustomers.updatedAt)) .limit(1); - return byCustomer[0]?.stackUserId ?? null; + return { + stackUserId: byCustomer[0]?.stackUserId ?? null, + customerRowExists: Boolean(byCustomer[0]), + }; } function expandedSubscription( diff --git a/web/tests/account-route.test.ts b/web/tests/account-route.test.ts index 542c21fdf387..c2a52bce820a 100644 --- a/web/tests/account-route.test.ts +++ b/web/tests/account-route.test.ts @@ -181,11 +181,13 @@ const runVmWorkflow = mock(async (...args: unknown[]) => { if (program.kind === "revokeUserIdentityLeasesForAccountDeletion") { routeEvents.push("revoke-identities"); if (revokeIdentityLeasesError) throw revokeIdentityLeasesError; - return 2; + return revokedIdentityLeaseCount; } routeEvents.push("destroy-vm"); + const destroyVmFailure = destroyVmFailureErrorsByProviderId.get(program.input.providerVmId); + if (destroyVmFailure) throw destroyVmFailure; if (destroyVmFailureProviderIds.has(program.input.providerVmId)) { - throw new Error(`destroy failed for ${program.input.providerVmId}`); + throw vmProviderOperationError("destroy", `destroy failed for ${program.input.providerVmId}`); } return undefined; }); @@ -260,9 +262,11 @@ let stripeCancelError: unknown = null; let stripeDeleteCustomerError: unknown = null; let removeTesterError: unknown = null; let destroyVmFailureProviderIds = new Set(); +let destroyVmFailureErrorsByProviderId = new Map(); let listedPersonalVmIds: ListedAccountVm[] = []; let listedPersonalVmIdsByBillingTeam: Record = {}; let revokeIdentityLeasesError: unknown = null; +let revokedIdentityLeaseCount = 2; let subrouterClientCreateError: unknown = null; let subrouterRevokeError: unknown = null; let stackUserSelectedTeam: unknown = null; @@ -534,9 +538,11 @@ beforeEach(() => { stripeDeleteCustomerError = null; removeTesterError = null; destroyVmFailureProviderIds = new Set(); + destroyVmFailureErrorsByProviderId = new Map(); listedPersonalVmIds = ["personal-vm-1", "personal-vm-2"]; listedPersonalVmIdsByBillingTeam = {}; revokeIdentityLeasesError = null; + revokedIdentityLeaseCount = 2; lastRevokeIdentityCall = null; subrouterClientCreateError = null; subrouterRevokeError = null; @@ -650,6 +656,7 @@ describe("account deletion route", () => { "metadata-update", "stripe-cancel", "stripe-delete-customer", + "revoke-identities", "list-vms", "destroy-vm", "destroy-vm", @@ -659,7 +666,6 @@ describe("account deletion route", () => { "vault-delete", "vault-delete", "vault-delete", - "revoke-identities", "transaction", "transaction-lock", "stack-delete", @@ -952,6 +958,8 @@ describe("account deletion route", () => { expect(response.status).toBe(200); expectIdentityRevocationHeartbeatConfigured(); expect(routeEvents.indexOf("revoke-identities")).toBeGreaterThan(-1); + expect(routeEvents.indexOf("revoke-identities")).toBeLessThan(routeEvents.indexOf("list-vms")); + expect(routeEvents.indexOf("revoke-identities")).toBeLessThan(routeEvents.indexOf("destroy-vm")); expect(routeEvents.indexOf("revoke-identities")).toBeLessThan(routeEvents.lastIndexOf("transaction")); expect(deletedTables).toContain(cloudVmLeases); }); @@ -1002,25 +1010,91 @@ describe("account deletion route", () => { expect(updateStackUser).toHaveBeenCalledTimes(1); }); - test("keeps deletion retryable when account SSH identity revocation fails", async () => { + test("does not destroy personal VMs when account SSH identity revocation fails before external mutation", async () => { revokeIdentityLeasesError = new Error("provider identity revoke failed"); const response = await DELETE(accountDeletionRequest()); + expect(response.status).toBe(500); + expect(await response.json()).toEqual({ error: "account_delete_failed" }); + expectIdentityRevocationHeartbeatConfigured(); + expect(listUserVms).not.toHaveBeenCalled(); + expect(destroyVm).not.toHaveBeenCalled(); + expect(transaction).toHaveBeenCalledTimes(1); + expect(deleteStackUser).not.toHaveBeenCalled(); + expect(updateStackUser).toHaveBeenNthCalledWith(1, { + clientReadOnlyMetadata: { cmuxAccountDeleting: true }, + }); + expect(updateStackUser).toHaveBeenNthCalledWith(2, { + clientReadOnlyMetadata: { cmuxPlan: "pro" }, + }); + expect(deletedTables).not.toContain(cloudVmLeases); + }); + + test("restores Stack metadata when VM cleanup fails before provider deletion starts", async () => { + listedPersonalVmIds = ["personal-vm-1"]; + revokedIdentityLeaseCount = 0; + destroyVmFailureErrorsByProviderId = new Map([ + [ + "personal-vm-1", + vmProviderOperationError("revokeSSHIdentity", "too many active identity leases pending cleanup: 9"), + ], + ]); + + const response = await DELETE(accountDeletionRequest()); + + expect(response.status).toBe(500); + expect(await response.json()).toEqual({ error: "account_delete_failed" }); + expect(routeEvents.indexOf("revoke-identities")).toBeLessThan(routeEvents.indexOf("destroy-vm")); + expect(destroyVm).toHaveBeenCalledTimes(1); + expect(transaction).toHaveBeenCalledTimes(1); + expect(deleteStackUser).not.toHaveBeenCalled(); + expect(updateStackUser).toHaveBeenNthCalledWith(1, { + clientReadOnlyMetadata: { cmuxAccountDeleting: true }, + }); + expect(updateStackUser).toHaveBeenNthCalledWith(2, { + clientReadOnlyMetadata: { cmuxPlan: "pro" }, + }); + expect(consoleError).toHaveBeenCalledWith( + "account.delete.failed", + "AccountDeletionDestructiveCleanupError: Failed to destroy 1 personal cloud VM", + ); + }); + + test("keeps VM cleanup retryable when prior identity revocation changed provider state", async () => { + listedPersonalVmIds = ["personal-vm-1"]; + revokedIdentityLeaseCount = 2; + destroyVmFailureErrorsByProviderId = new Map([ + [ + "personal-vm-1", + vmProviderOperationError("revokeSSHIdentity", "too many active identity leases pending cleanup: 9"), + ], + ]); + + const response = await DELETE(accountDeletionRequest()); + expect(response.status).toBe(500); expect(await response.json()).toEqual({ error: "account_delete_retryable", retryable: true, - destroyedVms: 2, + destroyedVms: 0, }); - expectIdentityRevocationHeartbeatConfigured(); + expect(routeEvents.indexOf("revoke-identities")).toBeLessThan(routeEvents.indexOf("destroy-vm")); expect(transaction).toHaveBeenCalledTimes(1); expect(deleteStackUser).not.toHaveBeenCalled(); - expect(deletedTables).not.toContain(cloudVmLeases); + expect(updateStackUser).toHaveBeenNthCalledWith(1, { + clientReadOnlyMetadata: { cmuxAccountDeleting: true }, + }); + expect(updateStackUser).toHaveBeenCalledTimes(1); + expect(consoleError).toHaveBeenCalledWith( + "account.delete.partial_after_destructive_cleanup", + "AccountDeletionDestructiveCleanupError: Failed to destroy 1 personal cloud VM", + ); }); test("keeps deletion retryable after Subrouter 404 removes local tenant state", async () => { listedPersonalVmIds = []; + revokedIdentityLeaseCount = 0; selectResults = [ [], [], @@ -1031,7 +1105,7 @@ describe("account deletion route", () => { [{ tenantId: "tenant-personal" }], ]; subrouterRevokeError = new subrouterClientModule.SubrouterClientError("revokeTenant", 404); - revokeIdentityLeasesError = new Error("identity lookup failed"); + stackDeleteError = new Error("stack unavailable after subrouter cleanup"); const response = await DELETE(accountDeletionRequest()); @@ -1043,8 +1117,8 @@ describe("account deletion route", () => { }); expect(revokeTenant).toHaveBeenCalledWith("tenant-personal"); expect(deletedTables).toContain(subrouterTenants); - expect(transaction).toHaveBeenCalledTimes(1); - expect(deleteStackUser).not.toHaveBeenCalled(); + expect(transaction).toHaveBeenCalledTimes(2); + expect(deleteStackUser).toHaveBeenCalledTimes(1); expect(updateStackUser).toHaveBeenNthCalledWith(1, { clientReadOnlyMetadata: { cmuxAccountDeleting: true }, }); @@ -1082,8 +1156,9 @@ describe("account deletion route", () => { expect(updateStackUser).toHaveBeenCalledTimes(1); }); - test("restores Stack metadata when local Subrouter configuration fails before revoke", async () => { + test("restores Stack metadata when local Subrouter configuration fails before external mutation", async () => { listedPersonalVmIds = []; + revokedIdentityLeaseCount = 0; selectResults = [ [], [], @@ -1457,10 +1532,10 @@ describe("account deletion route", () => { "transaction-lock", "tombstone-upsert", "metadata-update", + "revoke-identities", "list-vms", "destroy-vm", "destroy-vm", - "revoke-identities", "transaction", "transaction-lock", "stack-delete", @@ -1649,3 +1724,22 @@ function expectIdentityRevocationHeartbeatConfigured(): void { expect(lastRevokeIdentityCall?.userId).toBe(ACCOUNT_USER_ID); expect(typeof lastRevokeIdentityCall?.afterBatch).toBe("function"); } + +function vmProviderOperationError(operation: string, message: string): Error & { + _tag: "VmProviderOperationError"; + provider: ProviderId; + operation: string; + cause: Error; +} { + const error = new Error(message) as Error & { + _tag: "VmProviderOperationError"; + provider: ProviderId; + operation: string; + cause: Error; + }; + error._tag = "VmProviderOperationError"; + error.provider = "freestyle"; + error.operation = operation; + error.cause = new Error(message); + return error; +} diff --git a/web/tests/billing-purchase.test.ts b/web/tests/billing-purchase.test.ts index 9f9298943be5..f3fdb96dfe13 100644 --- a/web/tests/billing-purchase.test.ts +++ b/web/tests/billing-purchase.test.ts @@ -112,7 +112,13 @@ function checkoutInput(customerId = "cus_123") { }; } -function teamCheckoutInput(customerId = "cus_team") { +function teamCheckoutInput(customerId = "cus_team", stackUserId?: string) { + const metadata = { + stackTeamId: "team_123", + plan: "team", + app: "cmux", + ...(stackUserId ? { stackUserId } : {}), + }; return { session: { id: "cs_team", @@ -120,13 +126,13 @@ function teamCheckoutInput(customerId = "cus_team") { customer: customerId, customer_details: { email: "buyer@example.com" }, subscription: "sub_team", - metadata: { stackTeamId: "team_123", plan: "team", app: "cmux" }, + metadata, }, subscription: { id: "sub_team", customer: customerId, status: "active", - metadata: { stackTeamId: "team_123", plan: "team", app: "cmux" }, + metadata, cancel_at_period_end: false, items: { data: [ @@ -612,7 +618,7 @@ describe("recordCheckoutCompletion", () => { clientReadOnlyMetadata: { cmuxAccountDeleting: true }, update: mock(async () => undefined), }; - selectResults = [[{ stackUserId: "owner_123" }], []]; + selectResults = [[{ id: "cus_team", stackUserId: "owner_123" }], []]; await expect( recordCheckoutCompletion(teamCheckoutInput() as never, { @@ -641,6 +647,119 @@ describe("recordCheckoutCompletion", () => { expect(owner.update).not.toHaveBeenCalled(); }); + test("deletes a new Team checkout customer when account deletion wins before a customer row exists", async () => { + const cancelSubscription = mock(async () => undefined); + const deleteCustomer = mock(async () => undefined); + const owner = { + id: "owner_123", + primaryEmail: "owner@example.com", + clientReadOnlyMetadata: { cmuxAccountDeleting: true }, + update: mock(async () => undefined), + }; + + await expect( + recordCheckoutCompletion(teamCheckoutInput("cus_team_new", "owner_123") as never, { + db: fakeDb() as never, + stackApp: { + getUser: async () => owner, + getTeam: async () => { + throw new Error("should not load Stack team for blocked Team checkout"); + }, + } as never, + stripeClient: () => ({ + subscriptions: { cancel: cancelSubscription }, + customers: { del: deleteCustomer }, + }) as never, + }), + ).resolves.toEqual({ + skipped: "account_deletion_in_progress", + stackUserId: "owner_123", + subscriptionId: "sub_team", + }); + + expect(cancelSubscription).toHaveBeenCalledWith("sub_team"); + expect(deleteCustomer).toHaveBeenCalledWith("cus_team_new"); + expect(inserts).toHaveLength(0); + expect(updates).toHaveLength(0); + expect(owner.update).not.toHaveBeenCalled(); + }); + + test("preserves an existing Team checkout customer when account deletion blocks a metadata-owned checkout", async () => { + const cancelSubscription = mock(async () => undefined); + const deleteCustomer = mock(async () => undefined); + const owner = { + id: "owner_123", + primaryEmail: "owner@example.com", + clientReadOnlyMetadata: { cmuxAccountDeleting: true }, + update: mock(async () => undefined), + }; + selectResults = [[{ id: "cus_team_existing", stackUserId: "owner_123" }], []]; + + await expect( + recordCheckoutCompletion(teamCheckoutInput("cus_team_existing", "owner_123") as never, { + db: fakeDb() as never, + stackApp: { + getUser: async () => owner, + getTeam: async () => { + throw new Error("should not load Stack team for blocked Team checkout"); + }, + } as never, + stripeClient: () => ({ + subscriptions: { cancel: cancelSubscription }, + customers: { del: deleteCustomer }, + }) as never, + }), + ).resolves.toEqual({ + skipped: "account_deletion_in_progress", + stackUserId: "owner_123", + subscriptionId: "sub_team", + }); + + expect(cancelSubscription).toHaveBeenCalledWith("sub_team"); + expect(deleteCustomer).not.toHaveBeenCalled(); + expect(inserts).toHaveLength(0); + expect(updates).toHaveLength(0); + expect(owner.update).not.toHaveBeenCalled(); + }); + + test("deletes a new Team checkout customer when the existing team customer is different", async () => { + const cancelSubscription = mock(async () => undefined); + const deleteCustomer = mock(async () => undefined); + const owner = { + id: "owner_123", + primaryEmail: "owner@example.com", + clientReadOnlyMetadata: { cmuxAccountDeleting: true }, + update: mock(async () => undefined), + }; + selectResults = [[{ id: "cus_team_old", stackUserId: "owner_123" }], []]; + + await expect( + recordCheckoutCompletion(teamCheckoutInput("cus_team_new", "owner_123") as never, { + db: fakeDb() as never, + stackApp: { + getUser: async () => owner, + getTeam: async () => { + throw new Error("should not load Stack team for blocked Team checkout"); + }, + } as never, + stripeClient: () => ({ + subscriptions: { cancel: cancelSubscription }, + customers: { del: deleteCustomer }, + }) as never, + }), + ).resolves.toEqual({ + skipped: "account_deletion_in_progress", + stackUserId: "owner_123", + subscriptionId: "sub_team", + }); + + expect(cancelSubscription).toHaveBeenCalledWith("sub_team"); + expect(deleteCustomer).toHaveBeenCalledWith("cus_team_new"); + expect(inserts).toHaveLength(0); + expect(updates).toHaveLength(0); + expect(owner.update).not.toHaveBeenCalled(); + }); + test("clears Team metadata when a Team subscription lapses", async () => { const updateTeam = mock(async () => undefined); const team = { From 5d65ed8414ae3b5a85767d4445194a4c276767d9 Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Thu, 9 Jul 2026 07:51:10 -0700 Subject: [PATCH 73/89] Delete owned team Stripe rows during account deletion --- web/app/api/account/route.ts | 27 +++++++++++++++++++-------- web/tests/account-route.test.ts | 20 +++++++++++++------- 2 files changed, 32 insertions(+), 15 deletions(-) diff --git a/web/app/api/account/route.ts b/web/app/api/account/route.ts index 69d86f35f924..0407153f31cc 100644 --- a/web/app/api/account/route.ts +++ b/web/app/api/account/route.ts @@ -1,4 +1,4 @@ -import { and, asc, eq, inArray, isNotNull, isNull, or, sql } from "drizzle-orm"; +import { and, asc, eq, inArray, isNotNull, isNull, not, or, sql } from "drizzle-orm"; import * as Effect from "effect/Effect"; import { getStackServerApp, isStackConfigured } from "../../lib/stack"; @@ -867,14 +867,23 @@ async function deleteCmuxOwnedAccountRows(userId: string, accountTeamIds: readon eq(billingEmailClaims.stackUserId, userId), eq(billingEmailClaims.claimedByUserId, userId), )); - await tx.delete(stripeSubscriptions).where(and( - eq(stripeSubscriptions.stackUserId, userId), - eq(stripeSubscriptions.scope, "user"), - isNull(stripeSubscriptions.stackTeamId), + await tx.delete(stripeSubscriptions).where(or( + and( + eq(stripeSubscriptions.stackUserId, userId), + eq(stripeSubscriptions.scope, "user"), + isNull(stripeSubscriptions.stackTeamId), + ), + and( + eq(stripeSubscriptions.scope, "team"), + inArray(stripeSubscriptions.stackTeamId, deletionTeamIds), + ), )); - await tx.delete(stripeCustomers).where(and( - eq(stripeCustomers.stackUserId, userId), - isNull(stripeCustomers.stackTeamId), + await tx.delete(stripeCustomers).where(or( + and( + eq(stripeCustomers.stackUserId, userId), + isNull(stripeCustomers.stackTeamId), + ), + inArray(stripeCustomers.stackTeamId, deletionTeamIds), )); await tx .update(stripeSubscriptions) @@ -883,6 +892,7 @@ async function deleteCmuxOwnedAccountRows(userId: string, accountTeamIds: readon eq(stripeSubscriptions.stackUserId, userId), eq(stripeSubscriptions.scope, "team"), isNotNull(stripeSubscriptions.stackTeamId), + not(inArray(stripeSubscriptions.stackTeamId, deletionTeamIds)), )); await tx .update(stripeCustomers) @@ -890,6 +900,7 @@ async function deleteCmuxOwnedAccountRows(userId: string, accountTeamIds: readon .where(and( eq(stripeCustomers.stackUserId, userId), isNotNull(stripeCustomers.stackTeamId), + not(inArray(stripeCustomers.stackTeamId, deletionTeamIds)), )); await tx.delete(cloudVmBillingGrants).where(or( diff --git a/web/tests/account-route.test.ts b/web/tests/account-route.test.ts index c2a52bce820a..fa1bc412b5d2 100644 --- a/web/tests/account-route.test.ts +++ b/web/tests/account-route.test.ts @@ -596,17 +596,16 @@ describe("account deletion route", () => { expect(deletedTableCount).toBeGreaterThan(10); expect(deletedTables).toContain(cloudVmBillingGrants); expect(deletedTables).toContain(devices); - expect(updatedRows.map(({ table, values }) => ({ + const nonStripeUpdates = updatedRows.filter(({ table }) => + table !== stripeSubscriptions && table !== stripeCustomers + ); + expect(nonStripeUpdates.map(({ table, values }) => ({ table, values: stripUpdatedAt(values), }))).toEqual([ - { table: stripeSubscriptions, values: { stackUserId: "deleted-account" } }, - { table: stripeCustomers, values: { stackUserId: "deleted-account" } }, { table: cloudVmBases, values: { createdByUserId: "deleted-account" } }, { table: cloudVmBases, values: { lastOpenedByUserId: null } }, { table: cloudVmBaseGenerations, values: { createdByUserId: "deleted-account" } }, - { table: stripeSubscriptions, values: { stackUserId: "deleted-account" } }, - { table: stripeCustomers, values: { stackUserId: "deleted-account" } }, { table: cloudVmBases, values: { createdByUserId: "deleted-account" } }, { table: cloudVmBases, values: { lastOpenedByUserId: null } }, { table: cloudVmBaseGenerations, values: { createdByUserId: "deleted-account" } }, @@ -704,8 +703,11 @@ describe("account deletion route", () => { listedPersonalVmIdsByBillingTeam = { "team-personal": ["personal-team-vm"] }; stackUserTeams = [stackTeam("team-personal", ["account-user-1"])]; selectResults = [ - [{ id: "sub_user_active" }, { id: "sub_team_active" }], - [{ id: "cus_user" }, { id: "cus_team" }], + [ + { id: "sub_user_active" }, + { id: "sub_team_active", stackTeamId: "team-personal", scope: "team", status: "active" }, + ], + [{ id: "cus_user" }, { id: "cus_team", stackTeamId: "team-personal" }], [], [], [], @@ -732,6 +734,10 @@ describe("account deletion route", () => { expect(conditionColumnNames(subscriptionSelect?.condition)).toContain("stack_team_id"); const customerSelect = selectedWhere.find((entry) => entry.table === stripeCustomers); expect(conditionColumnNames(customerSelect?.condition)).toContain("stack_team_id"); + const subscriptionDelete = deletedWhere.find((entry) => entry.table === stripeSubscriptions); + expect(conditionColumnNames(subscriptionDelete?.condition)).toContain("stack_team_id"); + const customerDelete = deletedWhere.find((entry) => entry.table === stripeCustomers); + expect(conditionColumnNames(customerDelete?.condition)).toContain("stack_team_id"); expect(revokeTenant).toHaveBeenCalledWith("tenant-team-personal"); expect(transactionExecute).toHaveBeenCalledTimes(5); const grantDelete = deletedWhere.find((entry) => entry.table === cloudVmBillingGrants); From 812d4b50e2e2487d6584427956f6509c4a2de989 Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Thu, 9 Jul 2026 08:03:03 -0700 Subject: [PATCH 74/89] Fix deletion review state and support subject --- .../MobileSettingsLegalSupportSection.swift | 13 ++++++++++++- ios/cmux/Resources/Localizable.xcstrings | 17 +++++++++++++++++ web/app/api/account/route.ts | 3 ++- web/tests/account-route.test.ts | 13 ++++++------- 4 files changed, 37 insertions(+), 9 deletions(-) diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsLegalSupportSection.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsLegalSupportSection.swift index 3ae8f3221ad1..c41a3f2341ed 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsLegalSupportSection.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MobileSettingsLegalSupportSection.swift @@ -30,7 +30,18 @@ struct MobileSettingsLegalSupportSection: View { private static let privacyPolicyURL = URL(string: "https://cmux.com/privacy-policy")! private static let termsOfServiceURL = URL(string: "https://cmux.com/terms-of-service")! - private static let supportURL = URL(string: "mailto:feedback@manaflow.com?subject=cmux%20iOS%20support")! + private static var supportURL: URL { + var components = URLComponents() + components.scheme = "mailto" + components.path = "feedback@manaflow.com" + components.queryItems = [ + URLQueryItem( + name: "subject", + value: L10n.string("mobile.settings.supportEmailSubject", defaultValue: "cmux iOS support") + ) + ] + return components.url! + } private func externalLinkRow( title: String, diff --git a/ios/cmux/Resources/Localizable.xcstrings b/ios/cmux/Resources/Localizable.xcstrings index 0596f5eeaaaf..e74714745293 100644 --- a/ios/cmux/Resources/Localizable.xcstrings +++ b/ios/cmux/Resources/Localizable.xcstrings @@ -4557,6 +4557,23 @@ } } }, + "mobile.settings.supportEmailSubject": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "cmux iOS support" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "cmux iOS サポート" + } + } + } + }, "mobile.settings.switchMac": { "extractionState": "manual", "localizations": { diff --git a/web/app/api/account/route.ts b/web/app/api/account/route.ts index 0407153f31cc..f61b3a56a349 100644 --- a/web/app/api/account/route.ts +++ b/web/app/api/account/route.ts @@ -975,11 +975,12 @@ async function deletePersonalSubrouterTenant( const client = createSubrouterClientFromEnv(); for (const tenant of tenants) { - options.afterExternalMutation?.(); try { await client.revokeTenant(tenant.tenantId); + options.afterExternalMutation?.(); } catch (error) { if (!(error instanceof SubrouterClientError && error.status === 404)) throw error; + options.afterExternalMutation?.(); } } await db.delete(subrouterTenants).where(inArray(subrouterTenants.teamId, teamIds)); diff --git a/web/tests/account-route.test.ts b/web/tests/account-route.test.ts index fa1bc412b5d2..5ae80e5c9f13 100644 --- a/web/tests/account-route.test.ts +++ b/web/tests/account-route.test.ts @@ -1131,8 +1131,9 @@ describe("account deletion route", () => { expect(updateStackUser).toHaveBeenCalledTimes(1); }); - test("keeps deletion retryable when Subrouter revoke reaches the network before failing", async () => { + test("restores Stack metadata when Subrouter revoke fails before external mutation", async () => { listedPersonalVmIds = []; + revokedIdentityLeaseCount = 0; selectResults = [ [], [], @@ -1147,11 +1148,7 @@ describe("account deletion route", () => { const response = await DELETE(accountDeletionRequest()); expect(response.status).toBe(500); - expect(await response.json()).toEqual({ - error: "account_delete_retryable", - retryable: true, - destroyedVms: 0, - }); + expect(await response.json()).toEqual({ error: "account_delete_failed" }); expect(revokeTenant).toHaveBeenCalledWith("tenant-personal"); expect(deletedTables).not.toContain(subrouterTenants); expect(transaction).toHaveBeenCalledTimes(1); @@ -1159,7 +1156,9 @@ describe("account deletion route", () => { expect(updateStackUser).toHaveBeenNthCalledWith(1, { clientReadOnlyMetadata: { cmuxAccountDeleting: true }, }); - expect(updateStackUser).toHaveBeenCalledTimes(1); + expect(updateStackUser).toHaveBeenNthCalledWith(2, { + clientReadOnlyMetadata: { cmuxPlan: "pro" }, + }); }); test("restores Stack metadata when local Subrouter configuration fails before external mutation", async () => { From 4fa4b4cd032f20233af55da2789f389b944752dd Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Thu, 9 Jul 2026 08:12:25 -0700 Subject: [PATCH 75/89] Page Stack teams during account deletion --- web/app/api/account/route.ts | 74 +++++++++++++++++++++++++++++---- web/tests/account-route.test.ts | 49 +++++++++++++++++++++- 2 files changed, 113 insertions(+), 10 deletions(-) diff --git a/web/app/api/account/route.ts b/web/app/api/account/route.ts index f61b3a56a349..ef5033f604fc 100644 --- a/web/app/api/account/route.ts +++ b/web/app/api/account/route.ts @@ -74,13 +74,13 @@ type DeletableStackUser = { readonly id: string; readonly primaryEmail?: string | null; readonly selectedTeam?: unknown; - readonly listTeams?: () => Promise; + readonly listTeams?: (options?: StackPaginationOptions) => Promise; readonly delete: () => Promise; } & ProMetadataCustomer; type AccountDeletionStackTeam = { readonly id: string; - readonly listUsers?: () => Promise; + readonly listUsers?: (options?: StackPaginationOptions) => Promise; }; type RetainedTeamBillingOwner = { @@ -88,6 +88,15 @@ type RetainedTeamBillingOwner = { readonly stackUserId: string; }; +type StackPaginationOptions = { + readonly cursor?: string; + readonly limit?: number; +}; + +type StackPaginationPage = readonly unknown[] & { + readonly nextCursor?: string | null; +}; + type AccountDeletionTombstoneStart = | { readonly kind: "started" } | { readonly kind: "pending" } @@ -990,10 +999,7 @@ async function accountDeletionScopeForUser(user: DeletableStackUser): Promise<{ readonly teamIds: readonly string[]; readonly retainedTeamBillingOwners: readonly RetainedTeamBillingOwner[]; }> { - if (typeof user.listTeams !== "function") { - throw new Error("Stack team listing is required for account deletion"); - } - const listedTeams = await user.listTeams(); + const listedTeams = await listAllStackTeams(user); const teams = uniqueStackTeams([ stackTeamFromUnknown(user.selectedTeam), ...listedTeams.map(stackTeamFromUnknown), @@ -1024,6 +1030,34 @@ async function accountDeletionScopeForUser(user: DeletableStackUser): Promise<{ }; } +async function listAllStackTeams(user: DeletableStackUser): Promise { + if (typeof user.listTeams !== "function") { + throw new Error("Stack team listing is required for account deletion"); + } + + const teams: unknown[] = []; + const seenCursors = new Set(); + const limit = 100; + let cursor: string | undefined; + do { + const page = await user.listTeams({ cursor, limit }); + teams.push(...Array.from(page)); + const nextCursor = normalizedStackCursor(page.nextCursor); + if (!nextCursor) { + if (page.length >= limit && page.nextCursor === undefined) { + throw new Error("Stack team pagination is incomplete for account deletion"); + } + break; + } + if (seenCursors.has(nextCursor)) { + throw new Error("Stack team pagination looped during account deletion"); + } + seenCursors.add(nextCursor); + cursor = nextCursor; + } while (true); + return teams; +} + function stackTeamFromUnknown(value: unknown): AccountDeletionStackTeam | null { if (!value || typeof value !== "object") return null; const id = (value as { readonly id?: unknown }).id; @@ -1032,14 +1066,33 @@ function stackTeamFromUnknown(value: unknown): AccountDeletionStackTeam | null { return { id: id.trim(), listUsers: typeof listUsers === "function" - ? async () => await listUsers.call(value) + ? async (options) => await listUsers.call(value, options) : undefined, }; } async function stackTeamMemberIds(team: AccountDeletionStackTeam): Promise { if (typeof team.listUsers !== "function") return null; - const members = await team.listUsers(); + const members: unknown[] = []; + const seenCursors = new Set(); + const limit = 100; + let cursor: string | undefined; + do { + const page = await team.listUsers({ cursor, limit }); + members.push(...Array.from(page)); + const nextCursor = normalizedStackCursor(page.nextCursor); + if (!nextCursor) { + if (page.length >= limit && page.nextCursor === undefined) { + throw new Error(`Stack team ${team.id} membership pagination is incomplete`); + } + break; + } + if (seenCursors.has(nextCursor)) { + throw new Error(`Stack team ${team.id} membership pagination looped`); + } + seenCursors.add(nextCursor); + cursor = nextCursor; + } while (true); return uniqueNonEmptyStrings(members.flatMap((member) => { if (!member || typeof member !== "object") return []; const id = (member as { readonly id?: unknown }).id; @@ -1047,6 +1100,11 @@ async function stackTeamMemberIds(team: AccountDeletionStackTeam): Promise(); for (const team of values) { diff --git a/web/tests/account-route.test.ts b/web/tests/account-route.test.ts index 5ae80e5c9f13..313bdf5a01eb 100644 --- a/web/tests/account-route.test.ts +++ b/web/tests/account-route.test.ts @@ -57,6 +57,10 @@ type ListedAccountVm = string | { readonly providerVmId: string; readonly provider?: ProviderId; }; +type StackPage = readonly unknown[] & { readonly nextCursor?: string | null }; +type StackList = + | StackPage + | ((options?: { readonly cursor?: string; readonly limit?: number }) => StackPage | Promise); const deleteStackUser = mock(async () => { routeEvents.push("stack-delete"); @@ -270,7 +274,7 @@ let revokedIdentityLeaseCount = 2; let subrouterClientCreateError: unknown = null; let subrouterRevokeError: unknown = null; let stackUserSelectedTeam: unknown = null; -let stackUserTeams: readonly unknown[] = []; +let stackUserTeams: StackList = []; let useAccountRouteStubs = false; let lastRevokeIdentityCall: { readonly userId: string; readonly afterBatch?: unknown } | null = null; let vaultLockUsers: string[] = []; @@ -868,6 +872,28 @@ describe("account deletion route", () => { }); }); + test("pages through Stack teams before selecting account-owned data", async () => { + listedPersonalVmIds = []; + listedPersonalVmIdsByBillingTeam = { "team-personal-page-2": ["personal-team-vm"] }; + stackUserTeams = ({ cursor } = {}) => cursor === "page-2" + ? stackPage([stackTeam("team-personal-page-2", ["account-user-1"])]) + : stackPage([stackTeam("team-shared-page-1", ["account-user-1", "other-user"])], "page-2"); + + const response = await DELETE(accountDeletionRequest()); + + expect(response.status).toBe(200); + expect(await response.json()).toEqual({ ok: true, destroyedVms: 1 }); + expect(listUserVms).toHaveBeenCalledWith("account-user-1"); + expect(listUserVms).toHaveBeenCalledWith("account-user-1", "team-personal-page-2"); + expect(destroyVm).toHaveBeenCalledWith({ + userId: "account-user-1", + billingTeamId: "team-personal-page-2", + teamIds: ["account-user-1", "team-personal-page-2"], + providerVmId: "personal-team-vm", + provider: "freestyle", + }); + }); + test("reassigns retained shared-team Stripe billing to another team member", async () => { listedPersonalVmIds = []; stackUserSelectedTeam = stackTeam("team-shared", ["account-user-1", "other-user"]); @@ -926,6 +952,18 @@ describe("account deletion route", () => { expect(deleteStackUser).not.toHaveBeenCalled(); }); + test("fails closed when Stack team pagination loops", async () => { + stackUserTeams = () => stackPage([], "repeat"); + + const response = await DELETE(accountDeletionRequest()); + + expect(response.status).toBe(500); + expect(await response.json()).toEqual({ error: "account_delete_failed" }); + expect(transaction).not.toHaveBeenCalled(); + expect(updateStackUser).not.toHaveBeenCalled(); + expect(deleteStackUser).not.toHaveBeenCalled(); + }); + test("revokes the personal Subrouter tenant before deleting local rows", async () => { selectResults = [ [], @@ -1666,7 +1704,8 @@ function stackUser(id = "account-user-1") { primaryEmail: "account@example.com", clientReadOnlyMetadata: { cmuxPlan: "pro" }, selectedTeam: stackUserSelectedTeam, - listTeams: async () => stackUserTeams, + listTeams: async (options?: { readonly cursor?: string; readonly limit?: number }) => + typeof stackUserTeams === "function" ? await stackUserTeams(options) : stackUserTeams, update: updateStackUser, delete: deleteStackUser, }; @@ -1679,6 +1718,12 @@ function stackTeam(id: string, userIds: readonly string[]) { }; } +function stackPage(items: readonly unknown[], nextCursor?: string | null): StackPage { + const page = [...items] as unknown[] & { nextCursor?: string | null }; + if (nextCursor !== undefined) page.nextCursor = nextCursor; + return page; +} + function stripUpdatedAt(values: unknown): Record { const copy = { ...(values as Record) }; delete copy.updatedAt; From a70b4db7faef2d1981da25661715fb94d23a5ce3 Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Thu, 9 Jul 2026 08:19:45 -0700 Subject: [PATCH 76/89] Accept large non-paginated Stack teams --- web/app/api/account/route.ts | 14 ++------------ web/tests/account-route.test.ts | 16 ++++++++++++++++ 2 files changed, 18 insertions(+), 12 deletions(-) diff --git a/web/app/api/account/route.ts b/web/app/api/account/route.ts index ef5033f604fc..1fd6621d1289 100644 --- a/web/app/api/account/route.ts +++ b/web/app/api/account/route.ts @@ -1043,12 +1043,7 @@ async function listAllStackTeams(user: DeletableStackUser): Promise= limit && page.nextCursor === undefined) { - throw new Error("Stack team pagination is incomplete for account deletion"); - } - break; - } + if (!nextCursor) break; if (seenCursors.has(nextCursor)) { throw new Error("Stack team pagination looped during account deletion"); } @@ -1081,12 +1076,7 @@ async function stackTeamMemberIds(team: AccountDeletionStackTeam): Promise= limit && page.nextCursor === undefined) { - throw new Error(`Stack team ${team.id} membership pagination is incomplete`); - } - break; - } + if (!nextCursor) break; if (seenCursors.has(nextCursor)) { throw new Error(`Stack team ${team.id} membership pagination looped`); } diff --git a/web/tests/account-route.test.ts b/web/tests/account-route.test.ts index 313bdf5a01eb..b29cf4b9cecd 100644 --- a/web/tests/account-route.test.ts +++ b/web/tests/account-route.test.ts @@ -894,6 +894,22 @@ describe("account deletion route", () => { }); }); + test("accepts non-paginated Stack team member arrays with 100 members", async () => { + listedPersonalVmIds = []; + const teamMembers = [ + "account-user-1", + ...Array.from({ length: 99 }, (_, index) => `member-${index}`), + ]; + stackUserSelectedTeam = stackTeam("large-team", teamMembers); + + const response = await DELETE(accountDeletionRequest()); + + expect(response.status).toBe(200); + expect(await response.json()).toEqual({ ok: true, destroyedVms: 0 }); + expect(listUserVms).toHaveBeenCalledWith("account-user-1"); + expect(listUserVms).not.toHaveBeenCalledWith("account-user-1", "large-team"); + }); + test("reassigns retained shared-team Stripe billing to another team member", async () => { listedPersonalVmIds = []; stackUserSelectedTeam = stackTeam("team-shared", ["account-user-1", "other-user"]); From 2241674911d460f318ab229edfd2e92ffa99427e Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Thu, 9 Jul 2026 08:29:36 -0700 Subject: [PATCH 77/89] Fail closed on ownerless team checkout completion --- web/app/api/billing/checkout/route.ts | 2 ++ web/services/billing/purchase.ts | 38 ++++++++++++++---------- web/tests/billing-checkout-route.test.ts | 6 ++-- web/tests/billing-purchase.test.ts | 33 ++++++++++++++++++++ 4 files changed, 61 insertions(+), 18 deletions(-) diff --git a/web/app/api/billing/checkout/route.ts b/web/app/api/billing/checkout/route.ts index 0f1b8b55be53..0dd3fc010f81 100644 --- a/web/app/api/billing/checkout/route.ts +++ b/web/app/api/billing/checkout/route.ts @@ -122,6 +122,7 @@ async function stripeTeamCheckout(request: NextRequest) { const cancelUrl = new URL("/pricing?billing=cancelled", request.nextUrl.origin); const metadata = { stackTeamId: teamId, + stackUserId: user.id, plan: "team", app: "cmux", }; @@ -261,6 +262,7 @@ async function stripeCustomerForTeam( name: team.displayName?.trim() || "cmux Team", metadata: { stackTeamId: team.id, + stackUserId, app: "cmux", }, }); diff --git a/web/services/billing/purchase.ts b/web/services/billing/purchase.ts index f1d206477d4a..3a65778e8e5c 100644 --- a/web/services/billing/purchase.ts +++ b/web/services/billing/purchase.ts @@ -608,15 +608,25 @@ async function recordTeamCheckoutCompletion(input: { }); const checkoutOwnerStackUserId = input.stackUserId ?? checkoutCustomerOwnership.stackUserId; - const resolvedStackUserId = checkoutOwnerStackUserId ?? input.stackTeamId; - const ownerStackUserId = - resolvedStackUserId !== input.stackTeamId && resolvedStackUserId !== DELETED_ACCOUNT_ACTOR_ID - ? resolvedStackUserId - : null; - const owner = ownerStackUserId - ? await loadOptionalStackUser(ownerStackUserId, input.dependencies.stackApp) + const ownerStackUserId = checkoutOwnerStackUserId + ? teamSubscriptionOwnerStackUserId(checkoutOwnerStackUserId, input.stackTeamId) : null; - const lockedResult = await withAccountDeletionUserLock(db, resolvedStackUserId, async (tx) => { + if (!ownerStackUserId) { + await cleanupCheckoutStripeResourcesForAccountDeletion({ + subscription: input.subscription, + customerId: input.customerId, + dependencies: input.dependencies, + deleteCustomer: !checkoutCustomerOwnership.customerRowExists, + }); + return { + skipped: "account_deletion_in_progress", + stackUserId: checkoutOwnerStackUserId ?? input.stackTeamId, + subscriptionId: input.subscription.id, + }; + } + + const owner = await loadOptionalStackUser(ownerStackUserId, input.dependencies.stackApp); + const lockedResult = await withAccountDeletionUserLock(db, ownerStackUserId, async (tx) => { const transactionCustomerOwnership = await teamStripeCustomerOwnership(tx, { stackTeamId: input.stackTeamId, customerId: input.customerId, @@ -624,18 +634,16 @@ async function recordTeamCheckoutCompletion(input: { const stackUserId = input.stackUserId ?? transactionCustomerOwnership.stackUserId ?? - checkoutOwnerStackUserId ?? - input.stackTeamId; + checkoutOwnerStackUserId; const transactionOwnerStackUserId = - stackUserId !== input.stackTeamId && stackUserId !== DELETED_ACCOUNT_ACTOR_ID - ? stackUserId - : null; + stackUserId ? teamSubscriptionOwnerStackUserId(stackUserId, input.stackTeamId) : null; const ownerChangedDuringCheckout = transactionOwnerStackUserId !== ownerStackUserId; const observedExistingCheckoutCustomer = checkoutCustomerOwnership.customerRowExists || transactionCustomerOwnership.customerRowExists; if ( - stackUserId === DELETED_ACCOUNT_ACTOR_ID || + !transactionOwnerStackUserId || + !stackUserId || (await hasCheckoutBlockingAccountDeletionTombstone(stackUserId, tx)) || ownerChangedDuringCheckout || (transactionOwnerStackUserId && !owner) || @@ -645,7 +653,7 @@ async function recordTeamCheckoutCompletion(input: { checkoutCleanup: { deleteCustomer: !observedExistingCheckoutCustomer }, result: { skipped: "account_deletion_in_progress" as const, - stackUserId, + stackUserId: stackUserId ?? input.stackTeamId, subscriptionId: input.subscription.id, }, }; diff --git a/web/tests/billing-checkout-route.test.ts b/web/tests/billing-checkout-route.test.ts index 645939b7ac05..25924264c4c0 100644 --- a/web/tests/billing-checkout-route.test.ts +++ b/web/tests/billing-checkout-route.test.ts @@ -323,7 +323,7 @@ describe("billing checkout route", () => { expect(resolveTeamPrice).toHaveBeenCalled(); expect(createStripeCustomer).toHaveBeenCalledWith({ name: "Signed Team", - metadata: { stackTeamId: "team-signed-in", app: "cmux" }, + metadata: { stackTeamId: "team-signed-in", stackUserId: "user-signed-in", app: "cmux" }, }); expect(insertedStripeCustomers).toContainEqual({ id: "cus_team", @@ -342,9 +342,9 @@ describe("billing checkout route", () => { ], customer: "cus_team", client_reference_id: "team-signed-in", - metadata: { stackTeamId: "team-signed-in", plan: "team", app: "cmux" }, + metadata: { stackTeamId: "team-signed-in", stackUserId: "user-signed-in", plan: "team", app: "cmux" }, subscription_data: { - metadata: { stackTeamId: "team-signed-in", plan: "team", app: "cmux" }, + metadata: { stackTeamId: "team-signed-in", stackUserId: "user-signed-in", plan: "team", app: "cmux" }, }, allow_promotion_codes: true, success_url: diff --git a/web/tests/billing-purchase.test.ts b/web/tests/billing-purchase.test.ts index f3fdb96dfe13..ad7c50620d87 100644 --- a/web/tests/billing-purchase.test.ts +++ b/web/tests/billing-purchase.test.ts @@ -684,6 +684,39 @@ describe("recordCheckoutCompletion", () => { expect(owner.update).not.toHaveBeenCalled(); }); + test("cancels Team checkout completion when buyer ownership is missing", async () => { + const cancelSubscription = mock(async () => undefined); + const deleteCustomer = mock(async () => undefined); + selectResults = [[], []]; + + await expect( + recordCheckoutCompletion(teamCheckoutInput("cus_team_new") as never, { + db: fakeDb() as never, + stackApp: { + getUser: async () => { + throw new Error("should not load a Stack user without a checkout owner"); + }, + getTeam: async () => { + throw new Error("should not sync Stack team without a checkout owner"); + }, + } as never, + stripeClient: () => ({ + subscriptions: { cancel: cancelSubscription }, + customers: { del: deleteCustomer }, + }) as never, + }), + ).resolves.toEqual({ + skipped: "account_deletion_in_progress", + stackUserId: "team_123", + subscriptionId: "sub_team", + }); + + expect(cancelSubscription).toHaveBeenCalledWith("sub_team"); + expect(deleteCustomer).toHaveBeenCalledWith("cus_team_new"); + expect(inserts).toHaveLength(0); + expect(updates).toHaveLength(0); + }); + test("preserves an existing Team checkout customer when account deletion blocks a metadata-owned checkout", async () => { const cancelSubscription = mock(async () => undefined); const deleteCustomer = mock(async () => undefined); From dd8a18c1c07ec1a06484af350a70328337e5b18b Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Thu, 9 Jul 2026 08:36:53 -0700 Subject: [PATCH 78/89] Fail closed on ownerless team subscription webhooks --- web/services/billing/purchase.ts | 11 +++++---- web/tests/billing-purchase.test.ts | 39 ++++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+), 5 deletions(-) diff --git a/web/services/billing/purchase.ts b/web/services/billing/purchase.ts index 3a65778e8e5c..77ebfe4395e6 100644 --- a/web/services/billing/purchase.ts +++ b/web/services/billing/purchase.ts @@ -297,13 +297,14 @@ export async function applySubscriptionUpdate( mappedStackUserId && metadataStackUserId !== mappedStackUserId ) return { skipped: true }; - const stackUserId = mappedStackUserId ?? metadataStackUserId ?? teamScope.stackTeamId; - if (stackUserId === DELETED_ACCOUNT_ACTOR_ID) return { skipped: true }; + const stackUserId = mappedStackUserId ?? metadataStackUserId; + if (!stackUserId || stackUserId === DELETED_ACCOUNT_ACTOR_ID) return { skipped: true }; const isActive = isActiveStripeSubscriptionStatus(subscription.status); const ownerStackUserId = teamSubscriptionOwnerStackUserId(stackUserId, teamScope.stackTeamId); + if (!ownerStackUserId) return { skipped: true }; const lockedResult = await withAccountDeletionUserLock( db, - ownerStackUserId ?? stackUserId, + ownerStackUserId, async (tx): Promise< | { skipped: true } | { scope: "team"; stackTeamId: string; isActive: boolean } @@ -319,8 +320,8 @@ export async function applySubscriptionUpdate( metadataStackUserId !== transactionMappedStackUserId ) return { skipped: true }; - const transactionStackUserId = transactionMappedStackUserId ?? metadataStackUserId ?? teamScope.stackTeamId; - if (transactionStackUserId === DELETED_ACCOUNT_ACTOR_ID) return { skipped: true }; + const transactionStackUserId = transactionMappedStackUserId ?? metadataStackUserId; + if (!transactionStackUserId || transactionStackUserId === DELETED_ACCOUNT_ACTOR_ID) return { skipped: true }; const transactionOwnerStackUserId = teamSubscriptionOwnerStackUserId( transactionStackUserId, teamScope.stackTeamId, diff --git a/web/tests/billing-purchase.test.ts b/web/tests/billing-purchase.test.ts index ad7c50620d87..8b2f600cffbc 100644 --- a/web/tests/billing-purchase.test.ts +++ b/web/tests/billing-purchase.test.ts @@ -884,6 +884,45 @@ describe("recordCheckoutCompletion", () => { expect(updates.some((update) => update.table === stripeSubscriptions)).toBe(false); }); + test("skips ownerless legacy Team subscription webhooks before writing rows", async () => { + const getUser = mock(async () => { + throw new Error("should not load Stack user for ownerless Team subscription"); + }); + const getTeam = mock(async () => { + throw new Error("should not load Stack team for ownerless Team subscription"); + }); + selectResults = [[], []]; + + const result = await applySubscriptionUpdate( + { + id: "sub_team", + customer: "cus_team", + status: "active", + metadata: { stackTeamId: "team_123", plan: "team", app: "cmux" }, + cancel_at_period_end: false, + items: { + data: [ + { + quantity: 7, + current_period_end: 1_800_000_000, + price: { id: "price_team" }, + }, + ], + }, + } as never, + { + db: fakeDb() as never, + stackApp: { getUser, getTeam } as never, + }, + ); + + expect(result).toEqual({ skipped: true }); + expect(getUser).not.toHaveBeenCalled(); + expect(getTeam).not.toHaveBeenCalled(); + expect(inserts.some((insert) => insert.table === stripeSubscriptions)).toBe(false); + expect(updates.some((update) => update.table === stripeSubscriptions)).toBe(false); + }); + test("skips Team subscription webhooks for tombstoned metadata owners before writing rows", async () => { const getUser = mock(async () => { throw new Error("should not load Stack user after tombstone blocks Team subscription"); From 15452d2798ef831a4a5d6da5e831a36e25dfeea1 Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Thu, 9 Jul 2026 08:52:54 -0700 Subject: [PATCH 79/89] Serialize device registration with account deletion --- web/app/api/device-tokens/route.ts | 79 ++++++----- web/app/api/devices/route.ts | 191 ++++++++++++++------------ web/services/account/deletionLock.ts | 30 ++++ web/tests/device-tokens-route.test.ts | 43 +++++- web/tests/devices-route.test.ts | 26 +++- 5 files changed, 242 insertions(+), 127 deletions(-) diff --git a/web/app/api/device-tokens/route.ts b/web/app/api/device-tokens/route.ts index 9aa27d88ffae..1b5db000befe 100644 --- a/web/app/api/device-tokens/route.ts +++ b/web/app/api/device-tokens/route.ts @@ -14,6 +14,10 @@ import { normalizeApnsBundle, readBoundedJsonObject, } from "../../../services/apns/routePolicy"; +import { + AccountDeletionMutationBlockedError, + assertAccountDeletionUserMutationAllowed, +} from "../../../services/account/deletionLock"; export const runtime = "nodejs"; export const dynamic = "force-dynamic"; @@ -48,47 +52,56 @@ async function registerDeviceToken(request: Request): Promise { const db = cloudDb(); - const registered = await db.transaction(async (tx) => { - await tx.execute(sql`select pg_advisory_xact_lock(hashtextextended(${user.id}, 2))`); - - const [existingToken] = await tx - .select({ userId: deviceTokens.userId }) - .from(deviceTokens) - .where(eq(deviceTokens.deviceToken, deviceToken)) - .limit(1); + let registered: boolean; + try { + registered = await db.transaction(async (tx) => { + await assertAccountDeletionUserMutationAllowed(tx, user.id); + await tx.execute(sql`select pg_advisory_xact_lock(hashtextextended(${user.id}, 2))`); - if (existingToken?.userId !== user.id) { - const [registrationCount] = await tx - .select({ total: count() }) + const [existingToken] = await tx + .select({ userId: deviceTokens.userId }) .from(deviceTokens) - .where(and(eq(deviceTokens.userId, user.id), ne(deviceTokens.deviceToken, deviceToken))); - if (Number(registrationCount?.total ?? 0) >= MAX_DEVICE_TOKENS_PER_USER) { - return false; + .where(eq(deviceTokens.deviceToken, deviceToken)) + .limit(1); + + if (existingToken?.userId !== user.id) { + const [registrationCount] = await tx + .select({ total: count() }) + .from(deviceTokens) + .where(and(eq(deviceTokens.userId, user.id), ne(deviceTokens.deviceToken, deviceToken))); + if (Number(registrationCount?.total ?? 0) >= MAX_DEVICE_TOKENS_PER_USER) { + return false; + } } - } - await tx - .insert(deviceTokens) - .values({ - userId: user.id, - deviceToken, - bundleId: bundle.bundleId, - environment: bundle.environment, - platform, - }) - .onConflictDoUpdate({ - target: deviceTokens.deviceToken, - set: { + await tx + .insert(deviceTokens) + .values({ userId: user.id, + deviceToken, bundleId: bundle.bundleId, environment: bundle.environment, platform, - updatedAt: new Date(), - }, - }); - - return true; - }); + }) + .onConflictDoUpdate({ + target: deviceTokens.deviceToken, + set: { + userId: user.id, + bundleId: bundle.bundleId, + environment: bundle.environment, + platform, + updatedAt: new Date(), + }, + }); + + return true; + }); + } catch (error) { + if (error instanceof AccountDeletionMutationBlockedError) { + return jsonResponse({ error: "account_deletion_in_progress" }, 409); + } + throw error; + } if (!registered) { return jsonResponse({ error: "too_many_devices" }, 429); diff --git a/web/app/api/devices/route.ts b/web/app/api/devices/route.ts index d8907d7907ca..a5f10b478b54 100644 --- a/web/app/api/devices/route.ts +++ b/web/app/api/devices/route.ts @@ -24,6 +24,10 @@ import { manualRoutesAreValid, routesContainLoopback, } from "./route-classification"; +import { + AccountDeletionMutationBlockedError, + assertAccountDeletionUserMutationAllowed, +} from "../../../services/account/deletionLock"; export const runtime = "nodejs"; export const dynamic = "force-dynamic"; @@ -191,112 +195,121 @@ export async function POST(request: Request): Promise { const db = cloudDb(); const now = new Date(); - const registered = await db.transaction(async (tx) => { - // Serialize concurrent registrations for the same team so the per-team cap - // is enforced without a race (mirrors the device-tokens advisory lock). - await tx.execute(sql`select pg_advisory_xact_lock(hashtextextended(${team.teamId}, 7))`); - - // Device identity is per team: a row keyed by (teamId, deviceUuid). The - // same cmux device UUID registering under a different team is a separate, - // legitimate row (a Mac in two teams), so there is no cross-team conflict to - // guard against. Team B creating its own row cannot read or mutate team A's. - const [existingDevice] = await tx - .select({ id: devices.id, userId: devices.userId }) - .from(devices) - .where(and(eq(devices.teamId, team.teamId), eq(devices.deviceUuid, deviceUuid))) - .limit(1); - - // Only the user who registered a device row may update it. GET exposes - // device UUIDs to every team member, so without this a co-member could POST - // another member's device UUID and overwrite its attach routes (redirecting - // that user's phone reconnect at their own host). This keeps route - // population owned by the registering user, matching the pre-registry trust - // boundary where only the user's own pairing populated their phone's routes. - // Cryptographic proof-of-possession (so even the same user must prove they - // hold the device) is the deferred key-pinning phase. - if (existingDevice && existingDevice.userId !== user.id) { - return { error: "device_not_owned" as const }; - } - - if (!existingDevice) { - const [{ total }] = await tx - .select({ total: sql`count(*)::int` }) + let registered: { error: "device_not_owned" | "too_many_devices" | "too_many_instances" | null }; + try { + registered = await db.transaction(async (tx) => { + await assertAccountDeletionUserMutationAllowed(tx, user.id); + // Serialize concurrent registrations for the same team so the per-team cap + // is enforced without a race (mirrors the device-tokens advisory lock). + await tx.execute(sql`select pg_advisory_xact_lock(hashtextextended(${team.teamId}, 7))`); + + // Device identity is per team: a row keyed by (teamId, deviceUuid). The + // same cmux device UUID registering under a different team is a separate, + // legitimate row (a Mac in two teams), so there is no cross-team conflict to + // guard against. Team B creating its own row cannot read or mutate team A's. + const [existingDevice] = await tx + .select({ id: devices.id, userId: devices.userId }) .from(devices) - .where(eq(devices.teamId, team.teamId)); - if (Number(total) >= MAX_DEVICES_PER_TEAM) { - return { error: "too_many_devices" as const }; + .where(and(eq(devices.teamId, team.teamId), eq(devices.deviceUuid, deviceUuid))) + .limit(1); + + // Only the user who registered a device row may update it. GET exposes + // device UUIDs to every team member, so without this a co-member could POST + // another member's device UUID and overwrite its attach routes (redirecting + // that user's phone reconnect at their own host). This keeps route + // population owned by the registering user, matching the pre-registry trust + // boundary where only the user's own pairing populated their phone's routes. + // Cryptographic proof-of-possession (so even the same user must prove they + // hold the device) is the deferred key-pinning phase. + if (existingDevice && existingDevice.userId !== user.id) { + return { error: "device_not_owned" as const }; + } + + if (!existingDevice) { + const [{ total }] = await tx + .select({ total: sql`count(*)::int` }) + .from(devices) + .where(eq(devices.teamId, team.teamId)); + if (Number(total) >= MAX_DEVICES_PER_TEAM) { + return { error: "too_many_devices" as const }; + } } - } - const [deviceRow] = await tx - .insert(devices) - .values({ - teamId: team.teamId, - deviceUuid, - userId: user.id, - platform, - displayName, - labels: deviceLabels, - lastSeenAt: now, - updatedAt: now, - }) - .onConflictDoUpdate({ - target: [devices.teamId, devices.deviceUuid], - set: { + const [deviceRow] = await tx + .insert(devices) + .values({ + teamId: team.teamId, + deviceUuid, userId: user.id, platform, displayName, labels: deviceLabels, lastSeenAt: now, updatedAt: now, - }, - }) - .returning({ id: devices.id }); - const deviceRowId = deviceRow.id; - - // Cap instances per device row. `tag` is client-supplied and the instance - // key is `(deviceId, tag)`, so without this a single device could create - // unbounded rows by varying the tag. Re-registering an existing tag is an - // update (the onConflict below), so only a genuinely new tag counts. - const [existingInstance] = await tx - .select({ id: deviceAppInstances.id }) - .from(deviceAppInstances) - .where(and(eq(deviceAppInstances.deviceId, deviceRowId), eq(deviceAppInstances.tag, tag))) - .limit(1); - if (!existingInstance) { - const [{ total }] = await tx - .select({ total: sql`count(*)::int` }) + }) + .onConflictDoUpdate({ + target: [devices.teamId, devices.deviceUuid], + set: { + userId: user.id, + platform, + displayName, + labels: deviceLabels, + lastSeenAt: now, + updatedAt: now, + }, + }) + .returning({ id: devices.id }); + const deviceRowId = deviceRow.id; + + // Cap instances per device row. `tag` is client-supplied and the instance + // key is `(deviceId, tag)`, so without this a single device could create + // unbounded rows by varying the tag. Re-registering an existing tag is an + // update (the onConflict below), so only a genuinely new tag counts. + const [existingInstance] = await tx + .select({ id: deviceAppInstances.id }) .from(deviceAppInstances) - .where(eq(deviceAppInstances.deviceId, deviceRowId)); - if (Number(total) >= MAX_INSTANCES_PER_DEVICE) { - return { error: "too_many_instances" as const }; + .where(and(eq(deviceAppInstances.deviceId, deviceRowId), eq(deviceAppInstances.tag, tag))) + .limit(1); + if (!existingInstance) { + const [{ total }] = await tx + .select({ total: sql`count(*)::int` }) + .from(deviceAppInstances) + .where(eq(deviceAppInstances.deviceId, deviceRowId)); + if (Number(total) >= MAX_INSTANCES_PER_DEVICE) { + return { error: "too_many_instances" as const }; + } } - } - await tx - .insert(deviceAppInstances) - .values({ - deviceId: deviceRowId, - teamId: team.teamId, - tag, - routes, - labels: instanceLabels, - lastSeenAt: now, - updatedAt: now, - }) - .onConflictDoUpdate({ - target: [deviceAppInstances.deviceId, deviceAppInstances.tag], - set: { + await tx + .insert(deviceAppInstances) + .values({ + deviceId: deviceRowId, teamId: team.teamId, + tag, routes, labels: instanceLabels, lastSeenAt: now, updatedAt: now, - }, - }); - - return { error: null }; - }); + }) + .onConflictDoUpdate({ + target: [deviceAppInstances.deviceId, deviceAppInstances.tag], + set: { + teamId: team.teamId, + routes, + labels: instanceLabels, + lastSeenAt: now, + updatedAt: now, + }, + }); + + return { error: null }; + }); + } catch (error) { + if (error instanceof AccountDeletionMutationBlockedError) { + return jsonResponse({ error: "account_deletion_in_progress" }, 409); + } + throw error; + } if (registered.error === "device_not_owned") { return jsonResponse({ error: "device_not_owned" }, 403); diff --git a/web/services/account/deletionLock.ts b/web/services/account/deletionLock.ts index fb0c6382c06c..8bd79af8e14a 100644 --- a/web/services/account/deletionLock.ts +++ b/web/services/account/deletionLock.ts @@ -1,4 +1,16 @@ import { createHash } from "node:crypto"; +import { eq, sql } from "drizzle-orm"; +import type { cloudDb } from "../../db/client"; +import { accountDeletionTombstones } from "../../db/schema"; + +type CloudDbTransaction = Parameters["transaction"]>[0]>[0]; + +export class AccountDeletionMutationBlockedError extends Error { + constructor(readonly userId: string) { + super("Account deletion is in progress."); + this.name = "AccountDeletionMutationBlockedError"; + } +} export function accountDeletionUserHash(userId: string): string { return createHash("sha256").update(userId).digest("hex"); @@ -11,3 +23,21 @@ export function accountDeletionAdvisoryLockKey(userId: string): string { export function isBlockingAccountDeletionStatus(status: string): boolean { return status !== "failed"; } + +export async function assertAccountDeletionUserMutationAllowed( + tx: CloudDbTransaction, + userId: string, +): Promise { + await tx.execute(sql`select pg_advisory_xact_lock(hashtextextended(${accountDeletionAdvisoryLockKey(userId)}, 0))`); + const userIdHash = accountDeletionUserHash(userId); + const [deletion] = await tx + .select({ + userIdHash: accountDeletionTombstones.userIdHash, + status: accountDeletionTombstones.status, + }) + .from(accountDeletionTombstones) + .where(eq(accountDeletionTombstones.userIdHash, userIdHash)) + .limit(1); + if (deletion?.userIdHash !== userIdHash || !isBlockingAccountDeletionStatus(deletion.status)) return; + throw new AccountDeletionMutationBlockedError(userId); +} diff --git a/web/tests/device-tokens-route.test.ts b/web/tests/device-tokens-route.test.ts index f1f5a8540e19..d5fc066277df 100644 --- a/web/tests/device-tokens-route.test.ts +++ b/web/tests/device-tokens-route.test.ts @@ -1,7 +1,8 @@ -import { afterAll, beforeAll, describe, expect, mock, test } from "bun:test"; +import { afterAll, beforeAll, beforeEach, describe, expect, mock, test } from "bun:test"; import postgres, { type Sql } from "postgres"; import { closeCloudDbForTests } from "../db/client"; +import { accountDeletionUserHash } from "../services/account/deletionLock"; const runDbTests = process.env.CMUX_DB_TEST === "1"; const dbTest = runDbTests ? test : test.skip; @@ -38,11 +39,46 @@ afterAll(async () => { await sql?.end(); }); +beforeEach(async () => { + if (!sql) return; + await sql`truncate device_tokens, account_deletion_tombstones restart identity cascade`; + getUser.mockClear(); +}); + describe("device token route", () => { + dbTest("blocks registration while account deletion is in progress", async () => { + if (!sql) throw new Error("test database not initialized"); + + await sql` + insert into account_deletion_tombstones (user_id_hash, user_id, status) + values (${accountDeletionUserHash("push-user-1")}, ${"push-user-1"}, 'pending') + `; + + const response = await POST( + new Request("https://cmux.test/api/device-tokens", { + method: "POST", + headers: { + authorization: "Bearer access-token", + "x-stack-refresh-token": "refresh-token", + }, + body: JSON.stringify({ + deviceToken: "b".repeat(64), + bundleId: "dev.cmux.ios.push1", + platform: "ios", + }), + }), + ); + + expect(response.status).toBe(409); + expect(await response.json()).toEqual({ error: "account_deletion_in_progress" }); + const [stored] = await sql<{ total: number }[]>` + select count(*)::int as total from device_tokens where user_id = 'push-user-1' + `; + expect(stored.total).toBe(0); + }); + dbTest("serializes registration cap enforcement per user", async () => { if (!sql) throw new Error("test database not initialized"); - await sql`truncate device_tokens restart identity cascade`; - getUser.mockClear(); const responses = await Promise.all( Array.from({ length: 12 }, (_, index) => @@ -74,7 +110,6 @@ describe("device token route", () => { dbTest("canonicalizes token casing for register and delete", async () => { if (!sql) throw new Error("test database not initialized"); - await sql`truncate device_tokens restart identity cascade`; const token = "a".repeat(64); const headers = { diff --git a/web/tests/devices-route.test.ts b/web/tests/devices-route.test.ts index 9548c19dd049..c8ad49312818 100644 --- a/web/tests/devices-route.test.ts +++ b/web/tests/devices-route.test.ts @@ -2,6 +2,7 @@ import { afterAll, beforeAll, beforeEach, describe, expect, mock, test } from "b import postgres, { type Sql } from "postgres"; import { closeCloudDbForTests } from "../db/client"; +import { accountDeletionUserHash } from "../services/account/deletionLock"; const runDbTests = process.env.CMUX_DB_TEST === "1"; const dbTest = runDbTests ? test : test.skip; @@ -68,12 +69,35 @@ afterAll(async () => { beforeEach(async () => { if (!sql) return; - await sql`truncate devices, device_app_instances restart identity cascade`; + await sql`truncate devices, device_app_instances, account_deletion_tombstones restart identity cascade`; getUser.mockClear(); currentUserId = "registry-user-1"; }); describe("device registry route", () => { + dbTest("blocks registration while account deletion is in progress", async () => { + if (!sql) throw new Error("test database not initialized"); + + await sql` + insert into account_deletion_tombstones (user_id_hash, user_id, status) + values (${accountDeletionUserHash("registry-user-1")}, ${"registry-user-1"}, 'pending') + `; + + const response = await POST( + registerRequest({ + deviceId: DEVICE_A, + platform: "mac", + tag: "stable", + routes: [], + }), + ); + + expect(response.status).toBe(409); + expect(await response.json()).toEqual({ error: "account_deletion_in_progress" }); + const [{ total }] = await sql<{ total: number }[]>`select count(*)::int as total from devices`; + expect(total).toBe(0); + }); + dbTest("registers a Mac and its app instance, then lists it for the team", async () => { if (!sql) throw new Error("test database not initialized"); From a64c19f7020ffa30d752feae4216e0a4a48dba30 Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Thu, 9 Jul 2026 09:00:19 -0700 Subject: [PATCH 80/89] Block account mutations before scope discovery --- web/app/api/account/route.ts | 2 +- web/tests/account-route.test.ts | 17 +++++++++++++---- 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/web/app/api/account/route.ts b/web/app/api/account/route.ts index 1fd6621d1289..6364506ee07a 100644 --- a/web/app/api/account/route.ts +++ b/web/app/api/account/route.ts @@ -118,7 +118,6 @@ export async function DELETE(request: Request): Promise { let destroyedVms = 0; let restoreBillingEntitlementsOnFailure = true; try { - const accountScope = await accountDeletionScopeForUser(stackUser); const tombstoneStart = await markAccountDeletionTombstonePending(userId); accountDeletionTombstoneStarted = tombstoneStart.kind === "started"; if (tombstoneStart.kind === "pending") { @@ -130,6 +129,7 @@ export async function DELETE(request: Request): Promise { if (tombstoneStart.kind === "cleanupIncomplete") { return jsonResponse({ ok: true, cleanupIncomplete: true, destroyedVms: 0 }, 202); } + const accountScope = await accountDeletionScopeForUser(stackUser); await markAccountDeletingAndClearBillingEntitlements(stackUser); stackMetadataMarked = true; await resolveUserBillingForAccountDeletion( diff --git a/web/tests/account-route.test.ts b/web/tests/account-route.test.ts index b29cf4b9cecd..69f72d0895f0 100644 --- a/web/tests/account-route.test.ts +++ b/web/tests/account-route.test.ts @@ -875,14 +875,19 @@ describe("account deletion route", () => { test("pages through Stack teams before selecting account-owned data", async () => { listedPersonalVmIds = []; listedPersonalVmIdsByBillingTeam = { "team-personal-page-2": ["personal-team-vm"] }; - stackUserTeams = ({ cursor } = {}) => cursor === "page-2" - ? stackPage([stackTeam("team-personal-page-2", ["account-user-1"])]) - : stackPage([stackTeam("team-shared-page-1", ["account-user-1", "other-user"])], "page-2"); + let listedTeamsAfterTombstone = false; + stackUserTeams = ({ cursor } = {}) => { + listedTeamsAfterTombstone = listedTeamsAfterTombstone || routeEvents.includes("tombstone-upsert"); + return cursor === "page-2" + ? stackPage([stackTeam("team-personal-page-2", ["account-user-1"])]) + : stackPage([stackTeam("team-shared-page-1", ["account-user-1", "other-user"])], "page-2"); + }; const response = await DELETE(accountDeletionRequest()); expect(response.status).toBe(200); expect(await response.json()).toEqual({ ok: true, destroyedVms: 1 }); + expect(listedTeamsAfterTombstone).toBe(true); expect(listUserVms).toHaveBeenCalledWith("account-user-1"); expect(listUserVms).toHaveBeenCalledWith("account-user-1", "team-personal-page-2"); expect(destroyVm).toHaveBeenCalledWith({ @@ -975,7 +980,11 @@ describe("account deletion route", () => { expect(response.status).toBe(500); expect(await response.json()).toEqual({ error: "account_delete_failed" }); - expect(transaction).not.toHaveBeenCalled(); + expect(transaction).toHaveBeenCalledTimes(1); + expect(routeEvents).toContain("tombstone-upsert"); + expect(tombstoneUpdates.some((values) => + Boolean(values && typeof values === "object" && (values as { readonly status?: unknown }).status === "failed") + )).toBe(true); expect(updateStackUser).not.toHaveBeenCalled(); expect(deleteStackUser).not.toHaveBeenCalled(); }); From 4b0079d1c3bf7a05fa40dd3fc88840e452d6250d Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Thu, 9 Jul 2026 09:09:27 -0700 Subject: [PATCH 81/89] Skip providerless VMs during deletion teardown --- web/app/api/account/route.ts | 17 +++++++++++------ web/tests/account-route.test.ts | 28 +++++++++++++++++++++++++++- 2 files changed, 38 insertions(+), 7 deletions(-) diff --git a/web/app/api/account/route.ts b/web/app/api/account/route.ts index 6364506ee07a..7122f1cea1b9 100644 --- a/web/app/api/account/route.ts +++ b/web/app/api/account/route.ts @@ -454,23 +454,28 @@ async function listAccountDeletionCloudVms( userId: string, accountTeamIds: readonly string[], ): Promise> { + type ListedVm = { readonly providerVmId?: string | null; readonly provider: ProviderId }; const vms = new Map< string, { readonly providerVmId: string; readonly provider: ProviderId; readonly billingTeamId?: string | null } >(); - const legacyScopedVms = await runVmWorkflow(listUserVms(userId)); + const legacyScopedVms: readonly ListedVm[] = await runVmWorkflow(listUserVms(userId)); for (const vm of legacyScopedVms) { - vms.set(accountDeletionVmKey(vm), { - providerVmId: vm.providerVmId, + const providerVmId = vm.providerVmId; + if (!providerVmId) continue; + vms.set(accountDeletionVmKey({ provider: vm.provider, providerVmId }), { + providerVmId, provider: vm.provider, }); } for (const teamId of accountTeamIds) { if (teamId === userId) continue; - const teamScopedVms = await runVmWorkflow(listUserVms(userId, teamId)); + const teamScopedVms: readonly ListedVm[] = await runVmWorkflow(listUserVms(userId, teamId)); for (const vm of teamScopedVms) { - vms.set(accountDeletionVmKey(vm), { - providerVmId: vm.providerVmId, + const providerVmId = vm.providerVmId; + if (!providerVmId) continue; + vms.set(accountDeletionVmKey({ provider: vm.provider, providerVmId }), { + providerVmId, provider: vm.provider, billingTeamId: teamId, }); diff --git a/web/tests/account-route.test.ts b/web/tests/account-route.test.ts index 69f72d0895f0..1b1926069281 100644 --- a/web/tests/account-route.test.ts +++ b/web/tests/account-route.test.ts @@ -54,7 +54,7 @@ const realListUserVms = workflowsModule.listUserVms; const realRevokeUserIdentityLeasesForAccountDeletion = workflowsModule.revokeUserIdentityLeasesForAccountDeletion; const realRunVmWorkflow = workflowsModule.runVmWorkflow as (...args: unknown[]) => unknown; type ListedAccountVm = string | { - readonly providerVmId: string; + readonly providerVmId?: string | null; readonly provider?: ProviderId; }; type StackPage = readonly unknown[] & { readonly nextCursor?: string | null }; @@ -1294,6 +1294,32 @@ describe("account deletion route", () => { expect(deleteStackUser).toHaveBeenCalledTimes(1); }); + test("deletes failed providerless VM rows without provider teardown", async () => { + listedPersonalVmIds = [ + { providerVmId: null, provider: "freestyle" }, + "personal-vm-1", + ]; + transactionSelectResults = [[{ + id: "00000000-0000-4000-8000-000000000767", + providerVmId: null, + status: "failed", + }]]; + + const response = await DELETE(accountDeletionRequest()); + + expect(response.status).toBe(200); + expect(await response.json()).toEqual({ ok: true, destroyedVms: 1 }); + expect(destroyVm).toHaveBeenCalledTimes(1); + expect(destroyVm).toHaveBeenCalledWith({ + userId: "account-user-1", + teamIds: ["account-user-1"], + providerVmId: "personal-vm-1", + provider: "freestyle", + }); + expect(deletedTables).toContain(cloudVms); + expect(deleteStackUser).toHaveBeenCalledTimes(1); + }); + test("anonymizes retained shared-team VM rows without blocking deletion", async () => { transactionSelectResults = [[{ id: "00000000-0000-4000-8000-000000000766", From 5862c2ed01a277b05b0ee62b91ebba562d8d8353 Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Thu, 9 Jul 2026 09:23:21 -0700 Subject: [PATCH 82/89] Mark VM deletion destructive after provider destroy --- web/app/api/account/route.ts | 4 ++ web/services/vms/workflows.ts | 4 ++ web/tests/account-route.test.ts | 98 ++++++++++++++++++++++++--------- 3 files changed, 81 insertions(+), 25 deletions(-) diff --git a/web/app/api/account/route.ts b/web/app/api/account/route.ts index 7122f1cea1b9..8222fdd6d20d 100644 --- a/web/app/api/account/route.ts +++ b/web/app/api/account/route.ts @@ -417,11 +417,15 @@ async function destroyPersonalCloudVms( teamIds: readonly string[]; providerVmId: string; provider: ProviderId; + afterProviderDestroy: () => void; } = { userId, teamIds: accountTeamIds, providerVmId: vm.providerVmId, provider: vm.provider, + afterProviderDestroy: () => { + destructiveCleanupStarted = true; + }, }; if (vm.billingTeamId) destroyInput.billingTeamId = vm.billingTeamId; const destroyProgram = destroyVm(destroyInput); diff --git a/web/services/vms/workflows.ts b/web/services/vms/workflows.ts index a684ed88b118..71d8632b3e04 100644 --- a/web/services/vms/workflows.ts +++ b/web/services/vms/workflows.ts @@ -1250,6 +1250,7 @@ export function destroyVm(input: { readonly teamIds?: readonly string[]; readonly providerVmId: string; readonly provider?: ProviderId; + readonly afterProviderDestroy?: () => void; }) { return Effect.gen(function* () { const repo = yield* VmRepository; @@ -1263,6 +1264,9 @@ export function destroyVm(input: { return Effect.fail(err); }), ); + yield* Effect.sync(() => { + input.afterProviderDestroy?.(); + }); yield* repo.markDestroyed(vm.id); yield* repo.recordUsageEvent({ userId: input.userId, diff --git a/web/tests/account-route.test.ts b/web/tests/account-route.test.ts index 1b1926069281..1d213ce5bd89 100644 --- a/web/tests/account-route.test.ts +++ b/web/tests/account-route.test.ts @@ -163,7 +163,11 @@ const revokeUserIdentityLeasesForAccountDeletion = mock((...args: unknown[]) => }; }); const destroyVm = mock((...args: unknown[]) => { - const [input] = args as [{ readonly userId: string; readonly providerVmId: string }]; + const [input] = args as [{ + readonly userId: string; + readonly providerVmId: string; + readonly afterProviderDestroy?: () => void; + }]; return { kind: "destroyVm" as const, input, @@ -193,6 +197,9 @@ const runVmWorkflow = mock(async (...args: unknown[]) => { if (destroyVmFailureProviderIds.has(program.input.providerVmId)) { throw vmProviderOperationError("destroy", `destroy failed for ${program.input.providerVmId}`); } + program.input.afterProviderDestroy?.(); + const afterProviderError = destroyVmAfterProviderErrorsByProviderId.get(program.input.providerVmId); + if (afterProviderError) throw afterProviderError; return undefined; }); const deleteObject = mock(async (...args: unknown[]) => { @@ -267,6 +274,7 @@ let stripeDeleteCustomerError: unknown = null; let removeTesterError: unknown = null; let destroyVmFailureProviderIds = new Set(); let destroyVmFailureErrorsByProviderId = new Map(); +let destroyVmAfterProviderErrorsByProviderId = new Map(); let listedPersonalVmIds: ListedAccountVm[] = []; let listedPersonalVmIdsByBillingTeam: Record = {}; let revokeIdentityLeasesError: unknown = null; @@ -295,6 +303,7 @@ type WorkflowProgram = readonly billingTeamId?: string | null; readonly providerVmId: string; readonly provider?: ProviderId; + readonly afterProviderDestroy?: () => void; }; }; @@ -543,6 +552,7 @@ beforeEach(() => { removeTesterError = null; destroyVmFailureProviderIds = new Set(); destroyVmFailureErrorsByProviderId = new Map(); + destroyVmAfterProviderErrorsByProviderId = new Map(); listedPersonalVmIds = ["personal-vm-1", "personal-vm-2"]; listedPersonalVmIdsByBillingTeam = {}; revokeIdentityLeasesError = null; @@ -584,18 +594,18 @@ describe("account deletion route", () => { expect(await response.json()).toEqual({ ok: true, destroyedVms: 2 }); expect(listUserVms).toHaveBeenCalledWith("account-user-1"); expect(destroyVm).toHaveBeenCalledTimes(2); - expect(destroyVm).toHaveBeenCalledWith({ + expect(destroyVm).toHaveBeenCalledWith(expect.objectContaining({ userId: "account-user-1", teamIds: ["account-user-1"], providerVmId: "personal-vm-1", provider: "freestyle", - }); - expect(destroyVm).toHaveBeenCalledWith({ + })); + expect(destroyVm).toHaveBeenCalledWith(expect.objectContaining({ userId: "account-user-1", teamIds: ["account-user-1"], providerVmId: "personal-vm-2", provider: "freestyle", - }); + })); expect(transaction).toHaveBeenCalledTimes(3); expect(deletedTableCount).toBeGreaterThan(10); expect(deletedTables).toContain(cloudVmBillingGrants); @@ -688,18 +698,18 @@ describe("account deletion route", () => { expect(response.status).toBe(200); expect(await response.json()).toEqual({ ok: true, destroyedVms: 2 }); expect(destroyVm).toHaveBeenCalledTimes(2); - expect(destroyVm).toHaveBeenCalledWith({ + expect(destroyVm).toHaveBeenCalledWith(expect.objectContaining({ userId: "account-user-1", teamIds: ["account-user-1"], providerVmId: "shared-provider-id", provider: "freestyle", - }); - expect(destroyVm).toHaveBeenCalledWith({ + })); + expect(destroyVm).toHaveBeenCalledWith(expect.objectContaining({ userId: "account-user-1", teamIds: ["account-user-1"], providerVmId: "shared-provider-id", provider: "e2b", - }); + })); }); test("destroys personal-team scoped VMs before deleting account rows", async () => { @@ -725,13 +735,13 @@ describe("account deletion route", () => { expect(await response.json()).toEqual({ ok: true, destroyedVms: 1 }); expect(listUserVms).toHaveBeenCalledWith("account-user-1"); expect(listUserVms).toHaveBeenCalledWith("account-user-1", "team-personal"); - expect(destroyVm).toHaveBeenCalledWith({ + expect(destroyVm).toHaveBeenCalledWith(expect.objectContaining({ userId: "account-user-1", billingTeamId: "team-personal", teamIds: ["account-user-1", "team-personal"], providerVmId: "personal-team-vm", provider: "freestyle", - }); + })); expect(cancelledStripeSubscriptions).toEqual(["sub_user_active", "sub_team_active"]); expect(deletedStripeCustomers).toEqual(["cus_user", "cus_team"]); const subscriptionSelect = selectedWhere.find((entry) => entry.table === stripeSubscriptions); @@ -863,13 +873,13 @@ describe("account deletion route", () => { expect(await response.json()).toEqual({ ok: true, destroyedVms: 1 }); expect(listUserVms).toHaveBeenCalledWith("account-user-1"); expect(listUserVms).toHaveBeenCalledWith("account-user-1", "team-personal"); - expect(destroyVm).toHaveBeenCalledWith({ + expect(destroyVm).toHaveBeenCalledWith(expect.objectContaining({ userId: "account-user-1", billingTeamId: "team-personal", teamIds: ["account-user-1", "team-personal"], providerVmId: "personal-team-vm", provider: "freestyle", - }); + })); }); test("pages through Stack teams before selecting account-owned data", async () => { @@ -890,13 +900,13 @@ describe("account deletion route", () => { expect(listedTeamsAfterTombstone).toBe(true); expect(listUserVms).toHaveBeenCalledWith("account-user-1"); expect(listUserVms).toHaveBeenCalledWith("account-user-1", "team-personal-page-2"); - expect(destroyVm).toHaveBeenCalledWith({ + expect(destroyVm).toHaveBeenCalledWith(expect.objectContaining({ userId: "account-user-1", billingTeamId: "team-personal-page-2", teamIds: ["account-user-1", "team-personal-page-2"], providerVmId: "personal-team-vm", provider: "freestyle", - }); + })); }); test("accepts non-paginated Stack team member arrays with 100 members", async () => { @@ -1161,6 +1171,44 @@ describe("account deletion route", () => { ); }); + test("keeps VM cleanup retryable when provider destroy succeeds but DB mark fails", async () => { + listedPersonalVmIds = ["personal-vm-1"]; + revokedIdentityLeaseCount = 0; + destroyVmAfterProviderErrorsByProviderId = new Map([ + ["personal-vm-1", new Error("mark destroyed failed")], + ]); + + const response = await DELETE(accountDeletionRequest()); + + expect(response.status).toBe(500); + expect(await response.json()).toEqual({ + error: "account_delete_retryable", + retryable: true, + destroyedVms: 0, + }); + expect(destroyVm).toHaveBeenCalledWith(expect.objectContaining({ + userId: "account-user-1", + teamIds: ["account-user-1"], + providerVmId: "personal-vm-1", + provider: "freestyle", + })); + const destroyVmCalls = (destroyVm as unknown as { + mock: { calls: Array<[{ readonly afterProviderDestroy?: unknown }]> }; + }).mock.calls; + const [destroyInput] = destroyVmCalls[0]; + expect(typeof destroyInput.afterProviderDestroy).toBe("function"); + expect(transaction).toHaveBeenCalledTimes(1); + expect(deleteStackUser).not.toHaveBeenCalled(); + expect(updateStackUser).toHaveBeenNthCalledWith(1, { + clientReadOnlyMetadata: { cmuxAccountDeleting: true }, + }); + expect(updateStackUser).toHaveBeenCalledTimes(1); + expect(consoleError).toHaveBeenCalledWith( + "account.delete.partial_after_destructive_cleanup", + "AccountDeletionDestructiveCleanupError: Failed to destroy 1 personal cloud VM", + ); + }); + test("keeps deletion retryable after Subrouter 404 removes local tenant state", async () => { listedPersonalVmIds = []; revokedIdentityLeaseCount = 0; @@ -1310,12 +1358,12 @@ describe("account deletion route", () => { expect(response.status).toBe(200); expect(await response.json()).toEqual({ ok: true, destroyedVms: 1 }); expect(destroyVm).toHaveBeenCalledTimes(1); - expect(destroyVm).toHaveBeenCalledWith({ + expect(destroyVm).toHaveBeenCalledWith(expect.objectContaining({ userId: "account-user-1", teamIds: ["account-user-1"], providerVmId: "personal-vm-1", provider: "freestyle", - }); + })); expect(deletedTables).toContain(cloudVms); expect(deleteStackUser).toHaveBeenCalledTimes(1); }); @@ -1507,18 +1555,18 @@ describe("account deletion route", () => { destroyedVms: 1, }); expect(destroyVm).toHaveBeenCalledTimes(2); - expect(destroyVm).toHaveBeenCalledWith({ + expect(destroyVm).toHaveBeenCalledWith(expect.objectContaining({ userId: "account-user-1", teamIds: ["account-user-1"], providerVmId: "personal-vm-1", provider: "freestyle", - }); - expect(destroyVm).toHaveBeenCalledWith({ + })); + expect(destroyVm).toHaveBeenCalledWith(expect.objectContaining({ userId: "account-user-1", teamIds: ["account-user-1"], providerVmId: "personal-vm-2", provider: "freestyle", - }); + })); expect(transaction).toHaveBeenCalledTimes(1); expect(deleteStackUser).not.toHaveBeenCalled(); expect(updateStackUser).toHaveBeenNthCalledWith(1, { @@ -1547,18 +1595,18 @@ describe("account deletion route", () => { destroyedVms: 0, }); expect(destroyVm).toHaveBeenCalledTimes(2); - expect(destroyVm).toHaveBeenCalledWith({ + expect(destroyVm).toHaveBeenCalledWith(expect.objectContaining({ userId: "account-user-1", teamIds: ["account-user-1"], providerVmId: "personal-vm-1", provider: "freestyle", - }); - expect(destroyVm).toHaveBeenCalledWith({ + })); + expect(destroyVm).toHaveBeenCalledWith(expect.objectContaining({ userId: "account-user-1", teamIds: ["account-user-1"], providerVmId: "personal-vm-2", provider: "freestyle", - }); + })); expect(transaction).toHaveBeenCalledTimes(1); expect(deleteStackUser).not.toHaveBeenCalled(); expect(updateStackUser).toHaveBeenNthCalledWith(1, { From d84a3dfa25ea0b8949f5e076e9edd9e2aeac297a Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Thu, 9 Jul 2026 09:38:48 -0700 Subject: [PATCH 83/89] Keep account deletion cleanup progressing --- web/services/billing/purchase.ts | 35 +++++++++++++------- web/services/vms/workflows.ts | 5 ++- web/tests/billing-purchase.test.ts | 53 ++++++++++++++++++++++++++++++ web/tests/vm-workflows.test.ts | 34 +++++++++++++++++++ 4 files changed, 115 insertions(+), 12 deletions(-) diff --git a/web/services/billing/purchase.ts b/web/services/billing/purchase.ts index 77ebfe4395e6..e555f5e760e7 100644 --- a/web/services/billing/purchase.ts +++ b/web/services/billing/purchase.ts @@ -301,11 +301,15 @@ export async function applySubscriptionUpdate( if (!stackUserId || stackUserId === DELETED_ACCOUNT_ACTOR_ID) return { skipped: true }; const isActive = isActiveStripeSubscriptionStatus(subscription.status); const ownerStackUserId = teamSubscriptionOwnerStackUserId(stackUserId, teamScope.stackTeamId); - if (!ownerStackUserId) return { skipped: true }; - const lockedResult = await withAccountDeletionUserLock( - db, - ownerStackUserId, - async (tx): Promise< + const legacyTeamScopedOwner = stackUserId === teamScope.stackTeamId; + if (!ownerStackUserId && !legacyTeamScopedOwner) return { skipped: true }; + + const applyTeamUpdate = async ( + tx: BillingDbClient, + expectedOwner: + | { kind: "user"; stackUserId: string } + | { kind: "legacy-team" }, + ): Promise< | { skipped: true } | { scope: "team"; stackTeamId: string; isActive: boolean } > => { @@ -326,11 +330,13 @@ export async function applySubscriptionUpdate( transactionStackUserId, teamScope.stackTeamId, ); - if (transactionOwnerStackUserId !== ownerStackUserId) return { skipped: true }; - if (transactionOwnerStackUserId) { - if (await hasCheckoutBlockingAccountDeletionTombstone(transactionOwnerStackUserId, tx)) return { skipped: true }; - const owner = await loadOptionalStackUser(transactionOwnerStackUserId, dependencies.stackApp); + if (expectedOwner.kind === "user") { + if (transactionOwnerStackUserId !== expectedOwner.stackUserId) return { skipped: true }; + if (await hasCheckoutBlockingAccountDeletionTombstone(expectedOwner.stackUserId, tx)) return { skipped: true }; + const owner = await loadOptionalStackUser(expectedOwner.stackUserId, dependencies.stackApp); if (!owner || isAccountDeletionInProgress(owner)) return { skipped: true }; + } else if (transactionStackUserId !== teamScope.stackTeamId) { + return { skipped: true }; } await upsertTeamStripeCustomer(tx, { @@ -347,8 +353,15 @@ export async function applySubscriptionUpdate( }); return { scope: "team", stackTeamId: teamScope.stackTeamId, isActive }; - }, - ); + }; + + const lockedResult = ownerStackUserId + ? await withAccountDeletionUserLock( + db, + ownerStackUserId, + (tx) => applyTeamUpdate(tx, { kind: "user", stackUserId: ownerStackUserId }), + ) + : await db.transaction((tx) => applyTeamUpdate(tx, { kind: "legacy-team" })); if ("skipped" in lockedResult) return { skipped: true }; const team = await loadStackTeam(teamScope.stackTeamId, dependencies.stackApp); await syncTeamPlanMetadata(team, isActive); diff --git a/web/services/vms/workflows.ts b/web/services/vms/workflows.ts index 71d8632b3e04..bda69e355e2e 100644 --- a/web/services/vms/workflows.ts +++ b/web/services/vms/workflows.ts @@ -1337,7 +1337,10 @@ export function revokeUserIdentityLeasesForAccountDeletion( const revokedIds: string[] = []; for (const lease of leases) { const identityHandle = lease.providerIdentityHandle; - if (!identityHandle) continue; + if (!identityHandle) { + revokedIds.push(lease.id); + continue; + } const revoked = yield* revokeSSHIdentityForCleanup(providers, lease.provider, identityHandle).pipe( Effect.as(true), Effect.catchAll((err) => { diff --git a/web/tests/billing-purchase.test.ts b/web/tests/billing-purchase.test.ts index 8b2f600cffbc..46abcb7ef72e 100644 --- a/web/tests/billing-purchase.test.ts +++ b/web/tests/billing-purchase.test.ts @@ -847,6 +847,59 @@ describe("recordCheckoutCompletion", () => { }); }); + test("syncs legacy Team subscription webhooks whose customer owner is the team id", async () => { + const getUser = mock(async () => { + throw new Error("should not load Stack user for legacy Team-owned billing rows"); + }); + const updateTeam = mock(async () => undefined); + const team = { + id: "team_123", + clientReadOnlyMetadata: { cmuxPlan: "team", cmuxVmPlan: "pro" }, + update: updateTeam, + }; + selectResults = [[{ stackUserId: "team_123" }], [{ stackUserId: "team_123" }]]; + + const result = await applySubscriptionUpdate( + { + id: "sub_team", + customer: "cus_team", + status: "canceled", + metadata: { stackTeamId: "team_123", plan: "team", app: "cmux" }, + cancel_at_period_end: false, + items: { + data: [ + { + quantity: 7, + current_period_end: 1_800_000_000, + price: { id: "price_team" }, + }, + ], + }, + } as never, + { + db: fakeDb() as never, + stackApp: { + getUser, + getTeam: async () => team, + } as never, + }, + ); + + expect(result).toEqual({ scope: "team", stackTeamId: "team_123", isActive: false }); + expect(getUser).not.toHaveBeenCalled(); + expect( + inserts.some( + (insert) => + insert.table === stripeSubscriptions && + insert.values.scope === "team" && + insert.values.stackUserId === "team_123", + ), + ).toBe(true); + expect(updateTeam).toHaveBeenCalledWith({ + clientReadOnlyMetadata: { cmuxVmPlan: "pro" }, + }); + }); + test("skips Team subscription webhooks for deleted-account owner rows", async () => { const getTeam = mock(async () => { throw new Error("should not load Stack team for deleted account owner"); diff --git a/web/tests/vm-workflows.test.ts b/web/tests/vm-workflows.test.ts index 32190dca54dc..fcb5ce1007ed 100644 --- a/web/tests/vm-workflows.test.ts +++ b/web/tests/vm-workflows.test.ts @@ -478,6 +478,40 @@ describe("VM Effect workflows", () => { ]); }); + test("marks empty account-deletion SSH identity handles revoked without a provider call", async () => { + const revokedLeaseIds: string[] = []; + const repo = testWorkflowRepo({ + vm: testCloudVmRow(), + accountDeletionIdentityLeases: () => + Effect.succeed([ + testIdentityLease("lease-account-delete-empty", ""), + testIdentityLease("lease-account-delete-real", "identity-account-delete-real"), + ]), + revokedLeaseIds, + }); + const revokedIdentities: string[] = []; + const provider: VmProviderGatewayShape = { + ...unusedProviderGateway(), + revokeSSHIdentity: (_provider, identityHandle) => + Effect.sync(() => { + revokedIdentities.push(identityHandle); + }), + }; + + const revokedCount = await Effect.runPromise( + revokeUserIdentityLeasesForAccountDeletion("user-workflow-account-delete").pipe( + Effect.provide(workflowLayer(repo, provider)), + ), + ); + + expect(revokedCount).toBe(2); + expect(revokedIdentities).toEqual(["identity-account-delete-real"]); + expect(revokedLeaseIds).toEqual([ + "lease-account-delete-empty", + "lease-account-delete-real", + ]); + }); + test("revokes account-deletion SSH identities in bounded batches", async () => { const requestedLimits: number[] = []; const refreshedAfterBatch: number[] = []; From 3ff08ceaf7a1446409fd2e320f75da7484736612 Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Thu, 9 Jul 2026 09:48:37 -0700 Subject: [PATCH 84/89] Separate account deletion VM blocks --- web/services/vms/errors.ts | 13 ++++++++++++ web/services/vms/repository.ts | 18 ++++++++-------- web/services/vms/routeHelpers.ts | 12 +++++++++++ web/tests/vm-route-auth.test.ts | 35 ++++++++++++++++++++++++++++++-- web/tests/vm-workflows.test.ts | 6 ++---- 5 files changed, 70 insertions(+), 14 deletions(-) diff --git a/web/services/vms/errors.ts b/web/services/vms/errors.ts index f678ace09ed3..ff79ee23bfa4 100644 --- a/web/services/vms/errors.ts +++ b/web/services/vms/errors.ts @@ -35,6 +35,11 @@ export class VmCreateDisabledError extends Data.TaggedError("VmCreateDisabledErr readonly reason: string; }> {} +export class VmAccountDeletionInProgressError extends Data.TaggedError("VmAccountDeletionInProgressError")<{ + readonly provider?: ProviderId; + readonly phase?: "create"; +}> {} + export class VmImageConfigError extends Data.TaggedError("VmImageConfigError")<{ readonly provider: ProviderId; readonly image?: string; @@ -73,6 +78,7 @@ export type VmWorkflowError = | VmCreateInProgressError | VmCreateFailedError | VmCreateDisabledError + | VmAccountDeletionInProgressError | VmImageConfigError | VmLimitExceededError | VmCreateCreditsInsufficientError @@ -99,6 +105,12 @@ export function isVmCreateDisabledError(err: unknown): err is VmCreateDisabledEr return (err as { _tag?: string } | null)?._tag === "VmCreateDisabledError"; } +export function isVmAccountDeletionInProgressError( + err: unknown, +): err is VmAccountDeletionInProgressError { + return (err as { _tag?: string } | null)?._tag === "VmAccountDeletionInProgressError"; +} + export function isVmImageConfigError(err: unknown): err is VmImageConfigError { return (err as { _tag?: string } | null)?._tag === "VmImageConfigError"; } @@ -136,6 +148,7 @@ const vmWorkflowErrorTags = new Set([ "VmCreateInProgressError", "VmCreateFailedError", "VmCreateDisabledError", + "VmAccountDeletionInProgressError", "VmImageConfigError", "VmLimitExceededError", "VmCreateCreditsInsufficientError", diff --git a/web/services/vms/repository.ts b/web/services/vms/repository.ts index cebbafdf47db..1216e4def04c 100644 --- a/web/services/vms/repository.ts +++ b/web/services/vms/repository.ts @@ -23,8 +23,10 @@ import type { ProviderId } from "./drivers"; import { VmCreateDisabledError, VmCreateInProgressError, + VmAccountDeletionInProgressError, VmDatabaseError, VmLimitExceededError, + isVmAccountDeletionInProgressError, isVmCreateDisabledError, isVmLimitExceededError, } from "./errors"; @@ -86,7 +88,7 @@ export type VmRepositoryShape = { readonly imageVersion?: string | null; readonly maxActiveVms: number; readonly idempotencyKey?: string; - }) => Effect.Effect; + }) => Effect.Effect; readonly beginBaseOpen: (input: { readonly userId: string; readonly billingTeamId: string; @@ -97,7 +99,7 @@ export type VmRepositoryShape = { readonly imageVersion?: string | null; readonly maxActiveVms: number; readonly baseName?: string; - }) => Effect.Effect; + }) => Effect.Effect; readonly beginBaseReset: (input: { readonly userId: string; readonly billingTeamId: string; @@ -109,7 +111,7 @@ export type VmRepositoryShape = { readonly maxActiveVms: number; readonly baseName?: string; readonly reason?: string | null; - }) => Effect.Effect, VmCreateDisabledError | VmCreateInProgressError | VmDatabaseError | VmLimitExceededError>; + }) => Effect.Effect, VmCreateDisabledError | VmAccountDeletionInProgressError | VmCreateInProgressError | VmDatabaseError | VmLimitExceededError>; readonly markBaseCreateRunning: (input: { readonly baseId: string; readonly generation: number; @@ -270,9 +272,9 @@ async function assertAccountVmCreateAllowed( .where(eq(accountDeletionTombstones.userIdHash, userIdHash)) .limit(1); if (deletion?.userIdHash !== userIdHash || !isBlockingAccountDeletionStatus(deletion.status)) return; - throw new VmCreateDisabledError({ + throw new VmAccountDeletionInProgressError({ provider: input.provider, - reason: "Account deletion is in progress.", + phase: "create", }); } @@ -519,7 +521,7 @@ export const VmRepositoryLive = Layer.succeed(VmRepository, { throw err; } }, - catch: (cause) => isVmCreateDisabledError(cause) || isVmLimitExceededError(cause) + catch: (cause) => isVmCreateDisabledError(cause) || isVmAccountDeletionInProgressError(cause) || isVmLimitExceededError(cause) ? cause : new VmDatabaseError({ operation: "beginCreate", cause }), }), @@ -724,7 +726,7 @@ export const VmRepositoryLive = Layer.succeed(VmRepository, { throw err; } }, - catch: (cause) => isVmCreateDisabledError(cause) || isVmLimitExceededError(cause) + catch: (cause) => isVmCreateDisabledError(cause) || isVmAccountDeletionInProgressError(cause) || isVmLimitExceededError(cause) ? cause : new VmDatabaseError({ operation: "beginBaseOpen", cause }), }), @@ -889,7 +891,7 @@ export const VmRepositoryLive = Layer.succeed(VmRepository, { }; }); }, - catch: (cause) => isVmCreateDisabledError(cause) || isVmLimitExceededError(cause) + catch: (cause) => isVmCreateDisabledError(cause) || isVmAccountDeletionInProgressError(cause) || isVmLimitExceededError(cause) ? cause : new VmDatabaseError({ operation: "beginBaseReset", cause }), }), diff --git a/web/services/vms/routeHelpers.ts b/web/services/vms/routeHelpers.ts index c72d26420134..4dc976dabed1 100644 --- a/web/services/vms/routeHelpers.ts +++ b/web/services/vms/routeHelpers.ts @@ -8,6 +8,7 @@ import { } from "./entitlements"; import { isVmBillingError, + isVmAccountDeletionInProgressError, isVmCreateDisabledError, isVmDatabaseError, isVmProviderOperationError, @@ -257,6 +258,17 @@ export function vmRequiresProResponse(): Response { export function vmWorkflowErrorResponse(err: unknown): Response | null { const workflowError = vmWorkflowErrorCause(err) ?? err; + if (isVmAccountDeletionInProgressError(workflowError)) { + return vmErrorResponse({ + error: "account_deletion_in_progress", + status: 409, + message: "Account deletion is in progress.", + action: "Wait for account deletion to finish before creating Cloud VMs.", + phase: workflowError.phase ?? "create", + retryable: true, + }); + } + if (isVmCreateDisabledError(workflowError)) { return vmErrorResponse({ error: "vm_create_disabled", diff --git a/web/tests/vm-route-auth.test.ts b/web/tests/vm-route-auth.test.ts index 1495de65c601..ed1927d468f8 100644 --- a/web/tests/vm-route-auth.test.ts +++ b/web/tests/vm-route-auth.test.ts @@ -137,6 +137,7 @@ const snapshotRoute = await import("../app/api/vm/[id]/snapshot/route"); const sshRoute = await import("../app/api/vm/[id]/ssh-endpoint/route"); const restoreRoute = await import("../app/api/vm/restore/route"); const { + VmAccountDeletionInProgressError, VmCreateCreditsInsufficientError, VmCreateDisabledError, VmCreateFailedError, @@ -1259,7 +1260,7 @@ describe("VM REST auth", () => { rejectRunVmWorkflowWith( new VmCreateDisabledError({ provider: "freestyle", - reason: "Account deletion is in progress.", + reason: "Cloud VM creation is disabled.", }), ); @@ -1275,7 +1276,7 @@ describe("VM REST auth", () => { const payload = await response.json(); expect(payload).toMatchObject({ error: "vm_create_disabled", - reason: "Account deletion is in progress.", + reason: "Cloud VM creation is disabled.", phase: "create", }); expectNoCloudVmImplementationLeaks(payload); @@ -1283,6 +1284,36 @@ describe("VM REST auth", () => { expect(runVmWorkflow).toHaveBeenCalled(); }); + test("maps workflow account deletion blocks without environment-disabled guidance", async () => { + getUser.mockResolvedValue(authedStackUser()); + rejectRunVmWorkflowWith( + new VmAccountDeletionInProgressError({ + provider: "freestyle", + phase: "create", + }), + ); + + const response = await POST( + new Request("https://cmux.test/api/vm", { + method: "POST", + headers: { origin: "https://cmux.test" }, + body: JSON.stringify({ provider: "freestyle", image: "snapshot-test" }), + }), + ); + + expect(response.status).toBe(409); + const payload = await response.json(); + expect(payload).toMatchObject({ + error: "account_deletion_in_progress", + phase: "create", + retryable: true, + }); + expectNoCloudVmImplementationLeaks(payload); + expect(payload.action).toContain("account deletion"); + expect(payload.action).not.toContain("enable Cloud VM creation"); + expect(runVmWorkflow).toHaveBeenCalled(); + }); + test("blocks provider kill switch before workflow", async () => { process.env.CMUX_VM_E2B_ENABLED = "false"; getUser.mockResolvedValue(authedStackUser()); diff --git a/web/tests/vm-workflows.test.ts b/web/tests/vm-workflows.test.ts index fcb5ce1007ed..e67178ac59a0 100644 --- a/web/tests/vm-workflows.test.ts +++ b/web/tests/vm-workflows.test.ts @@ -23,6 +23,7 @@ import { } from "../services/vms/repository"; import { VmCreateCreditsInsufficientError, + VmAccountDeletionInProgressError, VmAccountDeletionIdentityRevocationError, VmCreateFailedError, VmCreateInProgressError, @@ -1846,10 +1847,7 @@ describe("VM Effect workflows", () => { throw new Error("expected Base VM creation to be blocked"); } catch (error) { const workflowError = vmWorkflowErrorCause(error) ?? error; - expect(isVmCreateDisabledError(workflowError)).toBe(true); - if (isVmCreateDisabledError(workflowError)) { - expect(workflowError.reason).toBe("Account deletion is in progress."); - } + expect(workflowError).toBeInstanceOf(VmAccountDeletionInProgressError); } } From 71b8c8ff21eedec75473a75796d0460b13e8334d Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Thu, 9 Jul 2026 10:00:23 -0700 Subject: [PATCH 85/89] Close account deletion cleanup gaps --- web/app/api/account/route.ts | 34 +++++++++++++++++---- web/app/api/billing/checkout/route.ts | 25 ++++++++++++++++ web/tests/account-route.test.ts | 33 ++++++++++++++++++++ web/tests/billing-checkout-route.test.ts | 38 ++++++++++++++++++++++++ 4 files changed, 125 insertions(+), 5 deletions(-) diff --git a/web/app/api/account/route.ts b/web/app/api/account/route.ts index 8222fdd6d20d..c1589af3e179 100644 --- a/web/app/api/account/route.ts +++ b/web/app/api/account/route.ts @@ -859,7 +859,10 @@ async function deleteCmuxOwnedAccountRows(userId: string, accountTeamIds: readon status: cloudVms.status, }) .from(cloudVms) - .where(eq(cloudVms.userId, userId)) + .where(or( + eq(cloudVms.userId, userId), + inArray(cloudVms.billingTeamId, deletionTeamIds), + )) .for("update"); const personalVmRows = userVmRows.filter((vm) => !vm.billingTeamId || deletionTeamIds.includes(vm.billingTeamId) @@ -877,6 +880,7 @@ async function deleteCmuxOwnedAccountRows(userId: string, accountTeamIds: readon `Personal cloud VM provider teardown or creation is still pending for ${unsafePersonalVmRows.length} row${unsafePersonalVmRows.length === 1 ? "" : "s"}`, ); } + const personalVmIds = personalVmRows.map((vm) => vm.id); await tx.delete(deviceTokens).where(eq(deviceTokens.userId, userId)); await tx.delete(notificationSendEvents).where(eq(notificationSendEvents.userId, userId)); @@ -932,10 +936,30 @@ async function deleteCmuxOwnedAccountRows(userId: string, accountTeamIds: readon ), )); await tx.delete(cloudVmNotificationDeliveries).where(eq(cloudVmNotificationDeliveries.userId, userId)); - await tx.delete(cloudVmNotificationEvents).where(eq(cloudVmNotificationEvents.userId, userId)); - await tx.delete(cloudVmUsageEvents).where(eq(cloudVmUsageEvents.userId, userId)); - await tx.delete(cloudVmLeases).where(eq(cloudVmLeases.userId, userId)); - await tx.delete(cloudVmSessions).where(eq(cloudVmSessions.userId, userId)); + await tx.delete(cloudVmNotificationEvents).where( + personalVmIds.length > 0 + ? or(eq(cloudVmNotificationEvents.userId, userId), inArray(cloudVmNotificationEvents.vmId, personalVmIds)) + : eq(cloudVmNotificationEvents.userId, userId), + ); + await tx.delete(cloudVmUsageEvents).where( + personalVmIds.length > 0 + ? or( + eq(cloudVmUsageEvents.userId, userId), + inArray(cloudVmUsageEvents.billingTeamId, deletionTeamIds), + inArray(cloudVmUsageEvents.vmId, personalVmIds), + ) + : or(eq(cloudVmUsageEvents.userId, userId), inArray(cloudVmUsageEvents.billingTeamId, deletionTeamIds)), + ); + await tx.delete(cloudVmLeases).where( + personalVmIds.length > 0 + ? or(eq(cloudVmLeases.userId, userId), inArray(cloudVmLeases.vmId, personalVmIds)) + : eq(cloudVmLeases.userId, userId), + ); + await tx.delete(cloudVmSessions).where( + personalVmIds.length > 0 + ? or(eq(cloudVmSessions.userId, userId), inArray(cloudVmSessions.vmId, personalVmIds)) + : eq(cloudVmSessions.userId, userId), + ); if (personalVmRows.length > 0) { await tx.delete(cloudVms).where(inArray(cloudVms.id, personalVmRows.map((vm) => vm.id))); } diff --git a/web/app/api/billing/checkout/route.ts b/web/app/api/billing/checkout/route.ts index 0dd3fc010f81..2f2f2c06ac98 100644 --- a/web/app/api/billing/checkout/route.ts +++ b/web/app/api/billing/checkout/route.ts @@ -51,6 +51,9 @@ async function stripeProCheckout(request: NextRequest) { const user = (await stackServerApp!.getUser({ or: "return-null" })) ?? (await stackServerApp!.getUser({ or: "anonymous" })); + if (isAccountDeletionInProgress(user)) { + return accountDeletionCheckoutRedirect(request); + } const status = await resolveProPlanStatus(user); if (status.isPro) { @@ -106,6 +109,9 @@ async function stripeTeamCheckout(request: NextRequest) { const user = (await stackServerApp!.getUser({ or: "return-null" })) ?? (await stackServerApp!.getUser({ or: "anonymous" })); + if (isAccountDeletionInProgress(user)) { + return accountDeletionCheckoutRedirect(request); + } const team = await checkoutTeamCustomer(user); const teamId = team.id; if (!teamId) { @@ -168,6 +174,9 @@ async function legacyStackCheckout( const user = (await stackServerApp!.getUser({ or: "return-null" })) ?? (await stackServerApp!.getUser({ or: "anonymous" })); + if (isAccountDeletionInProgress(user)) { + return accountDeletionCheckoutRedirect(request); + } if (plan === "pro" && (await hasActiveProSubscription(user))) { await syncProPlanMetadata(user, true); @@ -214,6 +223,22 @@ async function legacyStackCheckout( return NextResponse.redirect(checkoutUrl); } +function accountDeletionCheckoutRedirect(request: NextRequest) { + return NextResponse.redirect( + new URL("/pricing?billing=account_deletion_in_progress", request.url), + ); +} + +function isAccountDeletionInProgress(user: { readonly clientReadOnlyMetadata?: unknown }): boolean { + const metadata = user.clientReadOnlyMetadata; + return Boolean( + metadata && + typeof metadata === "object" && + !Array.isArray(metadata) && + (metadata as Record).cmuxAccountDeleting === true + ); +} + type CheckoutTeamCustomer = { readonly id?: string; readonly displayName?: string | null; diff --git a/web/tests/account-route.test.ts b/web/tests/account-route.test.ts index 1d213ce5bd89..6fb0ce8e8b46 100644 --- a/web/tests/account-route.test.ts +++ b/web/tests/account-route.test.ts @@ -6,6 +6,8 @@ import { cloudVmBases, cloudVmBillingGrants, cloudVmLeases, + cloudVmSessions, + cloudVmUsageEvents, cloudVms, devices, stripeCustomers, @@ -760,6 +762,37 @@ describe("account deletion route", () => { expect(conditionColumnNames(baseDelete?.condition)).toContain("scope_id"); }); + test("deletes account-owned team VM rows created by another user", async () => { + listedPersonalVmIds = []; + listedPersonalVmIdsByBillingTeam = { "team-personal": ["personal-team-vm"] }; + stackUserTeams = [stackTeam("team-personal", ["account-user-1"])]; + transactionSelectResults = [[{ + id: "00000000-0000-4000-8000-000000000768", + billingTeamId: "team-personal", + providerVmId: "personal-team-vm", + status: "destroyed", + }]]; + + const response = await DELETE(accountDeletionRequest()); + + expect(response.status).toBe(200); + expect(destroyVm).toHaveBeenCalledWith(expect.objectContaining({ + userId: "account-user-1", + billingTeamId: "team-personal", + teamIds: ["account-user-1", "team-personal"], + providerVmId: "personal-team-vm", + })); + expect(deletedTables).toContain(cloudVms); + expect(updatedRows.map(({ table }) => table)).not.toContain(cloudVms); + const usageDelete = deletedWhere.find((entry) => entry.table === cloudVmUsageEvents); + expect(conditionColumnNames(usageDelete?.condition)).toContain("billing_team_id"); + expect(conditionColumnNames(usageDelete?.condition)).toContain("vm_id"); + const leaseDelete = deletedWhere.find((entry) => entry.table === cloudVmLeases); + expect(conditionColumnNames(leaseDelete?.condition)).toContain("vm_id"); + const sessionDelete = deletedWhere.find((entry) => entry.table === cloudVmSessions); + expect(conditionColumnNames(sessionDelete?.condition)).toContain("vm_id"); + }); + test("joins an in-progress account deletion instead of rerunning destructive cleanup", async () => { transactionTombstoneSelectResults = [[{ userIdHash: "existing-hash", diff --git a/web/tests/billing-checkout-route.test.ts b/web/tests/billing-checkout-route.test.ts index 25924264c4c0..0b714b766c53 100644 --- a/web/tests/billing-checkout-route.test.ts +++ b/web/tests/billing-checkout-route.test.ts @@ -185,6 +185,23 @@ describe("billing checkout route", () => { }); }); + test("blocks Stack checkout while account deletion is in progress", async () => { + userResponses = [{ + ...signedInUser, + clientReadOnlyMetadata: { cmuxAccountDeleting: true }, + }]; + + const response = await GET( + new NextRequest("https://cmux.test/api/billing/checkout"), + ); + + expect(response.status).toBe(307); + expect(response.headers.get("location")).toBe( + "https://cmux.test/pricing?billing=account_deletion_in_progress", + ); + expect(signedInUser.createCheckoutUrl).not.toHaveBeenCalled(); + }); + test("syncs metadata when Stack says Pro checkout is already granted and products confirm it", async () => { userResponses = [signedInUser]; mockImplementation(signedInUser.createCheckoutUrl, async () => { @@ -353,6 +370,27 @@ describe("billing checkout route", () => { }); }); + test("blocks Stripe team checkout while account deletion is in progress", async () => { + stripeConfigured = true; + userResponses = [{ + ...signedInUser, + selectedTeam: teamCustomer, + clientReadOnlyMetadata: { cmuxAccountDeleting: true }, + }]; + + const response = await GET( + new NextRequest("https://cmux.test/api/billing/checkout?plan=team"), + ); + + expect(response.status).toBe(307); + expect(response.headers.get("location")).toBe( + "https://cmux.test/pricing?billing=account_deletion_in_progress", + ); + expect(createStripeCustomer).not.toHaveBeenCalled(); + expect(createStripeSession).not.toHaveBeenCalled(); + expect(teamCustomer.createCheckoutUrl).not.toHaveBeenCalled(); + }); + test("rejects unknown checkout plans", async () => { const response = await GET( new NextRequest("https://cmux.test/api/billing/checkout?plan=enterprise"), From 65327e972c8043f25d1ed927d97b8b4071d6fde3 Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Thu, 9 Jul 2026 10:16:29 -0700 Subject: [PATCH 86/89] Respect account deletion tombstone lease --- web/app/api/account/route.ts | 10 +---- web/services/account/deletionLock.ts | 27 ++++++++++++- web/services/billing/purchase.ts | 9 +++-- web/services/vms/repository.ts | 8 +++- web/tests/account-deletion-lock.test.ts | 36 +++++++++++++++++ web/tests/billing-purchase.test.ts | 4 +- web/tests/device-tokens-route.test.ts | 36 +++++++++++++++++ web/tests/devices-route.test.ts | 27 +++++++++++++ web/tests/vm-workflows.test.ts | 52 +++++++++++++++++++++++++ 9 files changed, 193 insertions(+), 16 deletions(-) create mode 100644 web/tests/account-deletion-lock.test.ts diff --git a/web/app/api/account/route.ts b/web/app/api/account/route.ts index c1589af3e179..5307563a749a 100644 --- a/web/app/api/account/route.ts +++ b/web/app/api/account/route.ts @@ -46,7 +46,7 @@ import { withVaultUserQuotaLock } from "../../../services/vault/usage"; import { accountDeletionAdvisoryLockKey, accountDeletionUserHash, - isBlockingAccountDeletionStatus, + isBlockingAccountDeletionTombstone, } from "../../../services/account/deletionLock"; import { unauthorized } from "../../../services/vms/auth"; import { @@ -103,8 +103,6 @@ type AccountDeletionTombstoneStart = | { readonly kind: "completed" } | { readonly kind: "cleanupIncomplete" }; -const ACCOUNT_DELETION_TOMBSTONE_LEASE_MS = 15 * 60 * 1000; - export async function DELETE(request: Request): Promise { const stackUser = await currentDeletableStackUser(request); if (!stackUser) return unauthorized(); @@ -286,7 +284,7 @@ async function markAccountDeletionTombstonePending(userId: string): Promise= ACCOUNT_DELETION_TOMBSTONE_LEASE_MS; -} - async function markAccountDeletionTombstoneCompleted(userId: string): Promise { const now = new Date(); await cloudDb() diff --git a/web/services/account/deletionLock.ts b/web/services/account/deletionLock.ts index 8bd79af8e14a..9ae7491620fc 100644 --- a/web/services/account/deletionLock.ts +++ b/web/services/account/deletionLock.ts @@ -20,10 +20,31 @@ export function accountDeletionAdvisoryLockKey(userId: string): string { return `account-deletion:${accountDeletionUserHash(userId)}`; } +export const ACCOUNT_DELETION_TOMBSTONE_LEASE_MS = 15 * 60 * 1000; + export function isBlockingAccountDeletionStatus(status: string): boolean { return status !== "failed"; } +export function isStaleAccountDeletionTombstone( + updatedAt: Date | null, + now: Date = new Date(), +): boolean { + return !updatedAt || now.getTime() - updatedAt.getTime() >= ACCOUNT_DELETION_TOMBSTONE_LEASE_MS; +} + +export function isBlockingAccountDeletionTombstone( + tombstone: { + readonly status: string; + readonly updatedAt: Date | null; + }, + now: Date = new Date(), +): boolean { + if (!isBlockingAccountDeletionStatus(tombstone.status)) return false; + if (tombstone.status === "completed" || tombstone.status === "cleanup_incomplete") return true; + return !isStaleAccountDeletionTombstone(tombstone.updatedAt, now); +} + export async function assertAccountDeletionUserMutationAllowed( tx: CloudDbTransaction, userId: string, @@ -34,10 +55,14 @@ export async function assertAccountDeletionUserMutationAllowed( .select({ userIdHash: accountDeletionTombstones.userIdHash, status: accountDeletionTombstones.status, + updatedAt: accountDeletionTombstones.updatedAt, }) .from(accountDeletionTombstones) .where(eq(accountDeletionTombstones.userIdHash, userIdHash)) .limit(1); - if (deletion?.userIdHash !== userIdHash || !isBlockingAccountDeletionStatus(deletion.status)) return; + if ( + deletion?.userIdHash !== userIdHash || + !isBlockingAccountDeletionTombstone(deletion) + ) return; throw new AccountDeletionMutationBlockedError(userId); } diff --git a/web/services/billing/purchase.ts b/web/services/billing/purchase.ts index e555f5e760e7..9372b6d6d297 100644 --- a/web/services/billing/purchase.ts +++ b/web/services/billing/purchase.ts @@ -12,7 +12,7 @@ import { import { accountDeletionAdvisoryLockKey, accountDeletionUserHash, - isBlockingAccountDeletionStatus, + isBlockingAccountDeletionTombstone, } from "../account/deletionLock"; import { PRO_PLAN_ID, @@ -451,11 +451,14 @@ async function hasCheckoutBlockingAccountDeletionTombstone( db: BillingDbClient, ): Promise { const [row] = await db - .select({ status: accountDeletionTombstones.status }) + .select({ + status: accountDeletionTombstones.status, + updatedAt: accountDeletionTombstones.updatedAt, + }) .from(accountDeletionTombstones) .where(eq(accountDeletionTombstones.userIdHash, accountDeletionUserHash(stackUserId))) .limit(1); - return row ? row.status === "completed" || isBlockingAccountDeletionStatus(row.status) : false; + return row ? isBlockingAccountDeletionTombstone(row) : false; } async function withAccountDeletionUserLock( diff --git a/web/services/vms/repository.ts b/web/services/vms/repository.ts index 1216e4def04c..6263faba10d8 100644 --- a/web/services/vms/repository.ts +++ b/web/services/vms/repository.ts @@ -17,7 +17,7 @@ import { import { accountDeletionAdvisoryLockKey, accountDeletionUserHash, - isBlockingAccountDeletionStatus, + isBlockingAccountDeletionTombstone, } from "../account/deletionLock"; import type { ProviderId } from "./drivers"; import { @@ -267,11 +267,15 @@ async function assertAccountVmCreateAllowed( .select({ userIdHash: accountDeletionTombstones.userIdHash, status: accountDeletionTombstones.status, + updatedAt: accountDeletionTombstones.updatedAt, }) .from(accountDeletionTombstones) .where(eq(accountDeletionTombstones.userIdHash, userIdHash)) .limit(1); - if (deletion?.userIdHash !== userIdHash || !isBlockingAccountDeletionStatus(deletion.status)) return; + if ( + deletion?.userIdHash !== userIdHash || + !isBlockingAccountDeletionTombstone(deletion) + ) return; throw new VmAccountDeletionInProgressError({ provider: input.provider, phase: "create", diff --git a/web/tests/account-deletion-lock.test.ts b/web/tests/account-deletion-lock.test.ts new file mode 100644 index 000000000000..0967e3244a9f --- /dev/null +++ b/web/tests/account-deletion-lock.test.ts @@ -0,0 +1,36 @@ +import { describe, expect, test } from "bun:test"; + +import { isBlockingAccountDeletionTombstone } from "../services/account/deletionLock"; + +describe("account deletion tombstone lock", () => { + test("blocks fresh nonterminal deletion tombstones", () => { + const now = new Date("2026-07-09T10:00:00.000Z"); + + expect(isBlockingAccountDeletionTombstone({ + status: "pending", + updatedAt: new Date("2026-07-09T09:55:00.000Z"), + }, now)).toBe(true); + }); + + test("does not block stale pending deletion tombstones", () => { + const now = new Date("2026-07-09T10:00:00.000Z"); + + expect(isBlockingAccountDeletionTombstone({ + status: "pending", + updatedAt: new Date("2026-07-09T09:44:59.999Z"), + }, now)).toBe(false); + }); + + test("keeps terminal deletion tombstones blocking after the lease", () => { + const now = new Date("2026-07-09T10:00:00.000Z"); + + expect(isBlockingAccountDeletionTombstone({ + status: "completed", + updatedAt: new Date("2026-07-09T09:00:00.000Z"), + }, now)).toBe(true); + expect(isBlockingAccountDeletionTombstone({ + status: "cleanup_incomplete", + updatedAt: new Date("2026-07-09T09:00:00.000Z"), + }, now)).toBe(true); + }); +}); diff --git a/web/tests/billing-purchase.test.ts b/web/tests/billing-purchase.test.ts index 46abcb7ef72e..a560bb7200eb 100644 --- a/web/tests/billing-purchase.test.ts +++ b/web/tests/billing-purchase.test.ts @@ -984,7 +984,7 @@ describe("recordCheckoutCompletion", () => { throw new Error("should not load Stack team after tombstone blocks Team subscription"); }); selectResults = [[], [], [], []]; - tombstoneSelectResults = [[{ status: "pending" }]]; + tombstoneSelectResults = [[{ status: "pending", updatedAt: new Date() }]]; const result = await applySubscriptionUpdate( { @@ -1171,7 +1171,7 @@ describe("recordCheckoutCompletion", () => { throw new Error("should not load Stack user after tombstone blocks subscription write"); }); selectResults = [[{ stackUserId: "user_123" }], [{ id: "sub_user" }]]; - tombstoneSelectResults = [[{ status: "pending" }]]; + tombstoneSelectResults = [[{ status: "pending", updatedAt: new Date() }]]; const result = await applySubscriptionUpdate( userSubscriptionUpdate({ status: "canceled" }) as never, diff --git a/web/tests/device-tokens-route.test.ts b/web/tests/device-tokens-route.test.ts index d5fc066277df..99b8ec873bae 100644 --- a/web/tests/device-tokens-route.test.ts +++ b/web/tests/device-tokens-route.test.ts @@ -77,6 +77,42 @@ describe("device token route", () => { expect(stored.total).toBe(0); }); + dbTest("allows registration after a pending account deletion lease expires", async () => { + if (!sql) throw new Error("test database not initialized"); + + await sql` + insert into account_deletion_tombstones (user_id_hash, user_id, status, updated_at) + values ( + ${accountDeletionUserHash("push-user-1")}, + ${"push-user-1"}, + 'pending', + now() - interval '20 minutes' + ) + `; + + const response = await POST( + new Request("https://cmux.test/api/device-tokens", { + method: "POST", + headers: { + authorization: "Bearer access-token", + "x-stack-refresh-token": "refresh-token", + }, + body: JSON.stringify({ + deviceToken: "b".repeat(64), + bundleId: "dev.cmux.ios.push1", + platform: "ios", + }), + }), + ); + + expect(response.status).toBe(200); + expect(await response.json()).toEqual({ ok: true }); + const [stored] = await sql<{ total: number }[]>` + select count(*)::int as total from device_tokens where user_id = 'push-user-1' + `; + expect(stored.total).toBe(1); + }); + dbTest("serializes registration cap enforcement per user", async () => { if (!sql) throw new Error("test database not initialized"); diff --git a/web/tests/devices-route.test.ts b/web/tests/devices-route.test.ts index c8ad49312818..59ba071e34b8 100644 --- a/web/tests/devices-route.test.ts +++ b/web/tests/devices-route.test.ts @@ -98,6 +98,33 @@ describe("device registry route", () => { expect(total).toBe(0); }); + dbTest("allows registration after a pending account deletion lease expires", async () => { + if (!sql) throw new Error("test database not initialized"); + + await sql` + insert into account_deletion_tombstones (user_id_hash, user_id, status, updated_at) + values ( + ${accountDeletionUserHash("registry-user-1")}, + ${"registry-user-1"}, + 'pending', + now() - interval '20 minutes' + ) + `; + + const response = await POST( + registerRequest({ + deviceId: DEVICE_A, + platform: "mac", + tag: "stable", + routes: [{ id: "r1", kind: "tailscale", priority: 0, endpoint: { host: "100.1.2.3", port: 51001 } }], + }), + ); + + expect(response.status).toBe(200); + const [{ total }] = await sql<{ total: number }[]>`select count(*)::int as total from devices`; + expect(total).toBe(1); + }); + dbTest("registers a Mac and its app instance, then lists it for the team", async () => { if (!sql) throw new Error("test database not initialized"); diff --git a/web/tests/vm-workflows.test.ts b/web/tests/vm-workflows.test.ts index e67178ac59a0..74c0a9372ced 100644 --- a/web/tests/vm-workflows.test.ts +++ b/web/tests/vm-workflows.test.ts @@ -1859,6 +1859,58 @@ describe("VM Effect workflows", () => { expect(vmCount).toBe("0"); }); + dbTest("opens Base after a pending account deletion lease expires", async () => { + if (!sql) throw new Error("test database not initialized"); + await sql` + truncate account_deletion_tombstones, cloud_vm_base_events, cloud_vm_base_generations, + cloud_vm_bases, cloud_vm_billing_grants, cloud_vm_usage_events, cloud_vm_leases, + cloud_vms restart identity cascade + `; + await sql` + insert into account_deletion_tombstones (user_id_hash, user_id, status, updated_at) + values ( + ${accountDeletionUserHash("user-base-stale-delete")}, + 'user-base-stale-delete', + 'pending', + now() - interval '20 minutes' + ) + `; + + let createCalls = 0; + const provider: VmProviderGatewayShape = { + create: () => + Effect.sync(() => { + createCalls += 1; + return { + provider: "e2b" as const, + providerVmId: "provider-vm-base-stale-delete", + status: "running" as const, + image: "cmuxd-ws:test", + createdAt: Date.now(), + }; + }), + destroy: () => Effect.void, + exec: () => Effect.succeed({ exitCode: 0, stdout: "", stderr: "" }), + openAttach: () => Effect.fail(new Error("unused") as never), + openSSH: () => Effect.fail(new Error("unused") as never), + revokeSSHIdentity: () => Effect.void, + }; + + const vm = await Effect.runPromise(openBaseVm({ + userId: "user-base-stale-delete", + billingCustomerType: "user", + billingTeamId: "user-base-stale-delete", + billingPlanId: "free", + maxActiveVms: 1, + provider: "e2b", + image: "cmuxd-ws:test", + baseName: "default", + }).pipe(Effect.provide(providerLayer(provider)))); + + expect(createCalls).toBe(1); + expect(vm.providerVmId).toBe("provider-vm-base-stale-delete"); + }); + dbTest("opens Base as one stable VM per account scope", async () => { if (!sql) throw new Error("test database not initialized"); await sql`truncate cloud_vm_billing_grants, cloud_vm_usage_events, cloud_vm_leases, cloud_vms restart identity cascade`; From 47f7ea59b0a0183937a7f503ffca9bdfe05d48bf Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Thu, 9 Jul 2026 10:35:49 -0700 Subject: [PATCH 87/89] Close account deletion route cleanup gaps --- web/app/api/account/route.ts | 22 ++++-- web/tests/account-route.test.ts | 129 +++++++++++++++++++++++++++++++- 2 files changed, 142 insertions(+), 9 deletions(-) diff --git a/web/app/api/account/route.ts b/web/app/api/account/route.ts index 5307563a749a..50dc9cad36d2 100644 --- a/web/app/api/account/route.ts +++ b/web/app/api/account/route.ts @@ -125,7 +125,10 @@ export async function DELETE(request: Request): Promise { return jsonResponse({ ok: true, destroyedVms: 0 }, 200); } if (tombstoneStart.kind === "cleanupIncomplete") { - return jsonResponse({ ok: true, cleanupIncomplete: true, destroyedVms: 0 }, 202); + const accountScope = await accountDeletionScopeForUser(stackUser); + await finishPostStackAccountCleanup(userId, accountScope.teamIds); + await markAccountDeletionTombstoneCompleted(userId); + return jsonResponse({ ok: true, destroyedVms: 0 }, 200); } const accountScope = await accountDeletionScopeForUser(stackUser); await markAccountDeletingAndClearBillingEntitlements(stackUser); @@ -198,6 +201,7 @@ export async function DELETE(request: Request): Promise { await deleteCmuxOwnedAccountRows(userId, accountScope.teamIds); cmuxOwnedRowsDeleted = true; try { + await markAccountDeletionTombstoneStackDeletePending(userId); await stackUser.delete(); } catch (error) { logAccountDeleteError("account.delete.stack_user_failed_after_data_delete", error); @@ -337,6 +341,17 @@ async function markAccountDeletionTombstoneFailed(userId: string, error: unknown .where(eq(accountDeletionTombstones.userIdHash, accountDeletionUserHash(userId))); } +async function markAccountDeletionTombstoneStackDeletePending(userId: string): Promise { + await cloudDb() + .update(accountDeletionTombstones) + .set({ + status: "stack_delete_pending", + updatedAt: new Date(), + errorMessage: null, + }) + .where(eq(accountDeletionTombstones.userIdHash, accountDeletionUserHash(userId))); +} + async function markAccountDeletionTombstoneCleanupIncomplete(userId: string, error: unknown): Promise { const now = new Date(); await cloudDb() @@ -658,7 +673,6 @@ async function resolveUserBillingForAccountDeletion( for (const customer of retainedTeamCustomers) { const retainedOwnerId = retainedOwnerByTeam.get(customer.stackTeamId ?? ""); if (!retainedOwnerId) throw new Error(`retained team billing owner missing for ${customer.stackTeamId}`); - options.beforeExternalRequest?.(); await client.customers.update(customer.id, { email: "", metadata: { @@ -679,7 +693,6 @@ async function resolveUserBillingForAccountDeletion( for (const subscription of retainedTeamSubscriptions) { const retainedOwnerId = retainedOwnerByTeam.get(subscription.stackTeamId ?? ""); if (!retainedOwnerId) throw new Error(`retained team billing owner missing for ${subscription.stackTeamId}`); - options.beforeExternalRequest?.(); await client.subscriptions.update(subscription.id, { metadata: { stackUserId: retainedOwnerId, @@ -713,7 +726,7 @@ function stripeSubscriptionBelongsToDeletingAccount( deletionTeamIds: readonly string[], ): boolean { const scope = subscription.scope ?? "user"; - if (scope === "user" && !subscription.stackTeamId) return true; + if (scope === "user") return true; return scope === "team" && typeof subscription.stackTeamId === "string" && deletionTeamIds.includes(subscription.stackTeamId); @@ -1016,7 +1029,6 @@ async function deletePersonalSubrouterTenant( options.afterExternalMutation?.(); } catch (error) { if (!(error instanceof SubrouterClientError && error.status === 404)) throw error; - options.afterExternalMutation?.(); } } await db.delete(subrouterTenants).where(inArray(subrouterTenants.teamId, teamIds)); diff --git a/web/tests/account-route.test.ts b/web/tests/account-route.test.ts index 6fb0ce8e8b46..fb5856ed5dbd 100644 --- a/web/tests/account-route.test.ts +++ b/web/tests/account-route.test.ts @@ -137,6 +137,13 @@ const updateRows = mock((table: unknown) => ({ ) { throw tombstoneCompleteError; } + if ( + table === accountDeletionTombstones && + (values as { readonly status?: unknown }).status === "cleanup_incomplete" && + tombstoneCleanupIncompleteError + ) { + throw tombstoneCleanupIncompleteError; + } }, }; }, @@ -229,11 +236,13 @@ const updateCustomer = mock(async (...args: unknown[]) => { const [customerId, params] = args as [string, Record]; routeEvents.push("stripe-update-customer"); updatedStripeCustomers.push({ id: customerId, params }); + if (stripeUpdateCustomerError) throw stripeUpdateCustomerError; }); const updateSubscription = mock(async (...args: unknown[]) => { const [subscriptionId, params] = args as [string, Record]; routeEvents.push("stripe-update-subscription"); updatedStripeSubscriptions.push({ id: subscriptionId, params }); + if (stripeUpdateSubscriptionError) throw stripeUpdateSubscriptionError; }); const removeTester = mock(async (...args: unknown[]) => { const [email] = args as [string]; @@ -246,6 +255,8 @@ const captureAscError = mock((..._args: unknown[]) => { const revokeTenant = mock(async (...args: unknown[]) => { const [tenantId] = args as [string]; routeEvents.push(`subrouter-revoke:${tenantId}`); + const sequenceError = subrouterRevokeErrors.shift(); + if (sequenceError) throw sequenceError; if (subrouterRevokeError) throw subrouterRevokeError; }); @@ -256,6 +267,7 @@ let selectedWhere: Array<{ readonly table: unknown; readonly condition: unknown let updatedRows: Array<{ readonly table: unknown; readonly values: unknown }> = []; let tombstoneUpdates: unknown[] = []; let tombstoneCompleteError: unknown = null; +let tombstoneCleanupIncompleteError: unknown = null; let routeEvents: string[] = []; let stackDeleteError: unknown = null; let stackUserIds: Array = []; @@ -273,6 +285,8 @@ let updatedStripeCustomers: Array<{ readonly id: string; readonly params: Record let updatedStripeSubscriptions: Array<{ readonly id: string; readonly params: Record }> = []; let stripeCancelError: unknown = null; let stripeDeleteCustomerError: unknown = null; +let stripeUpdateCustomerError: unknown = null; +let stripeUpdateSubscriptionError: unknown = null; let removeTesterError: unknown = null; let destroyVmFailureProviderIds = new Set(); let destroyVmFailureErrorsByProviderId = new Map(); @@ -283,6 +297,7 @@ let revokeIdentityLeasesError: unknown = null; let revokedIdentityLeaseCount = 2; let subrouterClientCreateError: unknown = null; let subrouterRevokeError: unknown = null; +let subrouterRevokeErrors: unknown[] = []; let stackUserSelectedTeam: unknown = null; let stackUserTeams: StackList = []; let useAccountRouteStubs = false; @@ -534,6 +549,7 @@ beforeEach(() => { updatedRows = []; tombstoneUpdates = []; tombstoneCompleteError = null; + tombstoneCleanupIncompleteError = null; routeEvents = []; stackDeleteError = null; stackUserIds = []; @@ -551,6 +567,8 @@ beforeEach(() => { updatedStripeSubscriptions = []; stripeCancelError = null; stripeDeleteCustomerError = null; + stripeUpdateCustomerError = null; + stripeUpdateSubscriptionError = null; removeTesterError = null; destroyVmFailureProviderIds = new Set(); destroyVmFailureErrorsByProviderId = new Map(); @@ -562,6 +580,7 @@ beforeEach(() => { lastRevokeIdentityCall = null; subrouterClientCreateError = null; subrouterRevokeError = null; + subrouterRevokeErrors = []; stackUserSelectedTeam = null; stackUserTeams = []; vaultLockUsers = []; @@ -655,6 +674,9 @@ describe("account deletion route", () => { ); expect(completedTombstone).toBeTruthy(); expect((completedTombstone as { readonly completedAt?: unknown }).completedAt).toBeInstanceOf(Date); + expect(tombstoneUpdates.some((update) => + (update as { readonly status?: unknown }).status === "stack_delete_pending" + )).toBe(true); const leaseRefreshes = tombstoneUpdates.filter((update) => Boolean( update && @@ -720,7 +742,7 @@ describe("account deletion route", () => { stackUserTeams = [stackTeam("team-personal", ["account-user-1"])]; selectResults = [ [ - { id: "sub_user_active" }, + { id: "sub_user_active", stackTeamId: "legacy-user-team", scope: "user", status: "active" }, { id: "sub_team_active", stackTeamId: "team-personal", scope: "team", status: "active" }, ], [{ id: "cus_user" }, { id: "cus_team", stackTeamId: "team-personal" }], @@ -834,7 +856,7 @@ describe("account deletion route", () => { expect(deleteStackUser).not.toHaveBeenCalled(); }); - test("returns cleanup incomplete when a retry sees a cleanup-incomplete tombstone", async () => { + test("resumes post-Stack cleanup when a retry sees a cleanup-incomplete tombstone", async () => { transactionTombstoneSelectResults = [[{ userIdHash: "existing-hash", status: "cleanup_incomplete", @@ -843,16 +865,18 @@ describe("account deletion route", () => { const response = await DELETE(accountDeletionRequest()); - expect(response.status).toBe(202); + expect(response.status).toBe(200); expect(await response.json()).toEqual({ ok: true, - cleanupIncomplete: true, destroyedVms: 0, }); expect(updateStackUser).not.toHaveBeenCalled(); expect(cancelSubscription).not.toHaveBeenCalled(); expect(listUserVms).not.toHaveBeenCalled(); expect(deleteStackUser).not.toHaveBeenCalled(); + expect(tombstoneUpdates.some((values) => + (values as { readonly status?: unknown }).status === "completed" + )).toBe(true); }); test("adopts a stale in-progress account deletion instead of blocking forever", async () => { @@ -1004,6 +1028,31 @@ describe("account deletion route", () => { }); }); + test("restores Stack metadata when retained shared-team Stripe transfer fails before mutation", async () => { + listedPersonalVmIds = []; + stackUserSelectedTeam = stackTeam("team-shared", ["account-user-1", "other-user"]); + selectResults = [ + [], + [{ id: "cus_shared", stackTeamId: "team-shared" }], + ]; + stripeUpdateCustomerError = new Error("stripe update timed out"); + + const response = await DELETE(accountDeletionRequest()); + + expect(response.status).toBe(500); + expect(await response.json()).toEqual({ error: "account_delete_failed" }); + expect(updateCustomer).toHaveBeenCalledWith("cus_shared", expect.objectContaining({ + metadata: expect.objectContaining({ stackUserId: "other-user" }), + })); + expect(deleteStackUser).not.toHaveBeenCalled(); + expect(updateStackUser).toHaveBeenNthCalledWith(1, { + clientReadOnlyMetadata: { cmuxAccountDeleting: true }, + }); + expect(updateStackUser).toHaveBeenNthCalledWith(2, { + clientReadOnlyMetadata: { cmuxPlan: "pro" }, + }); + }); + test("fails closed when Stack cannot list selected team members", async () => { stackUserSelectedTeam = { id: "team-shared" }; @@ -1305,6 +1354,39 @@ describe("account deletion route", () => { }); }); + test("restores Stack metadata when Subrouter 404 is followed by a pre-mutation failure", async () => { + listedPersonalVmIds = []; + revokedIdentityLeaseCount = 0; + selectResults = [ + [], + [], + [], + [], + [], + [], + [{ tenantId: "tenant-missing" }, { tenantId: "tenant-timeout" }], + ]; + subrouterRevokeErrors = [ + new subrouterClientModule.SubrouterClientError("revokeTenant", 404), + new Error("subrouter request timed out"), + ]; + + const response = await DELETE(accountDeletionRequest()); + + expect(response.status).toBe(500); + expect(await response.json()).toEqual({ error: "account_delete_failed" }); + expect(revokeTenant).toHaveBeenCalledWith("tenant-missing"); + expect(revokeTenant).toHaveBeenCalledWith("tenant-timeout"); + expect(deletedTables).not.toContain(subrouterTenants); + expect(deleteStackUser).not.toHaveBeenCalled(); + expect(updateStackUser).toHaveBeenNthCalledWith(1, { + clientReadOnlyMetadata: { cmuxAccountDeleting: true }, + }); + expect(updateStackUser).toHaveBeenNthCalledWith(2, { + clientReadOnlyMetadata: { cmuxPlan: "pro" }, + }); + }); + test("restores Stack metadata when local Subrouter configuration fails before external mutation", async () => { listedPersonalVmIds = []; revokedIdentityLeaseCount = 0; @@ -1762,6 +1844,45 @@ describe("account deletion route", () => { ); }); + test("records Stack-delete phase before post-Stack cleanup-incomplete marking can fail", async () => { + postStackVaultDeleteError = new Error("post-delete vault unavailable"); + tombstoneCleanupIncompleteError = new Error("tombstone unavailable"); + selectResults = [ + [], + [], + [], + [], + [], + [], + [], + [], + [], + [], + [{ id: "post-stack-session", latestObjectKey: "vault/u/account-user-1/post-stack-latest.jsonl.zst" }], + ]; + + const response = await DELETE(accountDeletionRequest()); + + expect(response.status).toBe(202); + expect(await response.json()).toEqual({ + ok: true, + cleanupIncomplete: true, + destroyedVms: 2, + }); + expect(deleteStackUser).toHaveBeenCalledTimes(1); + const statusUpdates = tombstoneUpdates + .map((values) => (values as { readonly status?: unknown }).status) + .filter(Boolean); + expect(statusUpdates).toContain("stack_delete_pending"); + expect(statusUpdates.indexOf("stack_delete_pending")).toBeLessThan( + statusUpdates.indexOf("cleanup_incomplete"), + ); + expect(consoleError).toHaveBeenCalledWith( + "account.delete.post_stack_cleanup_mark_incomplete", + "Error: tombstone unavailable", + ); + }); + test("returns accepted deletion when tombstone completion fails after the account is deleted", async () => { tombstoneCompleteError = new Error("tombstone unavailable"); From e957eaeaeaa3fd3fc343aeca04c55188004dd7c5 Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Thu, 9 Jul 2026 10:45:22 -0700 Subject: [PATCH 88/89] Preserve legacy team checkout completion --- web/services/billing/purchase.ts | 22 +++++++++---- web/tests/billing-purchase.test.ts | 51 ++++++++++++++++++++++++++++++ 2 files changed, 67 insertions(+), 6 deletions(-) diff --git a/web/services/billing/purchase.ts b/web/services/billing/purchase.ts index 9372b6d6d297..8d77ebefec6c 100644 --- a/web/services/billing/purchase.ts +++ b/web/services/billing/purchase.ts @@ -625,8 +625,12 @@ async function recordTeamCheckoutCompletion(input: { }); const checkoutOwnerStackUserId = input.stackUserId ?? checkoutCustomerOwnership.stackUserId; + const checkoutOwnerIsLegacyTeam = + checkoutOwnerStackUserId === input.stackTeamId; const ownerStackUserId = checkoutOwnerStackUserId - ? teamSubscriptionOwnerStackUserId(checkoutOwnerStackUserId, input.stackTeamId) + ? checkoutOwnerIsLegacyTeam + ? input.stackTeamId + : teamSubscriptionOwnerStackUserId(checkoutOwnerStackUserId, input.stackTeamId) : null; if (!ownerStackUserId) { await cleanupCheckoutStripeResourcesForAccountDeletion({ @@ -642,7 +646,9 @@ async function recordTeamCheckoutCompletion(input: { }; } - const owner = await loadOptionalStackUser(ownerStackUserId, input.dependencies.stackApp); + const owner = checkoutOwnerIsLegacyTeam + ? null + : await loadOptionalStackUser(ownerStackUserId, input.dependencies.stackApp); const lockedResult = await withAccountDeletionUserLock(db, ownerStackUserId, async (tx) => { const transactionCustomerOwnership = await teamStripeCustomerOwnership(tx, { stackTeamId: input.stackTeamId, @@ -652,8 +658,12 @@ async function recordTeamCheckoutCompletion(input: { input.stackUserId ?? transactionCustomerOwnership.stackUserId ?? checkoutOwnerStackUserId; - const transactionOwnerStackUserId = - stackUserId ? teamSubscriptionOwnerStackUserId(stackUserId, input.stackTeamId) : null; + const transactionOwnerIsLegacyTeam = stackUserId === input.stackTeamId; + const transactionOwnerStackUserId = stackUserId + ? transactionOwnerIsLegacyTeam + ? input.stackTeamId + : teamSubscriptionOwnerStackUserId(stackUserId, input.stackTeamId) + : null; const ownerChangedDuringCheckout = transactionOwnerStackUserId !== ownerStackUserId; const observedExistingCheckoutCustomer = checkoutCustomerOwnership.customerRowExists || @@ -661,9 +671,9 @@ async function recordTeamCheckoutCompletion(input: { if ( !transactionOwnerStackUserId || !stackUserId || - (await hasCheckoutBlockingAccountDeletionTombstone(stackUserId, tx)) || + (!transactionOwnerIsLegacyTeam && await hasCheckoutBlockingAccountDeletionTombstone(stackUserId, tx)) || ownerChangedDuringCheckout || - (transactionOwnerStackUserId && !owner) || + (!transactionOwnerIsLegacyTeam && transactionOwnerStackUserId && !owner) || (owner && isAccountDeletionInProgress(owner)) ) { return { diff --git a/web/tests/billing-purchase.test.ts b/web/tests/billing-purchase.test.ts index a560bb7200eb..1fe000100b95 100644 --- a/web/tests/billing-purchase.test.ts +++ b/web/tests/billing-purchase.test.ts @@ -609,6 +609,57 @@ describe("recordCheckoutCompletion", () => { }); }); + test("preserves legacy Team checkout rows owned by the team id", async () => { + const getUser = mock(async () => { + throw new Error("should not load Stack user for legacy team-owned checkout"); + }); + const updateTeam = mock(async () => undefined); + const cancelSubscription = mock(async () => undefined); + const deleteCustomer = mock(async () => undefined); + const team = { + id: "team_123", + clientReadOnlyMetadata: {}, + update: updateTeam, + }; + selectResults = [ + [{ id: "cus_team", stackUserId: "team_123" }], + [{ id: "cus_team", stackUserId: "team_123" }], + ]; + + const result = await recordCheckoutCompletion(teamCheckoutInput() as never, { + db: fakeDb() as never, + stackApp: { + getUser, + getTeam: async () => team, + } as never, + stripeClient: () => ({ + subscriptions: { cancel: cancelSubscription }, + customers: { del: deleteCustomer }, + }) as never, + }); + + expect(result).toEqual({ + scope: "team", + stackTeamId: "team_123", + subscriptionId: "sub_team", + }); + expect(getUser).not.toHaveBeenCalled(); + expect(cancelSubscription).not.toHaveBeenCalled(); + expect(deleteCustomer).not.toHaveBeenCalled(); + expect( + inserts.some( + (insert) => + insert.table === stripeCustomers && + insert.values.id === "cus_team" && + insert.values.stackUserId === "team_123" && + insert.values.stackTeamId === "team_123", + ), + ).toBe(true); + expect(updateTeam).toHaveBeenCalledWith({ + clientReadOnlyMetadata: { cmuxPlan: "team" }, + }); + }); + test("blocks Team checkout completion while the billing owner is deleting without deleting the team customer", async () => { const cancelSubscription = mock(async () => undefined); const deleteCustomer = mock(async () => undefined); From 260fb26c3fee3379af93844058cfb70889a095b5 Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Thu, 9 Jul 2026 11:00:11 -0700 Subject: [PATCH 89/89] Clear stale deletion auth lockouts --- web/services/vms/auth.ts | 27 +++++++++++++++++-- web/tests/vm-route-auth.test.ts | 46 +++++++++++++++++++++++++++++++++ 2 files changed, 71 insertions(+), 2 deletions(-) diff --git a/web/services/vms/auth.ts b/web/services/vms/auth.ts index b0363b2a89e4..8096ae7b9986 100644 --- a/web/services/vms/auth.ts +++ b/web/services/vms/auth.ts @@ -1,4 +1,11 @@ +import { eq } from "drizzle-orm"; import { getStackServerApp, isStackConfigured } from "../../app/lib/stack"; +import { cloudDb } from "../../db/client"; +import { accountDeletionTombstones } from "../../db/schema"; +import { + accountDeletionUserHash, + isBlockingAccountDeletionTombstone, +} from "../account/deletionLock"; import { billingPlanIdFromMetadata, billingTeamFromUnknown, @@ -77,7 +84,7 @@ async function authedUserFromStackUser( user: StackUserLike, options: { readonly requestedTeamId?: string | null; readonly allowDeletingAccount?: boolean }, ): Promise { - if (!options.allowDeletingAccount && isAccountDeletionInProgress(user.clientReadOnlyMetadata)) { + if (!options.allowDeletingAccount && await isAccountDeletionAuthBlocked(user)) { return null; } @@ -119,7 +126,23 @@ async function authedUserFromStackUser( }; } -function isAccountDeletionInProgress(metadata: unknown): boolean { +async function isAccountDeletionAuthBlocked(user: StackUserLike): Promise { + if (!hasAccountDeletionMetadataFlag(user.clientReadOnlyMetadata)) return false; + const userIdHash = accountDeletionUserHash(user.id); + const [deletion] = await cloudDb() + .select({ + userIdHash: accountDeletionTombstones.userIdHash, + status: accountDeletionTombstones.status, + updatedAt: accountDeletionTombstones.updatedAt, + }) + .from(accountDeletionTombstones) + .where(eq(accountDeletionTombstones.userIdHash, userIdHash)) + .limit(1); + return deletion?.userIdHash === userIdHash && + isBlockingAccountDeletionTombstone(deletion); +} + +function hasAccountDeletionMetadataFlag(metadata: unknown): boolean { return !!metadata && typeof metadata === "object" && !Array.isArray(metadata) && diff --git a/web/tests/vm-route-auth.test.ts b/web/tests/vm-route-auth.test.ts index ed1927d468f8..99262362c539 100644 --- a/web/tests/vm-route-auth.test.ts +++ b/web/tests/vm-route-auth.test.ts @@ -62,6 +62,7 @@ const realCreateAwsRdsIamPool = dbClientModule.createAwsRdsIamPool; let useWorkflowStubs = false; let useStubDb = false; +let authTombstoneRows: Array<{ userIdHash: string; status: string; updatedAt: Date | null }> = []; function callMock(fn: unknown, args: unknown[]) { return (fn as (...args: unknown[]) => unknown)(...args); @@ -120,6 +121,17 @@ mock.module("../db/client", () => ({ createAwsRdsIamPool: realCreateAwsRdsIamPool, closeCloudDbForTests: realCloseCloudDbForTests, cloudDb: () => { + if (authTombstoneRows.length > 0) { + return { + select: () => ({ + from: () => ({ + where: () => ({ + limit: async () => authTombstoneRows, + }), + }), + }), + }; + } if (!useStubDb) return realCloudDb(); throw new Error("DATABASE_URL is required for Cloud VM database access"); }, @@ -145,6 +157,7 @@ const { } = await import("../services/vms/errors"); const { verifyRequest } = await import("../services/vms/auth"); const { withAuthedVmApiRoute } = await import("../services/vms/routeHelpers"); +const { accountDeletionUserHash } = await import("../services/account/deletionLock"); beforeAll(() => { useWorkflowStubs = true; @@ -160,6 +173,7 @@ beforeEach(() => { restoreVmEnv(); getUser.mockClear(); getUser.mockResolvedValue(null); + authTombstoneRows = []; runVmWorkflow.mockClear(); createVm.mockClear(); openBaseVm.mockClear(); @@ -203,6 +217,7 @@ describe("VM REST auth", () => { }); test("rejects account-deleting users before reaching workflows", async () => { + authTombstoneRows = [accountDeletionAuthTombstone("user-1", "pending", new Date())]; getUser.mockResolvedValue({ id: "user-1", displayName: null, @@ -228,6 +243,29 @@ describe("VM REST auth", () => { expect(runVmWorkflow).not.toHaveBeenCalled(); }); + test("allows stale account-deleting metadata after tombstone lease expires", async () => { + authTombstoneRows = [accountDeletionAuthTombstone("user-1", "pending", new Date(0))]; + getUser.mockResolvedValue({ + id: "user-1", + displayName: null, + primaryEmail: "user@example.com", + clientReadOnlyMetadata: { cmuxAccountDeleting: true }, + selectedTeam: null, + listTeams: async () => [], + }); + + const user = await verifyRequest( + new Request("https://cmux.test/api/vm", { + headers: { + authorization: "Bearer access-token", + "x-stack-refresh-token": "refresh-token", + }, + }), + ); + + expect(user?.id).toBe("user-1"); + }); + test("rejects unauthenticated VM mutations before reaching workflows", async () => { const context = { params: Promise.resolve({ id: "provider-vm-1" }) }; const responses = await Promise.all([ @@ -1461,6 +1499,14 @@ function freePlanStackUser() { }; } +function accountDeletionAuthTombstone(userId: string, status: string, updatedAt: Date | null) { + return { + userIdHash: accountDeletionUserHash(userId), + status, + updatedAt, + }; +} + function expectNoCloudVmImplementationLeaks(payload: unknown): void { expect(JSON.stringify(payload)).not.toMatch( /Stack Auth|Freestyle|E2B|freestyle|e2b|CMUX_VM_|FREESTYLE_|E2B_|billingTeamId|itemId|billingCustomerId|manifest|snapshot|database|migration|\bsh-[a-z0-9]{8,24}\b|\bteam-[a-z0-9-]+\b/,