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.

Delete linked staging workspaces and programs when banning a user

Kiran K083609501a04
diff --git a/apps/web/app/(ee)/api/admin/ban/delete-workspace-admin.ts b/apps/web/app/(ee)/api/admin/ban/delete-workspace-admin.ts
deleted file mode 100644
index f245707ddc..0000000000
--- a/apps/web/app/(ee)/api/admin/ban/delete-workspace-admin.ts
+++ /dev/null
@@ -1,124 +0,0 @@
-import { linkCache } from "@/lib/api/links/cache";
-import { getWorkspaceLogoStorageKey } from "@/lib/api/workspaces/workspace-logo";
-import { qstash } from "@/lib/cron";
-import { prisma } from "@/lib/prisma";
-import { storage } from "@/lib/storage";
-import { stripe } from "@/lib/stripe";
-import { cancelSubscription } from "@/lib/stripe/cancel-subscription";
-import { WorkspaceProps } from "@/lib/types";
-import {
- APP_DOMAIN_WITH_NGROK,
- DUB_DOMAINS_ARRAY,
- LEGAL_USER_ID,
- LEGAL_WORKSPACE_ID,
-} from "@dub/utils";
-import { addToStripeFraudValueLists } from "app/(ee)/api/stripe/webhook/utils/add-to-stripe-fraud-value-lists";
-import Stripe from "stripe";
-import { deleteProgramAdmin } from "../programs/delete/delete-program-admin";
-
-export async function deleteWorkspaceAdmin(
- workspace: Pick<
- WorkspaceProps,
- "id" | "slug" | "logo" | "stripeId" | "defaultProgramId"
- >,
-) {
- while (true) {
- const defaultDomainLinks = await prisma.link.findMany({
- where: {
- projectId: workspace.id,
- domain: {
- in: DUB_DOMAINS_ARRAY,
- },
- },
- select: {
- id: true,
- domain: true,
- key: true,
- },
- take: 100,
- });
-
- if (defaultDomainLinks.length === 0) {
- break;
- }
-
- const [redisRes, prismaRes] = await Promise.allSettled([
- linkCache.expireMany(defaultDomainLinks),
- prisma.link.updateMany({
- where: {
- id: {
- in: defaultDomainLinks.map((link) => link.id),
- },
- },
- data: {
- projectId: LEGAL_WORKSPACE_ID,
- userId: LEGAL_USER_ID,
- },
- }),
- ]);
-
- console.log(
- `Banned ${defaultDomainLinks.length} default domain links for ${workspace.slug}`,
- redisRes,
- prismaRes,
- );
- }
-
- const logoKey = getWorkspaceLogoStorageKey({
- workspaceId: workspace.id,
- logoUrl: workspace.logo,
- });
-
- const deleteWorkspaceResponse = await Promise.allSettled([
- // delete workspace logo if it's a custom logo stored in R2
- logoKey && storage.delete({ key: logoKey }),
-
- // if they have a Stripe subscription, cancel it + add to fraud value lists
- workspace.stripeId &&
- cancelSubscription({
- customerId: workspace.stripeId,
- immediateCancellation: true,
- reason: "Customer was banned from Dub",
- }).then(async (res) => {
- console.log("Cancelled Stripe subscription", res);
-
- const stripeCustomer = (await stripe.customers.retrieve(
- workspace.stripeId!,
- {
- expand: ["invoice_settings.default_payment_method"],
- },
- )) as Stripe.Customer;
-
- const defaultPaymentMethod =
- stripeCustomer.invoice_settings?.default_payment_method;
-
- await addToStripeFraudValueLists({
- customerId: workspace.stripeId!,
- customerEmail: stripeCustomer.email,
- cardFingerprint:
- defaultPaymentMethod && typeof defaultPaymentMethod !== "string"
- ? defaultPaymentMethod.card?.fingerprint
- : undefined,
- });
- }),
-
- workspace.defaultProgramId &&
- deleteProgramAdmin(workspace.defaultProgramId),
- ]);
-
- console.log(`Deleted workspace ${workspace.slug}`, deleteWorkspaceResponse);
-
- // Queue the workspace for deletion
- const res = await qstash.publishJSON({
- url: `${APP_DOMAIN_WITH_NGROK}/api/cron/workspaces/delete`,
- body: {
- workspaceId: workspace.id,
- },
- });
-
- console.log("Queued workspace deletion", res);
-
- return {
- deleteWorkspaceResponse,
- };
-}
diff --git a/apps/web/app/(ee)/api/admin/ban/route.ts b/apps/web/app/(ee)/api/admin/ban/route.ts
index 32db0de551..e6cc128b0e 100644
--- a/apps/web/app/(ee)/api/admin/ban/route.ts
+++ b/apps/web/app/(ee)/api/admin/ban/route.ts
@@ -1,85 +1,20 @@
+import { banUser } from "@/lib/admin/ban-user";
import { withAdmin } from "@/lib/auth";
-import { updateConfig } from "@/lib/edge-config";
-import { extractEmailDomain } from "@/lib/email/extract-email-domain";
-import { prisma } from "@/lib/prisma";
-import { isStored, storage } from "@/lib/storage";
-import { R2_URL } from "@dub/utils";
-import { waitUntil } from "@vercel/functions";
import { NextResponse } from "next/server";
-import { deleteWorkspaceAdmin } from "./delete-workspace-admin";
// POST /api/admin/ban
export const POST = withAdmin(
async ({ req }) => {
const { email, blockEmailDomain } = await req.json();
- const user = await prisma.user.findUniqueOrThrow({
- where: {
- email,
- },
- select: {
- id: true,
- email: true,
- image: true,
- projects: {
- where: {
- role: "owner",
- },
- select: {
- project: {
- select: {
- id: true,
- slug: true,
- logo: true,
- stripeId: true,
- defaultProgramId: true,
- },
- },
- },
- },
- },
+ await banUser({
+ email,
+ blockEmailDomain,
});
- const emailDomain = extractEmailDomain(email);
-
- // block email in edge config first so that no feedback emails are sent
- await Promise.all([
- updateConfig({
- key: "emails",
- value: email,
- }),
- blockEmailDomain &&
- emailDomain &&
- updateConfig({
- key: "emailDomainTerms",
- value: emailDomain,
- }),
- ]);
-
- console.log(
- `Found user ${user.email} with ${user.projects.length} workspaces`,
- );
-
- waitUntil(
- Promise.allSettled(
- user.projects.map(({ project }) => deleteWorkspaceAdmin(project)),
- ).then(async () => {
- // delete user after all workspaces are deleted
- await prisma.user.delete({
- where: {
- id: user.id,
- },
- });
- console.log(`Deleted user ${user.email}`);
-
- if (user.image && isStored(user.image)) {
- await storage.delete({ key: user.image.replace(`${R2_URL}/`, "") });
- console.log(`Deleted user image ${user.image}`);
- }
- }),
- );
-
- return NextResponse.json({ success: true });
+ return NextResponse.json({
+ success: true,
+ });
},
{
requiredRoles: ["owner"],
diff --git a/apps/web/lib/admin/ban-user.ts b/apps/web/lib/admin/ban-user.ts
new file mode 100644
index 0000000000..0f22ef9b15
--- /dev/null
+++ b/apps/web/lib/admin/ban-user.ts
@@ -0,0 +1,87 @@
+import { prisma } from "@/lib/prisma";
+import { R2_URL } from "@dub/utils";
+import { WorkspaceRole } from "@prisma/client";
+import { waitUntil } from "@vercel/functions";
+import { updateConfig } from "../edge-config";
+import { extractEmailDomain } from "../email/extract-email-domain";
+import { isStored, storage } from "../storage";
+import { deleteWorkspace } from "./delete-workspace";
+
+type BanUserProps = {
+ email: string;
+ blockEmailDomain: boolean;
+};
+
+export async function banUser({ email, blockEmailDomain }: BanUserProps) {
+ const user = await prisma.user.findUniqueOrThrow({
+ where: {
+ email,
+ },
+ select: {
+ id: true,
+ email: true,
+ image: true,
+ projects: {
+ where: {
+ role: WorkspaceRole.owner,
+ },
+ select: {
+ project: {
+ select: {
+ id: true,
+ slug: true,
+ stripeId: true,
+ defaultProgramId: true,
+ },
+ },
+ },
+ },
+ },
+ });
+
+ const emailDomain = extractEmailDomain(email);
+
+ // Block email in edge config first so that no feedback emails are sent
+ await Promise.all([
+ updateConfig({
+ key: "emails",
+ value: email,
+ }),
+
+ blockEmailDomain &&
+ emailDomain &&
+ updateConfig({
+ key: "emailDomainTerms",
+ value: emailDomain,
+ }),
+ ]);
+
+ // TODO:
+ // This is doing too much in one function.
+ // We should move this to a background job to make sure it reliably deletes the user and workspaces.
+ waitUntil(deleteBannedUser(user));
+
+ return user;
+}
+
+export async function deleteBannedUser(
+ user: Awaited<ReturnType<typeof banUser>>,
+) {
+ const workspacesToDelete = user.projects.map(({ project }) => project);
+
+ await Promise.allSettled(
+ workspacesToDelete.map((workspace) => deleteWorkspace(workspace)),
+ );
+
+ await prisma.user.delete({
+ where: {
+ id: user.id,
+ },
+ });
+
+ if (user.image && isStored(user.image)) {
+ await storage.delete({
+ key: user.image.replace(`${R2_URL}/`, ""),
+ });
+ }
+}
diff --git a/apps/web/lib/admin/delete-workspace.ts b/apps/web/lib/admin/delete-workspace.ts
new file mode 100644
index 0000000000..78506046e8
--- /dev/null
+++ b/apps/web/lib/admin/delete-workspace.ts
@@ -0,0 +1,108 @@
+import { qstash } from "@/lib/cron";
+import { stripe } from "@/lib/stripe";
+import { cancelSubscription } from "@/lib/stripe/cancel-subscription";
+import {
+ APP_DOMAIN_WITH_NGROK,
+ DUB_DOMAINS_ARRAY,
+ LEGAL_USER_ID,
+ LEGAL_WORKSPACE_ID,
+ pluck,
+} from "@dub/utils";
+import { deleteProgramAdmin } from "app/(ee)/api/admin/programs/delete/delete-program-admin";
+import { addToStripeFraudValueLists } from "app/(ee)/api/stripe/webhook/utils/add-to-stripe-fraud-value-lists";
+import Stripe from "stripe";
+import { linkCache } from "../api/links/cache";
+import { prisma } from "../prisma";
+import { WorkspaceProps } from "../types";
+
+export async function deleteWorkspace(
+ workspace: Pick<
+ WorkspaceProps,
+ "id" | "slug" | "stripeId" | "defaultProgramId"
+ >,
+) {
+ await banWorkspaceDefaultDomainLinks(workspace);
+
+ await Promise.allSettled([
+ // If they have a Stripe subscription, cancel it + add to fraud value lists
+ workspace.stripeId && cancelBannedSubscription(workspace.stripeId),
+
+ workspace.defaultProgramId &&
+ deleteProgramAdmin(workspace.defaultProgramId),
+ ]);
+
+ console.log(`Deleted workspace ${workspace.slug}`);
+
+ // Queue the workspace for deletion
+ await qstash.publishJSON({
+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/workspaces/delete`,
+ body: {
+ workspaceId: workspace.id,
+ },
+ });
+}
+
+async function banWorkspaceDefaultDomainLinks(
+ workspace: Pick<WorkspaceProps, "id" | "slug">,
+) {
+ while (true) {
+ const defaultDomainLinks = await prisma.link.findMany({
+ where: {
+ projectId: workspace.id,
+ domain: {
+ in: DUB_DOMAINS_ARRAY,
+ },
+ },
+ select: {
+ id: true,
+ domain: true,
+ key: true,
+ },
+ take: 100,
+ });
+
+ if (defaultDomainLinks.length === 0) {
+ break;
+ }
+
+ await Promise.all([
+ prisma.link.updateMany({
+ where: {
+ id: {
+ in: pluck(defaultDomainLinks, "id"),
+ },
+ },
+ data: {
+ projectId: LEGAL_WORKSPACE_ID,
+ userId: LEGAL_USER_ID,
+ },
+ }),
+
+ linkCache.expireMany(defaultDomainLinks),
+ ]);
+ }
+}
+
+async function cancelBannedSubscription(stripeId: string) {
+ await cancelSubscription({
+ customerId: stripeId,
+ immediateCancellation: true,
+ reason: "Customer was banned from Dub",
+ });
+
+ const stripeCustomer = (await stripe.customers.retrieve(stripeId, {
+ expand: ["invoice_settings.default_payment_method"],
+ })) as Stripe.Customer;
+
+ const defaultPaymentMethod =
+ stripeCustomer.invoice_settings?.default_payment_method;
+
+ await addToStripeFraudValueLists({
+ customerId: stripeId,
+ customerEmail: stripeCustomer.email,
+ cardFingerprint:
+ defaultPaymentMethod && typeof defaultPaymentMethod !== "string"
+ ? defaultPaymentMethod.card?.fingerprint
+ : undefined,
+ });
+}
diff --git a/apps/web/lib/api/domains/validate-dub-link-subdomain.ts b/apps/web/lib/api/domains/validate-dub-link-subdomain.ts
index df55e4be84..6e1324f7de 100644
--- a/apps/web/lib/api/domains/validate-dub-link-subdomain.ts
+++ b/apps/web/lib/api/domains/validate-dub-link-subdomain.ts
@@ -51,9 +51,19 @@ export function validateDubLinkSubdomain(
// Staging workspaces use `{slug}.staging.dub.link` (e.g. acme.staging.dub.link)
if (lower.endsWith(STAGING_DUB_DOMAIN_SUFFIX)) {
- return validateDubLinkLabel(
+ const labelError = validateDubLinkLabel(
lower.slice(0, -STAGING_DUB_DOMAIN_SUFFIX.length),
);
+
+ if (labelError) {
+ return labelError;
+ }
+
+ // Only staging workspace provisioning may create these hosts.
+ return {
+ error: "This subdomain is reserved.",
+ code: "unprocessable_entity",
+ };
}
if (!lower.endsWith(DUB_LINK_SUFFIX)) {