The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
processLink function
Steven Teyf909180791bd
diff --git a/apps/web/app/api/links/[linkId]/route.ts b/apps/web/app/api/links/[linkId]/route.tsindex 15877eca78..61ae61ecb6 100644--- a/apps/web/app/api/links/[linkId]/route.ts+++ b/apps/web/app/api/links/[linkId]/route.ts@@ -1,5 +1,5 @@import { withAuth } from "@/lib/auth";-import { deleteLink, editLink, processKey } from "@/lib/api/links";+import { deleteLink, editLink, processKey, processLink } 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";@@ -32,49 +32,17 @@ export const PUT = withAuth();}- let { domain, key, url, rewrite } = updatedLink;-- // if it's a custom project- if (project) {- if (project.domains?.find((d) => d.slug === domain)) {- return new Response("Domain does not belong to project.", {- status: 403,- headers,- });- }- // if it's not a custom project, do some filtering- } else {- if (domain !== "dub.sh") {- return new Response("Invalid domain", {- status: 403,- headers,- });- }- 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 },- );- }- }+ const {+ link: processedLink,+ error,+ status,+ } = await processLink({+ payload: updatedLink,+ project,+ });- key = processKey(key);- if (!key) {- return new Response("Invalid key.", { status: 422, headers });+ if (!processedLink) {+ return new Response(error, { status, headers });}const [response, invalidFavicon] = await Promise.allSettled([@@ -82,13 +50,13 @@ export const PUT = withAuth(// link is guaranteed to exist because if not we will return 404domain: link!.domain,key: link!.key,- updatedLink,+ updatedLink: processedLink,}),- ...(!project && url+ ...(!project && processedLink.url? [- fetch(`${GOOGLE_FAVICON_URL}${getApexDomain(url)}`).then(- (res) => !res.ok,- ),+ fetch(+ `${GOOGLE_FAVICON_URL}${getApexDomain(processedLink.url)}`,+ ).then((res) => !res.ok),]: []),// @ts-ignore@@ -100,9 +68,9 @@ export const PUT = withAuth(if (!project && invalidFavicon) {await log({- message: `*${- session.user.email- }* edited a link (dub.sh/${key}) to the ${url} ${+ message: `*${session.user.email}* edited a link (dub.sh/${+ processedLink.key+ }) to the ${processedLink.url} ${invalidFavicon ? " but it has an invalid favicon :thinking_face:" : ""}`,type: "links",diff --git a/apps/web/app/api/links/route.ts b/apps/web/app/api/links/route.tsindex 421632fb08..1ed3a7c19a 100644--- a/apps/web/app/api/links/route.ts+++ b/apps/web/app/api/links/route.ts@@ -3,6 +3,7 @@ import {getLinksForProject,getRandomKey,processKey,+ processLink,} from "@/lib/api/links";import { withAuth } from "@/lib/auth";import { isBlacklistedDomain, isBlacklistedKey } from "@/lib/edge-config";@@ -53,85 +54,24 @@ export const POST = withAuth(return new Response("Missing or invalid body.", { status: 400, headers });}- 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 a custom project- if (project) {- if (!project.domains?.find((d) => d.slug === domain)) {- return new Response("Domain does not belong to project.", {- status: 403,- headers,- });- }- // if it's not a custom project, do some filtering- } else {- if (domain !== "dub.sh") {- return new Response("Invalid domain", {- status: 403,- headers,- });- }- 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,- });- }- }+ const { link, error, status } = await processLink({+ payload: body,+ project,+ });- key = processKey(key);- if (!key) {- return new Response("Invalid key.", { status: 422, headers });+ if (!link) {+ return new Response(error, { status, headers });}const [response, invalidFavicon] = await Promise.allSettled([addLink({- ...body,- key,+ ...link,projectId: project?.id || DUB_PROJECT_ID,userId: session.user.id,}),...(!project? [- fetch(`${GOOGLE_FAVICON_URL}${getApexDomain(url)}`).then(+ fetch(`${GOOGLE_FAVICON_URL}${getApexDomain(link.url)}`).then((res) => !res.ok,),]@@ -148,9 +88,9 @@ export const POST = withAuth(if (!project && invalidFavicon) {await log({- message: `*${- session.user.email- }* created a new link (dub.sh/${key}) for ${url} ${+ message: `*${session.user.email}* created a new link (dub.sh/${+ link.key+ }) for ${link.url} ${invalidFavicon ? " but it has an invalid favicon :thinking_face:" : ""}`,type: "links",diff --git a/apps/web/app/api/route.ts b/apps/web/app/api/route.tsindex ef0d56e695..db800b7a41 100644--- a/apps/web/app/api/route.ts+++ b/apps/web/app/api/route.ts@@ -477,7 +477,8 @@ export function GET(): NextResponse<OpenAPIV3.Document> {},geo: {type: "object",- description: "Geo targeting information for the short link.",+ description:+ 'Geo targeting information for the short link in JSON format {[COUNTRY]: "https://example.com" }. Learn more: https://dub.sh/geo',additionalProperties: {type: "string",format: "uri",diff --git a/apps/web/lib/api/links.ts b/apps/web/lib/api/links.tsindex 2603974dc8..6ef4e83fbd 100644--- a/apps/web/lib/api/links.ts+++ b/apps/web/lib/api/links.ts@@ -1,4 +1,8 @@-import { isReservedKey } from "@/lib/edge-config";+import {+ isBlacklistedDomain,+ isBlacklistedKey,+ isReservedKey,+} from "@/lib/edge-config";import prisma from "@/lib/prisma";import { redis } from "@/lib/upstash";import {@@ -8,10 +12,9 @@ import {truncate,validKeyRegex,} from "@dub/utils";-import { type Link as LinkProps } from "@prisma/client";import cloudinary from "cloudinary";import { isIframeable } from "../middleware/utils";-import { deleteClickData } from "../tinybird";+import { LinkProps, ProjectProps } from "../types";export async function getLinksForProject({projectId,@@ -193,6 +196,105 @@ export function processKey(key: string) {return key;}+export async function processLink({+ payload,+ project,+}: {+ payload: LinkProps;+ project: ProjectProps | null;+}) {+ let { domain, key, url, rewrite, geo } = payload;++ if (!url) {+ return {+ link: null,+ error: "Missing destination url.",+ status: 400,+ };+ }+ if (!domain) {+ return {+ link: null,+ error: "Missing short link domain.",+ status: 400,+ };+ }++ if (project) {+ if (!project.domains?.find((d) => d.slug === domain)) {+ return {+ link: null,+ error: "Domain does not belong to project.",+ status: 403,+ };+ }+ // if it's not a custom project, do some filtering+ } else {+ if (domain !== "dub.sh") {+ return {+ link: null,+ error: "Invalid domain",+ status: 403,+ };+ }+ if (key.includes("/")) {+ return {+ link: null,+ error:+ "Key cannot contain '/'. You can only use this with a custom domain.",+ status: 422,+ };+ }+ const keyBlacklisted = await isBlacklistedKey(key);+ if (keyBlacklisted) {+ return {+ link: null,+ error: "Invalid key.",+ status: 422,+ };+ }+ const domainBlacklisted = await isBlacklistedDomain(url);+ if (domainBlacklisted) {+ return {+ link: null,+ error: "Invalid url.",+ status: 422,+ };+ }+ if (rewrite) {+ return {+ link: null,+ error: "You can only use link cloaking on a custom domain.",+ status: 403,+ };+ }+ }++ // free plan restrictions+ if ((!project || project.plan === "free") && geo) {+ if (geo) {+ return {+ link: null,+ error: "You can only use geo targeting on a Pro plan.",+ status: 403,+ };+ }+ }++ if (!key) {+ key = await getRandomKey(domain);+ }++ return {+ link: {+ ...payload,+ key,+ },+ error: null,+ status: 200,+ };+}+export async function addLink(link: LinkProps) {const {domain,diff --git a/apps/web/lib/auth/index.ts b/apps/web/lib/auth/index.tsindex 3bffc1ab8d..5ea36f2052 100644--- a/apps/web/lib/auth/index.ts+++ b/apps/web/lib/auth/index.ts@@ -90,10 +90,19 @@ export const withAuth =}const apiKey = authorizationHeader.replace("Bearer ", "");+ if (!slug) {+ return new Response(+ "API access is only available for projects with custom domains.",+ {+ status: 403,+ },+ );+ }+const url = new URL(req.url || "", API_DOMAIN);if (url.pathname.includes("/stats/")) {- return new Response("Unauthorized: Invalid route.", {+ return new Response("API access is not available for stats yet.", {status: 403,});}diff --git a/apps/web/lib/types.ts b/apps/web/lib/types.tsindex aa1ce7d11c..b4c7a319ed 100644--- a/apps/web/lib/types.ts+++ b/apps/web/lib/types.ts@@ -1,4 +1,6 @@import { DirectorySyncProviders } from "@boxyhq/saml-jackson";++export { type Link as LinkProps } from "@prisma/client";export interface SimpleLinkProps {domain?: string;key: string;