The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Handle fraud charges automatically
Steven Tey5a1e2610de17
diff --git a/apps/web/app/(ee)/admin.dub.co/(dashboard)/components/disable-restore-workspace.tsx b/apps/web/app/(ee)/admin.dub.co/(dashboard)/components/disable-restore-workspace.tsxnew file mode 100644index 0000000000..cf9dff621e--- /dev/null+++ b/apps/web/app/(ee)/admin.dub.co/(dashboard)/components/disable-restore-workspace.tsx@@ -0,0 +1,133 @@+"use client";++import { LoadingSpinner } from "@dub/ui";+import { cn } from "@dub/utils";+import { useRef, useState } from "react";+import { toast } from "sonner";++export function DisableRestoreWorkspace() {+ const [pending, setPending] = useState<"disable" | "restore" | null>(null);+ const slugRef = useRef<HTMLInputElement>(null);++ const handleAction = async (+ action: "disable" | "restore",+ slug: string,+ ) => {+ const message =+ action === "disable"+ ? `Are you sure you want to disable all links for workspace "${slug}"? This will also downgrade owners to billing and members to viewer, and notify workspace owners by email.`+ : `Are you sure you want to restore all links for workspace "${slug}"? This will also revert billing users to owner and viewers to member.`;++ if (!window.confirm(message)) return;++ setPending(action);+ try {+ const res = await fetch(`/api/admin/workspaces/${action}`, {+ method: "POST",+ body: JSON.stringify({ slug }),+ });++ if (res.ok) {+ toast.success(+ action === "disable"+ ? "Workspace links disabled"+ : "Workspace links restored",+ );+ } else {+ const error = await res.text();+ toast.error(error || "Something went wrong. Please try again.");+ }+ } catch {+ toast.error(+ "Network error. Please check your connection and try again.",+ );+ } finally {+ setPending(null);+ }+ };++ return (+ <div className="flex flex-col space-y-5">+ <form+ onSubmit={(e) => {+ e.preventDefault();+ const slug = new FormData(e.currentTarget).get("slug");+ if (!slug || typeof slug !== "string") return;+ handleAction("disable", slug);+ }}+ >+ <Form slugRef={slugRef} pending={pending} onRestore={handleAction.bind(null, "restore")} />+ </form>+ </div>+ );+}++const Form = ({+ slugRef,+ pending,+ onRestore,+}: {+ slugRef: React.RefObject<HTMLInputElement | null>;+ pending: "disable" | "restore" | null;+ onRestore: (slug: string) => void;+}) => {+ const isPending = pending !== null;++ return (+ <div className="flex flex-col gap-2">+ <div className="relative flex w-full rounded-md shadow-sm">+ <span className="inline-flex items-center rounded-l-md border border-r-0 border-neutral-300 bg-neutral-50 px-3 text-neutral-500 sm:text-sm">+ app.dub.co+ </span>+ <input+ ref={slugRef}+ name="slug"+ id="workspace-slug"+ type="text"+ required+ disabled={isPending}+ autoComplete="off"+ className={cn(+ "block w-full rounded-r-md border-neutral-300 text-neutral-900 placeholder-neutral-400 focus:border-neutral-500 focus:outline-none focus:ring-neutral-500 sm:text-sm",+ isPending && "bg-neutral-100",+ )}+ placeholder="acme"+ />+ {isPending && (+ <LoadingSpinner className="absolute inset-y-0 right-2 my-auto h-full w-5 text-neutral-400" />+ )}+ </div>++ <div className="flex gap-2">+ <button+ type="submit"+ disabled={isPending}+ className={cn(+ "rounded-md bg-red-600 px-4 py-2 text-sm font-medium text-white hover:bg-red-700 focus:outline-none",+ isPending && "opacity-50",+ )}+ >+ {pending === "disable" ? "Disabling…" : "Disable links"}+ </button>+ <button+ type="button"+ disabled={isPending}+ onClick={() => {+ const input = slugRef.current;+ if (!input?.value) {+ input?.reportValidity();+ return;+ }+ onRestore(input.value);+ }}+ className={cn(+ "rounded-md bg-neutral-900 px-4 py-2 text-sm font-medium text-white hover:bg-neutral-700 focus:outline-none",+ isPending && "opacity-50",+ )}+ >+ {pending === "restore" ? "Restoring…" : "Restore links"}+ </button>+ </div>+ </div>+ );+};diff --git a/apps/web/app/(ee)/admin.dub.co/(dashboard)/components/slack-support-invite.tsx b/apps/web/app/(ee)/admin.dub.co/(dashboard)/components/slack-support-invite.tsxindex d65829700a..badff54aed 100644--- a/apps/web/app/(ee)/admin.dub.co/(dashboard)/components/slack-support-invite.tsx+++ b/apps/web/app/(ee)/admin.dub.co/(dashboard)/components/slack-support-invite.tsx@@ -78,7 +78,7 @@ const Form = ({ needsChannelId }: { needsChannelId: boolean }) => {<div className="relative flex w-full rounded-md shadow-sm"><span className="inline-flex items-center rounded-l-md border border-r-0 border-neutral-300 bg-neutral-50 px-3 text-neutral-500 sm:text-sm">- app.dub.co/+ app.dub.co</span><inputname="workspaceSlug"diff --git a/apps/web/app/(ee)/admin.dub.co/(dashboard)/page.tsx b/apps/web/app/(ee)/admin.dub.co/(dashboard)/page.tsxindex 6c53f3083d..a407e8d4af 100644--- a/apps/web/app/(ee)/admin.dub.co/(dashboard)/page.tsx+++ b/apps/web/app/(ee)/admin.dub.co/(dashboard)/page.tsx@@ -1,5 +1,6 @@import { BanLink } from "./components/ban-link";import { DeletePartnerAccount } from "./components/delete-partner-account";+import { DisableRestoreWorkspace } from "./components/disable-restore-workspace";import { ImpersonateUser } from "./components/impersonate-user";import { ImpersonateWorkspace } from "./components/impersonate-workspace";import { ResetLoginAttempts } from "./components/reset-login-attempts";@@ -56,6 +57,15 @@ export default function AdminPage() {</p><SlackSupportInvite /></div>+ <div className="flex flex-col space-y-4 px-5 py-10">+ <h2 className="text-xl font-semibold">Disable / Restore Workspace</h2>+ <p className="text-sm text-neutral-500">+ Disable or restore all links for a workspace. Disabling also+ downgrades owners to billing, members to viewer, and emails workspace+ owners. Restoring reverts those role changes.+ </p>+ <DisableRestoreWorkspace />+ </div></div>);}diff --git a/apps/web/app/(ee)/api/admin/workspaces/disable/route.ts b/apps/web/app/(ee)/api/admin/workspaces/disable/route.tsnew file mode 100644index 0000000000..d9e5ccd1b7--- /dev/null+++ b/apps/web/app/(ee)/api/admin/workspaces/disable/route.ts@@ -0,0 +1,95 @@+import { disableWorkspaceLinks } from "@/lib/api/workspaces/disable-workspace-links";+import { withAdmin } from "@/lib/auth";+import { queueBatchEmail } from "@/lib/email/queue-batch-email";+import { prisma } from "@/lib/prisma";+import { NextResponse } from "next/server";++// POST /api/admin/workspaces/disable+export const POST = withAdmin(+ async ({ req }) => {+ const { slug } = await req.json();++ const project = await prisma.project.findUnique({+ where: {+ slug,+ },+ include: {+ users: {+ where: {+ role: "owner",+ user: {+ email: {+ not: null,+ },+ },+ },+ select: {+ user: {+ select: {+ email: true,+ },+ },+ },+ },+ },+ });++ if (!project) {+ return new Response("Workspace not found", { status: 404 });+ }++ await disableWorkspaceLinks(project.id);++ const owners = project.users.map(({ user }) => user.email);++ if (owners.length > 0) {+ await queueBatchEmail(+ owners.map((email) => ({+ to: email!,+ variant: "notifications",+ subject: "Your Dub workspace has been disabled",+ templateName: "WorkspaceDisabled",+ templateProps: {+ email: email!,+ workspace: {+ name: project.name,+ slug: project.slug,+ usage: project.usage,+ usageLimit: project.usageLimit,+ plan: project.plan,+ },+ },+ })),+ );+ }++ const updatedOwners = await prisma.projectUsers.updateMany({+ where: {+ projectId: project.id,+ role: "owner",+ },+ data: {+ role: "billing",+ },+ });++ console.log(`Updated ${updatedOwners.count} owners to billing role`);++ const updatedMembers = await prisma.projectUsers.updateMany({+ where: {+ projectId: project.id,+ role: "member",+ },+ data: {+ role: "viewer",+ },+ });++ console.log(`Updated ${updatedMembers.count} members to viewer role`);++ return NextResponse.json({ success: true });+ },+ {+ requiredRoles: ["owner"],+ },+);diff --git a/apps/web/app/(ee)/api/admin/workspaces/restore/route.ts b/apps/web/app/(ee)/api/admin/workspaces/restore/route.tsnew file mode 100644index 0000000000..96b0944ea1--- /dev/null+++ b/apps/web/app/(ee)/api/admin/workspaces/restore/route.ts@@ -0,0 +1,84 @@+import { linkCache } from "@/lib/api/links/cache";+import { withAdmin } from "@/lib/auth";+import { prisma } from "@/lib/prisma";+import { NextResponse } from "next/server";++// POST /api/admin/workspaces/restore+export const POST = withAdmin(+ async ({ req }) => {+ const { slug } = await req.json();++ const project = await prisma.project.findUnique({+ where: {+ slug,+ },+ });++ if (!project) {+ return new Response("Workspace not found", { status: 404 });+ }++ while (true) {+ const linksToRestore = await prisma.link.findMany({+ where: {+ projectId: project.id,+ disabledAt: {+ not: null,+ },+ },+ take: 100,+ });+ if (linksToRestore.length === 0) {+ console.log("No more links to restore. Exiting...");+ break;+ }++ if (linksToRestore.length > 0) {+ const restoredLinks = await prisma.link.updateMany({+ where: {+ id: {+ in: linksToRestore.map((link) => link.id),+ },+ },+ data: {+ disabledAt: null,+ },+ });++ console.log(`Restored ${restoredLinks.count} links`);++ const res = await linkCache.expireMany(linksToRestore);+ console.log(res);+ }+ }++ const updatedOwners = await prisma.projectUsers.updateMany({+ where: {+ projectId: project.id,+ role: "billing",+ },+ data: {+ role: "owner",+ },+ });++ console.log(`Reverted ${updatedOwners.count} billing to owner role`);++ const updatedMembers = await prisma.projectUsers.updateMany({+ where: {+ projectId: project.id,+ role: "viewer",+ },+ data: {+ role: "member",+ },+ });++ console.log(`Reverted ${updatedMembers.count} viewers to member role`);++ return NextResponse.json({ success: true });+ },+ {+ requiredRoles: ["owner"],+ },+);diff --git a/apps/web/app/(ee)/api/cron/domains/verify/utils.ts b/apps/web/app/(ee)/api/cron/domains/verify/utils.tsindex 9859f4fe54..3b69f08f3e 100644--- a/apps/web/app/(ee)/api/cron/domains/verify/utils.ts+++ b/apps/web/app/(ee)/api/cron/domains/verify/utils.ts@@ -91,10 +91,10 @@ export const handleDomainUpdates = async ({},});if (linksClicks._sum.clicks && linksClicks._sum.clicks > 0) {- return await log({- message: `Domain *${domain}* has been invalid for > 30 days but has links with clicks, skipping.`,- type: "cron",- });+ console.log(+ `Domain "${domain}" has been invalid for > 30 days but has links with clicks, skipping...`,+ );+ return;}// else, delete the domaindiff --git a/apps/web/app/(ee)/api/stripe/webhook/payment-intent-payment-failed.ts b/apps/web/app/(ee)/api/stripe/webhook/payment-intent-payment-failed.tsnew file mode 100644index 0000000000..57ecab9086--- /dev/null+++ b/apps/web/app/(ee)/api/stripe/webhook/payment-intent-payment-failed.ts@@ -0,0 +1,150 @@+import { disableWorkspaceLinks } from "@/lib/api/workspaces/disable-workspace-links";+import { updateConfig } from "@/lib/edge-config";+import { prisma } from "@/lib/prisma";+import { stripe } from "@/lib/stripe";+import { LEGAL_USER_ID, log } from "@dub/utils";+import Stripe from "stripe";++const STRIPE_FRAUD_VALUE_LISTS = {+ CUSTOMER_ID: "rsl_1LeVdvAlJJEpqkPVEcNgjxqq",+ CUSTOMER_EMAIL: "rsl_1LeVdvAlJJEpqkPVhZw9Xvgw",+ CARD_FINGERPRINT: "rsl_1LeVdvAlJJEpqkPVvUZUm9eC",+};++export async function paymentIntentPaymentFailed(+ event: Stripe.PaymentIntentPaymentFailedEvent,+) {+ const {+ customer,+ last_payment_error,+ receipt_email: customerEmail,+ } = event.data.object;++ // should never happen, but just in case+ if (!customer || !last_payment_error) {+ return `Invalid payment intent attributes: ${JSON.stringify({ customer, last_payment_error })}`;+ }++ const customerId = customer as string;++ const workspace = await prisma.project.findUnique({+ where: {+ stripeId: customerId,+ },+ });++ if (workspace) {+ return `Workspace with stripeId ${customer} already created, so this is most likely a recurring payment failure, skipping...`;+ }++ const { decline_code, payment_method } = last_payment_error;++ if (decline_code !== "fraudulent") {+ return `Irrelevant decline code: ${decline_code}, skipping...`;+ }++ const cardFingerprint = payment_method?.card?.fingerprint;++ // add to Stripe Fraud Value Lists+ await Promise.allSettled([+ stripe.radar.valueListItems.create({+ value_list: STRIPE_FRAUD_VALUE_LISTS.CUSTOMER_ID,+ value: customerId,+ }),+ customerEmail+ ? stripe.radar.valueListItems.create({+ value_list: STRIPE_FRAUD_VALUE_LISTS.CUSTOMER_EMAIL,+ value: customerEmail,+ })+ : null,+ cardFingerprint+ ? stripe.radar.valueListItems.create({+ value_list: STRIPE_FRAUD_VALUE_LISTS.CARD_FINGERPRINT,+ value: cardFingerprint,+ })+ : null,+ ]).then((results) => {+ results.forEach((result, idx) => {+ if (result.status === "fulfilled" && result.value) {+ const listItem = [customerId, customerEmail, cardFingerprint][idx];+ const listName = Object.entries(STRIPE_FRAUD_VALUE_LISTS)[idx][0];+ console.log(+ `Added ${listItem} to ${listName} Fraud Value List: ${JSON.stringify(result.value, null, 2)}`,+ );+ }+ });+ });++ if (customerEmail) {+ const user = await prisma.user.findUnique({+ where: {+ email: customerEmail,+ },+ include: {+ projects: {+ where: {+ role: "owner",+ },+ select: {+ project: true,+ },+ },+ },+ });++ if (user) {+ const workspaces = user.projects.map(({ project }) => project);+ if (workspaces.length > 0) {+ for (const workspace of workspaces) {+ // this should never happen, but just in case+ if (workspace.plan !== "free") {+ await log({+ type: "errors",+ message: `[payment_intent.payment_failed]: Workspace ${workspace.slug} for fraudulent user ${user.email} is not a free plan, skipping...`,+ });+ continue;+ }+ // transfer ownership to legal user+ await prisma.projectUsers.update({+ where: {+ userId_projectId: {+ projectId: workspace.id,+ userId: user.id,+ },+ },+ data: {+ userId: LEGAL_USER_ID,+ },+ });+ // disable workspace links+ await disableWorkspaceLinks(workspace.id);+ }+ } else {+ console.log(`User ${user.email} has no workspaces, skipping...`);+ }++ // delete and ban user+ await Promise.allSettled([+ prisma.user.delete({+ where: {+ id: user.id,+ },+ }),+ updateConfig({+ key: "emails",+ value: user.email!,+ }),+ log({+ message: `Banned user ${user.email} for fraudulent Stripe charges: https://dashboard.stripe.com/customers/${customerId}`,+ type: "alerts",+ mention: true,+ })+ ]);++ } else {+ console.log(`User with email ${customerEmail} not found, skipping...`);+ }+ }++ return `Processed payment_intent.payment_failed event for customer ${customerId} (${customerEmail}) and card fingerprint ${cardFingerprint})`;+}diff --git a/apps/web/app/(ee)/api/stripe/webhook/route.ts b/apps/web/app/(ee)/api/stripe/webhook/route.tsindex 17c5e8d69d..0960440afb 100644--- a/apps/web/app/(ee)/api/stripe/webhook/route.ts+++ b/apps/web/app/(ee)/api/stripe/webhook/route.ts@@ -10,6 +10,7 @@ import { customerSubscriptionCreated } from "./customer-subscription-created";import { customerSubscriptionDeleted } from "./customer-subscription-deleted";import { customerSubscriptionUpdated } from "./customer-subscription-updated";import { invoicePaymentFailed } from "./invoice-payment-failed";+import { paymentIntentPaymentFailed } from "./payment-intent-payment-failed";import { paymentIntentRequiresAction } from "./payment-intent-requires-action";import { transferReversed } from "./transfer-reversed";@@ -22,6 +23,7 @@ const relevantEvents = new Set(["customer.subscription.updated","customer.subscription.deleted","invoice.payment_failed",+ "payment_intent.payment_failed","payment_intent.requires_action","transfer.reversed",]);@@ -76,6 +78,9 @@ export const POST = async (req: Request) => {case "invoice.payment_failed":response = await invoicePaymentFailed(event);break;+ case "payment_intent.payment_failed":+ response = await paymentIntentPaymentFailed(event);+ break;case "payment_intent.requires_action":response = await paymentIntentRequiresAction(event);break;diff --git a/apps/web/lib/api/workspaces/disable-workspace-links.ts b/apps/web/lib/api/workspaces/disable-workspace-links.tsnew file mode 100644index 0000000000..01d65dba53--- /dev/null+++ b/apps/web/lib/api/workspaces/disable-workspace-links.ts@@ -0,0 +1,42 @@+import { prisma } from "@/lib/prisma";+import { linkCache } from "../links/cache";++export async function disableWorkspaceLinks(workspaceId: string) {+ let totalDisabledLinks = 0;++ while (true) {+ const linksToDisable = await prisma.link.findMany({+ where: {+ projectId: workspaceId,+ disabledAt: null,+ },+ take: 100,+ });+ if (linksToDisable.length === 0) {+ console.log("No more links to disable. Exiting...");+ break;+ }++ if (linksToDisable.length > 0) {+ const disabledLinks = await prisma.link.updateMany({+ where: {+ id: {+ in: linksToDisable.map((link) => link.id),+ },+ },+ data: {+ disabledAt: new Date(),+ },+ });+ totalDisabledLinks += disabledLinks.count;++ console.log(`Disabled ${disabledLinks.count} links`);++ await linkCache.expireMany(linksToDisable);+ }++ console.log(+ `Completed disabling ${totalDisabledLinks} links for workspace ${workspaceId}`,+ );+ }+}diff --git a/apps/web/scripts/misc/disable-workspace-links.ts b/apps/web/scripts/misc/disable-workspace-links.tsdeleted file mode 100644index 9101fadbc4..0000000000--- a/apps/web/scripts/misc/disable-workspace-links.ts+++ /dev/null@@ -1,113 +0,0 @@-import { prisma } from "@/lib/prisma";-import "dotenv-flow/config";-import { linkCache } from "../../lib/api/links/cache";-import { queueBatchEmail } from "../../lib/email/queue-batch-email";--// script to disable all links for a workspace-async function main() {- const project = await prisma.project.findUniqueOrThrow({- where: {- slug: "xxx",- },- include: {- users: {- where: {- role: "owner",- user: {- email: {- not: null,- },- },- },- select: {- user: {- select: {- email: true,- },- },- },- },- },- });-- while (true) {- const linksToDisable = await prisma.link.findMany({- where: {- projectId: project.id,- disabledAt: null,- },- take: 100,- });- if (linksToDisable.length === 0) {- console.log("No more links to disable. Exiting...");- break;- }-- if (linksToDisable.length > 0) {- const disabledLinks = await prisma.link.updateMany({- where: {- id: {- in: linksToDisable.map((link) => link.id),- },- },- data: {- disabledAt: new Date(),- },- });-- console.log(`Disabled ${disabledLinks.count} links`);-- const res = await linkCache.expireMany(linksToDisable);- console.log(res);- }- }-- const owners = project.users.map(({ user }) => user.email);-- if (owners.length > 0) {- await queueBatchEmail(- owners.map((email) => ({- to: email!,- variant: "notifications",- subject: "Your Dub workspace has been disabled",- templateName: "WorkspaceDisabled",- templateProps: {- email: email!,- workspace: {- name: project.name,- slug: project.slug,- usage: project.usage,- usageLimit: project.usageLimit,- plan: project.plan,- },- },- })),- );- }-- const updatedOwners = await prisma.projectUsers.updateMany({- where: {- projectId: project.id,- role: "owner",- },- data: {- role: "billing",- },- });-- console.log(`Updated ${updatedOwners.count} owners to billing role`);-- const updatedMembers = await prisma.projectUsers.updateMany({- where: {- projectId: project.id,- role: "member",- },- data: {- role: "viewer",- },- });-- console.log(`Updated ${updatedMembers.count} members to viewer role`);-}--main();diff --git a/apps/web/scripts/misc/restore-workspace-access.ts b/apps/web/scripts/misc/restore-workspace-access.tsdeleted file mode 100644index bd078c0dc9..0000000000--- a/apps/web/scripts/misc/restore-workspace-access.ts+++ /dev/null@@ -1,72 +0,0 @@-import { prisma } from "@/lib/prisma";-import "dotenv-flow/config";-import { linkCache } from "../../lib/api/links/cache";--// script to restore access to a workspace for a user-async function main() {- const project = await prisma.project.findUniqueOrThrow({- where: {- slug: "xxx",- },- });-- while (true) {- const linksToRestore = await prisma.link.findMany({- where: {- projectId: project.id,- disabledAt: {- not: null,- },- },- take: 100,- });- if (linksToRestore.length === 0) {- console.log("No more links to restore. Exiting...");- break;- }-- if (linksToRestore.length > 0) {- const restoredLinks = await prisma.link.updateMany({- where: {- id: {- in: linksToRestore.map((link) => link.id),- },- },- data: {- disabledAt: null,- },- });-- console.log(`Restored ${restoredLinks.count} links`);-- const res = await linkCache.expireMany(linksToRestore);- console.log(res);- }- }-- const updatedOwners = await prisma.projectUsers.updateMany({- where: {- projectId: project.id,- role: "billing",- },- data: {- role: "owner",- },- });-- console.log(`Reverted ${updatedOwners.count} billing to owner role`);-- const updatedMembers = await prisma.projectUsers.updateMany({- where: {- projectId: project.id,- role: "viewer",- },- data: {- role: "member",- },- });-- console.log(`Reverted ${updatedMembers.count} viewers to member role`);-}--main();