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.

improve admin workflow

Steven Teyd58184a32af5
diff --git a/apps/web/app/(ee)/admin.dub.co/(dashboard)/components/ban-link.tsx b/apps/web/app/(ee)/admin.dub.co/(dashboard)/components/ban-link.tsx
index d5b2844a89..c1a1f40d12 100644
--- a/apps/web/app/(ee)/admin.dub.co/(dashboard)/components/ban-link.tsx
+++ b/apps/web/app/(ee)/admin.dub.co/(dashboard)/components/ban-link.tsx
@@ -1,82 +1,141 @@
"use client";
-import { Button, LoadingSpinner } from "@dub/ui";
-import { cn } from "@dub/utils";
-import { useRef, useState } from "react";
+import { Button, LinkLogo, LoadingSpinner } from "@dub/ui";
+import { ArrowUpRight2 } from "@dub/ui/icons";
+import {
+ cn,
+ getApexDomain,
+ getPrettyUrl,
+ isSafeLinkHref,
+ SHORT_DOMAIN,
+} from "@dub/utils";
+import { useEffect, useRef, useState } from "react";
import { toast } from "sonner";
+import { ImpersonateResult } from "./impersonate-user";
+import { UserInfoProps } from "./user-info";
+
+type LinkLookup = UserInfoProps & {
+ link: {
+ url: string;
+ };
+};
export function BanLink() {
const [key, setKey] = useState("");
const [pending, setPending] = useState(false);
const [banApexDomain, setBanApexDomain] = useState(false);
const [term, setTerm] = useState("");
- const [loadingTerm, setLoadingTerm] = useState(false);
+ const [loading, setLoading] = useState(false);
+ const [lookupError, setLookupError] = useState<string | null>(null);
+ const [linkInfo, setLinkInfo] = useState<LinkLookup | null>(null);
const keyRef = useRef<HTMLInputElement>(null);
- const suggestedKey = useRef("");
const requestId = useRef(0);
const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const banApexDomainRef = useRef(banApexDomain);
+ const termTouched = useRef(false);
- const loadSuggestedTerm = async (key: string) => {
+ banApexDomainRef.current = banApexDomain;
+
+ useEffect(() => {
+ return () => {
+ if (debounceRef.current) clearTimeout(debounceRef.current);
+ };
+ }, []);
+
+ const lookupLink = async (key: string, existingId?: number) => {
const normalized = key.trim();
if (!normalized) return null;
- const id = ++requestId.current;
- suggestedKey.current = normalized;
- setLoadingTerm(true);
- setTerm("");
+ const id = existingId ?? ++requestId.current;
+ setLoading(true);
try {
- const res = await fetch(
- `/api/admin/links/ban?domain=dub.sh&key=${encodeURIComponent(normalized)}`,
- ).then((r) => r.json());
+ const res = await fetch("/api/admin/impersonate", {
+ method: "POST",
+ body: JSON.stringify({
+ query: dubShortLinkQuery(normalized),
+ }),
+ });
if (id !== requestId.current) return null;
- if (res.error) {
- toast.error(res.error);
- suggestedKey.current = "";
+ if (!res.ok) {
+ const error = await res.text();
+ setLinkInfo(null);
+ if (res.status === 404) {
+ setLookupError(error);
+ } else {
+ toast.error(error);
+ setLookupError(null);
+ }
return null;
}
- let nextTerm = res.term as string;
- setTerm((current) => {
- nextTerm = current.trim() || nextTerm;
- return nextTerm;
- });
- return nextTerm;
+ const data = (await res.json()) as LinkLookup;
+ if (!data.link?.url) {
+ setLinkInfo(null);
+ setLookupError("Link not found");
+ return null;
+ }
+
+ setLookupError(null);
+ setLinkInfo(data);
+ if (banApexDomainRef.current && !termTouched.current) {
+ setTerm(apexTerm(data.link.url));
+ }
+ return data;
} catch {
if (id === requestId.current) {
toast.error("Failed to look up link");
- suggestedKey.current = "";
+ setLinkInfo(null);
+ setLookupError(null);
}
return null;
} finally {
- if (id === requestId.current) setLoadingTerm(false);
+ if (id === requestId.current) setLoading(false);
}
};
- const handleKeyChange = (key: string) => {
- setKey(key);
- if (!banApexDomain) return;
+ const handleKeyChange = (value: string) => {
+ setKey(value);
if (debounceRef.current) clearTimeout(debounceRef.current);
+ const id = ++requestId.current;
+ termTouched.current = false;
+ setTerm("");
+ setLookupError(null);
+ setLinkInfo(null);
+
+ const normalized = value.trim();
+ if (!normalized) {
+ setLoading(false);
+ return;
+ }
+
+ setLoading(true);
debounceRef.current = setTimeout(() => {
- if (key.trim() === suggestedKey.current) return;
- void loadSuggestedTerm(key);
- }, 300);
+ void lookupLink(normalized, id);
+ }, 400);
};
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
+ if (pending) return;
+
const form = e.currentTarget;
- const key = new FormData(form).get("key");
- if (!key || typeof key !== "string") return;
+ const rawKey = new FormData(form).get("key");
+ if (!rawKey || typeof rawKey !== "string" || !rawKey.trim()) return;
+ const key = rawKey.trim();
let termToBan = term.trim();
- if (banApexDomain && (key.trim() !== suggestedKey.current || !termToBan)) {
- termToBan = (await loadSuggestedTerm(key))?.trim() ?? "";
- if (!termToBan) return;
+ if (banApexDomain && !termToBan) {
+ const data = linkInfo ?? (await lookupLink(key));
+ termToBan = apexTerm(data?.link.url ?? "");
+ if (!termToBan) {
+ toast.error("Could not determine the apex domain");
+ return;
+ }
}
if (
@@ -91,7 +150,7 @@ export function BanLink() {
setPending(true);
try {
const params = new URLSearchParams({
- domain: "dub.sh",
+ domain: SHORT_DOMAIN,
key,
});
if (banApexDomain) params.set("term", termToBan);
@@ -118,9 +177,14 @@ export function BanLink() {
<form onSubmit={handleSubmit}>
<Form
pending={pending}
+ loading={loading}
keyRef={keyRef}
onKeyChange={handleKeyChange}
/>
+ {lookupError && (
+ <p className="mt-2 text-sm text-red-600">{lookupError}</p>
+ )}
+ {linkInfo && <LinkPreview data={linkInfo} />}
<label className="mt-3 flex cursor-pointer items-center gap-2 text-sm text-neutral-600">
<input
type="checkbox"
@@ -130,11 +194,8 @@ export function BanLink() {
const checked = e.target.checked;
setBanApexDomain(checked);
if (!checked) return;
-
- const key = keyRef.current?.value ?? "";
- if (key.trim() && key.trim() !== suggestedKey.current) {
- void loadSuggestedTerm(key);
- }
+ termTouched.current = false;
+ if (linkInfo?.link.url) setTerm(apexTerm(linkInfo.link.url));
}}
className="rounded border-neutral-300 text-neutral-900 focus:ring-neutral-500"
/>
@@ -147,52 +208,101 @@ export function BanLink() {
id="term"
type="text"
value={term}
- disabled={pending || loadingTerm}
+ disabled={pending || loading}
autoComplete="off"
spellCheck={false}
- onChange={(e) => setTerm(e.target.value)}
+ onChange={(e) => {
+ termTouched.current = true;
+ setTerm(e.target.value);
+ }}
placeholder=".example.com"
className={cn(
"block w-full rounded-md border-neutral-300 font-mono text-neutral-900 placeholder-neutral-400 focus:border-neutral-500 focus:outline-none focus:ring-neutral-500 sm:text-sm",
- (pending || loadingTerm) && "bg-neutral-100",
+ (pending || loading) && "bg-neutral-100",
)}
/>
- {loadingTerm && (
+ {loading && (
<LoadingSpinner className="absolute inset-y-0 right-2 my-auto h-full w-5 text-neutral-400" />
)}
</div>
)}
<div className="mt-4">
<Button
- text="Confirm Ban"
+ text="Ban link"
variant="danger"
loading={pending}
disabled={
!key.trim() ||
(banApexDomain && !term.trim()) ||
- loadingTerm ||
+ loading ||
pending
}
/>
</div>
</form>
+ {linkInfo && (
+ <ImpersonateResult key={linkInfo.impersonateUrl.app} data={linkInfo} />
+ )}
+ </div>
+ );
+}
+
+function LinkPreview({ data }: { data: LinkLookup }) {
+ const { link } = data;
+ const apexDomain = getApexDomain(link.url);
+ const destinationHref = isSafeLinkHref(link.url) ? link.url : undefined;
+
+ return (
+ <div className="mt-4 overflow-hidden rounded-xl border border-neutral-200 bg-white">
+ <div className="flex items-center gap-3 px-3.5 py-3">
+ <div className="relative flex-none rounded-full border border-neutral-200 bg-gradient-to-t from-neutral-100 p-1.5">
+ <LinkLogo
+ apexDomain={apexDomain}
+ className="size-5 shrink-0 sm:size-6"
+ />
+ </div>
+ <div className="min-w-0">
+ <p className="text-[11px] font-medium uppercase tracking-wide text-neutral-400">
+ Destination URL
+ </p>
+ {destinationHref ? (
+ <a
+ href={destinationHref}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="group flex min-w-0 items-center gap-1 text-sm font-medium text-neutral-900"
+ >
+ <span className="truncate">{getPrettyUrl(link.url)}</span>
+ <ArrowUpRight2 className="size-3.5 shrink-0 text-neutral-400 transition-colors group-hover:text-neutral-700" />
+ </a>
+ ) : (
+ <p className="truncate text-sm font-medium text-neutral-900">
+ {getPrettyUrl(link.url) || link.url}
+ </p>
+ )}
+ </div>
+ </div>
</div>
);
}
const Form = ({
pending,
+ loading,
keyRef,
onKeyChange,
}: {
pending: boolean;
+ loading: boolean;
keyRef: React.RefObject<HTMLInputElement | null>;
onKeyChange: (key: string) => void;
}) => {
+ const busy = pending || loading;
+
return (
<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-5 text-neutral-500 sm:text-sm">
- dub.sh
+ {SHORT_DOMAIN}
</span>
<input
ref={keyRef}
@@ -211,19 +321,47 @@ const Form = ({
onChange={(e) => onKeyChange(e.currentTarget.value)}
onPaste={(e: React.ClipboardEvent<HTMLInputElement>) => {
e.preventDefault();
- // if pasting in https://dub.sh/xxx or dub.sh/xxx, extract xxx
- const text = e.clipboardData.getData("text/plain");
- const key =
- text.startsWith("https://dub.sh/") || text.startsWith("dub.sh/")
- ? text.replace("https://dub.sh/", "").replace("dub.sh/", "")
- : text;
+ const key = extractDubKey(e.clipboardData.getData("text/plain"));
e.currentTarget.value = key;
onKeyChange(key);
}}
/>
- {pending && (
+ {busy && (
<LoadingSpinner className="absolute inset-y-0 right-2 my-auto h-full w-5 text-neutral-400" />
)}
</div>
);
};
+
+function dubShortLinkQuery(key: string) {
+ const path = key
+ .split("/")
+ .map((segment) => encodeURIComponent(segment))
+ .join("/");
+ return `https://${SHORT_DOMAIN}/${path}`;
+}
+
+function extractDubKey(text: string) {
+ const trimmed = text.trim();
+ try {
+ const url = trimmed.includes("://")
+ ? new URL(trimmed)
+ : trimmed.includes("/")
+ ? new URL(`https://${trimmed}`)
+ : undefined;
+ if (url) {
+ const host = url.hostname.replace(/^www\./, "").toLowerCase();
+ if (host === SHORT_DOMAIN) {
+ return decodeURIComponent(url.pathname.replace(/^\/+|\/+$/g, ""));
+ }
+ }
+ } catch {
+ // keep the pasted text
+ }
+ return trimmed;
+}
+
+function apexTerm(url: string) {
+ const apex = getApexDomain(url);
+ return apex ? `.${apex}` : "";
+}
diff --git a/apps/web/app/(ee)/admin.dub.co/(dashboard)/components/impersonate-user.tsx b/apps/web/app/(ee)/admin.dub.co/(dashboard)/components/impersonate-user.tsx
index fb144e7cad..7e9c88953b 100644
--- a/apps/web/app/(ee)/admin.dub.co/(dashboard)/components/impersonate-user.tsx
+++ b/apps/web/app/(ee)/admin.dub.co/(dashboard)/components/impersonate-user.tsx
@@ -7,9 +7,59 @@ import { useFormStatus } from "react-dom";
import { toast } from "sonner";
import UserInfo, { UserInfoProps, UserInfoSkeleton } from "./user-info";
+export function ImpersonateResult({ data }: { data: UserInfoProps }) {
+ const [blockEmailDomain, setBlockEmailDomain] = useState(false);
+
+ return (
+ <form
+ action={async () => {
+ const emailDomain = data.email.split("@")[1];
+ const blockDomainMessage = blockEmailDomain
+ ? ` and block signups from @${emailDomain}`
+ : "";
+
+ if (
+ !confirm(
+ `This will ban the user ${data.email} and delete all their workspaces and links${blockDomainMessage}. Are you sure?`,
+ )
+ ) {
+ return;
+ }
+ await fetch("/api/admin/ban", {
+ method: "POST",
+ body: JSON.stringify({
+ email: data.email,
+ blockEmailDomain,
+ }),
+ }).then(async (res) => {
+ if (res.ok) {
+ toast.success("User has been banned");
+ } else {
+ const error = await res.text();
+ toast.error(error);
+ }
+ });
+ }}
+ >
+ <UserInfo data={data} />
+ <label className="mt-4 flex cursor-pointer items-center gap-2 text-sm text-neutral-600">
+ <input
+ type="checkbox"
+ checked={blockEmailDomain}
+ onChange={(e) => setBlockEmailDomain(e.target.checked)}
+ className="rounded border-neutral-300 text-neutral-900 focus:ring-neutral-500"
+ />
+ Also block signups from @{data.email.split("@")[1]}
+ </label>
+ <div className="mt-4">
+ <BanButton />
+ </div>
+ </form>
+ );
+}
+
export function ImpersonateUser() {
const [data, setData] = useState<UserInfoProps | null>(null);
- const [blockEmailDomain, setBlockEmailDomain] = useState(false);
return (
<div className="flex flex-col space-y-5">
@@ -22,7 +72,6 @@ export function ImpersonateUser() {
}),
}).then(async (res) => {
if (res.ok) {
- setBlockEmailDomain(false);
setData(await res.json());
} else {
const error = await res.text();
@@ -34,50 +83,7 @@ export function ImpersonateUser() {
<Form />
</form>
{data ? (
- <form
- action={async () => {
- const emailDomain = data.email.split("@")[1];
- const blockDomainMessage = blockEmailDomain
- ? ` and block signups from @${emailDomain}`
- : "";
-
- if (
- !confirm(
- `This will ban the user ${data.email} and delete all their workspaces and links${blockDomainMessage}. Are you sure?`,
- )
- ) {
- return;
- }
- await fetch("/api/admin/ban", {
- method: "POST",
- body: JSON.stringify({
- email: data.email,
- blockEmailDomain,
- }),
- }).then(async (res) => {
- if (res.ok) {
- toast.success("User has been banned");
- } else {
- const error = await res.text();
- toast.error(error);
- }
- });
- }}
- >
- <UserInfo data={data} />
- <label className="mt-4 flex cursor-pointer items-center gap-2 text-sm text-neutral-600">
- <input
- type="checkbox"
- checked={blockEmailDomain}
- onChange={(e) => setBlockEmailDomain(e.target.checked)}
- className="rounded border-neutral-300 text-neutral-900 focus:ring-neutral-500"
- />
- Also block signups from @{data.email.split("@")[1]}
- </label>
- <div className="mt-4">
- <BanButton />
- </div>
- </form>
+ <ImpersonateResult key={data.impersonateUrl.app} data={data} />
) : (
<UserInfoSkeleton />
)}
@@ -116,7 +122,7 @@ const Form = () => {
}
e.currentTarget.value = text;
}}
- placeholder="[email protected], acme, acme.com, or cus_"
+ placeholder="[email protected], acme, acme.com, dub.sh/abc, or cus_"
aria-invalid="true"
/>
{pending && (
diff --git a/apps/web/app/(ee)/admin.dub.co/(dashboard)/page.tsx b/apps/web/app/(ee)/admin.dub.co/(dashboard)/page.tsx
index 11a4ffef78..acb267f926 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,5 @@
-import { isAdminAccessRestricted } from "@/lib/auth/admin-access-guard";
import { getSession } from "@/lib/auth";
+import { isAdminAccessRestricted } from "@/lib/auth/admin-access-guard";
import { BanLink } from "./components/ban-link";
import { DeletePartnerAccount } from "./components/delete-partner-account";
import { DeleteProgram } from "./components/delete-program";
@@ -17,16 +17,19 @@ export default async function AdminPage() {
<div className="flex flex-col space-y-4 px-5 py-10">
<h2 className="text-xl font-semibold">Impersonate User</h2>
<p className="text-sm text-neutral-500">
- Get a login link by user/partner email, workspace slug, domain, or
- Stripe customer ID. Workspace, domain, and Stripe lookups impersonate
- the main owner.
+ Get a login link by user/partner email, workspace slug, domain, dub.sh
+ link, or Stripe customer ID. Lookups impersonate the main owner of a
+ given workspace
</p>
<ImpersonateUser />
</div>
{showModerationTools && (
<div className="flex flex-col space-y-4 px-5 py-10">
<h2 className="text-xl font-semibold">Ban Link</h2>
- <p className="text-sm text-neutral-500">Ban a dub.sh link</p>
+ <p className="text-sm text-neutral-500">
+ Ban a dub.sh link. The destination shows up as you type, with the
+ creator's account below.
+ </p>
<BanLink />
</div>
)}
diff --git a/apps/web/app/(ee)/api/admin/impersonate/route.ts b/apps/web/app/(ee)/api/admin/impersonate/route.ts
index 6dfa6ef0e8..af9962aff5 100644
--- a/apps/web/app/(ee)/api/admin/impersonate/route.ts
+++ b/apps/web/app/(ee)/api/admin/impersonate/route.ts
@@ -8,6 +8,7 @@ import { emailSchema } from "@/lib/zod/schemas/auth";
import {
APP_DOMAIN,
isAppHostname,
+ isDubDomain,
PARTNERS_DOMAIN,
validDomainRegex,
validSlugRegex,
@@ -17,7 +18,9 @@ import { randomBytes } from "crypto";
import { NextResponse } from "next/server";
const userSelect = {
+ name: true,
email: true,
+ image: true,
projects: {
select: {
project: {
@@ -42,6 +45,11 @@ const userSelect = {
},
},
},
+ where: {
+ project: {
+ environment: "production",
+ },
+ },
orderBy: {
project: {
totalClicks: "desc",
@@ -106,7 +114,32 @@ type ImpersonateIdentifier =
| { type: "email"; email: string }
| { type: "slug"; slug: string }
| { type: "domain"; domain: string }
- | { type: "stripeCustomerId"; stripeCustomerId: string };
+ | { type: "stripeCustomerId"; stripeCustomerId: string }
+ | { type: "link"; domain: string; key: string };
+
+type ImpersonateUserRecord = Prisma.UserGetPayload<{
+ select: typeof userSelect;
+}>;
+
+type ImpersonateProject = Prisma.UserGetPayload<{
+ select: typeof userSelect;
+}>["projects"][number]["project"];
+
+type ImpersonateLinkDetails = {
+ domain: string;
+ key: string;
+ url: string;
+ shortLink: string;
+ createdBy: boolean;
+ project: ImpersonateProject | null;
+};
+
+type FindUserResult =
+ | { error: string }
+ | { user: ImpersonateUserRecord; link?: ImpersonateLinkDetails };
+
+const IMPERSONATE_QUERY_ERROR =
+ "Enter a user email, workspace slug, domain, short link, or Stripe customer ID";
const STRIPE_CUSTOMER_ID_REGEX = /cus_[a-zA-Z0-9]+/;
@@ -114,10 +147,7 @@ function parseImpersonateQuery(
raw: unknown,
): ImpersonateIdentifier | { error: string } {
if (typeof raw !== "string" || !raw.trim()) {
- return {
- error:
- "Enter a user email, workspace slug, domain, or Stripe customer ID",
- };
+ return { error: IMPERSONATE_QUERY_ERROR };
}
let query = raw.trim();
@@ -164,6 +194,15 @@ function parseImpersonateQuery(
}
}
+ if (hostname && pathname) {
+ const dubDomain = hostname.replace(/^www\./, "");
+ const key = decodePathKey(pathname);
+ // dub.sh/abc (and other Dub short domains) impersonate the link creator
+ if (key && isDubDomain(dubDomain)) {
+ return { type: "link", domain: dubDomain, key };
+ }
+ }
+
const domain = normalizeDomainInput(hostname ?? query);
if (validDomainRegex.test(domain)) {
return { type: "domain", domain };
@@ -174,9 +213,17 @@ function parseImpersonateQuery(
return { type: "slug", slug };
}
- return {
- error: "Enter a user email, workspace slug, domain, or Stripe customer ID",
- };
+ return { error: IMPERSONATE_QUERY_ERROR };
+}
+
+function decodePathKey(pathname: string) {
+ const key = pathname.replace(/^\/+|\/+$/g, "");
+ if (!key) return "";
+ try {
+ return decodeURIComponent(key);
+ } catch {
+ return key;
+ }
}
// POST /api/admin/impersonate
@@ -197,16 +244,21 @@ export const POST = withAdmin(async ({ req }) => {
}
const { user: response } = result;
+ const link = "link" in result ? result.link : undefined;
if (!response.email) {
return new Response("User not found", { status: 404 });
}
+ const workspaces = await serializeWorkspaces(
+ response.projects.map(({ project }) => project),
+ );
+
const data = {
email: response.email,
- workspaces: await serializeWorkspaces(
- response.projects.map(({ project }) => project),
- ),
+ name: response.name,
+ image: response.image,
+ workspaces,
programs:
response.partners.length > 0
? response.partners[0].partner.programs.map(({ program, ...rest }) => ({
@@ -215,14 +267,35 @@ export const POST = withAdmin(async ({ req }) => {
}))
: [],
impersonateUrl: await getImpersonateUrl(response.email),
+ ...(link
+ ? {
+ link: {
+ domain: link.domain,
+ key: link.key,
+ url: link.url,
+ shortLink: link.shortLink,
+ createdBy: link.createdBy,
+ workspace: await serializeLinkWorkspace(link.project, workspaces),
+ },
+ }
+ : {}),
};
return NextResponse.json(data);
});
-type ImpersonateProject = Prisma.UserGetPayload<{
- select: typeof userSelect;
-}>["projects"][number]["project"];
+async function serializeLinkWorkspace(
+ project: ImpersonateProject | null,
+ workspaces: Awaited<ReturnType<typeof serializeWorkspaces>>,
+) {
+ if (!project) return null;
+
+ return (
+ workspaces.find((workspace) => workspace.id === project.id) ??
+ (await serializeWorkspaces([project]))[0] ??
+ null
+ );
+}
async function serializeWorkspaces(projects: ImpersonateProject[]) {
const useLast30DaysStats = projects.length <= 2;
@@ -340,7 +413,87 @@ async function getLast30DayWorkspaceStats(projects: ImpersonateProject[]) {
return new Map(entries);
}
-async function findUser(identifier: ImpersonateIdentifier) {
+async function findUserByLink(
+ domain: string,
+ key: string,
+): Promise<FindUserResult> {
+ const link = await prisma.link.findUnique({
+ where: { domain_key: { domain, key } },
+ select: {
+ domain: true,
+ key: true,
+ url: true,
+ shortLink: true,
+ user: {
+ select: {
+ id: true,
+ email: true,
+ },
+ },
+ project: {
+ select: {
+ ...userSelect.projects.select.project.select,
+ users: {
+ where: ownerSelect.users.where,
+ orderBy: ownerSelect.users.orderBy,
+ take: ownerSelect.users.take,
+ select: {
+ user: {
+ select: {
+ id: true,
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ });
+
+ if (!link) {
+ return { error: "Link not found" };
+ }
+
+ const creatorId = link.user?.email ? link.user.id : null;
+ const userId = creatorId ?? link.project?.users[0]?.user.id;
+
+ if (!userId) {
+ return { error: "Link owner not found" };
+ }
+
+ const user = await prisma.user.findUnique({
+ where: { id: userId },
+ select: userSelect,
+ });
+
+ if (!user?.email) {
+ return { error: "Link owner not found" };
+ }
+
+ const project = link.project
+ ? (({ users: _users, ...rest }) => rest)(link.project)
+ : null;
+
+ return {
+ user,
+ link: {
+ domain: link.domain,
+ key: link.key,
+ url: link.url,
+ shortLink: link.shortLink,
+ createdBy: Boolean(creatorId),
+ project,
+ },
+ };
+}
+
+async function findUser(
+ identifier: ImpersonateIdentifier,
+): Promise<FindUserResult> {
+ if (identifier.type === "link") {
+ return findUserByLink(identifier.domain, identifier.key);
+ }
+
if (identifier.type === "email") {
const userEmails = [identifier.email];
const partner = await prisma.partner.findUnique({
diff --git a/apps/web/app/(ee)/api/admin/links/ban/route.ts b/apps/web/app/(ee)/api/admin/links/ban/route.ts
index 25c71a14ab..fa0233c2cf 100644
--- a/apps/web/app/(ee)/api/admin/links/ban/route.ts
+++ b/apps/web/app/(ee)/api/admin/links/ban/route.ts
@@ -4,43 +4,12 @@ import { updateConfig } from "@/lib/edge-config";
import { prisma } from "@/lib/prisma";
import { domainKeySchema } from "@/lib/zod/schemas/links";
import {
+ getDomainWithoutWWW,
LEGAL_USER_ID,
LEGAL_WORKSPACE_ID,
- getApexDomain,
- getDomainWithoutWWW,
} from "@dub/utils";
import { NextResponse } from "next/server";
-// GET /api/admin/links/ban – suggest the apex-domain term for a link
-export const GET = withAdmin(
- async ({ searchParams }) => {
- const { domain, key } = domainKeySchema.parse(searchParams);
-
- const link = await prisma.link.findUnique({
- where: { domain_key: { domain, key } },
- select: { url: true },
- });
-
- if (!link) {
- return NextResponse.json({ error: "Link not found" }, { status: 404 });
- }
-
- const apexDomain = getApexDomain(link.url);
-
- if (!apexDomain) {
- return NextResponse.json(
- { error: "Could not determine the apex domain" },
- { status: 400 },
- );
- }
-
- return NextResponse.json({ term: `.${apexDomain}` });
- },
- {
- requiredRoles: ["owner"],
- },
-);
-
// DELETE /api/admin/links/ban – ban a dub.sh link by key
export const DELETE = withAdmin(
async ({ searchParams }) => {