The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Updated /links endpoint
Steven Teyc4f806a60b6d
diff --git a/apps/docs/api-reference/endpoint/create-a-new-link.mdx b/apps/docs/api-reference/endpoint/create-a-new-link.mdxindex d752d6cbaf..ecb7957b98 100644--- a/apps/docs/api-reference/endpoint/create-a-new-link.mdx+++ b/apps/docs/api-reference/endpoint/create-a-new-link.mdx@@ -1,3 +1,3 @@----openapi: post /links+openapi: post /projects/{slug}/links---diff --git a/apps/docs/api-reference/endpoint/delete-a-link.mdx b/apps/docs/api-reference/endpoint/delete-a-link.mdxindex 65fe792665..6c7fc3582d 100644--- a/apps/docs/api-reference/endpoint/delete-a-link.mdx+++ b/apps/docs/api-reference/endpoint/delete-a-link.mdx@@ -1,3 +1,3 @@----openapi: delete /links/{key}----\ No newline at end of file+openapi: delete /projects/{slug}/links/{linkId}+---diff --git a/apps/docs/api-reference/endpoint/edit-a-link.mdx b/apps/docs/api-reference/endpoint/edit-a-link.mdxindex 98d7e2e9ec..2db00c24e1 100644--- a/apps/docs/api-reference/endpoint/edit-a-link.mdx+++ b/apps/docs/api-reference/endpoint/edit-a-link.mdx@@ -1,3 +1,3 @@----openapi: put /links/{key}+openapi: put /projects/{slug}/links/{linkId}---diff --git a/apps/docs/api-reference/endpoint/retrieve-a-link.mdx b/apps/docs/api-reference/endpoint/retrieve-a-link.mdxindex ca4cf85c04..b60d428dd9 100644--- a/apps/docs/api-reference/endpoint/retrieve-a-link.mdx+++ b/apps/docs/api-reference/endpoint/retrieve-a-link.mdx@@ -1,3 +1,3 @@----openapi: get /links/{key}+openapi: get /projects/{slug}/links/info---diff --git a/apps/docs/api-reference/endpoint/retrieve-a-list-of-links.mdx b/apps/docs/api-reference/endpoint/retrieve-a-list-of-links.mdxindex 2bc6ffea29..b55a9c429c 100644--- a/apps/docs/api-reference/endpoint/retrieve-a-list-of-links.mdx+++ b/apps/docs/api-reference/endpoint/retrieve-a-list-of-links.mdx@@ -1,3 +1,3 @@----openapi: get /links----\ No newline at end of file+openapi: get /projects/{slug}/links+---diff --git a/apps/web/app/api/links-app/[linkId]/archive/route.ts b/apps/web/app/api/links-app/[linkId]/archive/route.tsnew file mode 100644index 0000000000..4799b79d92--- /dev/null+++ b/apps/web/app/api/links-app/[linkId]/archive/route.ts@@ -0,0 +1,19 @@+import { archiveLink } from "@/lib/api/links";+import { withAuth } from "@/lib/auth";+import { NextResponse } from "next/server";++// POST /api/projects/[slug]/links/[linkId]/archive – archive a link+export const POST = withAuth(async ({ headers, link }) => {+ const response = await archiveLink(link!.domain || "dub.sh", link!.key, true);+ return NextResponse.json(response, { headers });+});++// DELETE /api/projects/[slug]/links/[linkId]/archive – unarchive a link+export const DELETE = withAuth(async ({ headers, link }) => {+ const response = await archiveLink(+ link!.domain || "dub.sh",+ link!.key,+ false,+ );+ return NextResponse.json(response, { headers });+});diff --git a/apps/web/app/api/links-app/[linkId]/route.ts b/apps/web/app/api/links-app/[linkId]/route.tsnew file mode 100644index 0000000000..1ccaacc701--- /dev/null+++ b/apps/web/app/api/links-app/[linkId]/route.ts@@ -0,0 +1,108 @@+import { withAuth } from "@/lib/auth";+import { deleteLink, editLink, processKey } from "@/lib/api/links";+import { NextResponse } from "next/server";+import { isBlacklistedDomain, isBlacklistedKey } from "@/lib/edge-config";+import { GOOGLE_FAVICON_URL, getApexDomain, log } from "@dub/utils";++// PUT /api/projects/[slug]/links/[linkId] – update a link+export const PUT = withAuth(+ async ({ req, headers, project, link, session }) => {+ let body;+ try {+ body = await req.json();+ } catch (error) {+ return new Response("Missing body.", { status: 400, headers });+ }+ if (Object.keys(body).length === 0) {+ return new Response("No fields to update.", { status: 304, headers });+ }++ const updatedLink = {+ ...link,+ ...body,+ };++ let { key, url, rewrite } = updatedLink;++ // for default dub.sh links (not part of a project)+ if (!project) {+ if (key.includes("/")) {+ return new Response("Key cannot contain '/'.", {+ status: 422,+ headers,+ });+ }+ const keyBlacklisted = await isBlacklistedKey(key);+ if (keyBlacklisted) {+ return new Response("Invalid key.", { status: 422, headers });+ }+ const domainBlacklisted = await isBlacklistedDomain(url);+ if (domainBlacklisted) {+ return new Response("Invalid url.", { status: 422, headers });+ }+ if (rewrite) {+ return new Response(+ "You can only use link cloaking on a custom domain.",+ { status: 403, headers },+ );+ }+ }++ key = processKey(key);+ if (!key) {+ return new Response("Invalid key.", { status: 422, headers });+ }++ const [response, invalidFavicon] = await Promise.allSettled([+ editLink({+ // link is guaranteed to exist because if not we will return 404+ domain: link!.domain,+ key: link!.key,+ updatedLink,+ }),+ ...(!project && url+ ? [+ fetch(`${GOOGLE_FAVICON_URL}${getApexDomain(url)}`).then(+ (res) => !res.ok,+ ),+ ]+ : []),+ // @ts-ignore+ ]).then((results) => results.map((result) => result.value));++ if (response === null) {+ return new Response("Key already exists.", { status: 409, headers });+ }++ if (!project && invalidFavicon) {+ await log({+ message: `*${+ session.user.email+ }* edited a link (dub.sh/${key}) to the ${url} ${+ invalidFavicon ? " but it has an invalid favicon :thinking_face:" : ""+ }`,+ type: "links",+ mention: true,+ });+ }++ return NextResponse.json(response, {+ headers,+ });+ },+ {+ needNotExceededUsage: true,+ },+);++// DELETE /api/projects/[slug]/links/[linkId] – delete a link+export const DELETE = withAuth(async ({ headers, link }) => {+ // link is guaranteed to exist because if not we will return 404+ const response = await deleteLink({+ domain: link!.domain,+ key: link!.key,+ });+ return NextResponse.json(response[0], {+ headers,+ });+});diff --git a/apps/web/app/api/links-app/route.ts b/apps/web/app/api/links-app/route.tsnew file mode 100644index 0000000000..6272c67aa4--- /dev/null+++ b/apps/web/app/api/links-app/route.ts@@ -0,0 +1,146 @@+import {+ addLink,+ getLinksForProject,+ getRandomKey,+ processKey,+} from "@/lib/api/links";+import { withAuth } from "@/lib/auth";+import { isBlacklistedDomain, isBlacklistedKey } from "@/lib/edge-config";+import {+ DUB_PROJECT_ID,+ GOOGLE_FAVICON_URL,+ getApexDomain,+ log,+} from "@dub/utils";+import { NextResponse } from "next/server";++// GET /api/links – get all user links+export const GET = withAuth(+ async ({ headers, searchParams, project, session }) => {+ const { domain, tagId, search, sort, page, userId, showArchived } =+ searchParams as {+ domain?: string;+ tagId?: string;+ search?: string;+ sort?: "createdAt" | "clicks" | "lastClicked";+ page?: string;+ userId?: string;+ showArchived?: string;+ };+ const response = await getLinksForProject({+ projectId: project?.id || DUB_PROJECT_ID,+ domain,+ tagId,+ search,+ sort,+ page,+ userId: project?.id ? userId : session.user.id,+ showArchived: showArchived === "true" ? true : false,+ });+ return NextResponse.json(response, {+ headers,+ });+ },+);++// POST /api/links – create a new link+export const POST = withAuth(+ async ({ req, headers, session, project }) => {+ const body = await req.json();+ let { domain, key, url, rewrite, geo } = body;++ if (!url) {+ return new Response("Missing destination url.", { status: 400, headers });+ }+ if (!domain) {+ return new Response("Missing short link domain.", {+ status: 400,+ headers,+ });+ }++ if (!key) {+ key = await getRandomKey(domain);+ }++ // if it's not a custom project, do some filtering+ if (!project) {+ if (key.includes("/")) {+ return new Response("Key cannot contain '/'.", {+ status: 422,+ headers,+ });+ }+ const keyBlacklisted = await isBlacklistedKey(key);+ if (keyBlacklisted) {+ return new Response("Invalid key.", { status: 422, headers });+ }+ const domainBlacklisted = await isBlacklistedDomain(url);+ if (domainBlacklisted) {+ return new Response("Invalid url.", { status: 422, headers });+ }+ if (rewrite) {+ return new Response(+ "You can only use link cloaking on a custom domain.",+ { status: 403, headers },+ );+ }+ }++ // free plan restrictions+ if (!project || project.plan === "free") {+ if (geo) {+ return new Response("You can only use geo targeting on a Pro plan.", {+ status: 403,+ headers,+ });+ }+ }++ key = processKey(key);+ if (!key) {+ return new Response("Invalid key.", { status: 422, headers });+ }++ const [response, invalidFavicon] = await Promise.allSettled([+ addLink({+ ...body,+ key,+ projectId: project?.id || DUB_PROJECT_ID,+ userId: session.user.id,+ }),+ ...(!project+ ? [+ fetch(`${GOOGLE_FAVICON_URL}${getApexDomain(url)}`).then(+ (res) => !res.ok,+ ),+ ]+ : []),+ // @ts-ignore+ ]).then((results) => results.map((result) => result.value));++ if (response === null) {+ return new Response("Duplicate key: this short link already exists.", {+ status: 409,+ headers,+ });+ }++ if (!project && invalidFavicon) {+ await log({+ message: `*${+ session.user.email+ }* created a new link (dub.sh/${key}) for ${url} ${+ invalidFavicon ? " but it has an invalid favicon :thinking_face:" : ""+ }`,+ type: "links",+ mention: true,+ });+ }++ return NextResponse.json(response, { headers });+ },+ {+ needNotExceededUsage: true,+ },+);diff --git a/apps/web/app/api/links/count/route.ts b/apps/web/app/api/links/count/route.tsnew file mode 100644index 0000000000..086b3584e9--- /dev/null+++ b/apps/web/app/api/links/count/route.ts@@ -0,0 +1,19 @@+import { getLinksCount } from "@/lib/api/links";+import { withAuth } from "@/lib/auth";+import { DUB_PROJECT_ID } from "@dub/utils";+import { NextResponse } from "next/server";++// GET /api/projects/[slug]/links/count – get the number of links for a project+export const GET = withAuth(+ async ({ headers, searchParams, project, session }) => {+ const { userId } = searchParams;+ const count = await getLinksCount({+ searchParams,+ projectId: project?.id || DUB_PROJECT_ID,+ userId: project?.id ? userId : session.user.id,+ });+ return NextResponse.json(count, {+ headers,+ });+ },+);diff --git a/apps/web/app/api/links/exists/route.ts b/apps/web/app/api/links/exists/route.tsnew file mode 100644index 0000000000..1cb8679cba--- /dev/null+++ b/apps/web/app/api/links/exists/route.ts@@ -0,0 +1,12 @@+import { withAuth } from "@/lib/auth";+import { checkIfKeyExists } from "@/lib/api/links";+import { NextResponse } from "next/server";++// GET /api/projects/[slug]/links/exists – check if a link exists+export const GET = withAuth(async ({ headers, searchParams }) => {+ const { domain, key } = searchParams;+ const response = await checkIfKeyExists(domain || "dub.sh", key);+ return NextResponse.json(response, {+ headers,+ });+});diff --git a/apps/web/app/api/links/info/route.ts b/apps/web/app/api/links/info/route.tsnew file mode 100644index 0000000000..5b8a8a2778--- /dev/null+++ b/apps/web/app/api/links/info/route.ts@@ -0,0 +1,19 @@+import { withAuth } from "@/lib/auth";+import prisma from "@/lib/prisma";+import { NextResponse } from "next/server";++// GET /api/projects/[slug]/links/info – get the info for a link+export const GET = withAuth(async ({ headers, searchParams }) => {+ const { domain, key } = searchParams;+ const response = await prisma.link.findUnique({+ where: {+ domain_key: {+ domain: domain || "dub.sh",+ key,+ },+ },+ });+ return NextResponse.json(response, {+ headers,+ });+});diff --git a/apps/web/app/api/links/random/route.ts b/apps/web/app/api/links/random/route.tsnew file mode 100644index 0000000000..f973dff498--- /dev/null+++ b/apps/web/app/api/links/random/route.ts@@ -0,0 +1,12 @@+import { withAuth } from "@/lib/auth";+import { getRandomKey } from "@/lib/api/links";+import { NextResponse } from "next/server";++// GET /api/projects/[slug]/links/random – get a random available link key+export const GET = withAuth(async ({ headers, searchParams }) => {+ const { domain } = searchParams;+ const response = await getRandomKey(domain || "dub.sh");+ return NextResponse.json(response, {+ headers,+ });+});diff --git a/apps/web/app/api/projects/[slug]/links/[linkId]/archive/route.ts b/apps/web/app/api/projects/[slug]/links/[linkId]/archive/route.tsnew file mode 100644index 0000000000..5d3e353290--- /dev/null+++ b/apps/web/app/api/projects/[slug]/links/[linkId]/archive/route.ts@@ -0,0 +1 @@+export * from "../../../../../links-app/[linkId]/archive/route";diff --git a/apps/web/app/api/projects/[slug]/links/[linkId]/route.ts b/apps/web/app/api/projects/[slug]/links/[linkId]/route.tsnew file mode 100644index 0000000000..220562f1b5--- /dev/null+++ b/apps/web/app/api/projects/[slug]/links/[linkId]/route.ts@@ -0,0 +1 @@+export * from "../../../../links-app/[linkId]/route";diff --git a/apps/web/app/api/projects/[slug]/links/count/route.ts b/apps/web/app/api/projects/[slug]/links/count/route.tsnew file mode 100644index 0000000000..9323ac6eed--- /dev/null+++ b/apps/web/app/api/projects/[slug]/links/count/route.ts@@ -0,0 +1 @@+export * from "../../../../links/count/route";diff --git a/apps/web/app/api/projects/[slug]/links/exists/route.ts b/apps/web/app/api/projects/[slug]/links/exists/route.tsnew file mode 100644index 0000000000..ed3baf39a0--- /dev/null+++ b/apps/web/app/api/projects/[slug]/links/exists/route.ts@@ -0,0 +1 @@+export * from "../../../../links/exists/route";diff --git a/apps/web/app/api/projects/[slug]/links/info/route.ts b/apps/web/app/api/projects/[slug]/links/info/route.tsnew file mode 100644index 0000000000..f9b4660eb4--- /dev/null+++ b/apps/web/app/api/projects/[slug]/links/info/route.ts@@ -0,0 +1 @@+export * from "../../../../links/info/route";diff --git a/apps/web/app/api/projects/[slug]/links/random/route.ts b/apps/web/app/api/projects/[slug]/links/random/route.tsnew file mode 100644index 0000000000..4b8030b4e5--- /dev/null+++ b/apps/web/app/api/projects/[slug]/links/random/route.ts@@ -0,0 +1 @@+export * from "../../../../links/random/route";diff --git a/apps/web/app/api/projects/[slug]/links/route.ts b/apps/web/app/api/projects/[slug]/links/route.tsnew file mode 100644index 0000000000..0bac60cc29--- /dev/null+++ b/apps/web/app/api/projects/[slug]/links/route.ts@@ -0,0 +1 @@+export * from "../../../links-app/route";diff --git a/apps/web/app/api/route.ts b/apps/web/app/api/route.tsindex ca356a280e..3afc01db60 100644--- a/apps/web/app/api/route.ts+++ b/apps/web/app/api/route.ts@@ -25,7 +25,7 @@ export function GET(): NextResponse<OpenAPIV3.Document> {},],paths: {- "/links": {+ "/projects/{slug}/links": {get: {description:"Retrieve a list of links for the authenticated user or project. The list will be paginated and the provided query parameters allow filtering the returned links.",@@ -40,24 +40,24 @@ export function GET(): NextResponse<OpenAPIV3.Document> {{name: "slug",description:- "The slug for the project to retrieve links for. E.g. for app.dub.co/vercel, the slug is 'vercel'.",- in: "query",+ "The slug for the project to retrieve links for. E.g. for app.dub.co/acme, the slug is 'acme'.",+ in: "path",required: true,schema: {description:- "The slug for the project to retrieve links for. E.g. for app.dub.co/vercel, the slug is 'vercel'.",+ "The slug for the project to retrieve links for. E.g. for app.dub.co/acme, the slug is 'acme'.",type: "string",},},{name: "domain",description:- "The domain to filter the links by. E.g. 'vercel.fyi' or 'stey.me'. If not provided, all links for the project will be returned.",+ "The domain to filter the links by. E.g. 'ac.me'. If not provided, all links for the project will be returned.",in: "query",required: false,schema: {description:- "The domain to filter the links by. E.g. 'vercel.fyi' or 'stey.me'. If not provided, all links for the project will be returned.",+ "The domain to filter the links by. E.g. 'ac.me'. If not provided, all links for the project will be returned.",type: "string",},},@@ -163,12 +163,12 @@ export function GET(): NextResponse<OpenAPIV3.Document> {{name: "slug",description:- "The slug for the project to create links for. E.g. for app.dub.co/vercel, the slug is 'vercel'.",- in: "query",+ "The slug for the project to retrieve links for. E.g. for app.dub.co/acme, the slug is 'acme'.",+ in: "path",required: true,schema: {description:- "The slug for the project to create links for. E.g. for app.dub.co/vercel, the slug is 'vercel'.",+ "The slug for the project to retrieve links for. E.g. for app.dub.co/acme, the slug is 'acme'.",type: "string",},},@@ -199,10 +199,11 @@ export function GET(): NextResponse<OpenAPIV3.Document> {},},},- "/links/{key}": {+ "/projects/{slug}/links/info": {get: {- description: "Retrieve a link for the authenticated user or project.",- operationId: "getLink",+ description:+ "Retrieve the info for a link from their domain and key.",+ operationId: "getLinkInfo",security: [{bearerToken: [],@@ -211,14 +212,14 @@ export function GET(): NextResponse<OpenAPIV3.Document> {summary: "Retrieve a link",parameters: [{- name: "key",+ name: "slug",description:- "The key of the link to retrieve. E.g. for dub.sh/github, the key is 'github'.",+ "The slug for the project to retrieve links for. E.g. for app.dub.co/acme, the slug is 'acme'.",in: "path",required: true,schema: {description:- "The key of the link to retrieve. E.g. for dub.sh/github, the key is 'github'.",+ "The slug for the project to retrieve links for. E.g. for app.dub.co/acme, the slug is 'acme'.",type: "string",},},@@ -235,14 +236,14 @@ export function GET(): NextResponse<OpenAPIV3.Document> {},},{- name: "slug",+ name: "key",description:- "The project slug of the link to retrieve. E.g. for app.dub.co/vercel, the slug is 'vercel'.",+ "The key of the link to retrieve. E.g. for dub.sh/github, the key is 'github'.",in: "query",required: true,schema: {description:- "The project slug of the link to retrieve. E.g. for app.dub.co/vercel, the slug is 'vercel'.",+ "The key of the link to retrieve. E.g. for dub.sh/github, the key is 'github'.",type: "string",},},@@ -260,6 +261,8 @@ export function GET(): NextResponse<OpenAPIV3.Document> {},},},+ },+ "/projects/{slug}/links/{linkId}": {put: {description: "Edit link for the authenticated user or project.",operationId: "editLink",@@ -271,38 +274,26 @@ export function GET(): NextResponse<OpenAPIV3.Document> {summary: "Edit a link",parameters: [{- name: "key",+ name: "slug",description:- "The key of the link to edit. E.g. for dub.sh/github, the key is 'github'.",+ "The slug for the project to retrieve links for. E.g. for app.dub.co/acme, the slug is 'acme'.",in: "path",required: true,schema: {description:- "The key of the link to edit. E.g. for dub.sh/github, the key is 'github'.",- type: "string",- },- },- {- name: "domain",- description:- "The domain of the link to edit. E.g. for dub.sh/github, the domain is 'dub.sh'.",- in: "query",- required: true,- schema: {- description:- "The domain of the link to edit. E.g. for dub.sh/github, the domain is 'dub.sh'.",+ "The slug for the project to retrieve links for. E.g. for app.dub.co/acme, the slug is 'acme'.",type: "string",},},{- name: "slug",+ name: "linkId",description:- "The project slug of the link to edit. E.g. for app.dub.co/vercel, the slug is 'vercel'.",- in: "query",+ "The id of the link to edit. You can get this via the getLinkInfo endpoint.",+ in: "path",required: true,schema: {description:- "The project slug of the link to edit. E.g. for app.dub.co/vercel, the slug is 'vercel'.",+ "The id of the link to edit. You can get this via the getLinkInfo endpoint.",type: "string",},},@@ -342,38 +333,26 @@ export function GET(): NextResponse<OpenAPIV3.Document> {summary: "Delete a link",parameters: [{- name: "key",+ name: "slug",description:- "The key of the link to delete. E.g. for dub.sh/github, the key is 'github'.",+ "The slug for the project to retrieve links for. E.g. for app.dub.co/acme, the slug is 'acme'.",in: "path",required: true,schema: {description:- "The key of the link to delete. E.g. for dub.sh/github, the key is 'github'.",- type: "string",- },- },- {- name: "domain",- description:- "The domain of the link to delete. E.g. for dub.sh/github, the domain is 'dub.sh'.",- in: "query",- required: true,- schema: {- description:- "The domain of the link to delete. E.g. for dub.sh/github, the domain is 'dub.sh'.",+ "The slug for the project to retrieve links for. E.g. for app.dub.co/acme, the slug is 'acme'.",type: "string",},},{- name: "slug",+ name: "linkId",description:- "The project slug of the link to delete. E.g. for app.dub.co/vercel, the slug is 'vercel'.",- in: "query",+ "The id of the link to delete. You can get this via the `getLinkInfo` endpoint.",+ in: "path",required: true,schema: {description:- "The project slug of the link to delete. E.g. for app.dub.co/vercel, the slug is 'vercel'.",+ "The id of the link to delete. You can get this via the `getLinkInfo` endpoint.",type: "string",},},diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/billing/page-client.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/billing/page-client.tsxindex 50a8c6a4af..a9fb1a54bc 100644--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/billing/page-client.tsx+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/billing/page-client.tsx@@ -20,7 +20,7 @@ export default function ProjectBillingClient() {const { slug, plan, usage, usageLimit, billingCycleStart } = useProject();const { data: links } = useSWR<number>(- `/api/links/_count?slug=${slug}`,+ `/api/projects/${slug}/links/count`,fetcher,);const [clicked, setClicked] = useState(false);diff --git a/apps/web/lib/api/links.ts b/apps/web/lib/api/links.tsindex f014f925a5..36d3a2ba3f 100644--- a/apps/web/lib/api/links.ts+++ b/apps/web/lib/api/links.ts@@ -64,15 +64,15 @@ export async function getLinksForProject({}export async function getLinksCount({- req,+ searchParams,projectId,userId,}: {- req: NextApiRequest;+ searchParams: Record<string, string>;projectId: string;userId?: string | null;}) {- let { groupBy, search, domain, tagId, showArchived } = req.query as {+ let { groupBy, search, domain, tagId, showArchived } = searchParams as {groupBy?: "domain" | "tagId";search?: string;domain?: string;diff --git a/apps/web/lib/auth.ts b/apps/web/lib/auth.tsindex 7a51ecb5c1..6b06dec55d 100644--- a/apps/web/lib/auth.ts+++ b/apps/web/lib/auth.ts@@ -4,6 +4,8 @@ import { Link as LinkProps } from "@prisma/client";import { PlanProps, ProjectProps } from "./types";import { getServerSession } from "next-auth/next";import { createHash } from "crypto";+import { API_DOMAIN } from "@dub/utils";+import { ratelimit } from "./upstash";export interface Session {user: {@@ -47,6 +49,7 @@ interface WithAuthHandler {req,params,searchParams,+ headers,session,project,domain,@@ -55,6 +58,7 @@ interface WithAuthHandler {req: Request;params: Record<string, string>;searchParams: Record<string, string>;+ headers?: Record<string, string>;session: Session;project: ProjectProps;domain: string;@@ -78,16 +82,106 @@ export const withAuth =req: Request,{ params }: { params: Record<string, string> | undefined },) => {- const session = await getSession();- if (!session?.user.id) {- return new Response("Unauthorized: Login required.", { status: 401 });- }-const searchParams = getSearchParams(req.url);- const { key } = searchParams;- const { slug } = params || {};- // domain can either be a path param or a query param- const domain = params?.domain || searchParams?.domain;+ const { slug, domain, linkId } = params || {};++ let session: Session | undefined;+ let headers = {};++ const authorizationHeader = req.headers.get("Authorization");+ if (authorizationHeader) {+ if (!authorizationHeader.includes("Bearer ")) {+ return new Response(+ "Misconfigured authorization header. Did you forget to add 'Bearer '? Learn more: https://dub.sh/auth ",+ {+ status: 400,+ },+ );+ }+ const apiKey = authorizationHeader.replace("Bearer ", "");+ // if there is no slug, it's the default dub.sh link+ if (!slug) {+ return new Response(+ "Unauthorized: API is not supported for dub.sh links yet.",+ {+ status: 403,+ },+ );+ }++ const url = new URL(req.url || "", API_DOMAIN);++ if (url.pathname.includes("/stats/")) {+ return new Response("Unauthorized: Invalid route.", {+ status: 403,+ });+ }++ const hashedKey = hashToken(apiKey, {+ noSecret: true,+ });++ const user = await prisma.user.findFirst({+ where: {+ tokens: {+ some: {+ hashedKey,+ },+ },+ },+ select: {+ id: true,+ name: true,+ email: true,+ },+ });+ if (!user) {+ return new Response("Unauthorized: Invalid API key.", {+ status: 401,+ });+ }++ const { success, limit, reset, remaining } = await ratelimit(+ 10,+ "1 s",+ ).limit(apiKey);++ headers = {+ "Retry-After": reset.toString(),+ "X-RateLimit-Limit": limit.toString(),+ "X-RateLimit-Remaining": remaining.toString(),+ "X-RateLimit-Reset": reset.toString(),+ };++ if (!success) {+ return new Response("Too many requests.", {+ status: 429,+ headers,+ });+ }+ await prisma.token.update({+ where: {+ hashedKey,+ },+ data: {+ lastUsed: new Date(),+ },+ });+ session = {+ user: {+ id: user.id,+ name: user.name || "",+ email: user.email || "",+ },+ };+ } else {+ session = await getSession();+ if (!session?.user.id) {+ return new Response("Unauthorized: Login required.", {+ status: 401,+ });+ }+ }const [project, link] = (await Promise.all([slug &&@@ -116,19 +210,15 @@ export const withAuth =},},}),- domain &&- key &&+ linkId &&prisma.link.findUnique({where: {- domain_key: {- domain,- key,- },+ id: linkId,},}),])) as [ProjectProps | undefined, LinkProps | undefined];- // it's a project+ // project checksif (slug) {if (!project || !project.users) {// project doesn't exist@@ -215,10 +305,18 @@ export const withAuth =status: 403,});}- } else if (link) {- // no slug means it's a generic Dub.sh link- // thus, we need to make sure the user is the owner of the link- if (link.userId !== session.user.id) {+ }++ // link checks+ if (linkId) {+ if (!link) {+ return new Response("Link not found.", {+ status: 404,+ });+ }++ // if it's the default dub.sh link, we need to make sure the user is the owner of the link+ if (link.domain === "dub.sh" && link.userId !== session.user.id) {return new Response("Unauthorized: Invalid link.", {status: 401,});@@ -229,6 +327,7 @@ export const withAuth =req,params: params || {},searchParams,+ headers,session,project: project as ProjectProps,domain,diff --git a/apps/web/lib/swr/use-links-count.ts b/apps/web/lib/swr/use-links-count.tsindex 1edebb6372..7f699785b4 100644--- a/apps/web/lib/swr/use-links-count.ts+++ b/apps/web/lib/swr/use-links-count.ts@@ -7,12 +7,11 @@ export default function useLinksCount({}: {groupBy?: "domain" | "tagId";} = {}) {- const params = useParams() as { slug?: string };+ const { slug } = useParams() as { slug?: string };const searchParams = useSearchParams();const { data, error } = useSWR<any>(- `/api/links/_count${getQueryString({- params,+ `/api${slug ? `/projects/${slug}` : ""}/links/count${getQueryString({searchParams,...(groupBy && { groupBy }),})}`,diff --git a/apps/web/lib/swr/use-links.ts b/apps/web/lib/swr/use-links.tsindex f7d04621c4..eac151c628 100644--- a/apps/web/lib/swr/use-links.ts+++ b/apps/web/lib/swr/use-links.ts@@ -5,7 +5,7 @@ import { UserProps } from "../types";import { useParams, useSearchParams } from "next/navigation";export default function useLinks() {- const params = useParams() as { slug?: string };+ const { slug } = useParams() as { slug?: string };const searchParams = useSearchParams();const { data: links, isValidating } = useSWR<@@ -13,8 +13,7 @@ export default function useLinks() {user: UserProps;})[]>(- `/api/links${getQueryString({- params,+ `/api${slug ? `/projects/${slug}/links` : "/links-app"}${getQueryString({searchParams,})}`,fetcher,diff --git a/apps/web/pages/api/links/[key]/archive.ts b/apps/web/pages/api/links/[key]/archive.tsdeleted file mode 100644index b899b84071..0000000000--- a/apps/web/pages/api/links/[key]/archive.ts+++ /dev/null@@ -1,17 +0,0 @@-import { archiveLink } from "@/lib/api/links";-import { withLinksAuth } from "@/lib/auth-links";--export default withLinksAuth(async (req, res, _session, _project, domain) => {- const { key } = req.query as { key: string };-- if (req.method === "POST") {- const response = await archiveLink(domain || "dub.sh", key, true);- return res.status(200).json(response);- } else if (req.method === "DELETE") {- const response = await archiveLink(domain || "dub.sh", key, false);- return res.status(200).json(response);- } else {- res.setHeader("Allow", ["POST", "DELETE"]);- return res.status(405).end(`Method ${req.method} Not Allowed`);- }-});diff --git a/apps/web/pages/api/links/[key]/exists.ts b/apps/web/pages/api/links/[key]/exists.tsdeleted file mode 100644index cb1e92a5a3..0000000000--- a/apps/web/pages/api/links/[key]/exists.ts+++ /dev/null@@ -1,19 +0,0 @@-import { checkIfKeyExists } from "@/lib/api/links";-import { withLinksAuth } from "@/lib/auth-links";--export default withLinksAuth(- async (req, res, _session, _project, domain) => {- // GET /api/links/[key]/exists - check if a key exists- if (req.method === "GET") {- const { key } = req.query as { key: string };- const response = await checkIfKeyExists(domain || "dub.sh", key);- return res.status(200).json(response);- } else {- res.setHeader("Allow", ["GET"]);- return res.status(405).end(`Method ${req.method} Not Allowed`);- }- },- {- skipKeyCheck: true,- },-);diff --git a/apps/web/pages/api/links/_count.ts b/apps/web/pages/api/links/_count.tsdeleted file mode 100644index b5cd1087f6..0000000000--- a/apps/web/pages/api/links/_count.ts+++ /dev/null@@ -1,19 +0,0 @@-import { getLinksCount } from "@/lib/api/links";-import { withLinksAuth } from "@/lib/auth-links";-import { DUB_PROJECT_ID } from "@dub/utils";--export default withLinksAuth(async (req, res, session, project) => {- // GET /api/links/_count – get the number of links for a project- if (req.method === "GET") {- const { userId } = req.query as { userId?: string };- const count = await getLinksCount({- req,- projectId: project?.id || DUB_PROJECT_ID,- userId: project?.id ? userId : session.user.id,- });- return res.status(200).json(count);- } else {- res.setHeader("Allow", ["GET"]);- return res.status(405).end(`Method ${req.method} Not Allowed`);- }-});diff --git a/apps/web/pages/api/links/_random.ts b/apps/web/pages/api/links/_random.tsdeleted file mode 100644index 59dab18b80..0000000000--- a/apps/web/pages/api/links/_random.ts+++ /dev/null@@ -1,13 +0,0 @@-import { getRandomKey } from "@/lib/api/links";-import { withLinksAuth } from "@/lib/auth-links";--export default withLinksAuth(async (req, res, _session, _project, domain) => {- // GET /api/links/_random – get a random key for a project- if (req.method === "GET") {- const response = await getRandomKey(domain || "dub.sh");- return res.status(200).json(response);- } else {- res.setHeader("Allow", ["GET"]);- return res.status(405).end(`Method ${req.method} Not Allowed`);- }-});diff --git a/apps/web/pages/api/stripe/webhook.ts b/apps/web/pages/api/stripe/webhook.tsdeleted file mode 100644index 8926208409..0000000000--- a/apps/web/pages/api/stripe/webhook.ts+++ /dev/null@@ -1,220 +0,0 @@-import prisma from "@/lib/prisma";-import { stripe } from "@/lib/stripe";-import { getPlanFromPriceId, isNewCustomer } from "@/lib/stripe/utils";-import { redis } from "@/lib/upstash";-import { log } from "@dub/utils";-import { sendEmail } from "emails";-import UpgradeEmail from "emails/upgrade-email";-import { NextApiRequest, NextApiResponse } from "next";-import { Readable } from "node:stream";-import Stripe from "stripe";--// Stripe requires the raw body to construct the event.-export const config = {- api: {- bodyParser: false,- },-};--async function buffer(readable: Readable) {- const chunks: Buffer[] = [];- for await (const chunk of readable) {- chunks.push(typeof chunk === "string" ? Buffer.from(chunk) : chunk);- }- return Buffer.concat(chunks);-}--const relevantEvents = new Set([- "checkout.session.completed",- "customer.subscription.updated",- "customer.subscription.deleted",-]);--export default async function webhookHandler(- req: NextApiRequest,- res: NextApiResponse,-) {- // POST /api/stripe/webhook – listen to Stripe webhooks- if (req.method === "POST") {- const buf = await buffer(req);- const sig = req.headers["stripe-signature"];- const webhookSecret = process.env.STRIPE_WEBHOOK_SECRET;- let event: Stripe.Event;- try {- if (!sig || !webhookSecret) return;- event = stripe.webhooks.constructEvent(buf, sig, webhookSecret);- } catch (err: any) {- console.log(`❌ Error message: ${err.message}`);- return res.status(400).send(`Webhook Error: ${err.message}`);- }- if (relevantEvents.has(event.type)) {- try {- if (event.type === "checkout.session.completed") {- const checkoutSession = event.data.object as Stripe.Checkout.Session;-- if (- checkoutSession.client_reference_id === null ||- checkoutSession.customer === null- ) {- await log({- message: "Missing items in Stripe webhook callback",- type: "cron",- mention: true,- });- return;- }-- // when the project subscribes to a plan, set their stripe customer ID- // in the database for easy identification in future webhook events- // also update the billingCycleStart to today's date-- await prisma.project.update({- where: {- id: checkoutSession.client_reference_id,- },- data: {- stripeId: checkoutSession.customer.toString(),- billingCycleStart: new Date().getDate(),- },- });-- // for subscription updates- } else if (event.type === "customer.subscription.updated") {- const subscriptionUpdated = event.data.object as Stripe.Subscription;- const priceId = subscriptionUpdated.items.data[0].price.id;- const newCustomer = isNewCustomer(event.data.previous_attributes);-- const plan = getPlanFromPriceId(priceId);- const usageLimit = plan.quota;- const stripeId = subscriptionUpdated.customer.toString();-- // If a project upgrades/downgrades their subscription, update their usage limit in the database.- const data = await prisma.project.update({- where: {- stripeId,- },- data: {- usageLimit,- plan: plan.slug,- },- select: {- users: {- where: {- role: "owner",- },- select: {- user: {- select: {- name: true,- email: true,- },- },- },- },- },- });- if (!data) {- await log({- message:- "Project not found in Stripe webhook `customer.subscription.created` callback",- type: "cron",- mention: true,- });- return;- }-- // Send thank you email to project owner if they are a new customer- if (newCustomer) {- const owner = data.users[0].user;-- await sendEmail({- email: owner.email as string,- subject: `Thank you for upgrading to Dub ${plan.name}!`,- react: UpgradeEmail({- name: owner.name,- email: owner.email as string,- plan: plan.name,- }),- marketing: true,- });- }-- // If project cancels their subscription- } else if (event.type === "customer.subscription.deleted") {- const subscriptionDeleted = event.data.object as Stripe.Subscription;-- const stripeId = subscriptionDeleted.customer.toString();-- // If a project deletes their subscription, reset their usage limit in the database to 1000.- // Also remove the root domain redirect for all their domains from Redis.- const project = await prisma.project.findUnique({- where: {- stripeId,- },- select: {- name: true,- domains: true,- },- });-- if (!project) {- await log({- message:- "Project not found in Stripe webhook `customer.subscription.deleted` callback",- type: "cron",- mention: true,- });- return;- }-- const projectDomains = project.domains.map((domain) => domain.slug);-- const pipeline = redis.pipeline();- // remove root domain redirect for all domains- projectDomains.forEach((domain) => {- pipeline.del(`root:${domain}`);- });-- await Promise.all([- prisma.project.update({- where: {- stripeId,- },- data: {- usageLimit: 1000,- plan: "free",- },- }),- pipeline.exec(),- log({- message:- ":cry: Project *`" +- project.name +- "`* deleted their subscription",- type: "cron",- mention: true,- }),- ]);- } else {- throw new Error("Unhandled relevant event!");- }- } catch (error) {- await log({- message: `Stripe webook failed. Error: ${error.message}`,- type: "cron",- mention: true,- });- return res- .status(400)- .send('Webhook error: "Webhook handler failed. View logs."');- }- } else {- return res.status(400).send(`🤷♀️ Unhandled event type: ${event.type}`);- }-- res.status(200).json({ received: true });- } else {- res.setHeader("Allow", ["POST"]);- return res.status(405).end(`Method ${req.method} Not Allowed`);- }-}diff --git a/apps/web/ui/links/link-card.tsx b/apps/web/ui/links/link-card.tsxindex b655b4d61c..d53ab2184e 100644--- a/apps/web/ui/links/link-card.tsx+++ b/apps/web/ui/links/link-card.tsx@@ -92,12 +92,13 @@ export default function LinkCard({const { data: clicks } = useSWR<number>(isVisible &&!exceededUsage &&- `/api/links/${encodeURIComponent(key)}/stats/clicks${- slug ? `?slug=${slug}&domain=${domain}` : ""- }`,+ `/api${+ slug ? `/projects/${slug}` : ""+ }/stats/clicks?domain=${domain}&key=${key}`,fetcher,{fallbackData: props.clicks,+ dedupingInterval: 60000,},);diff --git a/apps/web/ui/modals/add-edit-domain-modal.tsx b/apps/web/ui/modals/add-edit-domain-modal.tsxindex 8221705042..8b25b4bad0 100644--- a/apps/web/ui/modals/add-edit-domain-modal.tsx+++ b/apps/web/ui/modals/add-edit-domain-modal.tsx@@ -111,7 +111,9 @@ function AddEditDomainModal({await Promise.all([mutate(`/api/projects/${slug}/domains`),mutate(- (key) => typeof key === "string" && key.startsWith(`/api/links`),+ (key) =>+ typeof key === "string" &&+ key.startsWith(`/api/projects/${slug}/links`),undefined,{ revalidate: true },),diff --git a/apps/web/ui/modals/add-edit-link-modal/index.tsx b/apps/web/ui/modals/add-edit-link-modal/index.tsxindex fd57df943a..b564e9ec21 100644--- a/apps/web/ui/modals/add-edit-link-modal/index.tsx+++ b/apps/web/ui/modals/add-edit-link-modal/index.tsx@@ -37,7 +37,6 @@ import punycode from "punycode/";import {Dispatch,SetStateAction,- Suspense,UIEvent,useCallback,useContext,@@ -117,9 +116,9 @@ function AddEditLinkModal({!keyError) {fetch(- `/api/links/${encodeURIComponent(debouncedKey)}/exists${- slug ? `?slug=${slug}&domain=${domain}` : ""- }`,+ `/api${+ slug ? `/projects/${slug}` : ""+ }/links/exists?domain=${domain}&key=${debouncedKey}`,).then(async (res) => {if (res.status === 200) {const exists = await res.json();@@ -133,7 +132,7 @@ function AddEditLinkModal({setKeyError(null);setGeneratingKey(true);const res = await fetch(- `/api/links/_random${slug ? `?slug=${slug}&domain=${domain}` : ""}`,+ `/api${slug ? `/projects/${slug}` : ""}/links/random?domain=${domain}`,);const key = await res.json();setData((prev) => ({ ...prev, key }));@@ -228,14 +227,14 @@ function AddEditLinkModal({if (props?.key) {return {method: "PUT",- url: `/api/links/${encodeURIComponent(props.key)}${- slug ? `?slug=${slug}&domain=${props.domain}` : ""+ url: `/api${slug ? `/projects/${slug}/links` : "/links-app"}/${+ props.id}`,};} else {return {method: "POST",- url: `/api/links${slug ? `?slug=${slug}&domain=${domain}` : ""}`,+ url: `/api${slug ? `/projects/${slug}/links` : "/links-app"}`,};}}, [props, slug, domain]);@@ -355,15 +354,20 @@ function AddEditLinkModal({});await Promise.all([mutate(- `/api/links${getQueryString({- params,- searchParams,- })}`,+ (key) =>+ typeof key === "string" &&+ key.startsWith(+ `/api${+ slug ? `/projects/${slug}/links` : "/links-app"+ }`,+ ),),mutate((key) =>typeof key === "string" &&- key.startsWith(`/api/links/_count`),+ key.startsWith(+ `/api${slug ? `/projects/${slug}` : ""}/links/count`,+ ),undefined,{ revalidate: true },),diff --git a/apps/web/ui/modals/archive-link-modal.tsx b/apps/web/ui/modals/archive-link-modal.tsxindex 966c22d88c..4de79abb01 100644--- a/apps/web/ui/modals/archive-link-modal.tsx+++ b/apps/web/ui/modals/archive-link-modal.tsx@@ -74,9 +74,9 @@ function ArchiveLinkModal({e.preventDefault();setArchiving(true);fetch(- `/api/links/${encodeURIComponent(props.key)}/archive${- slug ? `?slug=${slug}&domain=${domain}` : ""- }`,+ `/api${slug ? `/projects/${slug}/links` : "/links-app"}/${+ props.id+ }/archive`,{method: archived ? "POST" : "DELETE",headers: {@@ -87,15 +87,20 @@ function ArchiveLinkModal({if (res.status === 200) {await Promise.all([mutate(- `/api/links${getQueryString({- params,- searchParams,- })}`,+ (key) =>+ typeof key === "string" &&+ key.startsWith(+ `/api${+ slug ? `/projects/${slug}/links` : "/links-app"+ }`,+ ),),mutate((key) =>typeof key === "string" &&- key.startsWith(`/api/links/_count`),+ key.startsWith(+ `/api${slug ? `/projects/${slug}` : ""}/links/count`,+ ),undefined,{ revalidate: true },),diff --git a/apps/web/ui/modals/delete-link-modal.tsx b/apps/web/ui/modals/delete-link-modal.tsxindex 1a97a7889c..12cca2fccc 100644--- a/apps/web/ui/modals/delete-link-modal.tsx+++ b/apps/web/ui/modals/delete-link-modal.tsx@@ -68,8 +68,8 @@ function DeleteLinkModal({e.preventDefault();setDeleting(true);fetch(- `/api/links/${encodeURIComponent(props.key)}${- slug ? `?slug=${slug}&domain=${domain}` : ""+ `/api${slug ? `/projects/${slug}/links` : "/links-app"}/${+ props.id}`,{method: "DELETE",@@ -80,11 +80,19 @@ function DeleteLinkModal({).then(async (res) => {if (res.status === 200) {await Promise.all([- mutate(`/api/links${getQueryString({ params, searchParams })}`),mutate((key) =>typeof key === "string" &&- key.startsWith(`/api/links/_count`),+ key.startsWith(+ `/api${slug ? `/projects/${slug}/links` : "/links-app"}`,+ ),+ ),+ mutate(+ (key) =>+ typeof key === "string" &&+ key.startsWith(+ `/api${slug ? `/projects/${slug}` : ""}/links/count`,+ ),undefined,{ revalidate: true },),diff --git a/apps/web/ui/modals/provider.tsx b/apps/web/ui/modals/provider.tsxindex b5642a34ae..8be2d5f134 100644--- a/apps/web/ui/modals/provider.tsx+++ b/apps/web/ui/modals/provider.tsx@@ -65,15 +65,19 @@ export default function ModalProvider({ children }: { children: ReactNode }) {// if pollLinks is true, start polling links endpoint every 500 ms (stop after 20 seconds)const pollingInterval = setInterval(() => {mutate(- `/api/links${getQueryString({- params,+ `/api${+ slug ? `/projects/${slug}/links` : "/links-app"+ }${getQueryString({searchParams,})}`,);mutate(`/api/projects/${slug}/tags`);mutate((key) =>- typeof key === "string" && key.startsWith(`/api/links/_count`),+ typeof key === "string" &&+ key.startsWith(+ `/api${slug ? `/projects/${slug}` : ""}/links/count`,+ ),undefined,{ revalidate: true },);diff --git a/apps/web/ui/projects/project-card.tsx b/apps/web/ui/projects/project-card.tsxindex c421bbe1dc..79cac92d71 100644--- a/apps/web/ui/projects/project-card.tsx+++ b/apps/web/ui/projects/project-card.tsx@@ -21,7 +21,7 @@ export default function ProjectCard({primaryDomain,}: ProjectWithDomainProps) {const { data: count } = useSWR<number>(- `/api/links/_count?slug=${slug}`,+ `/api${slug ? `/projects/${slug}` : ""}/links/count`,fetcher,);return (diff --git a/apps/web/ui/shared/blur-image.tsx b/apps/web/ui/shared/blur-image.tsxindex af56a674b9..3a9d6a2bce 100644--- a/apps/web/ui/shared/blur-image.tsx+++ b/apps/web/ui/shared/blur-image.tsx@@ -21,6 +21,7 @@ export function BlurImage(props: ImageProps) {onError={() => {setSrc(`https://avatar.vercel.sh/${props.alt}`); // if the image fails to load, use the default avatar}}+ unoptimized/>);}diff --git a/packages/utils/src/index.ts b/packages/utils/src/index.tsindex 75f1b09593..88aba42d3f 100644--- a/packages/utils/src/index.ts+++ b/packages/utils/src/index.ts@@ -344,19 +344,13 @@ export const getDomainWithoutWWW = (url: string) => {};export const getQueryString = ({- params,searchParams,groupBy,}: {- params: Record<string, string>;searchParams: URLSearchParams | ReadonlyURLSearchParams | null;groupBy?: "domain" | "tagId";}) => {- const { slug } = params;const newSearchParams = new URLSearchParams(searchParams?.toString());- if (slug) {- newSearchParams.set("slug", slug);- }if (groupBy) {newSearchParams.set("groupBy", groupBy);}