Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

Address review: guard deauth and backfill writes

Kiran K86d9fcd85e63
diff --git a/apps/web/app/(ee)/api/stripe/integration/webhook/account-application-deauthorized.ts b/apps/web/app/(ee)/api/stripe/integration/webhook/account-application-deauthorized.ts
index a98c034da9..348f4b8e9a 100644
--- a/apps/web/app/(ee)/api/stripe/integration/webhook/account-application-deauthorized.ts
+++ b/apps/web/app/(ee)/api/stripe/integration/webhook/account-application-deauthorized.ts
@@ -17,24 +17,38 @@ export async function accountApplicationDeauthorized({
};
}
- await prisma.$transaction([
- prisma.project.update({
+ const disconnected = await prisma.$transaction(async (tx) => {
+ // Only disconnect if the workspace is still connected to the deauthorized account
+ const { count } = await tx.project.updateMany({
where: {
id: workspace.id,
+ stripeConnectId: stripeAccountId,
},
data: {
stripeConnectId: null,
stripeConnectMode: null,
},
- }),
+ });
- prisma.installedIntegration.deleteMany({
+ if (count === 0) {
+ return false;
+ }
+
+ await tx.installedIntegration.deleteMany({
where: {
projectId: workspace.id,
integrationId: STRIPE_INTEGRATION_ID,
},
- }),
- ]);
+ });
+
+ return true;
+ });
+
+ if (!disconnected) {
+ return {
+ response: `Workspace ${workspace.id} is no longer connected to Stripe Connect account ${stripeAccountId}. Skipping...`,
+ };
+ }
return {
response: `Stripe Connect account ${stripeAccountId} deauthorized for workspace ${workspace.id}`,
diff --git a/apps/web/scripts/stripe/backfill-stripe-connect-mode.ts b/apps/web/scripts/stripe/backfill-stripe-connect-mode.ts
index 2b490c641c..e23ad24f29 100644
--- a/apps/web/scripts/stripe/backfill-stripe-connect-mode.ts
+++ b/apps/web/scripts/stripe/backfill-stripe-connect-mode.ts
@@ -10,6 +10,7 @@ const BATCH_SIZE = 100;
// Run after adding the nullable column and before swapping the stripeConnectId unique index
async function main() {
let totalUpdated = 0;
+ let totalSkipped = 0;
let cursor: string | undefined;
while (true) {
@@ -54,47 +55,70 @@ async function main() {
cursor = workspaces[workspaces.length - 1].id;
const updates = workspaces.map((workspace) => {
- const parsed = stripeIntegrationSettingsSchema.safeParse(
- workspace.installedIntegrations[0]?.settings ?? {},
+ const settings = workspace.installedIntegrations[0]?.settings as
+ | { stripeMode?: unknown }
+ | null
+ | undefined;
+
+ // Parse only stripeMode so unrelated invalid settings don't reset the mode to live
+ const parsed = stripeIntegrationSettingsSchema.shape.stripeMode.safeParse(
+ settings?.stripeMode,
);
return {
id: workspace.id,
- stripeConnectId: workspace.stripeConnectId,
- stripeConnectMode: parsed.success ? parsed.data.stripeMode : "live",
+ stripeConnectId: workspace.stripeConnectId!,
+ stripeConnectMode: parsed.success ? parsed.data : "live",
};
});
if (DRY_RUN) {
console.table(updates);
+ totalUpdated += updates.length;
} else {
- await Promise.all(
+ const results = await Promise.all(
updates.map(async ({ id, stripeConnectId, stripeConnectMode }) => {
- await prisma.project.update({
+ // Skip workspaces whose connection changed after they were selected
+ const { count } = await prisma.project.updateMany({
where: {
id,
+ stripeConnectId,
+ stripeConnectMode: null,
},
data: {
stripeConnectMode,
},
});
- console.log(
- `Set stripeConnectMode=${stripeConnectMode} for workspace ${id} (${stripeConnectId})`,
- );
+ if (count === 0) {
+ console.log(
+ `Skipped workspace ${id} (${stripeConnectId}): connection changed during backfill`,
+ );
+ } else {
+ console.log(
+ `Set stripeConnectMode=${stripeConnectMode} for workspace ${id} (${stripeConnectId})`,
+ );
+ }
+
+ return count;
}),
);
- }
- totalUpdated += updates.length;
+ const updated = results.reduce((sum, count) => sum + count, 0);
+
+ totalUpdated += updated;
+ totalSkipped += updates.length - updated;
+ }
console.log(
- `${DRY_RUN ? "Would backfill" : "Backfilled"} ${updates.length} workspaces up to ${cursor}`,
+ `${DRY_RUN ? "Would backfill" : "Processed"} ${updates.length} workspaces up to ${cursor}`,
);
}
console.log(
- `Done. ${DRY_RUN ? "Would backfill" : "Backfilled"} ${totalUpdated} workspaces.`,
+ DRY_RUN
+ ? `Done. Would backfill ${totalUpdated} workspaces.`
+ : `Done. Backfilled ${totalUpdated} workspaces, skipped ${totalSkipped}.`,
);
}
diff --git a/apps/web/tests/stripe/account-application-deauthorized.test.ts b/apps/web/tests/stripe/account-application-deauthorized.test.ts
new file mode 100644
index 0000000000..e1df96c7c9
--- /dev/null
+++ b/apps/web/tests/stripe/account-application-deauthorized.test.ts
@@ -0,0 +1,96 @@
+import { STRIPE_INTEGRATION_ID } from "@dub/utils";
+import type Stripe from "stripe";
+import { beforeEach, describe, expect, test, vi } from "vitest";
+import { accountApplicationDeauthorized } from "../../app/(ee)/api/stripe/integration/webhook/account-application-deauthorized";
+
+const mocks = vi.hoisted(() => ({
+ updateMany: vi.fn(),
+ deleteMany: vi.fn(),
+}));
+
+vi.mock("@/lib/prisma", () => {
+ const tx = {
+ project: {
+ updateMany: mocks.updateMany,
+ },
+ installedIntegration: {
+ deleteMany: mocks.deleteMany,
+ },
+ };
+
+ return {
+ prisma: {
+ $transaction: (fn: (client: typeof tx) => Promise<unknown>) => fn(tx),
+ },
+ };
+});
+
+const event = {} as Stripe.AccountApplicationDeauthorizedEvent;
+
+const workspace = {
+ id: "ws_test",
+ stripeConnectId: "acct_test",
+ defaultProgramId: null,
+ webhookEnabled: false,
+ environment: "staging" as const,
+};
+
+describe("accountApplicationDeauthorized", () => {
+ beforeEach(() => {
+ mocks.updateMany.mockReset();
+ mocks.deleteMany.mockReset();
+ });
+
+ test("disconnects the workspace and removes its Stripe installation", async () => {
+ mocks.updateMany.mockResolvedValue({ count: 1 });
+
+ const result = await accountApplicationDeauthorized({
+ event,
+ mode: "test",
+ workspace,
+ });
+
+ expect(mocks.updateMany).toHaveBeenCalledWith({
+ where: {
+ id: "ws_test",
+ stripeConnectId: "acct_test",
+ },
+ data: {
+ stripeConnectId: null,
+ stripeConnectMode: null,
+ },
+ });
+ expect(mocks.deleteMany).toHaveBeenCalledWith({
+ where: {
+ projectId: "ws_test",
+ integrationId: STRIPE_INTEGRATION_ID,
+ },
+ });
+ expect(result.response).toContain("deauthorized for workspace ws_test");
+ });
+
+ test("keeps the installation when the workspace is no longer connected to the account", async () => {
+ mocks.updateMany.mockResolvedValue({ count: 0 });
+
+ const result = await accountApplicationDeauthorized({
+ event,
+ mode: "test",
+ workspace,
+ });
+
+ expect(mocks.deleteMany).not.toHaveBeenCalled();
+ expect(result.response).toContain("no longer connected");
+ });
+
+ test("skips non-live deauthorization for production workspaces", async () => {
+ const result = await accountApplicationDeauthorized({
+ event,
+ mode: "test",
+ workspace: { ...workspace, environment: "production" },
+ });
+
+ expect(mocks.updateMany).not.toHaveBeenCalled();
+ expect(mocks.deleteMany).not.toHaveBeenCalled();
+ expect(result.response).toContain("Skipping");
+ });
+});