The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
improve admin
Steven Tey682ab2881b87
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.tsxnew file mode 100644index 0000000000..d5b2844a89--- /dev/null+++ b/apps/web/app/(ee)/admin.dub.co/(dashboard)/components/ban-link.tsx@@ -0,0 +1,229 @@+"use client";++import { Button, LoadingSpinner } from "@dub/ui";+import { cn } from "@dub/utils";+import { useRef, useState } from "react";+import { toast } from "sonner";++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 keyRef = useRef<HTMLInputElement>(null);+ const suggestedKey = useRef("");+ const requestId = useRef(0);+ const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);++ const loadSuggestedTerm = async (key: string) => {+ const normalized = key.trim();+ if (!normalized) return null;++ const id = ++requestId.current;+ suggestedKey.current = normalized;+ setLoadingTerm(true);+ setTerm("");++ try {+ const res = await fetch(+ `/api/admin/links/ban?domain=dub.sh&key=${encodeURIComponent(normalized)}`,+ ).then((r) => r.json());++ if (id !== requestId.current) return null;++ if (res.error) {+ toast.error(res.error);+ suggestedKey.current = "";+ return null;+ }++ let nextTerm = res.term as string;+ setTerm((current) => {+ nextTerm = current.trim() || nextTerm;+ return nextTerm;+ });+ return nextTerm;+ } catch {+ if (id === requestId.current) {+ toast.error("Failed to look up link");+ suggestedKey.current = "";+ }+ return null;+ } finally {+ if (id === requestId.current) setLoadingTerm(false);+ }+ };++ const handleKeyChange = (key: string) => {+ setKey(key);+ if (!banApexDomain) return;+ if (debounceRef.current) clearTimeout(debounceRef.current);++ debounceRef.current = setTimeout(() => {+ if (key.trim() === suggestedKey.current) return;+ void loadSuggestedTerm(key);+ }, 300);+ };++ const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {+ e.preventDefault();+ const form = e.currentTarget;+ const key = new FormData(form).get("key");+ if (!key || typeof key !== "string") return;++ let termToBan = term.trim();++ if (banApexDomain && (key.trim() !== suggestedKey.current || !termToBan)) {+ termToBan = (await loadSuggestedTerm(key))?.trim() ?? "";+ if (!termToBan) return;+ }++ if (+ !window.confirm(+ banApexDomain+ ? `Are you sure you want to ban this link and the term "${termToBan}"?`+ : "Are you sure you want to ban this link?",+ )+ )+ return;++ setPending(true);+ try {+ const params = new URLSearchParams({+ domain: "dub.sh",+ key,+ });+ if (banApexDomain) params.set("term", termToBan);++ const res = await fetch(`/api/admin/links/ban?${params}`, {+ method: "DELETE",+ }).then((r) => r.json());+ if (res.error) {+ toast.error(res.error);+ } else {+ toast.success(+ banApexDomain+ ? `Link banned and ${termToBan} added to the blocklist`+ : "Link has been banned",+ );+ }+ } finally {+ setPending(false);+ }+ };++ return (+ <div className="flex flex-col space-y-5">+ <form onSubmit={handleSubmit}>+ <Form+ pending={pending}+ keyRef={keyRef}+ onKeyChange={handleKeyChange}+ />+ <label className="mt-3 flex cursor-pointer items-center gap-2 text-sm text-neutral-600">+ <input+ type="checkbox"+ checked={banApexDomain}+ disabled={pending}+ onChange={(e) => {+ 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);+ }+ }}+ className="rounded border-neutral-300 text-neutral-900 focus:ring-neutral-500"+ />+ Ban apex domain+ </label>+ {banApexDomain && (+ <div className="relative mt-3">+ <input+ name="term"+ id="term"+ type="text"+ value={term}+ disabled={pending || loadingTerm}+ autoComplete="off"+ spellCheck={false}+ onChange={(e) => 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",+ )}+ />+ {loadingTerm && (+ <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"+ variant="danger"+ loading={pending}+ disabled={+ !key.trim() ||+ (banApexDomain && !term.trim()) ||+ loadingTerm ||+ pending+ }+ />+ </div>+ </form>+ </div>+ );+}++const Form = ({+ pending,+ keyRef,+ onKeyChange,+}: {+ pending: boolean;+ keyRef: React.RefObject<HTMLInputElement | null>;+ onKeyChange: (key: string) => void;+}) => {+ 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+ </span>+ <input+ ref={keyRef}+ name="key"+ id="key"+ type="text"+ required+ disabled={pending}+ 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",+ pending && "bg-neutral-100",+ )}+ placeholder="IG47WZs"+ aria-invalid="true"+ 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;+ e.currentTarget.value = key;+ onKeyChange(key);+ }}+ />+ {pending && (+ <LoadingSpinner className="absolute inset-y-0 right-2 my-auto h-full w-5 text-neutral-400" />+ )}+ </div>+ );+};diff --git a/apps/web/app/(ee)/admin.dub.co/(dashboard)/links/components/disable-restore-workspace.tsx b/apps/web/app/(ee)/admin.dub.co/(dashboard)/components/disable-restore-workspace.tsxsimilarity index 100%rename from apps/web/app/(ee)/admin.dub.co/(dashboard)/links/components/disable-restore-workspace.tsxrename to apps/web/app/(ee)/admin.dub.co/(dashboard)/components/disable-restore-workspace.tsxdiff --git a/apps/web/app/(ee)/admin.dub.co/(dashboard)/links/components/ban-link.tsx b/apps/web/app/(ee)/admin.dub.co/(dashboard)/links/components/ban-link.tsxdeleted file mode 100644index 7458f8049a..0000000000--- a/apps/web/app/(ee)/admin.dub.co/(dashboard)/links/components/ban-link.tsx+++ /dev/null@@ -1,84 +0,0 @@-"use client";--import { LoadingSpinner } from "@dub/ui";-import { cn } from "@dub/utils";-import { useState } from "react";-import { toast } from "sonner";--export function BanLink() {- const [pending, setPending] = useState(false);-- const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {- e.preventDefault();- const form = e.currentTarget;- const key = new FormData(form).get("key");- if (!key || typeof key !== "string") return;-- if (!window.confirm("Are you sure you want to ban this link?")) return;-- setPending(true);- try {- const res = await fetch(- `/api/admin/links/ban?domain=dub.sh&key=${encodeURIComponent(key)}`,- { method: "DELETE" },- ).then((r) => r.json());- if (res.error) {- toast.error(res.error);- } else {- toast.success("Link has been banned");- }- } finally {- setPending(false);- }- };-- return (- <div className="flex flex-col space-y-5">- <form onSubmit={handleSubmit}>- <Form pending={pending} />- </form>- </div>- );-}--const Form = ({ pending }: { pending: boolean }) => {- 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- </span>- <input- name="key"- id="key"- type="text"- required- disabled={pending}- 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",- pending && "bg-neutral-100",- )}- placeholder="IG47WZs"- aria-invalid="true"- 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");- if (- text.startsWith("https://dub.sh/") ||- text.startsWith("dub.sh/")- ) {- e.currentTarget.value = text- .replace("https://dub.sh/", "")- .replace("dub.sh/", "");- } else {- e.currentTarget.value = text;- }- }}- />- {pending && (- <LoadingSpinner className="absolute inset-y-0 right-2 my-auto h-full w-5 text-neutral-400" />- )}- </div>- );-};diff --git a/apps/web/app/(ee)/admin.dub.co/(dashboard)/links/layout.tsx b/apps/web/app/(ee)/admin.dub.co/(dashboard)/links/layout.tsxdeleted file mode 100644index 5635cb0e38..0000000000--- a/apps/web/app/(ee)/admin.dub.co/(dashboard)/links/layout.tsx+++ /dev/null@@ -1,22 +0,0 @@-import { PageWidthWrapper } from "@/ui/layout/page-width-wrapper";-import { Suspense } from "react";-import { LinksNavTabs } from "./links-nav-tabs";--export default function AdminLinksLayout({- children,-}: {- children: React.ReactNode;-}) {- return (- <PageWidthWrapper className="pb-12 pt-4">- <div className="border-border-subtle overflow-hidden rounded-xl border bg-neutral-100">- <Suspense>- <LinksNavTabs />- <div className="border-border-subtle -mx-px -mb-px space-y-4 rounded-xl border bg-white p-4">- {children}- </div>- </Suspense>- </div>- </PageWidthWrapper>- );-}diff --git a/apps/web/app/(ee)/admin.dub.co/(dashboard)/links/links-nav-tabs.tsx b/apps/web/app/(ee)/admin.dub.co/(dashboard)/links/links-nav-tabs.tsxdeleted file mode 100644index 5c07458ac4..0000000000--- a/apps/web/app/(ee)/admin.dub.co/(dashboard)/links/links-nav-tabs.tsx+++ /dev/null@@ -1,26 +0,0 @@-"use client";--import { PageNavTabs } from "@/ui/layout/page-nav-tabs";-import { GridLayoutRows, ShieldAlert } from "@dub/ui";-import { useMemo } from "react";--export function LinksNavTabs() {- const tabs = useMemo(- () => [- {- id: "moderation",- label: "Moderation",- icon: ShieldAlert,- href: "/links",- },- {- id: "list",- label: "Links List",- icon: GridLayoutRows,- },- ],- [],- );-- return <PageNavTabs basePath="/links" tabs={tabs} />;-}diff --git a/apps/web/app/(ee)/admin.dub.co/(dashboard)/links/list/page.tsx b/apps/web/app/(ee)/admin.dub.co/(dashboard)/links/list/page.tsxdeleted file mode 100644index 655308eb39..0000000000--- a/apps/web/app/(ee)/admin.dub.co/(dashboard)/links/list/page.tsx+++ /dev/null@@ -1,10 +0,0 @@-import { WorkspaceLinksList } from "app/app.dub.co/(dashboard)/[slug]/links/page-client";-import { Suspense } from "react";--export default function AdminLinksList() {- return (- <Suspense>- <WorkspaceLinksList />- </Suspense>- );-}diff --git a/apps/web/app/(ee)/admin.dub.co/(dashboard)/links/page.tsx b/apps/web/app/(ee)/admin.dub.co/(dashboard)/links/page.tsxindex 20ed6ddefc..8827a0a285 100644--- a/apps/web/app/(ee)/admin.dub.co/(dashboard)/links/page.tsx+++ b/apps/web/app/(ee)/admin.dub.co/(dashboard)/links/page.tsx@@ -1,23 +1,12 @@-import { BanLink } from "./components/ban-link";-import { DisableRestoreWorkspace } from "./components/disable-restore-workspace";+import { WorkspaceLinksList } from "app/app.dub.co/(dashboard)/[slug]/links/page-client";+import { Suspense } from "react";-export default function AdminLinksPage() {+export default function AdminLinks() {return (- <div className="mx-auto flex w-full max-w-screen-sm flex-col divide-y divide-neutral-200">- <div className="flex flex-col space-y-4 px-1 py-6">- <h2 className="text-xl font-semibold">Ban Link</h2>- <p className="text-sm text-neutral-500">Ban a dub.sh link</p>- <BanLink />+ <Suspense>+ <div className="pb-12 pt-4">+ <WorkspaceLinksList /></div>- <div className="flex flex-col space-y-4 px-1 py-6">- <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>+ </Suspense>);}diff --git a/apps/web/app/(ee)/admin.dub.co/(dashboard)/page.tsx b/apps/web/app/(ee)/admin.dub.co/(dashboard)/page.tsxindex 09eba94f73..11a4ffef78 100644--- a/apps/web/app/(ee)/admin.dub.co/(dashboard)/page.tsx+++ b/apps/web/app/(ee)/admin.dub.co/(dashboard)/page.tsx@@ -1,10 +1,17 @@+import { isAdminAccessRestricted } from "@/lib/auth/admin-access-guard";+import { getSession } from "@/lib/auth";+import { BanLink } from "./components/ban-link";import { DeletePartnerAccount } from "./components/delete-partner-account";import { DeleteProgram } from "./components/delete-program";+import { DisableRestoreWorkspace } from "./components/disable-restore-workspace";import { ImpersonateUser } from "./components/impersonate-user";import { ResetLoginAttempts } from "./components/reset-login-attempts";import { SlackSupportInvite } from "./components/slack-support-invite";-export default function AdminPage() {+export default async function AdminPage() {+ const session = await getSession();+ const showModerationTools = !isAdminAccessRestricted(session?.user?.id);+return (<div className="mx-auto flex w-full max-w-screen-sm flex-col divide-y divide-neutral-200 overflow-auto bg-white"><div className="flex flex-col space-y-4 px-5 py-10">@@ -16,6 +23,13 @@ export default function AdminPage() {</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>+ <BanLink />+ </div>+ )}<div className="flex flex-col space-y-4 px-5 py-10"><h2 className="text-xl font-semibold">Delete Stripe Express Account</h2><p className="text-sm text-neutral-500">@@ -54,6 +68,17 @@ export default function AdminPage() {</p><SlackSupportInvite /></div>+ {showModerationTools && (+ <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/links/ban/route.ts b/apps/web/app/(ee)/api/admin/links/ban/route.tsindex bb683fe89b..25c71a14ab 100644--- a/apps/web/app/(ee)/api/admin/links/ban/route.ts+++ b/apps/web/app/(ee)/api/admin/links/ban/route.ts@@ -6,14 +6,53 @@ import { domainKeySchema } from "@/lib/zod/schemas/links";import {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 keyexport const DELETE = withAdmin(async ({ searchParams }) => {const { domain, key } = domainKeySchema.parse(searchParams);+ const term = searchParams.term?.trim();++ if (term && !/[a-z0-9]/i.test(term)) {+ return NextResponse.json(+ { error: "Invalid domain term" },+ { status: 400 },+ );+ }const link = await prisma.link.findUnique({where: { domain_key: { domain, key } },@@ -38,11 +77,17 @@ export const DELETE = withAdmin(linkCache.set({ ...link, projectId: LEGAL_WORKSPACE_ID }),- urlDomain &&- updateConfig({- key: "domains",- value: urlDomain,- }),+ term+ ? updateConfig({+ key: "terms",+ value: term,+ })+ : urlDomain+ ? updateConfig({+ key: "domains",+ value: urlDomain,+ })+ : Promise.resolve(),]);return NextResponse.json(response);